/*====================================================================*/
/*  descgpt-general.js – Settings page  */
/*====================================================================*/
jQuery(document).ready(function ($) {
    const $form = $('.descgpt-settings-form');
    const $modelSelect = $('#descgpt_model');
    const $updateBtn = $('#descgpt_update_api_key');
    const $verifyBtn = $('#descgpt_verify_api_key');
    const $cancelBtn = $('#descgpt_cancel_api_key');
    const $apiInput = $('#descgpt_api_key');
    const $apiMasked = $('#descgpt_api_key_masked');
    const $apiMessage = $('#descgpt_api_key_message');
    
    const settings = window.descgptwSettings || {};
    const strings = settings.strings || {};
    const ajaxUrl = settings.ajaxurl || '';
    const verifyNonce = settings.verifyNonce || '';
    const modelsNonce = settings.modelsNonce || '';
    let hasSavedKey = settings.hasSavedApiKey || false;
    const savedModel = settings.savedModel || '';

    function showMessage(txt, success = false) {
        $apiMessage
            .text(txt)
            .removeClass('text-green-600 text-red-600')
            .addClass(success ? 'text-green-600' : 'text-red-600');
    }

    function toggleEditMode(enable) {
        const $input = $('#descgpt_api_key');
        const $masked = $('#descgpt_api_key_masked');

        if (enable) {
            if (!$input.length) {
                $input = $('<input>').attr({
                    type: 'text',
                    id: 'descgpt_api_key',
                    name: 'descgpt_api_key',
                    class: 'block w-full sm:w-64 rounded-lg border-gray-300 px-3 py-2 text-sm',
                    placeholder: 'Enter your OpenAI API key...'
                }).insertBefore($masked);
            }
            $input.show().focus();
            $masked.hide();
            $verifyBtn.removeClass('hidden');
            $cancelBtn.removeClass('hidden');
            $updateBtn.hide();
        } else {
            $input.hide().removeAttr('name'); // Prevent empty submit
            $masked.show();
            $verifyBtn.addClass('hidden');
            $cancelBtn.addClass('hidden');
            if (hasSavedKey) $updateBtn.show();
        }
    }

    function fetchModels(apiKey = '') {
        $modelSelect.html('<option value="">' + (strings.loading_models || 'Loading models…') + '</option>');

        $.post(ajaxUrl, {
            action: 'descgpt_get_models',
            nonce: modelsNonce,
            api_key: apiKey
        }, function (res) {
            $modelSelect.empty();
            if (res.success && Array.isArray(res.data)) {
                $modelSelect.append('<option value="">' + (strings.select_model || 'Select a model') + '</option>');
                $.each(res.data, function (i, m) {
                    const selected = (savedModel === m.id || (!savedModel && m.id === 'gpt-4o-mini')) ? ' selected' : '';
                    $modelSelect.append('<option value="' + m.id + '"' + selected + '>' + m.name + '</option>');
                });
            } else {
                $modelSelect.html('<option value="">' + (strings.no_models || 'No models available.') + '</option>');
            }
        }, 'json').fail(function (xhr) {
            console.log('AJAX fail:', xhr);
            $modelSelect.html('<option value="">' + (strings.error_models || 'Error loading models') + '</option>');
        });
    }

    function verifyAndSaveKey(key) {
        showMessage('Verifying API key…');
        $.post(ajaxUrl, {
            action: 'descgpt_verify_api_key',
            api_key: key,
            security: verifyNonce
        }, function (res) {
            if (res.success) {
                showMessage('API key verified!', true);

                // Add hidden input for form submit
                $form.find('input[name="descgpt_api_key"]').remove();
                $('<input>').attr({
                    type: 'hidden',
                    name: 'descgpt_api_key',
                    value: key
                }).appendTo($form);

                // Update masked display
                const last4 = key.slice(-4);
                $apiMasked.val('••••••••••••••••'.slice(0, -last4.length) + last4);

                // Update state
                hasSavedKey = true;
                toggleEditMode(false);
                fetchModels(key);
            } else {
                showMessage(res.data?.message || 'Verification failed.');
            }
        }, 'json').fail(function () {
            showMessage('Network error. Please try again.');
        });
    }

    // === EVENT HANDLERS ===
    $updateBtn.on('click', function (e) {
        e.preventDefault();
        toggleEditMode(true);
    });

    $verifyBtn.on('click', function (e) {
        e.preventDefault();
        const key = $apiInput.val().trim();
        if (key) verifyAndSaveKey(key);
        else showMessage('Please enter a valid API key.');
    });

    $cancelBtn.on('click', function (e) {
        e.preventDefault();
        toggleEditMode(false);
        $apiInput.val('');
    });

    $apiInput.on('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            $verifyBtn.trigger('click');
        }
    });

    // === INITIAL STATE ===
    if (hasSavedKey) {
        toggleEditMode(false);
        fetchModels();
    } else {
        // FIRST LOAD: Show input + verify button
        toggleEditMode(true);
        $updateBtn.hide(); // No update button yet
        $modelSelect.html('<option value="">Add an API key to load models.</option>');
    }

    // Debug
    $form.on('submit', function () {
        console.log('Form submit →', $(this).serialize());
    });
});

// UNSAVED CHANGES WARNING SCRIPT
document.addEventListener('DOMContentLoaded', function () {
    // Look for your custom form — give it a class or fallback to the first <form> in the page
    const form = document.querySelector('form.space-y-8') || document.querySelector('form');
    if (!form) return; // stop if no form found

    const inputs = form.querySelectorAll('input, select, textarea');
    const warningBox = document.getElementById('descgpt-unsaved-warning');
    let isChanged = false;
    const originalValues = {};

    // Store initial values
    inputs.forEach(input => {
        if (input.id) {
            originalValues[input.id] = input.value;
        }
    });

    // Detect changes
    inputs.forEach(input => {
        input.addEventListener('input', () => handleChange(input));
        input.addEventListener('change', () => handleChange(input));
    });

    function handleChange(input) {
        const original = originalValues[input.id];
        if (input.value !== original) {
            input.classList.add('descgpt-field-changed');
            isChanged = true;
            if (warningBox) warningBox.style.display = 'block';
        } else {
            input.classList.remove('descgpt-field-changed');
            isChanged = Array.from(inputs).some(i => i.value !== originalValues[i.id]);
            if (!isChanged && warningBox) warningBox.style.display = 'none';
        }
    }

    // Reset warning after successful submit
    form.addEventListener('submit', () => {
        isChanged = false;
        if (warningBox) warningBox.style.display = 'none';
    });

    // Warn before leaving
    window.addEventListener('beforeunload', function (e) {
        if (isChanged) {
            e.preventDefault();
            e.returnValue = 'You have unsaved changes. Do you really want to leave this page?';
        }
    });
});
