// popup.js (loadPendingField এর সমস্যা সমাধানের পরের এবং Fill Page Button সহ ভার্সন)
document.addEventListener('DOMContentLoaded', () => {
    const profileNameInput = document.getElementById('profileName');
    const fieldsContainer = document.getElementById('fieldsContainer');
    const addFieldButton = document.getElementById('addFieldButton');
    const saveProfileButton = document.getElementById('saveProfileButton');
    const activeProfileSelect = document.getElementById('activeProfileSelect');
    const setActiveButton = document.getElementById('setActiveButton');
    const deleteProfileButton = document.getElementById('deleteProfileButton');
    const statusMessage = document.getElementById('statusMessage');
    const extensionEnabledToggle = document.getElementById('extensionEnabledToggle');
    const exportProfilesButton = document.getElementById('exportProfilesButton');
    const importFileInput = document.getElementById('importFile');
    const fillPageButton = document.getElementById('fillPageButton');

    const FIELD_TYPES = [
        { value: 'text', label: 'Text' },
        { value: 'password', label: 'Password' },
        { value: 'email', label: 'Email' },
        { value: 'number', label: 'Number' },
        { value: 'date', label: 'Date (YYYY-MM-DD)' },
        { value: 'tel', label: 'Telephone' },
        { value: 'url', label: 'URL' },
        { value: 'textarea', label: 'Textarea' },
        { value: 'select', label: 'Select (Dropdown)' },
        { value: 'radio', label: 'Radio Button' },
        { value: 'checkbox', label: 'Checkbox (true/false)' }
    ];

    function displayStatus(message, isError = false) {
        statusMessage.textContent = message;
        statusMessage.style.color = isError ? 'red' : 'green';
        statusMessage.style.fontWeight = 'bold';
        setTimeout(() => statusMessage.textContent = '', 4000);
    }

    function addFieldEntry(selector = '', value = '', type = 'text') {
        const fieldEntryDiv = document.createElement('div');
        fieldEntryDiv.classList.add('field-entry');
        let typeOptionsHTML = '';
        FIELD_TYPES.forEach(ft => {
            typeOptionsHTML += `<option value="${ft.value}" ${type === ft.value ? 'selected' : ''}>${ft.label}</option>`;
        });
        fieldEntryDiv.innerHTML = `
            <input type="text" class="field-selector" placeholder="ফিল্ড সিলেক্টর" value="${selector}">
            <input type="text" class="field-value" placeholder="ফিল্ড ভ্যালু" value="${value}">
            <select class="field-type-select">
                ${typeOptionsHTML}
            </select>
            <button class="remove-field" title="এই ফিল্ডটি সরান">X</button>
        `;
        fieldsContainer.appendChild(fieldEntryDiv);
        fieldEntryDiv.querySelector('.remove-field').addEventListener('click', () => {
            fieldEntryDiv.remove();
        });
    }

    function updateFillPageButtonState() {
        const selectedProfile = activeProfileSelect.value;
        const isExtensionActive = extensionEnabledToggle.checked;
        fillPageButton.disabled = !(selectedProfile && isExtensionActive);
    }

    addFieldButton.addEventListener('click', () => addFieldEntry());

    saveProfileButton.addEventListener('click', () => {
        const profileName = profileNameInput.value.trim();
        if (!profileName) {
            displayStatus('প্রোফাইলের নাম দিন!', true);
            return;
        }
        const fields = [];
        document.querySelectorAll('#fieldsContainer .field-entry').forEach(entry => {
            const selector = entry.querySelector('.field-selector').value.trim();
            const value = entry.querySelector('.field-value').value;
            const type = entry.querySelector('.field-type-select').value;
            if (selector) {
                fields.push({ selector, value, type });
            }
        });
        chrome.storage.sync.get(['profiles', 'profilesOrder'], (data) => {
            let profiles = data.profiles || {};
            let profilesOrder = data.profilesOrder || [];
            if (!profilesOrder.includes(profileName) && !profiles[profileName]) {
                profilesOrder.push(profileName);
            }
            profiles[profileName] = { fields: fields };
            chrome.storage.sync.set({ profiles, profilesOrder }, () => {
                displayStatus(`প্রোফাইল "${profileName}" সেভ হয়েছে!`);
                loadProfiles(); // এটি activeProfileSelect.value সেট করবে এবং change ইভেন্ট ট্রিগার করবে
                activeProfileSelect.value = profileName; // নিশ্চিত করা যে নতুন সেভ করা প্রোফাইল সিলেক্টেড
                // loadProfiles এর ভেতরের dispatchEvent('change') updateFillPageButtonState কল করবে
            });
        });
    });

    function loadProfiles() {
        chrome.storage.sync.get(['profiles', 'activeProfile', 'profilesOrder'], (data) => {
            const profiles = data.profiles || {};
            const activeProfileName = data.activeProfile || '';
            let profilesOrder = data.profilesOrder || Object.keys(profiles);

            profilesOrder = profilesOrder.filter(pName => profiles[pName]);
            const unOrderedProfiles = Object.keys(profiles).filter(pName => !profilesOrder.includes(pName));
            profilesOrder = [...profilesOrder, ...unOrderedProfiles];

            const previouslySelected = activeProfileSelect.value;
            activeProfileSelect.innerHTML = '<option value="">-- কোনো প্রোফাইল নয় --</option>';
            profilesOrder.forEach(name => {
                if (profiles[name]) {
                    const option = document.createElement('option');
                    option.value = name;
                    option.textContent = name;
                    activeProfileSelect.appendChild(option);
                }
            });

            if (profiles[previouslySelected]) {
                activeProfileSelect.value = previouslySelected;
            } else if (activeProfileName && profiles[activeProfileName]) {
                activeProfileSelect.value = activeProfileName;
            }
            activeProfileSelect.dispatchEvent(new Event('change')); // এটি updateFillPageButtonState কল করবে
        });
    }

    activeProfileSelect.addEventListener('change', () => {
        const selectedProfileName = activeProfileSelect.value;
        if (selectedProfileName) {
            chrome.storage.sync.get(['profiles'], (data) => {
                const profileData = data.profiles[selectedProfileName];
                if (profileData && profileData.fields) {
                    profileNameInput.value = selectedProfileName;
                    fieldsContainer.innerHTML = '';
                    profileData.fields.forEach(field => addFieldEntry(field.selector, field.value, field.type));
                    if (profileData.fields.length === 0) addFieldEntry();
                } else if (Array.isArray(profileData)) {
                    console.warn(`Profile "${selectedProfileName}" is in old format. Re-save to update.`);
                    profileNameInput.value = selectedProfileName;
                    fieldsContainer.innerHTML = '';
                    profileData.forEach(field => addFieldEntry(field.selector, field.value, 'text'));
                    if (profileData.length === 0) addFieldEntry();
                } else if (profileData) {
                     console.error("Profile data is an object but missing 'fields'. Profile:", selectedProfileName, profileData);
                     profileNameInput.value = selectedProfileName;
                     fieldsContainer.innerHTML = '';
                     addFieldEntry();
                }
            });
        } else {
            profileNameInput.value = '';
            fieldsContainer.innerHTML = '';
            addFieldEntry();
        }
        updateFillPageButtonState();
    });

    setActiveButton.addEventListener('click', () => {
        const selectedProfile = activeProfileSelect.value;
        chrome.storage.sync.set({ activeProfile: selectedProfile }, () => {
            displayStatus(selectedProfile ? `"${selectedProfile}" এখন অ্যাক্টিভ প্রোফাইল।` : 'কোনো প্রোফাইল অ্যাক্টিভ নেই।');
        });
    });

    deleteProfileButton.addEventListener('click', () => {
        const profileToDelete = activeProfileSelect.value;
        if (!profileToDelete) {
            displayStatus('মোছার জন্য একটি প্রোফাইল সিলেক্ট করুন!', true);
            return;
        }
        if (!confirm(`আপনি কি সত্যিই "${profileToDelete}" প্রোফাইলটি মুছতে চান?`)) return;
        chrome.storage.sync.get(['profiles', 'activeProfile', 'profilesOrder'], (data) => {
            let { profiles = {}, activeProfile = '', profilesOrder = [] } = data;
            if (profiles[profileToDelete]) {
                delete profiles[profileToDelete];
                if (activeProfile === profileToDelete) activeProfile = '';
                profilesOrder = profilesOrder.filter(pName => pName !== profileToDelete);
                chrome.storage.sync.set({ profiles, activeProfile, profilesOrder }, () => {
                    displayStatus(`প্রোফাইল "${profileToDelete}" মুছে ফেলা হয়েছে।`);
                    if(profileNameInput.value === profileToDelete) {
                        profileNameInput.value = '';
                        fieldsContainer.innerHTML = '';
                        addFieldEntry();
                    }
                    loadProfiles(); // এটি activeProfileSelect.value রিসেট/আপডেট করবে এবং change ইভেন্ট ট্রিগার করবে
                });
            }
        });
    });

    extensionEnabledToggle.addEventListener('change', () => {
        const isEnabled = extensionEnabledToggle.checked;
        chrome.storage.sync.set({ extensionEnabled: isEnabled }, () => {
            displayStatus(`অটোফিল এখন ${isEnabled ? 'সক্রিয়' : 'নিষ্ক্রিয়'}`);
            updateFillPageButtonState();
        });
    });

    function loadExtensionState() {
        chrome.storage.sync.get('extensionEnabled', (data) => {
            extensionEnabledToggle.checked = data.extensionEnabled === undefined ? true : data.extensionEnabled;
            updateFillPageButtonState();
        });
    }

    exportProfilesButton.addEventListener('click', () => {
        chrome.storage.sync.get(['profiles', 'profilesOrder'], (dataToExport) => {
            const exportData = {
                profiles: dataToExport.profiles || {},
                profilesOrder: dataToExport.profilesOrder || []
            };
            if (!exportData.profiles || Object.keys(exportData.profiles).length === 0) {
                displayStatus('এক্সপোর্ট করার মতো কোনো প্রোফাইল নেই!', true); return;
            }
            const jsonData = JSON.stringify(exportData, null, 2);
            const blob = new Blob([jsonData], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url; a.download = 'autofill_profiles_data.json';
            document.body.appendChild(a); a.click();
            document.body.removeChild(a); URL.revokeObjectURL(url);
            displayStatus('প্রোফাইল ডেটা এক্সপোর্ট করা হয়েছে।');
        });
    });

    importFileInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const importedData = JSON.parse(e.target.result);
                if (typeof importedData !== 'object' || importedData === null || typeof importedData.profiles !== 'object') {
                    throw new Error("অবৈধ ফাইলের গঠন। 'profiles' অবজেক্ট আবশ্যক।");
                }
                const importedProfiles = importedData.profiles;
                const importedOrder = Array.isArray(importedData.profilesOrder) ? importedData.profilesOrder : [];
                for (const pName in importedProfiles) {
                    if (typeof importedProfiles[pName] !== 'object' || !Array.isArray(importedProfiles[pName].fields)) {
                        throw new Error(`প্রোফাইল "${pName}" এর গঠন সঠিক নয়। 'fields' অ্যারে আবশ্যক।`);
                    }
                    delete importedProfiles[pName].color;
                    delete importedProfiles[pName].icon;
                }
                chrome.storage.sync.get(['profiles', 'profilesOrder'], (currentData) => {
                    let { profiles = {}, profilesOrder = [] } = currentData;
                    profiles = { ...profiles, ...importedProfiles };
                    const combinedOrder = [...profilesOrder];
                    importedOrder.forEach(pName => {
                        if (importedProfiles[pName] && !combinedOrder.includes(pName)) combinedOrder.push(pName);
                    });
                    profilesOrder = combinedOrder.filter(pName => profiles[pName]);
                    chrome.storage.sync.set({ profiles, profilesOrder }, () => {
                        displayStatus('প্রোফাইল সফলভাবে ইম্পোর্ট করা হয়েছে!');
                        loadProfiles(); // এটি activeProfileSelect.value রিসেট/আপডেট করবে এবং change ইভেন্ট ট্রিগার করবে
                        importFileInput.value = '';
                    });
                });
            } catch (err) {
                displayStatus(`ইম্পোর্ট করার সময় ত্রুটি: ${err.message}`, true);
                importFileInput.value = '';
            }
        };
        reader.readAsText(file);
    });

    fillPageButton.addEventListener('click', () => {
        const selectedProfileName = activeProfileSelect.value;
        if (!selectedProfileName || !extensionEnabledToggle.checked) {
            displayStatus('একটি প্রোফাইল সিলেক্ট করুন এবং এক্সটেনশন সক্রিয় রাখুন!', true);
            return;
        }
        chrome.storage.sync.get('profiles', (data) => {
            if (data.profiles && data.profiles[selectedProfileName]) {
                const profileToFill = data.profiles[selectedProfileName];
                chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
                    if (tabs.length > 0) {
                        const activeTabId = tabs[0].id;
                        chrome.tabs.sendMessage(activeTabId, { type: "FORCE_FILL_FORM", profileData: profileToFill }, (response) => {
                            if (chrome.runtime.lastError) {
                                console.error("Error sending FORCE_FILL_FORM message:", chrome.runtime.lastError.message);
                                displayStatus(`পেজ পূরণে সমস্যা: ${chrome.runtime.lastError.message}`, true);
                            } else if (response && response.success) {
                                displayStatus(`প্রোফাইল "${selectedProfileName}" দিয়ে পেজ পূরণ করা হয়েছে।`);
                                window.close();
                            } else {
                                displayStatus(`পেজ পূরণে সমস্যা: ${response ? response.error : 'Unknown error'}`, true);
                            }
                        });
                    } else { displayStatus('সক্রিয় ট্যাব খুঁজে পাওয়া যায়নি!', true); }
                });
            } else { displayStatus('সিলেক্ট করা প্রোফাইল খুঁজে পাওয়া যায়নি!', true); }
        });
    });

    function loadPendingField() {
        chrome.storage.local.get('pendingField', (data) => {
            if (data.pendingField && data.pendingField.selector) {
                const currentFieldsElements = document.querySelectorAll('#fieldsContainer .field-entry');
                let lastFieldIsEmpty = false;

                if (currentFieldsElements.length > 0) {
                    const lastEntry = currentFieldsElements[currentFieldsElements.length - 1];
                    const lastSelector = lastEntry.querySelector('.field-selector').value.trim();
                    const lastValue = lastEntry.querySelector('.field-value').value;
                    if (!lastSelector && !lastValue) {
                        lastFieldIsEmpty = true;
                    }
                }
                const defaultTypeForPending = 'text';
                if (currentFieldsElements.length === 0 || !lastFieldIsEmpty) {
                    addFieldEntry(data.pendingField.selector, data.pendingField.value, defaultTypeForPending);
                } else if (lastFieldIsEmpty) {
                    const lastEntry = currentFieldsElements[currentFieldsElements.length - 1];
                    lastEntry.querySelector('.field-selector').value = data.pendingField.selector;
                    lastEntry.querySelector('.field-value').value = data.pendingField.value;
                    lastEntry.querySelector('.field-type-select').value = defaultTypeForPending;
                }
                chrome.storage.local.remove('pendingField');
                displayStatus('কনটেক্সট মেনু থেকে ফিল্ড যোগ করা হয়েছে। একটি প্রোফাইল নাম দিয়ে সেভ করুন।');
            } else if (fieldsContainer.children.length === 0 && profileNameInput.value === '') {
                addFieldEntry();
            }
        });
    }

    loadExtensionState();
    loadProfiles();
    loadPendingField();
    // updateFillPageButtonState(); // এই কলটি loadExtensionState এবং loadProfiles এর মাধ্যমে হয়ে যাবে
});