/**
 * PIKEY Content Script
 * Listens for messages from the extension popup to autofill fields.
 */

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "autofill") {
        const { username, password } = request.data;
        
        // Try to find login fields
        const passwordFields = document.querySelectorAll('input[type="password"]');
        const userFields = document.querySelectorAll('input[type="email"], input[type="text"], input[name*="user"], input[name*="login"]');

        if (passwordFields.length > 0) {
            passwordFields[0].value = password;
            // Dispatch input event to trigger any site listeners
            passwordFields[0].dispatchEvent(new Event('input', { bubbles: true }));
        }

        if (userFields.length > 0) {
            // Find the most likely username field (usually near the password)
            let bestUserField = userFields[0];
            userFields.forEach(field => {
                if (field.name && (field.name.includes('user') || field.name.includes('login'))) {
                    bestUserField = field;
                }
            });
            bestUserField.value = username;
            bestUserField.dispatchEvent(new Event('input', { bubbles: true }));
        }

        sendResponse({ status: "success" });
    }
});
