// content.js

async function fillFormFields(fields, currentTabId) {
    if (!Array.isArray(fields)) {
        console.error("AutoFill: `fields` parameter is not an array. Cannot iterate.", fields);
        return;
    }
    // console.log("AutoFill: Filling form with fields:", JSON.parse(JSON.stringify(fields)));

    for (const field of fields) {
        if (!field || typeof field.selector !== 'string' || field.value === undefined || typeof field.type !== 'string') {
            console.warn("AutoFill: Skipping invalid field object:", field);
            continue;
        }
        // console.log("AutoFill: Attempting to fill selector:", field.selector, "Type:", field.type, "Value:", field.value);
        try {
            const elements = document.querySelectorAll(field.selector); // Use querySelectorAll for radio buttons
            if (elements.length === 0) {
                // console.warn(`AutoFill: Element not found for selector "${field.selector}"`);
                continue;
            }

            // querySelectorAll returns a NodeList. We usually want the first one, unless it's radio.
            const element = (field.type === 'radio' && elements.length > 1) ? null : elements[0]; // For radio, we'll iterate elements

            if (field.type === 'radio') {
                let radioSelected = false;
                elements.forEach(radioEl => {
                    if (radioEl.tagName === 'INPUT' && radioEl.type === 'radio') {
                        if (radioEl.value === field.value) {
                            if (radioEl.disabled) return;
                            radioEl.checked = true;
                            radioSelected = true;
                            // Dispatch events for the selected radio
                            ['focus', 'input', 'change', 'blur'].forEach(eventType => {
                                radioEl.dispatchEvent(new Event(eventType, { bubbles: true, cancelable: true }));
                            });
                        }
                    }
                });
                if (!radioSelected) {
                    // console.warn(`AutoFill: Radio option with value "${field.value}" not found for selector/group "${field.selector}"`);
                }
                continue; // Radio handled, move to next field
            }

            // For all other types, use the first matched element
            if (!element) { // Should not happen if not radio and elements.length > 0
                // console.warn(`AutoFill: Element could not be determined for selector "${field.selector}" (not a radio group).`);
                continue;
            }

            let wasReadOnly = element.readOnly;
            let wasDisabled = element.disabled;

            if (wasDisabled) {
                // console.log(`AutoFill: Skipped disabled field "${field.selector}"`);
                continue;
            }

            if (wasReadOnly && (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')) {
                element.readOnly = false;
            }

            let fieldHandled = false;

            if (field.type === 'checkbox') {
                const targetValue = String(field.value).toLowerCase();
                if (targetValue === 'true' || targetValue === 'checked' || (element.value && element.value === field.value && targetValue !== 'false')) {
                    element.checked = true;
                } else {
                    element.checked = false;
                }
                fieldHandled = true;
            }
            else if (field.type === 'date' && element.classList.contains('datepicker') && (element.id === 'JoiningDate' || element.id === 'ClientDOB' || element.id === 'DevicePurchaseDate' || element.id === 'BillingStartDate')) {
                // console.log(`AutoFill: Attempting to fill datepicker ${field.selector} by messaging background script. Type: ${field.type}`);
                try {
                    const response = await chrome.runtime.sendMessage({
                        type: "FILL_DATEPICKER_FIELD",
                        payload: {
                            tabId: currentTabId,
                            selector: field.selector,
                            value: field.value
                        }
                    });
                    if (response && response.success) {
                        // console.log(`AutoFill: Datepicker ${field.selector} (type: ${field.type}) handled via background script.`);
                        fieldHandled = true;
                    } else {
                        console.warn(`AutoFill: Background script failed to handle datepicker ${field.selector}. Falling back. Response:`, response);
                        element.value = field.value; // Fallback
                        fieldHandled = true; // Still consider it handled by fallback
                    }
                } catch (e) {
                    console.error(`AutoFill: Error messaging background for datepicker ${field.selector}:`, e, "Falling back.");
                    element.value = field.value; // Fallback
                    fieldHandled = true; // Still consider it handled by fallback
                }
            }
            else if (['text', 'password', 'email', 'number', 'date', 'tel', 'url', 'textarea'].includes(field.type)) {
                // For 'date' type that is not a special datepicker, set value directly
                // Browsers expect YYYY-MM-DD for <input type="date">
                if (field.type === 'date' && element.type === 'date' && !field.value.match(/^\d{4}-\d{2}-\d{2}$/)) {
                    console.warn(`AutoFill: Value "${field.value}" for date input "${field.selector}" is not YYYY-MM-DD. Browser might not accept it.`);
                }
                element.value = field.value;
                fieldHandled = true;
            }
            else if (field.type === 'select' && element.tagName === 'SELECT') {
                let optionFound = false;
                for (let i = 0; i < element.options.length; i++) {
                    if (element.options[i].value === field.value || element.options[i].text === field.value) {
                        element.selectedIndex = i;
                        optionFound = true;
                        break;
                    }
                }
                if (!optionFound) {
                    // console.warn(`AutoFill: Select option not found for selector "${field.selector}" (type: ${field.type}) with value "${field.value}"`);
                }
                fieldHandled = true;
            }
            else { // Default fallback for unhandled or mismatched types
                // console.log(`AutoFill: Field type "${field.type}" for selector "${field.selector}" has no specific handler or element type mismatch. Using default value set.`);
                element.value = field.value;
                fieldHandled = true;
            }

            // Dispatch events if the field was handled (i.e., not skipped)
            if (fieldHandled) {
                element.dispatchEvent(new Event('focus', { bubbles: true, cancelable: true }));
                element.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
                element.dispatchEvent(new Event('change', { bubbles: true, cancelable: true }));
                element.dispatchEvent(new Event('blur', { bubbles: true, cancelable: true }));
            }

            if (wasReadOnly && (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')) {
                element.readOnly = true;
            }

        } catch (error) {
            console.error(`AutoFill: General error filling field with selector "${field.selector}":`, error);
        }
    }
}

async function initAutofill() {
    let currentTabId;
    try {
        const response = await chrome.runtime.sendMessage({ type: "GET_TAB_ID_FOR_CONTENT_SCRIPT_CONTEXT" });
        if (response && response.tabId) {
            currentTabId = response.tabId;
        } else {
            console.error("AutoFill: Could not get Tab ID for content script context from background.");
        }
    } catch (e) {
        console.error("AutoFill: Error messaging background for Tab ID:", e);
    }

    chrome.storage.sync.get(['extensionEnabled', 'activeProfile', 'profiles'], async (data) => {
        const isExtensionEnabled = data.extensionEnabled === undefined ? true : data.extensionEnabled;
        if (!isExtensionEnabled) {
            // console.log('AutoFill Extension is disabled. Skipping autofill.');
            return;
        }

        if (data.activeProfile && data.profiles && data.profiles[data.activeProfile]) {
            const profileName = data.activeProfile;
            const profileData = data.profiles[profileName];
            let activeProfileFields = null;

            if (profileData && typeof profileData === 'object' && profileData.fields && Array.isArray(profileData.fields)) {
                activeProfileFields = profileData.fields;
                // console.log(`AutoFill: Loading fields for profile "${profileName}" (New Format).`);
            } else if (profileData && Array.isArray(profileData)) {
                // console.warn(`AutoFill: Profile "${profileName}" is in old format. Fields will be treated as 'text' type. Please re-save the profile to update to the new format.`);
                activeProfileFields = profileData.map(field => ({ ...field, type: field.type || 'text' }));
            } else {
                console.error(`AutoFill: Active profile "${profileName}" data is malformed or 'fields' array is missing. Profile data:`, profileData);
                return;
            }

            if (activeProfileFields && activeProfileFields.length > 0) {
                const executeFill = async () => {
                    // console.log('AutoFill: Starting fill process...');
                    await fillFormFields(activeProfileFields, currentTabId);
                };

                if (document.readyState !== 'complete') {
                    window.addEventListener('load', () => {
                        // console.log('AutoFill: Window "load" event triggered. Waiting a bit more.');
                        setTimeout(executeFill, 1000);
                    });
                } else {
                    // console.log('AutoFill: Document already fully loaded (complete state). Waiting a bit.');
                    setTimeout(executeFill, 500);
                }
            } else if (activeProfileFields && activeProfileFields.length === 0) {
                // console.log(`AutoFill: Active profile "${profileName}" has no fields defined. Nothing to fill.`);
            } else {
                 // console.log(`AutoFill: No valid fields found for active profile "${profileName}".`);
            }
        } else {
            // console.log('AutoFill: No active profile or profiles found for autofill.');
        }
    });
}

// Listener for messages, e.g., from popup to force fill
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === "FORCE_FILL_FORM") {
        if (request.profileData && request.profileData.fields && Array.isArray(request.profileData.fields)) {
            // console.log("AutoFill (content.js): FORCE_FILL_FORM received with fields:", request.profileData.fields);

            async function forceFill() {
                 let tabIdForForceFill;
                 try {
                    // It's good practice to get the tabId again if possible,
                    // or ensure it's passed correctly with the message if this message
                    // originated from background after a popup interaction.
                    // For simplicity, if initAutofill's currentTabId is available, we might use it,
                    // but it's safer if the initiator (popup via background) provides the target tabId.
                    // Assuming this message is directly from popup to content script (less common for executeScript actions)
                    // or that the required tabId is implicitly the current tab.
                    // The most robust way: popup -> background -> content_script (with tabId from background)
                    // For now, let's assume fillFormFields can handle a potentially undefined currentTabId
                    // if the "FILL_DATEPICKER_FIELD" message needs it.

                    // Let's get the tabId again to be safe for the datepicker calls
                    const response = await chrome.runtime.sendMessage({ type: "GET_TAB_ID_FOR_CONTENT_SCRIPT_CONTEXT" });
                    if (response && response.tabId) {
                        tabIdForForceFill = response.tabId;
                    } else {
                        console.warn("AutoFill (FORCE_FILL): Could not get tabId for potential datepicker operations.");
                    }

                    await fillFormFields(request.profileData.fields, tabIdForForceFill);
                    sendResponse({ success: true, message: "Form fill initiated by popup." });
                 } catch(e) {
                    console.error("Error during FORCE_FILL:", e);
                    sendResponse({ success: false, error: e.message });
                 }
            }
            forceFill(); // Call the async function
            return true; // Indicates that the response is sent asynchronously
        } else {
            console.error("FORCE_FILL_FORM: profileData or fields missing/invalid in request.", request);
            sendResponse({ success: false, error: "Missing or invalid profile data or fields." });
        }
    }
    // Ensure other message types are not accidentally caught or missing a 'return true' if async
    return false; // Default for synchronous message handlers or if not handling this message type
});


// Start the autofill process
initAutofill();