/**
 * FunnelKit Square Admin JavaScript
 *
 * Handles DOM manipulation and AJAX interactions for the Square payment gateway
 * settings page in WooCommerce admin.
 *
 * @since 1.0.0
 * @package FunnelKit_Square
 */

/* global fkwcsq_params, fkwcsq_test_connection, fkwcsq_import_square_products, fkwcsq_manual_sync */

jQuery(document).ready(function ($) {
    'use strict';

    // Initialize selectWoo for enhanced select fields
    $('.multiselect').selectWoo();

    /**
     * Initialize Square environment switching functionality
     *
     * Sets up event handlers for environment changes and manages
     * the visibility of sandbox vs production fields.
     *
     * @returns {boolean} True if initialization was successful, false otherwise
     */
    function initSquareEnvironment() {
        // Cache DOM elements for better performance
        const $environmentSelect = $('#fkwcsq_settings\\[environment\\]');
        const $sandboxFields = $('.sandbox-field').closest('tr');
        const $connectionRow = $('.fkwcsq-connection-row');
        const $locationSettingsLive = $('select[name="fkwcsq_settings[location_id]"]').closest('tr');
        const $locationSettingsSandbox = $('select[name="fkwcsq_settings[sandbox_location_id]"]').closest('tr');

        // Validate required elements exist
        if (!$environmentSelect.length) {
            console.warn('FKWCSQ: Environment select not found');
            return false;
        }

        // Create a map of elements to toggle for better maintainability
        const elementsToToggle = {
            sandbox: {
                show: [$sandboxFields, $locationSettingsSandbox],
                hide: [$connectionRow, $locationSettingsLive]
            },
            production: {
                show: [$connectionRow, $locationSettingsLive],
                hide: [$sandboxFields, $locationSettingsSandbox]
            }
        };

        /**
         * Toggle element visibility based on environment
         *
         * @param {jQuery} $elements - jQuery elements to toggle
         * @param {boolean} show - Whether to show or hide elements
         */
        function toggleElements($elements, show) {
            $elements.forEach(function ($element) {
                if ($element && $element.length) {
                    $element[show ? 'show' : 'hide']();
                }
            });
        }

        /**
         * Handle environment change
         *
         * @param {string} environment - The selected environment ('sandbox', 'sandbox_admin_only', or 'production')
         */
        function handleEnvironmentChange(environment) {
            const isSandbox = environment === 'sandbox' || environment === 'sandbox_admin_only';
            const config = elementsToToggle[isSandbox ? 'sandbox' : 'production'];

            // Toggle elements based on environment
            toggleElements(config.show, true);
            toggleElements(config.hide, false);
            const $testModeDesc = $('.test-mode-admin-only-desc');
            if (environment === 'sandbox_admin_only') {
                if ($testModeDesc.length === 0) {
                    const descHtml = '<p class="description test-mode-admin-only-desc">This will enable Test mode only for the admin users. While other users will continue to process payments in Live mode.</p><p class="description test-mode-admin-only-desc"><strong>Please note that this setting should always be switched back to live mode once testing is completed to avoid such issues in the future.</strong></p>';
                    $environmentSelect.after(descHtml);
                } else {
                    $testModeDesc.show();
                }
            } else {
                $testModeDesc.hide();
            }
        }

        // Bind change event handler
        $environmentSelect.on('change', function () {
            const selectedEnvironment = $(this).val();
            handleEnvironmentChange(selectedEnvironment);
        });

        // Trigger initial environment setup
        const currentEnvironment = $environmentSelect.val();
        if (currentEnvironment) {
            handleEnvironmentChange(currentEnvironment);
        }

        return true;
    }

    /**
     * Show loading UI
     *
     * @param {string} message - Loading message (optional)
     */
    function showLoading(message = '') {
        $.blockUI({ message });
        $('body').css('cursor', 'progress');
    }

    /**
     * Hide loading UI
     */
    function hideLoading() {
        $.unblockUI();
        $('body').css('cursor', 'default');
    }

    /**
     * Handle disconnect confirmation
     */
    function initDisconnectHandler () {
        $('.fkwcsq-disconnect-button').on('click', function (e) {
            if (typeof fkwcsq_params === 'undefined' || !fkwcsq_params.i18n || !fkwcsq_params.i18n.disconnect_confirm) {
                console.error('FKWCSQ: Disconnect confirmation text not available');
                return;
            }

            if (!confirm(fkwcsq_params.i18n.disconnect_confirm)) {
                e.preventDefault();
            }
        });
    }

    /**
     * Handle test connection functionality
     */
    function initTestConnectionHandler() {
        $('#fkwcsq-test-connection').on('click', function () {
            const $btn = $(this);

            // Check if required parameters are available
            if (typeof fkwcsq_test_connection === 'undefined') {
                console.error('FKWCSQ: fkwcsq_test_connection not defined');
                alert('Test connection configuration not available');
                return;
            }

            // Show loading state
            showLoading();
            $btn.prop('disabled', true).text('Testing...');

            $.get(fkwcsq_test_connection.ajax_url, {
                action: 'fkwcsq_test_square_connection',
                nonce: fkwcsq_test_connection.nonce
            }, function (response) {
                hideLoading();
                $btn.prop('disabled', false).text('Test Connection');

                if (response.success) {
                    alert(response.data);
                } else {
                    alert(response.data || 'Connection failed');
                }
            }).fail(function () {
                hideLoading();
                $btn.prop('disabled', false).text('Test Connection');
                alert('Connection test failed. Please try again.');
            });
        });
    }

    /**
     * Handle import products functionality
     */
    function initImportProductsHandler() {
        $('#fkwcsq-import-square-products').on('click', function (e) {
            e.preventDefault();

            if (!confirm('Are you sure you want to import all products from Square?')) {
                return;
            }

            const $btn = $(this);

            // Check if required parameters are available
            if (typeof fkwcsq_import_square_products === 'undefined') {
                console.error('FKWCSQ: fkwcsq_import_square_products not defined');
                alert('Import configuration not available');
                return;
            }

            // Disable button and show loading state
            $btn.prop('disabled', true).text('Importing...');
            showLoading();

            $.post(fkwcsq_import_square_products.ajaxurl, {
                action: 'fkwcsq_import_square_products',
                _wpnonce: fkwcsq_import_square_products.nonce
            }, function (response) {
                hideLoading();
                $btn.prop('disabled', false).text('Import All Products from Square');

                if (response.success) {
                    alert(response.data);
                } else {
                    alert(`Import failed: ${response.data || 'Unknown error'}`);
                }
            }).fail(function () {
                hideLoading();
                $btn.prop('disabled', false).text('Import All Products from Square');
                alert('Import failed. Please try again.');
            });
        });
    }

    /**
     * Handle manual sync functionality
     */
    function initManualSyncHandler() {
        $('#fkwcsq-manual-sync').on('click', function (e) {
            e.preventDefault();

            if (!confirm('Are you sure you want to run manual sync now?')) {
                return;
            }

            const $btn = $(this);

            // Check if required parameters are available
            if (typeof fkwcsq_manual_sync === 'undefined') {
                console.error('FKWCSQ: fkwcsq_manual_sync not defined');
                alert('Manual sync configuration not available');
                return;
            }

            // Disable button and show loading state
            $btn.prop('disabled', true).text('Syncing...');
            showLoading();

            $.post(fkwcsq_manual_sync.ajaxurl, {
                action: 'fkwcsq_manual_sync',
                _wpnonce: fkwcsq_manual_sync.nonce
            }, function (response) {
                hideLoading();
                $btn.prop('disabled', false).text('Sync Now');

                if (response.success) {
                    alert(response.data);
                } else {
                    alert(`Sync failed: ${response.data || 'Unknown error'}`);
                }
            }).fail(function () {
                hideLoading();
                $btn.prop('disabled', false).text('Sync Now');
                alert('Sync failed. Please try again.');
            });
        });
    }

    /**
     * Toggle import section visibility based on sync direction
     */
    function toggleImportSection() {
        const syncDirection = $('.fkwcsq-sync-direction').val();
        const $importSection = $('#fkwcsq-import-products-table');
        const $importProductsRow = $('#fkwcsq-import-products-table');
        const $manualSyncRow = $('#fkwcsq-manual-sync').closest('tr');
        // Hide the sync interval row when sync direction is disabled
        const $syncIntervalRow = $('select[name="fkwcsq_settings[sync_interval]"]').closest('tr');
        const $syncNotice = $('.fksi-sync-notice');

        if (syncDirection === 'disabled') {
            $importSection.hide();
            $syncIntervalRow.hide();
            $importProductsRow.hide();
            $manualSyncRow.hide();
            $syncNotice.hide();
        } else {
            $importSection.show();
            $syncIntervalRow.show();
            $manualSyncRow.show();
            $importProductsRow.show();
            $syncNotice.show();
        }
    }

    function appendSquareSyncNotice() {
        // Find the sync direction field row
        const $syncDirectionRow = $('.fkwcsq-sync-direction').closest('tr');

        if ($syncDirectionRow.length) {
            // Check if notice already exists to avoid duplicates
            if ($syncDirectionRow.find('.fksi-sync-notice').length === 0) {
                // Find the description paragraph within the same row
                const $descriptionP = $syncDirectionRow.find('p.description');

                if ($descriptionP.length) {
                    // Create the notice HTML
                    const noticeHtml = `
                        <div class="notice notice-warning fksi-sync-notice" style="margin: 10px 0;">
                            <p>
                                <strong>Square Sync Notice:</strong>
                                For WooCommerce to Square sync to work, you must enable Square sync on individual products.
                                <a href="https://funnelkit.com/docs/square-gateway-for-woocommerce/product-data-sync/woocommerce-to-square/" target="_blank" class="fksi-learn-more">Learn More</a>
                            </p>
                        </div>
                        <style>
                        .fksi-sync-notice .notice-dismiss {
                            display: none !important;
                        }
                        </style>
                    `;

                    // Insert the notice after the description paragraph
                    $descriptionP.after(noticeHtml);
                } else {
                    console.warn('FKWCSQ: Description paragraph not found in sync direction row');
                }
            }
        } else {
            console.warn('FKWCSQ: Sync direction row not found, cannot append notice');
        }
    }

    /**
     * Initialize sync direction change handler
     */
    function initSyncDirectionHandler() {
        $('.fkwcsq-sync-direction').on('change', function () {
            toggleImportSection();
        });
    }

    /**
     * Initialize Apple Pay domain verification functionality
     */
    function initApplePayDomainVerification() {
        $('#fkwcsq-reverify-apple-pay-domain').on('click', function (e) {
            e.preventDefault();

            const $button = $(this);
            const $status = $('#fkwcsq-apple-pay-domain-status');

            // Disable button and show verifying state
            $button.prop('disabled', true).text(fkwcsq_params.apple_pay.verifying_text);
            $status.html(`<span class="fkwcsq-status-verifying">⏳ ${fkwcsq_params.apple_pay.verifying_domain_text}</span>`)
                .removeClass('fkwcsq-status-success fkwcsq-status-error')
                .addClass('fkwcsq-status-verifying');

            // Make AJAX request
            $.ajax({
                url: fkwcsq_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'fkwcsq_reverify_apple_pay_domain',
                    nonce: fkwcsq_params.apple_pay.nonce
                },
                success(response) {
                    if (response.success) {
                        $status.html(`<span class="fkwcsq-status-success">✅ ${response.data.message}</span>`)
                            .removeClass('fkwcsq-status-verifying fkwcsq-status-error')
                            .addClass('fkwcsq-status-success');
                    } else {
                        $status.html(`<span class="fkwcsq-status-error">❌ ${response.data.message}</span>`)
                            .removeClass('fkwcsq-status-verifying fkwcsq-status-success')
                            .addClass('fkwcsq-status-error');
                    }
                },
                error() {
                    $status.html(`<span class="fkwcsq-status-error">❌ ${fkwcsq_params.apple_pay.verification_failed_text}</span>`)
                        .removeClass('fkwcsq-status-verifying fkwcsq-status-success')
                        .addClass('fkwcsq-status-error');
                },
                complete() {
                    // Re-enable button
                    $button.prop('disabled', false).text(fkwcsq_params.apple_pay.reverify_text);
                }
            });
        });
    }

    /**
     * Initialize all functionality
     */
    function init() {
        // Initialize Square environment with error handling
        const environmentInitialized = initSquareEnvironment();
        if (!environmentInitialized) {
            console.warn('FKWCSQ: Square environment initialization failed');
        }

        // Initialize event handlers
        initDisconnectHandler();
        initTestConnectionHandler();
        initImportProductsHandler();
        initManualSyncHandler();
        initSyncDirectionHandler();
        appendSquareSyncNotice();

        initApplePayDomainVerification();

        // Initial import section check
        toggleImportSection();
    }

    $('.square-connect-btn').on('click', function (e) {
        e.preventDefault();

        // Disable beforeunload warning
        $(window).off('beforeunload');
        window.onbeforeunload = null;

        // Force redirect
        window.location.href = $(this).data('url');
    });

    /**
     * Initialize webhook simulation functionality
     */
    function initWebhookSimulation() {
        $('.fkwcsq-simulate-webhook').on('click', function (e) {
            e.preventDefault();
            // Show loading
            showLoading();
            $.ajax({
                url: fkwcsq_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'fkwcsq_simulate_webhook',
                    nonce: fkwcsq_params.nonce
                },
                success(response) {
                    hideLoading();
                    if (response.success) {
                        const data = response.data;
                        if (data.response_code === 200) {
                            alert('The webhook was received successfully!');
                        } else {
                            alert('The webhook was received but with warning');
                        }
                    } else {
                        alert('The webhook wasn\'t received or failed!');
                    }
                },
                error() {
                    hideLoading();
                    alert('✗ The webhook wasn\'t received or failed!');
                }
            });
        });
    }

    // Initialize when document is ready
    init();
    initWebhookSimulation();
});
