/**
 * Guard Dog Settings Page JavaScript
 */

jQuery(document).ready(function($) {
    // Tabbed interface logic for settings page
    $('.guard-dog-tabbed-interface').each(function() {
        var $container = $(this);
        var $tabLinks = $container.find('.guard-dog-tab-link');
        var $tabPanels = $container.find('.guard-dog-tab-panel');
        var storageKey = $tabLinks.first().data('storage-key') || 'guard_dog_settings_tab';

        // Restore active tab from localStorage
        var savedTab = localStorage.getItem(storageKey);
        if (savedTab && $container.find('.guard-dog-tab-link[data-tab="' + savedTab + '"]').length) {
            $tabLinks.removeClass('active');
            $tabPanels.removeClass('active');
            $container.find('.guard-dog-tab-link[data-tab="' + savedTab + '"]').addClass('active');
            $container.find('#' + savedTab).addClass('active');
        }

        $tabLinks.on('click', function(e) {
            e.preventDefault();
            var tabId = $(this).data('tab');
            $tabLinks.removeClass('active');
            $(this).addClass('active');
            $tabPanels.removeClass('active');
            $container.find('#' + tabId).addClass('active');
            // Save active tab to localStorage
            localStorage.setItem(storageKey, tabId);
        });
    });

    // Enhanced confirmation for destructive actions
    $('.guard-dog-data-management-button').on('click', function(e) {
        // Let the form submit naturally, confirmation is handled by onclick attribute
        console.log('Data management action triggered:', $(this).text().trim());
    });

    // Enhanced confirmation for reset button
    $('.guard-dog-reset-button').on('click', function(e) {
        // Let the form submit naturally, confirmation is handled by onclick attribute
        console.log('Reset settings action triggered');
    });

    // Tools Actions - only for non-form buttons
    $('.guard-dog-tools-button').not('button[type="submit"]').on('click', function(e) {
        e.preventDefault();
        var action = $(this).text().trim();
        
        switch(action) {
            case 'Test Email Notifications':
                alert('Test email notifications would be implemented here');
                break;
            case 'Run Health Check':
                alert('Health check would be implemented here');
                break;
            case 'Generate Support Report':
                alert('Generate support report would be implemented here');
                break;
        }
    });

    // Auto-hide settings messages after 5 seconds
    setTimeout(function() {
        $('.notice').not('.inline, .guard-dog-google-help-panel').fadeOut(1000);
    }, 5000);

    // Fix duplicate IDs to prevent browser console warnings
    var nonceCounter = 0;
    $('input[id="_wpnonce"]').each(function() {
        $(this).attr('id', '_wpnonce_' + nonceCounter++);
    });

    var guard_dog_nonce_counter = 0;
    $('input[id="guard_dog_nonce"]').each(function() {
        $(this).attr('id', 'guard_dog_nonce_' + guard_dog_nonce_counter++);
    });

    function toggleGoogleAuthModeFields() {
        var selectedProvider = $('#guard_dog_email_provider').val();
        var $mode = $('#google_auth_mode');
        if (!$mode.length) {
            return;
        }

        var mode = $mode.val();
        var $appPasswordRow = $('#google_app_password').closest('tr');
        var $oauthClientIdRow = $('#google_oauth_client_id').closest('tr');
        var $oauthClientSecretRow = $('#google_oauth_client_secret').closest('tr');
        var $oauthRefreshTokenRow = $('#google_oauth_refresh_token').closest('tr');
        var $authEmailRow = $('#google_auth_email').closest('tr');
        var $oauthControlsRow = $('.guard-dog-google-oauth-controls');

        if (selectedProvider !== 'google') {
            return;
        }

        // Auth email is still shown in both modes because it is useful for sender/account clarity.
        $authEmailRow.show();

        if (mode === 'oauth') {
            $appPasswordRow.hide();
            $appPasswordRow.find('input, select, textarea, button').prop('disabled', true);
            $oauthClientIdRow.show();
            $oauthClientIdRow.find('input, select, textarea, button').prop('disabled', false);
            $oauthClientSecretRow.show();
            $oauthClientSecretRow.find('input, select, textarea, button').prop('disabled', false);
            $oauthRefreshTokenRow.show();
            $oauthRefreshTokenRow.find('input, select, textarea, button').prop('disabled', false);
            $oauthControlsRow.show();
            $oauthControlsRow.find('input, select, textarea, button').prop('disabled', false);
            return;
        }

        $appPasswordRow.show();
        $appPasswordRow.find('input, select, textarea, button').prop('disabled', false);
        $oauthClientIdRow.hide();
        $oauthClientIdRow.find('input, select, textarea, button').prop('disabled', true);
        $oauthClientSecretRow.hide();
        $oauthClientSecretRow.find('input, select, textarea, button').prop('disabled', true);
        $oauthRefreshTokenRow.hide();
        $oauthRefreshTokenRow.find('input, select, textarea, button').prop('disabled', true);
        $oauthControlsRow.hide();
        $oauthControlsRow.find('input, select, textarea, button').prop('disabled', true);
    }

    function toggleProviderFields() {
        var $providerSelect = $('#guard_dog_email_provider');
        if (!$providerSelect.length) {
            return;
        }

        var selectedProvider = $providerSelect.val();
        var $configWrapper = $('#email-provider-config');
        var $configHeading = $('#guard-dog-provider-config-heading');
        var hasProvider = !!selectedProvider;

        if ($configWrapper.length) {
            $configWrapper.toggle(hasProvider);
        }

        $('.guard-dog-provider-row').each(function() {
            var $row = $(this);
            var rowProvider = $row.data('provider');
            var isActive = hasProvider && rowProvider === selectedProvider;

            $row.toggle(isActive);
            $row.find('input, select, textarea, button').prop('disabled', !isActive);
        });

        $('.guard-dog-provider-context').each(function() {
            var $context = $(this);
            var contextProvider = $context.data('provider');
            $context.toggle(hasProvider && contextProvider === selectedProvider);
        });

        if ($configHeading.length) {
            if (!hasProvider) {
                $configHeading.text(guard_dog_settings.strings.providerConfigFallback || 'Email Provider Configuration');
            } else {
                var selectedLabel = $.trim($providerSelect.find('option:selected').text());
                var suffix = guard_dog_settings.strings.providerConfigSuffix || 'Configuration';
                $configHeading.text(selectedLabel + ' ' + suffix);
            }
        }

        toggleGoogleAuthModeFields();
    }

    $(document).on('change', '#guard_dog_email_provider', toggleProviderFields);
    $(document).on('change', '#google_auth_mode', toggleGoogleAuthModeFields);
    toggleProviderFields();
    toggleGoogleAuthModeFields();

    var googleAliasesCache = [];
    function seedGoogleAliasSelect() {
        var $select = $('#guard-dog-google-alias-select');
        if (!$select.length) {
            return;
        }

        var currentEmail = $select.attr('data-current-email') || '';
        var currentName = $select.attr('data-current-name') || '';
        var promptText = guard_dog_settings.strings.selectAliasPrompt || guard_dog_settings.strings.selectAliasFirst;

        $select.empty();

        if (!currentEmail) {
            $select.append($('<option>', {
                value: '',
                text: promptText,
                selected: true
            }));
            return;
        }

        var savedLabel = currentEmail;
        if (currentName) {
            savedLabel += ' - ' + currentName;
        }
        savedLabel += ' (' + guard_dog_settings.strings.savedAliasLabel + ')';

        $select.append($('<option>', {
            value: currentEmail,
            text: savedLabel,
            selected: true
        }));
    }

    seedGoogleAliasSelect();

    $('.guard-dog-google-help').each(function() {
        var $help = $(this);
        var $toggle = $help.find('.guard-dog-google-help-toggle');
        var $panel = $help.find('.guard-dog-google-help-panel');

        function setHelpOpenState(isOpen) {
            $toggle.attr('aria-expanded', isOpen ? 'true' : 'false');
            $panel.prop('hidden', !isOpen);
            $help.toggleClass('is-open', isOpen);

            var showLabel = $toggle.attr('data-show-label') || 'Show Google OAuth setup help';
            var hideLabel = $toggle.attr('data-hide-label') || 'Hide Google OAuth setup help';
            $toggle.text(isOpen ? hideLabel : showLabel);
        }

        setHelpOpenState($toggle.attr('aria-expanded') === 'true');

        $toggle.on('click', function(e) {
            e.preventDefault();
            setHelpOpenState($toggle.attr('aria-expanded') !== 'true');
        });
    });

    function shouldSaveBeforeGoogleOAuthConnect() {
        return $('#guard_dog_email_provider').val() === 'google';
    }

    function buildGoogleOAuthAutostartReferer(urlString) {
        var targetUrl = new URL(urlString || window.location.href, window.location.origin);
        targetUrl.searchParams.set('guard_dog_google_oauth_autostart', '1');

        return targetUrl.pathname + targetUrl.search + targetUrl.hash;
    }

    function maybeAutoStartGoogleOAuthConnect() {
        var params = new URLSearchParams(window.location.search);
        if (params.get('guard_dog_google_oauth_autostart') !== '1' || params.get('settings-updated') !== 'true') {
            return;
        }

        var $connectButton = $('#guard-dog-google-oauth-connect');
        if (!$connectButton.length || !shouldSaveBeforeGoogleOAuthConnect()) {
            return;
        }

        var connectUrl = $connectButton.attr('href');
        if (!connectUrl) {
            return;
        }

        window.location.assign(connectUrl);
    }

    $('#guard-dog-google-oauth-connect').on('click', function(e) {
        var $button = $(this);
        var $form = $('.guard-dog-email-provider-form');
        var $result = $('#guard-dog-google-oauth-result');
        var $referer = $form.find('input[name="_wp_http_referer"]').first();

        if (!$form.length || !$referer.length || !shouldSaveBeforeGoogleOAuthConnect()) {
            return;
        }

        e.preventDefault();

        $referer.val(buildGoogleOAuthAutostartReferer($referer.val()));
        $button.addClass('disabled').attr('aria-disabled', 'true');

        if ($result.length) {
            $result.html('<div class="notice notice-info"><p>' + guard_dog_settings.strings.savingSettingsBeforeOAuth + '</p></div>');
        }

        $form.trigger('submit');
    });

    maybeAutoStartGoogleOAuthConnect();
    $('#guard-dog-google-oauth-disconnect').on('click', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#guard-dog-google-oauth-result');
        var nonce = $button.data('nonce') || (guard_dog_settings.googleOAuthDisconnectNonce || '');

        if ($button.prop('disabled')) {
            return;
        }

        $button.prop('disabled', true);
        $result.html('<div class="notice notice-info"><p>' + guard_dog_settings.strings.disconnectingOAuth + '</p></div>');

        $.ajax({
            url: guard_dog_settings.ajaxUrl,
            type: 'POST',
            data: {
                action: 'guard_dog_google_oauth_disconnect',
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    $result.html('<div class="notice notice-success"><p>' + (response.data && response.data.message ? response.data.message : guard_dog_settings.strings.oauthDisconnected) + '</p></div>');
                    setTimeout(function() {
                        window.location.reload();
                    }, 800);
                    return;
                }

                $result.html('<div class="notice notice-error"><p>' + (response.data && response.data.message ? response.data.message : guard_dog_settings.strings.oauthDisconnectFailed) + '</p></div>');
            },
            error: function(xhr) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.data && response.data.message) {
                        $result.html('<div class="notice notice-error"><p>' + response.data.message + '</p></div>');
                    } else {
                        $result.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.oauthDisconnectFailed + '</p></div>');
                    }
                } catch (err) {
                    $result.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.oauthDisconnectFailed + '</p></div>');
                }
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });

    $('#guard-dog-google-alias-preflight').on('click', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#guard-dog-google-alias-preflight-result');
        var fromEmail = $('#google_from_email').val();
        var nonce = $button.data('nonce') || (guard_dog_settings.googleAliasPreflightNonce || '');

        if (!fromEmail) {
            $result.html('<div class="notice notice-warning"><p>' + guard_dog_settings.strings.fromEmailRequired + '</p></div>');
            return;
        }

        if ($button.prop('disabled')) {
            return;
        }

        $button.prop('disabled', true);
        $result.html('<div class="notice notice-info"><p>' + guard_dog_settings.strings.checkingAlias + '</p></div>');

        $.ajax({
            url: guard_dog_settings.ajaxUrl,
            type: 'POST',
            data: {
                action: 'guard_dog_google_alias_preflight',
                nonce: nonce,
                from_email: fromEmail
            },
            success: function(response) {
                if (response.success) {
                    var message = response.data && response.data.message ? response.data.message : guard_dog_settings.strings.anErrorOccurred;
                    var noticeType = response.data && response.data.match ? 'success' : 'warning';
                    $result.html('<div class="notice notice-' + noticeType + '"><p>' + message + '</p></div>');
                    return;
                }

                $result.html('<div class="notice notice-error"><p>' + (response.data && response.data.message ? response.data.message : guard_dog_settings.strings.anErrorOccurred) + '</p></div>');
            },
            error: function(xhr) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.data && response.data.message) {
                        $result.html('<div class="notice notice-error"><p>' + response.data.message + '</p></div>');
                    } else {
                        $result.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.networkError + '</p></div>');
                    }
                } catch (err) {
                    $result.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.networkError + '</p></div>');
                }
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });

    $('#guard-dog-google-aliases-load').on('click', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#guard-dog-google-aliases-result');
        var $select = $('#guard-dog-google-alias-select');
        var $applyButton = $('#guard-dog-google-alias-apply');
        var nonce = $button.data('nonce') || (guard_dog_settings.googleAliasListNonce || '');

        if ($button.prop('disabled')) {
            return;
        }

        $button.prop('disabled', true);
        $applyButton.prop('disabled', true);
        $result.html('<div class="notice notice-info"><p>' + guard_dog_settings.strings.loadingAliases + '</p></div>');

        $.ajax({
            url: guard_dog_settings.ajaxUrl,
            type: 'POST',
            data: {
                action: 'guard_dog_google_aliases_list',
                nonce: nonce
            },
            success: function(response) {
                if (!response.success) {
                    $result.html('<div class="notice notice-error"><p>' + (response.data && response.data.message ? response.data.message : guard_dog_settings.strings.aliasLoadFailed) + '</p></div>');
                    return;
                }

                var aliases = response.data && Array.isArray(response.data.aliases) ? response.data.aliases : [];
                var currentFromEmail = response.data && response.data.current_from_email ? response.data.current_from_email : '';
                googleAliasesCache = aliases;
                $select.attr('data-current-email', currentFromEmail);
                $select.data('currentEmail', currentFromEmail);
                $select.attr('data-current-name', response.data && response.data.current_from_name ? response.data.current_from_name : '');
                $select.data('currentName', response.data && response.data.current_from_name ? response.data.current_from_name : '');

                $select.empty();
                $select.append($('<option>', {
                    value: '',
                    text: guard_dog_settings.strings.selectAliasPrompt || guard_dog_settings.strings.selectAliasFirst
                }));

                aliases.forEach(function(alias) {
                    var email = alias && alias.email ? alias.email : '';
                    if (!email) {
                        return;
                    }

                    var label = email;
                    if (alias.display_name) {
                        label += ' - ' + alias.display_name;
                    }
                    if (alias.verification_status) {
                        label += ' [' + alias.verification_status + ']';
                    }
                    if (alias.is_primary) {
                        label += ' (primary)';
                    }

                    var $option = $('<option>', {
                        value: email,
                        text: label
                    });

                    $option.attr('data-display-name', alias.display_name || '');
                    $select.append($option);
                });

                if (currentFromEmail && $select.find('option').filter(function() { return $(this).val() === currentFromEmail; }).length) {
                    $select.val(currentFromEmail);
                } else {
                    $select.val('');
                }

                $applyButton.prop('disabled', !$select.val());

                if (!aliases.length) {
                    $result.html('<div class="notice notice-warning"><p>' + guard_dog_settings.strings.noAliasesFound + '</p></div>');
                    return;
                }

                var successText = (response.data && response.data.message ? response.data.message : guard_dog_settings.strings.aliasesLoaded);
                $result.html('<div class="notice notice-success"><p>' + successText + ' (' + aliases.length + ')</p></div>');
            },
            error: function(xhr) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.data && response.data.message) {
                        $result.html('<div class="notice notice-error"><p>' + response.data.message + '</p></div>');
                    } else {
                        $result.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.aliasLoadFailed + '</p></div>');
                    }
                } catch (err) {
                    $result.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.aliasLoadFailed + '</p></div>');
                }
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });

    $('#guard-dog-google-alias-select').on('change', function() {
        var $applyButton = $('#guard-dog-google-alias-apply');
        $applyButton.prop('disabled', !$(this).val());
    });

    $('#guard-dog-google-alias-apply').on('click', function(e) {
        e.preventDefault();

        var $button = $(this);
        var $result = $('#guard-dog-google-aliases-result');
        var $select = $('#guard-dog-google-alias-select');
        var email = $select.val();

        if (!email) {
            $result.html('<div class="notice notice-warning"><p>' + guard_dog_settings.strings.selectAliasFirst + '</p></div>');
            return;
        }

        var alias = null;
        googleAliasesCache.forEach(function(item) {
            if (item && item.email === email) {
                alias = item;
            }
        });

        $('#google_from_email').val(email).trigger('change');
        if (alias && alias.display_name && !$('#google_from_name').val()) {
            $('#google_from_name').val(alias.display_name).trigger('change');
        }

        $select.attr('data-current-email', email);
        $select.data('currentEmail', email);
        $select.attr('data-current-name', alias && alias.display_name ? alias.display_name : ($('#google_from_name').val() || ''));
        $select.data('currentName', alias && alias.display_name ? alias.display_name : ($('#google_from_name').val() || ''));

        $button.prop('disabled', false);
        $result.html('<div class="notice notice-success"><p>' + guard_dog_settings.strings.aliasApplied + '</p></div>');
    });

    // Test email provider configuration
    $('#test-email-provider').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var resultDiv = $('#test-email-result');
        var testEmail = $('#test_email').val();

        // Prevent double-clicking
        if (button.prop('disabled')) {
            return;
        }

        if (!testEmail) {
            resultDiv.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.pleaseEnterEmail + '</p></div>');
            return;
        }

        // Disable button and show loading
        button.prop('disabled', true).text(guard_dog_settings.strings.sending);
        resultDiv.html('<div class="notice notice-info"><p>' + guard_dog_settings.strings.sendingTestEmail + '</p></div>');

        $.ajax({
            url: guard_dog_settings.ajaxUrl,
            type: 'POST',
            data: {
                action: 'guard_dog_test_email_provider',
                test_email: testEmail,
                nonce: guard_dog_settings.nonce
            },
            success: function(response) {
                if (response.success) {
                    resultDiv.html('<div class="notice notice-success"><p>' + response.data.message + '</p></div>');
                } else {
                    resultDiv.html('<div class="notice notice-error"><p>' + (response.data ? response.data.message : guard_dog_settings.strings.anErrorOccurred) + '</p></div>');
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', xhr.responseText);
                
                // Try to parse the response for better error messages
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.data && response.data.message) {
                        // Check if it's a rate limit error (429) and show as warning instead of error
                        if (xhr.status === 429) {
                            resultDiv.html('<div class="notice notice-warning"><p>' + response.data.message + '</p></div>');
                        } else {
                            resultDiv.html('<div class="notice notice-error"><p>' + response.data.message + '</p></div>');
                        }
                    } else {
                        resultDiv.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.networkError + '</p></div>');
                    }
                } catch (e) {
                    resultDiv.html('<div class="notice notice-error"><p>' + guard_dog_settings.strings.networkError + '</p></div>');
                }
            },
            complete: function() {
                button.prop('disabled', false).text(guard_dog_settings.strings.sendTestEmail);
            }
        });
    });
}); 
