/**
 * AI Featured Image Generator - Settings Page JS
 */
jQuery(document).ready(function($) {
    var providerSelect = $('#aifi-provider');
    var modelSelect = $('#aifi-model');
    var aspectRatioSelect = $('#aifi-aspect-ratio');
    var aspectRatioList = $('#aifi-aspect-ratio-list');

    // Get provider value - from select if available, otherwise from PHP-provided value
    function getCurrentProvider() {
        return providerSelect.length ? providerSelect.val() : aifiSettingsData.currentProvider;
    }

    // Get model value - from select if available, otherwise from PHP-provided value
    function getCurrentModel() {
        return modelSelect.length ? modelSelect.val() : aifiSettingsData.currentModel;
    }

    function updateModelOptions(provider) {
        if (!window.aifiModelsData || !window.aifiModelsData[provider]) return;
        var models = window.aifiModelsData[provider];
        var disabled = window.aifiDisabledModels && window.aifiDisabledModels[provider] ? window.aifiDisabledModels[provider] : [];
        var currentValue = modelSelect.val();

        modelSelect.empty();

        $.each(models, function(value, label) {
            var isDisabled = disabled.indexOf(value) !== -1;
            var option = $('<option></option>')
                .attr('value', value)
                .text(isDisabled ? label + ' (Pro)' : label)
                .prop('disabled', isDisabled);
            modelSelect.append(option);
        });

        var $currentOption = modelSelect.find('option[value="' + currentValue + '"]');
        var optionUsable = $currentOption.length > 0 && !$currentOption.prop('disabled');
        if (optionUsable) {
            modelSelect.val(currentValue);
        } else {
            modelSelect.val(modelSelect.find('option:not(:disabled)').first().val());
        }
    }

    function updateAspectRatios(model) {
        if (!window.aifiAspectRatiosData || !aspectRatioSelect.length) {
            return;
        }

        var currentValue = aspectRatioSelect.val();
        var ratios = window.aifiAspectRatiosData;

        // Clear existing options
        aspectRatioSelect.empty();

        // Build list of available ratios and update the list
        var listHtml = '';

        // Add options based on model support
        $.each(ratios, function(value, data) {
            if (data.models && data.models.indexOf(model) !== -1) {
                var option = $('<option></option>')
                    .attr('value', value)
                    .text(data.label);
                aspectRatioSelect.append(option);

                // Get model-specific resolution
                var resolution = data.resolutions[model] || '';
                listHtml += '<li>' + data.label + ' \u2014 ' + resolution + '</li>';
            }
        });

        // Update the resolution list
        if (aspectRatioList.length) {
            aspectRatioList.html(listHtml);
        }

        // Update the description based on model
        var descriptionEl = $('#aifi-aspect-ratio-description');
        if (descriptionEl.length) {
            if (model === 'gemini-2.5-flash-image') {
                descriptionEl.text(aifiSettingsData.i18n.aspectRatioFlash);
            } else {
                descriptionEl.text(aifiSettingsData.i18n.aspectRatioOther);
            }
        }

        // Try to maintain current selection if it exists in new options
        var optionExists = aspectRatioSelect.find('option[value="' + currentValue + '"]').length > 0;
        if (optionExists) {
            aspectRatioSelect.val(currentValue);
        } else {
            // Select the first option if current value doesn't exist
            aspectRatioSelect.val(aspectRatioSelect.find('option').first().val());
        }
    }

    function toggleModelSpecificFields(model) {
        // Show/hide fields specific to models that support imageSize (Gemini 3.1 Flash and 3 Pro)
        var supportsImageSize = model === 'gemini-3-pro-image-preview' || model === 'gemini-3.1-flash-image-preview';
        $('.aifi-gemini-3-pro-only').toggle(supportsImageSize);
    }

    // GPT Image 2-only fields (background, moderation)
    function toggleGpt2Fields(model) {
        var isGpt2 = (model === 'gpt-image-2');
        $('.aifi-openai-gpt2-field').toggle(isGpt2);
        // If switching away from gpt-image-2, reset background to auto so format unlock fires
        if (!isGpt2) {
            var bgSelect = $('#aifi-openai-background');
            if (bgSelect.length && bgSelect.val() === 'transparent') {
                bgSelect.val('auto').trigger('change');
            }
        }
    }

    // Filter the OpenAI size dropdown to only show sizes valid for the current model
    var sizeSelect      = $('#aifi-default-size');
    var inlineSizeSelect = $('#aifi-inline-default-size');

    function updateSizeOptions(model, $select) {
        if (!$select || !$select.length) return;
        var isGpt2 = (model === 'gpt-image-2' || model === 'chatgpt-image-latest');
        var currentVal = $select.val();
        var firstAvailable = null;

        $select.find('option').each(function() {
            var isGpt2Only = $(this).data('gpt2-only') == 1;
            var visible = isGpt2 || !isGpt2Only;
            $(this).toggle(visible);
            if (visible && firstAvailable === null) firstAvailable = $(this).val();
        });

        // If the saved value is now hidden, reset to first visible option
        var selectedOption = $select.find('option[value="' + currentVal + '"]');
        if (!selectedOption.length || !selectedOption.is(':visible')) {
            $select.val(firstAvailable);
        }
    }

    function toggleProviderFields() {
        var provider = getCurrentProvider();
        var allProviders = ['openai', 'gemini', 'stability', 'grok'];

        // Hide all provider-specific field rows and inline fields
        $.each(allProviders, function(_, p) {
            $('.aifi-' + p + '-only').hide();
            $('.aifi-' + p + '-field').hide();
        });

        // Show fields for the selected provider
        $('.aifi-' + provider + '-only').show();
        $('.aifi-' + provider + '-field').show();

        // Hide/show the Output Settings section heading on Featured tab (OpenAI only)
        var showFeaturedOutput = (provider === 'openai');
        $('.aifi-tab-panel[data-panel="featured"] h2').each(function() {
            if ($(this).text().trim() === aifiSettingsData.i18n.outputSettings) {
                $(this).toggle(showFeaturedOutput);
                $(this).next('p').toggle(showFeaturedOutput);
            }
        });

        // Hide/show the Output Settings section on Inline tab (OpenAI and Stability have output fields)
        var showInlineOutput = (provider === 'openai' || provider === 'stability');
        $('.aifi-tab-panel[data-panel="inline"] h2').each(function() {
            if ($(this).text().trim() === aifiSettingsData.i18n.outputSettings) {
                $(this).toggle(showInlineOutput);
                $(this).next('p').toggle(showInlineOutput);
                $(this).nextAll('.aifi-auto-optimize-notice').first().toggle(showInlineOutput);
            }
        });

        // Toggle provider capabilities notice
        var $capBox = $('#aifi-provider-capabilities');
        if ($capBox.length) {
            $capBox.find('[class^="aifi-cap-"]').hide();
            $capBox.find('.aifi-cap-' + provider).show();
        }

        // Update model dropdown options (only if on General tab with model select)
        if (modelSelect.length) {
            updateModelOptions(provider);
        }

        // Update aspect ratios and model-specific fields if Gemini is selected
        if (provider === 'gemini') {
            var currentModel = getCurrentModel();
            updateAspectRatios(currentModel);
            toggleModelSpecificFields(currentModel);
        }

        // Update OpenAI model-specific fields and size options
        if (provider === 'openai') {
            var openaiModel = getCurrentModel();
            toggleGpt2Fields(openaiModel);
            updateSizeOptions(openaiModel, sizeSelect);
            updateSizeOptions(openaiModel, inlineSizeSelect);
        }

    }

    // Run on page load
    toggleProviderFields();

    // Run when provider changes
    providerSelect.on('change', function() {
        toggleProviderFields();
        toggleQualityFieldForFormat();
    });

    // Run when model changes (for Gemini aspect ratios and OpenAI gpt2 fields)
    modelSelect.on('change', function() {
        var provider = getCurrentProvider();
        var currentModel = $(this).val();
        if (provider === 'gemini') {
            updateAspectRatios(currentModel);
            toggleModelSpecificFields(currentModel);
        }
        if (provider === 'openai') {
            toggleGpt2Fields(currentModel);
            updateSizeOptions(currentModel, sizeSelect);
            updateSizeOptions(currentModel, inlineSizeSelect);
        }
    });

    // Output format change handler - hide quality slider for PNG (lossless format)
    var outputFormatSelect = $('select[name="' + aifiSettingsData.optionName + '[output_format]"]');

    function toggleQualityFieldForFormat() {
        var format = outputFormatSelect.val();
        var isPNG = format === 'png';
        var provider = getCurrentProvider();
        // Quality slider is OpenAI-only (not supported by Gemini, Stability, or Grok)
        var isOpenAI = provider === 'openai';
        $('.aifi-lossy-format-only').toggle(!isPNG && isOpenAI);
    }

    // Run on page load and when format changes
    if (outputFormatSelect.length) {
        toggleQualityFieldForFormat();
        outputFormatSelect.on('change', toggleQualityFieldForFormat);
    }

    // Background → format lock: transparent background requires PNG output
    var backgroundSelect = $('#aifi-openai-background');

    function handleBackgroundChange() {
        if (!outputFormatSelect.length) return;
        if (backgroundSelect.val() === 'transparent') {
            outputFormatSelect.val('png').trigger('change');
            outputFormatSelect.find('option:not([value="png"])').prop('disabled', true);
        } else {
            outputFormatSelect.find('option').prop('disabled', false);
        }
    }

    if (backgroundSelect.length) {
        handleBackgroundChange();
        backgroundSelect.on('change', handleBackgroundChange);
    }

    // Alt Text field toggles
    var altTextToggle = $('#aifi-auto-alt-text');
    var altTextSource = $('#aifi-alt-text-source');

    function toggleAltTextFields() {
        var enabled = altTextToggle.is(':checked');
        var isCustom = altTextSource.val() === 'custom';
        $('.aifi-alt-text-enabled-only').toggle(enabled);
        $('.aifi-alt-text-custom-only').toggle(enabled && isCustom);
    }

    if (altTextToggle.length) {
        toggleAltTextFields();
        altTextToggle.on('change', toggleAltTextFields);
        altTextSource.on('change', toggleAltTextFields);
    }

    // Toggle form/sidebar visibility based on active tab
    function toggleBulkTabLayout(tab) {
        var isBulk = tab === 'bulk';
        // Hide the settings form (and submit) when bulk tab is active
        $('.aifi-settings-form').toggle(!isBulk);
        // Toggle sidebar: hide on bulk tab so content takes full width
        $('.aifi-settings-sidebar').toggle(!isBulk);
        // Switch to single-column layout when bulk tab is active
        $('.aifi-settings-layout').css('grid-template-columns', isBulk ? '1fr' : '');
    }

    // Tab switching (no page reload)
    $('.aifi-tabs-nav .aifi-tab').on('click', function(e) {
        e.preventDefault();
        var tab = $(this).data('tab');
        if (!tab) return;

        // Update active tab styling
        $('.aifi-tabs-nav .aifi-tab').removeClass('aifi-tab-active');
        $(this).addClass('aifi-tab-active');

        // Show/hide tab panels
        $('.aifi-tab-panel').hide();
        $('.aifi-tab-panel[data-panel="' + tab + '"]').show();

        // Swap sidebar Quick Tips list to match the active tab
        $('.aifi-tips-list[data-tips-for]').hide();
        $('.aifi-tips-list[data-tips-for="' + tab + '"]').show();

        // Update hidden input for form submission
        $('#aifi-active-tab').val(tab);

        // Update URL without reload
        var url = new URL(window.location);
        url.searchParams.set('tab', tab);
        window.history.replaceState({}, '', url);

        // Toggle bulk/settings layout
        toggleBulkTabLayout(tab);

        // Hide Save button on Pro-only tabs that show upsell panels
        toggleSaveButton(tab);

        // Re-run provider field toggling for the newly visible tab
        toggleProviderFields();
        if (outputFormatSelect.length) {
            toggleQualityFieldForFormat();
        }
    });

    // Hide Save button when active tab panel contains an upsell (Pro-only tab for free users)
    function toggleSaveButton(tab) {
        var $panel = $('.aifi-tab-panel[data-panel="' + tab + '"]');
        var hasUpsell = $panel.find('.aifi-inline-upsell').length > 0;
        $('.aifi-settings-submit').toggle(!hasUpsell);
    }

    // Run on page load to handle initial bulk tab state
    var initialTab = new URL(window.location).searchParams.get('tab') || 'general';
    toggleBulkTabLayout(initialTab);
    toggleSaveButton(initialTab);

    // API key test connection
    $('.aifi-test-key-btn').on('click', function() {
        var $btn = $(this);
        var $result = $btn.next('.aifi-test-key-result');
        var provider = $btn.data('provider');
        var inputId = $btn.data('input');
        var apiKey = $('#' + inputId).val();

        if (!apiKey) {
            $result.text(aifiSettingsData.i18n.keyInvalid)
                .css('color', '#dc2626')
                .show();
            return;
        }

        $btn.prop('disabled', true);
        $result.text(aifiSettingsData.i18n.testing)
            .css('color', '#6b7280')
            .show();

        $.ajax({
            url: aifiSettingsData.restUrl + '/validate-key',
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aifiSettingsData.nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({
                provider: provider,
                api_key: apiKey
            }),
            processData: false,
            success: function(response) {
                $result.text(response.message || aifiSettingsData.i18n.keyValid)
                    .css('color', '#059669')
                    .show();
            },
            error: function(xhr) {
                var message = aifiSettingsData.i18n.keyInvalid;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                $result.text(message)
                    .css('color', '#dc2626')
                    .show();
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // Custom Styles - Add row
    $(document).on('click', '#aifi-add-custom-style', function() {
        var $tbody = $('#aifi-custom-styles-table tbody');
        var idx = $tbody.find('tr.aifi-custom-style-row').length;
        var optionName = 'aifi_settings[custom_styles][' + idx + ']';
        var $row = $(
            '<tr class="aifi-custom-style-row">' +
                '<td><input type="text" name="' + optionName + '[name]" value="" class="regular-text" placeholder="e.g. Dreamy"></td>' +
                '<td><input type="text" name="' + optionName + '[prompt]" value="" class="large-text" placeholder="e.g. in a dreamy impressionist style"></td>' +
                '<td><button type="button" class="button aifi-remove-custom-style" aria-label="Remove style"><span class="dashicons dashicons-trash"></span></button></td>' +
            '</tr>'
        );
        $tbody.append($row);
        $row.find('input[type="text"]').first().focus();
    });

    // Custom Styles - Remove row and re-index
    $(document).on('click', '.aifi-remove-custom-style', function() {
        $(this).closest('tr.aifi-custom-style-row').remove();
        // Re-index remaining rows so indices are sequential
        $('#aifi-custom-styles-table tbody tr.aifi-custom-style-row').each(function(i) {
            $(this).find('input[type="text"]').each(function() {
                var name = $(this).attr('name');
                $(this).attr('name', name.replace(/\[custom_styles\]\[\d+\]/, '[custom_styles][' + i + ']'));
            });
        });
    });

    // Review request notice — dismissal handler.
    $(document).on('click', '.aifi-review-notice [data-aifi-review-action]', function(e) {
        var $btn    = $(this);
        var $notice = $btn.closest('.aifi-review-notice');
        var action  = $btn.attr('data-aifi-review-action');
        var rest    = $notice.attr('data-rest');
        var nonce   = $notice.attr('data-nonce');

        if (!rest || !nonce) return;

        if (action !== 'done') {
            e.preventDefault();
        }

        $.ajax({
            url: rest,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({ state: action }),
            processData: false
        });

        $notice.addClass('aifi-review-hiding');
        setTimeout(function() { $notice.remove(); }, 250);
    });
});
