<el-dialog>
    <dialog id="myDialogShare" aria-labelledby="dialog-title"
        class="fixed inset-0 size-auto max-h-none max-w-none overflow-y-auto bg-transparent backdrop:bg-transparent">
        <el-dialog-backdrop
            class="fixed inset-0 bg-gray-500/75 transition-opacity data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in"></el-dialog-backdrop>

        <div tabindex="0"
            class="flex min-h-full items-end justify-center p-4 text-center focus:outline-none outline-none outline-transparent shadow-none focus:border-0 border-0 text-shadow-none focus:text-shadow-none  sm:items-center sm:p-0">
            <el-dialog-panel
                class="ml-[300px] relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in sm:my-8 sm:w-full md:max-w-3xl data-closed:sm:translate-y-0 data-closed:sm:scale-95">
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div>

                        <!-- Laravel Blade Form (No Alpine.js) -->
                        <form action="{{ route('rate-my-pay.store') }}" method="POST"
                            enctype="multipart/form-data">
                            @csrf

                            <!-- Success Message -->
                            @if (session('success'))
                                <div
                                    class="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-center gap-3">
                                    <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor"
                                        viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    <span class="text-green-800 font-medium">{{ session('success') }}</span>
                                </div>
                            @endif

                            <!-- Info badges -->
                            <div class="flex flex-wrap gap-4 mb-6 text-sm text-gray-600">
                                <div class="flex items-center gap-2">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    <span>Will taken only 50 seconds</span>
                                </div>
                                <div class="flex items-center gap-2">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                    <span>100% anonymous</span>
                                </div>
                                <div class="flex items-center gap-2">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    <span>Worldwide submission</span>
                                </div>
                            </div>

                            <!-- Job Experience Selection -->
                            <div class="mb-6">
                                <label for="job_experience_id" class="block text-sm font-medium text-gray-900 mb-2">
                                    Select Job Experience
                                </label>
                                <div class="relative">
                                    <select id="job_experience_id" name="job_experience_id" required
                                        class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none @error('job_experience_id') border-red-500 @enderror">
                                        <option value="">Choose a job experience...</option>
                                        @foreach($experiences ?? [] as $job)
                                            <option value="{{ $job->id }}" 
                                                {{ old('job_experience_id') == $job->id ? 'selected' : '' }}
                                                data-salary="{{ $job->annual_base_salary }}"
                                                data-bonus="{{ $job->bonus_commission }}"
                                                data-equity="{{ $job->equity }}"
                                                data-currency="{{ $job->currency }}"
                                                data-benefits="{{ $job->benefits }}">
                                                {{ $job->job_title }} at {{ $job->company_name }} - {{ $job->formatted_salary }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                                    </div>
                                </div>
                                @error('job_experience_id')
                                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                                
                                <!-- Salary Preview (Optional - can be shown when job is selected) -->
                                <div id="salary-preview" class="mt-3 p-3 bg-gray-50 rounded-lg hidden">
                                    <h4 class="font-medium text-gray-900 mb-2">Salary Details</h4>
                                    <div class="grid grid-cols-2 gap-2 text-sm">
                                        <div>
                                            <span class="text-gray-600">Base Salary:</span>
                                            <span id="preview-base-salary" class="font-medium ml-2"></span>
                                        </div>
                                        <div>
                                            <span class="text-gray-600">Bonus:</span>
                                            <span id="preview-bonus" class="font-medium ml-2"></span>
                                        </div>
                                        <div>
                                            <span class="text-gray-600">Equity:</span>
                                            <span id="preview-equity" class="font-medium ml-2"></span>
                                        </div>
                                        <div>
                                            <span class="text-gray-600">Total:</span>
                                            <span id="preview-total" class="font-medium ml-2 text-green-600"></span>
                                        </div>
                                    </div>
                                    <div class="mt-2">
                                        <span class="text-gray-600">Benefits:</span>
                                        <span id="preview-benefits" class="font-medium ml-2"></span>
                                    </div>
                                </div>
                            </div>

                            <!-- Privacy toggle -->
                            <div class="flex items-center justify-end gap-3 mb-6">
                                <span class="text-sm text-gray-600">Public:</span>
                                <label class="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" name="is_anonymous" value="1" class="sr-only peer"
                                        {{ old('is_anonymous') ? 'checked' : '' }}>
                                    <div
                                        class="w-11 h-6 bg-gray-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600">
                                    </div>
                                </label>
                                <span class="text-sm font-medium text-gray-900">Anonymous</span>
                            </div>

                            <!-- Communities Selection -->
                            <div class="mb-6">
                                <label for="communitySearch" class="block text-sm font-medium text-gray-900 mb-3">
                                    Share with Communities
                                </label>
                                
                                <!-- Search Input -->
                                <div class="relative mb-4">
                                    <input 
                                        type="text" 
                                        id="communitySearch" 
                                        placeholder="Search communities..." 
                                        class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                        autocomplete="off"
                                    />
                                    <svg class="absolute right-3 top-3.5 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                    </svg>
                                </div>

                                <!-- Selected Items -->
                                <div id="selectedContainer" class="mb-4 min-h-0">
                                    <div id="selectedTags" class="flex flex-wrap gap-2"></div>
                                </div>

                                <!-- Dropdown Options -->
                                <div id="dropdownContainer" class="relative">
                                    <div id="optionsDropdown" class="hidden absolute z-10 w-full bg-white border border-gray-300 rounded-lg shadow-lg mt-1 max-h-64 overflow-y-auto">
                                        <div id="optionsList" class="p-2">
                                            @foreach($communities ?? [] as $community)
                                                <label class="flex items-center px-3 py-2 hover:bg-gray-100 rounded cursor-pointer transition-all group">
                                                    <input 
                                                        type="checkbox" 
                                                        value="{{ $community->id }}"
                                                        class="w-4 h-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500 cursor-pointer community-checkbox"
                                                        {{ in_array($community->id, old('community_ids', [])) ? 'checked' : '' }}
                                                    />
                                                    <span class="ml-3 text-gray-800 group-hover:text-gray-900">{{ $community->name }}</span>
                                                </label>
                                            @endforeach
                                        </div>
                                        <div id="noResults" class="hidden p-4 text-center text-gray-500 text-sm">
                                            No communities found
                                        </div>
                                    </div>
                                </div>

                                <!-- Hidden Select for Form Submission -->
                                <select id="communities" name="community_ids[]" multiple class="hidden">
                                    @foreach($communities ?? [] as $community)
                                        <option value="{{ $community->id }}" 
                                            {{ in_array($community->id, old('community_ids', [])) ? 'selected' : '' }}>
                                            {{ $community->name }}
                                        </option>
                                    @endforeach
                                </select>

                                <p class="mt-3 text-sm text-gray-500">
                                    Select one or more communities to share your post.
                                </p>
                                @error('community_ids')
                                    <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                            <!-- Write Post -->
                            <div class="mb-6">
                                <label for="content" class="block text-sm font-medium text-gray-900 mb-2">
                                    Write Post
                                </label>
                                <textarea id="content" name="content" rows="4" placeholder="Share your thoughts about this compensation, work experience, or any insights..."
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none @error('content') border-red-500 @enderror">{{ old('content') }}</textarea>
                                @error('content')
                                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                          <!-- Upload area -->
                            <div class="mb-6">
                                <label
                                    class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition cursor-pointer block">

                                    <!-- Add ID here -->
                                    <input 
                                        type="file" 
                                        name="payslip" 
                                        id="img"
                                        class="hidden"
                                        accept=".pdf,.jpg,.jpeg,.png"
                                    >

                                    <div class="flex flex-col items-center gap-3">
                                        <div class="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                                            <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor"
                                                viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                    d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                                            </svg>
                                        </div>
                                        <div>
                                            <span class="text-blue-600 hover:underline font-medium">Click to upload payslip</span>
                                            <span class="text-gray-600"> or drag and drop</span>
                                        </div>
                                        <p class="text-xs text-gray-500">
                                            PDF, JPG, PNG files (Max: 5MB)
                                        </p>
                                    </div>
                                </label>

                                <!-- Error Message (add ID here) -->
                                <p id="imgError" class="text-red-600 text-sm mt-1 hidden"></p>

                                <!-- File preview -->
                                <div id="filePreview" class="mt-3 hidden text-sm text-gray-700 flex items-center gap-3">

                                    <!-- PDF/JPG/PNG icon stays as-is -->
                                    <svg class="w-6 h-6 text-gray-500" fill="none" stroke="currentColor"
                                        viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M7 7V3h10v4m0 0h4v14H3V7h4m10 0v14M7 7h10" />
                                    </svg>

                                    <span id="fileName"></span>
                                </div>

                                <!-- Image preview (NEW) -->
                                <img 
                                    id="previewImage" 
                                    class="w-20 h-20 rounded mt-2 opacity-0 transition-opacity duration-300 hidden"
                                />

                                @error('payslip')
                                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                            <div class="flex gap-20 justify-between">
                                <button type="button" command="close" commandfor="myDialogShare"
                                    class="w-1/4 py-3 bg-white text-black border font-medium rounded-lg hover:bg-white transition">Cancel</button>

                                <!-- Submit button -->
                                <button type="submit"
                                    class="w-1/2 py-3 bg-blue-900 text-white font-medium rounded-lg hover:bg-blue-800 transition">
                                    Share Post
                                </button>
                            </div>

                        </form>
                    </div>
                </div>

            </el-dialog-panel>
        </div>
    </dialog>
</el-dialog>

<script>
    // JavaScript to show salary preview when job is selected
    document.addEventListener('DOMContentLoaded', function() {
        const jobSelect = document.getElementById('job_experience_id');
        const previewDiv = document.getElementById('salary-preview');
        
        if (jobSelect) {
            jobSelect.addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                
                if (selectedOption.value) {
                    const baseSalary = parseFloat(selectedOption.getAttribute('data-salary')) || 0;
                    const bonus = parseFloat(selectedOption.getAttribute('data-bonus')) || 0;
                    const equity = parseFloat(selectedOption.getAttribute('data-equity')) || 0;
                    const currency = selectedOption.getAttribute('data-currency') || 'NGN';
                    const benefits = selectedOption.getAttribute('data-benefits') || 'None';
                    const total = baseSalary + bonus + equity;
                    
                    // Format numbers with commas
                    const formatNumber = (num) => num.toLocaleString();
                    
                    // Update preview
                    document.getElementById('preview-base-salary').textContent = `${formatNumber(baseSalary)} ${currency}`;
                    document.getElementById('preview-bonus').textContent = `${formatNumber(bonus)} ${currency}`;
                    document.getElementById('preview-equity').textContent = `${formatNumber(equity)} ${currency}`;
                    document.getElementById('preview-total').textContent = `${formatNumber(total)} ${currency}`;
                    document.getElementById('preview-benefits').textContent = benefits;
                    
                    // Show preview
                    previewDiv.classList.remove('hidden');
                } else {
                    previewDiv.classList.add('hidden');
                }
            });
        }
    });

    const searchInput = document.getElementById('communitySearch');
    const dropdown = document.getElementById('optionsDropdown');
    const optionsList = document.getElementById('optionsList');
    const selectedTags = document.getElementById('selectedTags');
    const hiddenSelect = document.getElementById('communities');
    const noResults = document.getElementById('noResults');

    let selected = new Set();

    // Initialize with pre-selected values
    document.querySelectorAll('.community-checkbox:checked').forEach(checkbox => {
        selected.add(checkbox.value);
    });

    function renderOptions(filter = '') {
        const checkboxes = Array.from(document.querySelectorAll('.community-checkbox'));
        let visibleCount = 0;

        checkboxes.forEach(checkbox => {
            const label = checkbox.closest('label');
            const text = checkbox.nextElementSibling.textContent.toLowerCase();
            const matches = text.includes(filter.toLowerCase());
            label.style.display = matches ? '' : 'none';
            if (matches) visibleCount++;
        });

        noResults.classList.toggle('hidden', visibleCount > 0);
    }

    function updateSelected() {
        selectedTags.innerHTML = '';

        const selectedArray = Array.from(selected);
        if (selectedArray.length === 0) {
            selectedTags.innerHTML = '<p class="text-sm text-gray-400">No communities selected</p>';
            return;
        }

        selectedArray.forEach(id => {
            const checkbox = document.querySelector(`input[value="${id}"]`);
            const name = checkbox.nextElementSibling.textContent;

            const tag = document.createElement('div');
            tag.className = 'bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium flex items-center gap-2';
            tag.innerHTML = `
                <span>${name}</span>
                <button type="button" class="hover:text-blue-900 font-bold" data-id="${id}">×</button>
            `;

            tag.querySelector('button').addEventListener('click', (e) => {
                e.preventDefault();
                selected.delete(id);
                const checkbox = document.querySelector(`input[value="${id}"]`);
                checkbox.checked = false;
                updateSelected();
            });

            selectedTags.appendChild(tag);
        });
    }

    // Event listeners
    document.querySelectorAll('.community-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            if (checkbox.checked) {
                selected.add(checkbox.value);
            } else {
                selected.delete(checkbox.value);
            }
            updateSelected();
        });
    });

    searchInput.addEventListener('focus', () => {
        dropdown.classList.remove('hidden');
        renderOptions(searchInput.value);
    });

    searchInput.addEventListener('input', () => {
        renderOptions(searchInput.value);
    });

    document.addEventListener('click', (e) => {
        if (!e.target.closest('#dropdownContainer') && !e.target.closest('#communitySearch')) {
            dropdown.classList.add('hidden');
        }
    });

    document.addEventListener("DOMContentLoaded", () => {
        const fileInput = document.querySelector('input[name="payslip"]');
        const filePreview = document.getElementById("filePreview");
        const fileName = document.getElementById("fileName");

        if (fileInput) {
            fileInput.addEventListener("change", () => {
                if (fileInput.files.length > 0) {
                    fileName.textContent = fileInput.files[0].name;
                    filePreview.classList.remove("hidden");
                } else {
                    filePreview.classList.add("hidden");
                }
            });
        }
    });

    document.getElementById('img').addEventListener('change', function () {
        const file = this.files[0];
        const preview = document.getElementById('previewImage');
        const errorText = document.getElementById('imgError');

        // Reset UI
        preview.style.border = "none";
        errorText.classList.add('hidden');
        preview.classList.add('opacity-0');
        preview.classList.add('hidden');

        if (!file) return;

        const maxSizeMB = 5;
        const allowedTypes = [
            'application/pdf',
            'image/jpeg',
            'image/png',
            'image/jpg'
        ];

        // File type check
        if (!allowedTypes.includes(file.type)) {
            preview.src = "";
            errorText.innerText = "Only PDF, JPG, and PNG files are allowed.";
            errorText.classList.remove('hidden');
            this.value = "";
            return;
        }

        // File size check
        if (file.size > maxSizeMB * 1024 * 1024) {
            preview.src = "";
            errorText.innerText = `File is too large! Maximum allowed size is ${maxSizeMB}MB.`;
            errorText.classList.remove('hidden');
            this.value = "";
            return;
        }

        // PDF should not show an image preview
        if (file.type === 'application/pdf') {
            preview.src = "";
            preview.classList.add('hidden');
            return;
        }

        // JPG/PNG preview
        const reader = new FileReader();
        reader.onload = function (event) {
            preview.src = event.target.result;
            preview.classList.remove('hidden');
            preview.classList.remove('opacity-0'); // Fade-in animation
        };
        reader.readAsDataURL(file);
    });

    updateSelected();
</script>