/**
 * ZainPay WooCommerce Payment Gateway Admin JavaScript
 */

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

    /**
     * Object to handle ZainPay admin functionality.
     */
    var pgzw_zainpay_admin = {
        fieldSel: function(field) {
            return '#woocommerce_pgzw_zainpay_' + field + ', #woocommerce_pgzw_' + field;
        },

        /**
         * Initialize event handlers and UI updates.
         */
        init: function() {
            $(this.fieldSel('testmode')).on('change', this.onTestModeChange);
            
            $(this.fieldSel('custom_metadata')).on('change', this.onCustomMetadataChange);
            
            $(this.fieldSel('autocomplete_order')).on('change', this.onAutocompleteOrderChange);
            
            $(this.fieldSel('payment_page')).on('change', this.onPaymentPageChange);
            
            this.onTestModeChange.call(this);
            this.onCustomMetadataChange.call(this);
            this.onAutocompleteOrderChange.call(this);
            this.onPaymentPageChange.call(this);
            
            this.initCopyCallbackUrl();
            this.renderSidebar();
            this.initPostboxes();
        },

        /**
         * Handle test mode toggle.
         */
        onTestModeChange: function() {
            var isTestMode = $(pgzw_zainpay_admin.fieldSel('testmode')).is(':checked');
            
            if (isTestMode) {
                // Show test mode fields
                $(pgzw_zainpay_admin.fieldSel('test_api_token')).closest('tr').show();
                $(pgzw_zainpay_admin.fieldSel('test_zainbox_code')).closest('tr').show();
                $('.pgzw-test-field').closest('tr').show();
                
                // Hide live mode fields
                $('.pgzw-live-field').closest('tr').hide(); 
                
                // Add test mode notice
                pgzw_zainpay_admin.showTestModeNotice();
            } else {
                // Hide test mode fields
                $(pgzw_zainpay_admin.fieldSel('test_api_token')).closest('tr').hide();
                $(pgzw_zainpay_admin.fieldSel('test_zainbox_code')).closest('tr').hide();
                $('.pgzw-test-field').closest('tr').hide();
                
                // Show live mode fields
                $('.pgzw-live-field').closest('tr').show();
                
                // Remove test mode notice
                pgzw_zainpay_admin.hideTestModeNotice();
            }

            pgzw_zainpay_admin.onPaymentPageChange();
        },

        /**
         * Handle custom metadata toggle.
         */
        onPaymentPageChange: function() {
            var paymentOption = $(pgzw_zainpay_admin.fieldSel('payment_page')).val();
            var isInline = (paymentOption === 'inline');
            var isTestMode = $(pgzw_zainpay_admin.fieldSel('testmode')).is(':checked');

            // Always start by hiding both inline key rows
            var $testInlineRow = $(pgzw_zainpay_admin.fieldSel('test_inline_key')).closest('tr');
            var $liveInlineRow = $(pgzw_zainpay_admin.fieldSel('live_inline_key')).closest('tr');
            $testInlineRow.hide();
            $liveInlineRow.hide();

            if (isInline) {
                if (isTestMode) {
                    $testInlineRow.show();
                } else {
                    $liveInlineRow.show();
                }
            }
        },

        onCustomMetadataChange: function() {
            var isEnabled = $(pgzw_zainpay_admin.fieldSel('custom_metadata')).is(':checked');
            
            // Show/hide metadata options
            var metadataFields = [
                pgzw_zainpay_admin.fieldSel('meta_order_id'),
                pgzw_zainpay_admin.fieldSel('meta_name'),
                pgzw_zainpay_admin.fieldSel('meta_email'),
                pgzw_zainpay_admin.fieldSel('meta_phone')
            ];
            
            $.each(metadataFields, function(index, field) {
                if (isEnabled) {
                    $(field).closest('tr').show();
                } else {
                    $(field).closest('tr').hide();
                }
            });
        },

        /**
         * Handle autocomplete order toggle.
         */
        onAutocompleteOrderChange: function() {
            var isEnabled = $(pgzw_zainpay_admin.fieldSel('autocomplete_order')).is(':checked');
            
            if (isEnabled) {
                pgzw_zainpay_admin.showAutocompleteWarning();
            } else {
                pgzw_zainpay_admin.hideAutocompleteWarning();
            }
        },

        /**
         * Show test mode notice.
         */
        showTestModeNotice: function() {
            var notice = '<div id="pgzw-test-mode-notice" class="notice notice-warning inline"><p><strong>Test Mode Enabled:</strong> ZainPay is in test mode. No live transactions will be processed.</p></div>';
            
            if ($('#pgzw-test-mode-notice').length === 0) {
                $(pgzw_zainpay_admin.fieldSel('testmode')).closest('tr').after('<tr><td colspan="2">' + notice + '</td></tr>');
            }
        },

        /**
         * Hide test mode notice.
         */
        hideTestModeNotice: function() {
            $('#pgzw-test-mode-notice').closest('tr').remove();
        },

        /**
         * Show autocomplete warning.
         */
        showAutocompleteWarning: function() {
            var warning = '<div id="pgzw-autocomplete-warning" class="notice notice-info inline"><p><strong>Note:</strong> Orders will be automatically marked as completed after successful payment. This is recommended for digital/virtual products only.</p></div>';
            
            if ($('#pgzw-autocomplete-warning').length === 0) {
                $(pgzw_zainpay_admin.fieldSel('autocomplete_order')).closest('tr').after('<tr><td colspan="2">' + warning + '</td></tr>'); 
            }
        },

        /**
         * Hide autocomplete warning.
         */
        hideAutocompleteWarning: function() {
            $('#pgzw-autocomplete-warning').closest('tr').remove();
        },

        /**
         * Initialize copy callback URL functionality.
         */
        initCopyCallbackUrl: function() {
            var copyButton = '<button type="button" id="zainpay-copy-callback" class="button button-secondary" style="margin-left: 10px;">Copy URL</button><span id="zainpay-copy-message" class="zainpay-copy-message" style="margin-left: 10px; font-weight: bold;"></span>';
            $(pgzw_zainpay_admin.fieldSel('callback_url')).after(copyButton);
            
            $(document).on('click', '#zainpay-copy-callback', this.copyCallbackUrl);
        },

        /**
         * Copy callback URL to clipboard.
         */
        copyCallbackUrl: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $messageContainer = $button.siblings('.pgzw-copy-message');
            var $callbackField = $(pgzw_zainpay_admin.fieldSel('callback_url')).first();
            var callbackUrl = $callbackField.val();
            
            if (!callbackUrl) {
                $messageContainer.html('<span style="color: #d63638;">⚠ No URL to copy</span>');
                return;
            }
            
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(callbackUrl).then(function() {
                    $messageContainer.html('<span style="color: #00a32a;">✓ Copied!</span>');
                    setTimeout(function() {
                        $messageContainer.empty();
                    }, 2000);
                }).catch(function() {
                    pgzw_zainpay_admin.fallbackCopyToClipboard(callbackUrl, $messageContainer);
                });
            } else {
                pgzw_zainpay_admin.fallbackCopyToClipboard(callbackUrl, $messageContainer);
            }
        },

        /**
         * Fallback copy method for older browsers.
         */
        fallbackCopyToClipboard: function(text, $messageContainer) {
            var textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                var successful = document.execCommand('copy');
                if (successful) {
                    $messageContainer.html('<span style="color: #00a32a;">✓ Copied!</span>');
                    setTimeout(function() {
                        $messageContainer.empty();
                    }, 2000);
                } else {
                    $messageContainer.html('<span style="color: #d63638;">✗ Copy failed</span>');
                }
            } catch (err) {
                $messageContainer.html('<span style="color: #d63638;">✗ Copy not supported</span>');
            }
            
            document.body.removeChild(textArea);
        },

        renderSidebar: function() {
            var sections = (typeof pgzw_admin_params !== 'undefined' && pgzw_admin_params.sidebar_sections) ? pgzw_admin_params.sidebar_sections : [];
            var toggleLabel = (typeof pgzw_admin_params !== 'undefined' && pgzw_admin_params.toggle_label) ? pgzw_admin_params.toggle_label : 'Toggle panel: %s';
            if (!sections.length) {
                return;
            }

            var $form = $('#mainform');
            if (!$form.length) {
                return;
            }

            var $content = $form.parent('.pgzw-settings-content');
            if (!$content.length) {
                $form.wrap('<div class="pgzw-settings-content"></div>');
                $content = $form.parent('.pgzw-settings-content');
            }

            var $layout = $content.parent('.pgzw-settings-layout');
            if (!$layout.length) {
                $content.wrap('<div class="pgzw-settings-layout"></div>');
                $layout = $content.parent('.pgzw-settings-layout');
            }

            if ($layout.find('.pgzw-settings-sidebar').length) {
                return;
            }

            var $sidebar = $('<div class="pgzw-settings-sidebar"><div id="postbox-container-1" class="postbox-container"><div class="meta-box-sortables"></div></div></div>');
            var $container = $sidebar.find('.meta-box-sortables');

            $.each(sections, function(index, section) {
                if (!section || !section.title || !section.content) {
                    return;
                }
                var $postbox = $('<div class="postbox"></div>');
                var $header = $('<div class="postbox-header"><h3 class="hndle is-non-sortable"><span></span></h3><div class="handle-actions hide-if-no-js"><button type="button" class="handlediv" aria-expanded="true"><span class="screen-reader-text"></span><span class="toggle-indicator" aria-hidden="true"></span></button></div></div>');
                $header.find('span').text(section.title);
                var labelText = toggleLabel.replace('%s', section.title);
                $header.find('.screen-reader-text').text(labelText);
                $header.find('.handlediv').attr('aria-label', labelText);
                var $inside = $('<div class="inside"></div>');
                $inside.html(section.content);
                $postbox.append($header).append($inside);
                $container.append($postbox);
            });

            $layout.append($sidebar);
        },

        initPostboxes: function() {
            if (typeof postboxes === 'undefined') {
                return;
            }
            var page = (typeof pagenow !== 'undefined' && pagenow) ? pagenow : 'woocommerce_page_wc-settings';
            postboxes.add_postbox_toggles(page);
        },

        
    };

    pgzw_zainpay_admin.init();
});
