/**
 * Uply Admin Dashboard JavaScript
 * Handles tab navigation, subtabs, feature card clicks, and AJAX form saving.
 */
jQuery(document).ready(function ($) {
    'use strict';

    // ============================================
    // Tab Navigation
    // ============================================
    // ============================================
    // Tab Navigation & Persistence
    // ============================================
    var $navLinks = $('.ustt-nav-link');
    var $tabContents = $('.ustt-tab-content');

    // Handle clicks on locked items (delegation)
    document.addEventListener('click', function (e) {
        // Check if clicked element or parent is a locked item
        const lockedItem = e.target.closest('.ustt-locked');
        if (lockedItem) {
            e.preventDefault();
            e.stopPropagation();

            // Show upgrade prompt via modern Toast instead of intrusive browser confirm()
            const message = usttObj.strings.pro_required || 'This is a Pro feature.';
            const upgradeUrl = (usttObj.upgrade_url && usttObj.upgrade_url !== '#')
                ? usttObj.upgrade_url
                : 'admin.php?page=ustt-settings&tab=account';

            // Custom toast with upgrade link
            showToast(
                message + ' <a href="' + upgradeUrl + '" style="color:#fff; text-decoration:underline; font-weight:700; margin-left:10px;">Upgrade Now</a>',
                'info'
            );
            return false;
        }
    }, true); // Use capture phase to ensure we catch it before other handlers

    // Determine Active Tab on Load
    var activeTab = 'overview'; // Fallback default

    // 1. Check PHP localized active tab (from Menu Clicks like ustt-stt)
    if (typeof usttObj !== 'undefined' && usttObj.active_tab && usttObj.active_tab !== '') {
        activeTab = usttObj.active_tab;
    }
    // 2. Check URL Parameter (from history matching)
    else {
        var urlParams = new URLSearchParams(window.location.search);
        var tabParam = urlParams.get('tab');
        if (tabParam) {
            activeTab = tabParam;
        }
        // 3. Check LocalStorage (from simple refresh)
        else if (localStorage.getItem('ustt_active_tab')) {
            activeTab = localStorage.getItem('ustt_active_tab');
        }
    }

    // Initialize
    switchTab(activeTab);

    $navLinks.on('click', function (e) {
        e.preventDefault();
        var targetTab = $(this).data('tab');
        switchTab(targetTab);
    });

    function switchTab(tabId) {
        // Validate tabId exists
        if (!$('#ustt-tab-' + tabId).length) return;

        // Update nav links
        $navLinks.removeClass('active');
        $navLinks.filter('[data-tab="' + tabId + '"]').addClass('active');

        // Update tab content
        $tabContents.removeClass('active');
        $('#ustt-tab-' + tabId).addClass('active');

        // Update Sidebar Menu Sync
        // Mapping: overview -> ustt-settings, scroll-to-top -> ustt-stt, progress-bar -> ustt-pb, read-time -> ustt-rt
        var menuSlug = 'ustt-settings';
        if (tabId === 'scroll-to-top') menuSlug = 'ustt-stt';
        else if (tabId === 'progress-bar') menuSlug = 'ustt-pb';
        else if (tabId === 'read-time') menuSlug = 'ustt-rt';

        var $submenuItems = $('#toplevel_page_ustt-settings .wp-submenu li');
        $submenuItems.removeClass('current');
        $submenuItems.find('a[href*="page=' + menuSlug + '"]').parent().addClass('current');

        // Save to LocalStorage
        localStorage.setItem('ustt_active_tab', tabId);

        // Update URL State (Friendly URL)
        // This ensures refreshes stay on the same tab even if originally clicked via submenu
        if (history.replaceState) {
            var newUrl = new URL(window.location.href);
            newUrl.searchParams.set('page', 'ustt-settings'); // Unify to main page
            newUrl.searchParams.set('tab', tabId);
            history.replaceState({ path: newUrl.href }, '', newUrl.href);
        }

        // Scroll to top of main content
        $('.ustt-main').scrollTop(0);
    }

    // ============================================
    // Sub-Tab Navigation
    // ============================================
    $('.ustt-subtab').on('click', function () {
        var $this = $(this);
        var subtabId = $this.data('subtab');
        var $container = $this.closest('.ustt-tab-content');

        // Update subtab buttons
        $container.find('.ustt-subtab').removeClass('active');
        $this.addClass('active');

        // Update subtab content
        $container.find('.ustt-subtab-content').removeClass('active');
        $('#ustt-subtab-' + subtabId).addClass('active');
    });

    // ============================================
    // Feature Card Click Navigation
    // ============================================
    $('.ustt-feature-card[data-goto]').on('click', function () {
        var targetTab = $(this).data('goto');
        switchTab(targetTab);
    });

    // ============================================
    // UI Interactions for Settings
    // ============================================

    // 1. Accordion Toggle
    $('.ustt-accordion-header').on('click', function () {
        $(this).parent('.ustt-accordion-item').toggleClass('active');
    });

    // 2. Enable Switch Toggle Logic
    function setupEnableToggle(toggleName, targetSelector) {
        var $toggle = $('input[name="' + toggleName + '"]');

        function updateState() {
            var isEnabled = $toggle.is(':checked');
            var $targets = $(targetSelector);

            if (isEnabled) {
                $targets.removeClass('ustt-disabled');
            } else {
                $targets.addClass('ustt-disabled');
            }
        }

        $toggle.on('change', updateState);
        updateState(); // Init
    }

    // Init Toggles
    setupEnableToggle('stt_enable', '#ustt-stt-settings-card');
    setupEnableToggle('pb_enable', '#ustt-tab-progress-bar .ustt-settings-card');
    setupEnableToggle('rt_enable', '#ustt-tab-read-time .ustt-settings-card');

    // 3. Radio Pill Active State (Fallback/Enhancement)
    $('.ustt-radio-pill input').on('change', function () {
        var name = $(this).attr('name');
        $('input[name="' + name + '"]').closest('.ustt-radio-pill').removeClass('active');
        $(this).closest('.ustt-radio-pill').addClass('active');
    });
    // Init Radio State
    $('.ustt-radio-pill input:checked').closest('.ustt-radio-pill').addClass('active');

    // ============================================
    // Custom Builder Tab Switching (Scroll to Top)
    // ============================================
    $('#ustt-tab-scroll-to-top .ustt-template-tab').on('click', function () {
        var tab = $(this).data('tab');

        // Update tab buttons (scoped to STT only)
        $('#ustt-tab-scroll-to-top .ustt-template-tab').removeClass('active');
        $(this).addClass('active');

        // Update tab content (scoped to STT only)
        $('#ustt-tab-scroll-to-top .ustt-template-tab-content').removeClass('active');
        if (tab === 'templates') {
            $('#ustt-templates-tab').addClass('active');
            $('#stt-custom-mode').val('0');
            $('#ustt-custom-builder-settings').hide();
        } else if (tab === 'custom') {
            $('#ustt-custom-tab').addClass('active');
            $('#stt-custom-mode').val('1');
            $('#ustt-custom-builder-settings').show();
        }
    });

    // Init custom mode UI on load
    if ($('#ustt-tab-scroll-to-top .ustt-template-tab.active').data('tab') === 'custom') {
        $('#ustt-custom-builder-settings').show();
    }

    // Custom Builder Background Toggle
    $('input[name="stt_custom_bg_enable"]').on('change', function () {
        if ($(this).is(':checked')) {
            $('#ustt-custom-bg-options').slideDown();
            $('#ustt-custom-hover-bg-wrap').fadeIn();
        } else {
            $('#ustt-custom-bg-options').slideUp();
            $('#ustt-custom-hover-bg-wrap').fadeOut();
        }
    });

    // Custom Builder Border Toggle
    $('input[name="stt_custom_border_enable"]').on('change', function () {
        if ($(this).is(':checked')) {
            $('#ustt-custom-border-options').slideDown();
        } else {
            $('#ustt-custom-border-options').slideUp();
        }
    });

    // Event Listeners for Inputs (Text updates only)
    $(document).on('input change', 'input[name^="stt_"]', function () {
        // Range slider text update
        if (this.id === 'stt-size-slider') {
            $('#stt-size-value').text($(this).val() + 'px');
        }
        if (this.type === 'color') {
            $(this).siblings('.ustt-color-value').text($(this).val().toUpperCase());
        }
    });

    // ============================================
    // Progress Bar Template Tab Switching
    // ============================================
    $('#ustt-pb-template-tabs .ustt-template-tab').on('click', function () {
        var tab = $(this).data('pb-tab');

        // Update tab buttons (scoped to PB only)
        $('#ustt-pb-template-tabs .ustt-template-tab').removeClass('active');
        $(this).addClass('active');

        // Update tab content
        $('#ustt-pb-templates-tab, #ustt-pb-custom-tab').removeClass('active');
        if (tab === 'pb-templates') {
            $('#ustt-pb-templates-tab').addClass('active');
            $('#pb-custom-mode').val('0');
        } else if (tab === 'pb-custom') {
            $('#ustt-pb-custom-tab').addClass('active');
            $('#pb-custom-mode').val('1');
        }
    });

    // PB template selection highlight
    $('.ustt-pb-template-item input[type="radio"]').on('change', function () {
        $('.ustt-pb-template-item').removeClass('selected');
        $(this).closest('.ustt-pb-template-item').addClass('selected');
    });

    // PB Height Slider
    $('#pb-height-slider').on('input', function () {
        $('#pb-height-value').text($(this).val() + 'px');
    });

    // Color picker value updates (generic, works for PB too)
    // Initialize WP Color Picker
    // Pattern 1: input.ustt-color-picker (Read Time text inputs)
    // Pattern 2: .ustt-color-picker input[type="color"] (STT/PB native color inputs inside wrapper divs)
    $('input.ustt-color-picker, .ustt-color-picker input[type="color"]').wpColorPicker({
        change: function (event, ui) {
            // Trigger input event to update preview
            $(event.target).val(ui.color.toString()).trigger('change');
            setTimeout(updateReadTimePreview, 50);
        },
        clear: function () {
            setTimeout(updateReadTimePreview, 50);
        }
    });

    $(document).on('input change', 'input[type="color"]', function () {
        $(this).siblings('.ustt-color-value').text($(this).val().toUpperCase());
    });

    // ============================================
    // Read Time Live Preview Logic
    // ============================================
    function updateReadTimePreview() {
        return; // Disabled live preview per user request
        /* Orig Logic:
        var textColor = $('input[name="rt_text_color"]').val();
        var bgColor = $('input[name="rt_bg_color"]').val();
        var fontSize = $('input[name="rt_font_size"]').val();
        var padding = $('input[name="rt_padding"]').val();
        var margin = $('input[name="rt_margin"]').val();
        
        var $previews = $('.ustt-read-time'); // Target all read time previews in the grid
        
        if (textColor) {
            $previews.css('color', textColor + ' !important');
            // Create a style tag if not exists to force !important via class since .css() doesn't support !important easily
            // Actually, for direct element style, we can just use attr
            $previews.each(function () {
                this.style.setProperty('color', textColor, 'important');
            });
        } else {
            $previews.each(function () {
                this.style.removeProperty('color');
            });
        }
        
        if (bgColor) {
            $previews.each(function () {
                this.style.setProperty('background-color', bgColor, 'important');
                this.style.setProperty('border-color', bgColor, 'important');
            });
        } else {
            $previews.each(function () {
                this.style.removeProperty('background-color');
                this.style.removeProperty('border-color');
            });
        }
        
        if (fontSize) {
            $previews.css('font-size', fontSize + 'px');
        }
        
        if (padding) {
            $previews.css('padding', padding);
        }
        
            // Margin might not be visible in grid preview layout, but we can set it
            // if (margin) $previews.css('margin', margin);
            */
    }

    // Attach listeners to Read Time inputs
    $('input[name^="rt_"]').on('input change', function () {
        updateReadTimePreview();
    });

    // Read Time Template Defaults Mapping
    var rt_defaults = {
        'ustt-rt-1': { bg: '#f3f4f6', text: '#374151' },
        'ustt-rt-2': { bg: '#dbeafe', text: '#1e40af' },
        'ustt-rt-3': { bg: '#1f2937', text: '#f9fafb' },
        'ustt-rt-4': { bg: '', text: '#6b7280' }, // transparent
        'ustt-rt-5': { bg: '#f9fafb', text: '#4b5563' },
        'ustt-rt-6': { bg: '', text: '#ffffff' }, // gradient
        'ustt-rt-7': { bg: '', text: '#ffffff' }, // gradient
        'ustt-rt-8': { bg: '', text: '#374151' }, // glass
        'ustt-rt-9': { bg: '#000000', text: '#00ff00' },
        'ustt-rt-10': { bg: '#ffffff', text: '#111827' },
        'ustt-rt-11': { bg: '', text: '#1f2937' }, // transparent
        'ustt-rt-12': { bg: '#fffbeb', text: '#b45309' },
        'ustt-rt-13': { bg: '#1a1a1a', text: '#33ff33' },
        'ustt-rt-14': { bg: '#f3e8ff', text: '#7e22ce' },
        'ustt-rt-15': { bg: '', text: '#6b7280' }, // transparent
        'ustt-rt-16': { bg: '#ecfdf5', text: '#047857' },
        'ustt-rt-17': { bg: '#dc2626', text: '#ffffff' },
        'ustt-rt-18': { bg: '', text: '#4b5563' }, // transparent
        'ustt-rt-19': { bg: '#3b82f6', text: '#ffffff' },
        'ustt-rt-20': { bg: '#facc15', text: '#000000' },
        'ustt-rt-21': { bg: '#ccfbf1', text: '#0f766e' },
        'ustt-rt-22': { bg: '', text: '#ffffff' }, // gradient
        'ustt-rt-23': { bg: '#fef3c7', text: '#92400e' },
        'ustt-rt-24': { bg: '#ffffff', text: '#374151' },
        'ustt-rt-25': { bg: '#000000', text: '#00ffff' },
        'ustt-rt-26': { bg: '#166534', text: '#dcfce7' },
        'ustt-rt-27': { bg: '#fdf2f8', text: '#db2777' },
        'ustt-rt-28': { bg: '#f8fafc', text: '#334155' },
        'ustt-rt-29': { bg: '#525252', text: '#d4d4d4' },
        'ustt-rt-30': { bg: '', text: '#ffffff' } // gradient
    };

    $('input[name="rt_template"]').on('change', function () {
        var templateId = $(this).val();
        var defaults = rt_defaults[templateId];

        if (defaults) {
            // Update Text Color
            var $textPicker = $('input[name="rt_text_color"]');
            if (defaults.text) {
                $textPicker.wpColorPicker('color', defaults.text);
            } else {
                $textPicker.closest('.wp-picker-container').find('.wp-picker-clear').click();
            }

            // Update BG Color
            var $bgPicker = $('input[name="rt_bg_color"]');
            if (defaults.bg) {
                $bgPicker.wpColorPicker('color', defaults.bg);
            } else {
                $bgPicker.closest('.wp-picker-container').find('.wp-picker-clear').click();
            }
        }
    });

    // Also trigger on color picker close/change specifically if needed (handled by input change above usually)
    $('.wp-color-picker').on('change', function () {
        setTimeout(updateReadTimePreview, 50); // Small delay to ensure value is updated
    });

    // Init on load
    // setTimeout(updateReadTimePreview, 500); // Optional: if we want to enforce saved settings on load, but PHP usually handles initial render. 
    // Actually, PHP renders the grid with standard classes, NOT with user settings inline. 
    // So we SHOULD run this on load to reflect saved settings in the preview immediately.
    setTimeout(updateReadTimePreview, 500);
    // ============================================
    function showToast(message, type) {
        // Remove existing toast
        $('.ustt-toast').remove();

        var $toast = $('<div class="ustt-toast ' + (type || 'success') + '">' + message + '</div>');
        $('body').append($toast);

        // Trigger animation
        setTimeout(function () {
            $toast.addClass('show');
        }, 10);

        // Auto-hide after 3 seconds
        setTimeout(function () {
            $toast.removeClass('show');
            setTimeout(function () {
                $toast.remove();
            }, 300);
        }, 3000);
    }

    // ============================================
    // AJAX Form Saving
    // ============================================
    // Targets: STT save (id), PB save (id), RT save (id), or any generic save button in future
    var $saveBtn = $('#ustt-stt-save, #ustt-pb-save, #ustt-rt-save');
    var $form = $('.ustt-form');

    $saveBtn.on('click', function (e) {
        e.preventDefault();
        saveSettings($(this));
    });

    function saveSettings($btn) {
        var btnHtml = $btn.html();
        $btn.prop('disabled', true).text(usttObj.strings.saving);

        // Serialize form data
        var formData = {};
        $form.find('input, select, textarea').each(function () {
            var $input = $(this);
            var name = $input.attr('name');

            if (!name) return;

            // Handle checkboxes
            if ($input.attr('type') === 'checkbox') {
                if ($input.is(':checked')) {
                    // Check if it's an array (ends with [])
                    if (name.endsWith('[]')) {
                        var cleanName = name.slice(0, -2);
                        if (!formData[cleanName]) {
                            formData[cleanName] = [];
                        }
                        formData[cleanName].push($input.val());
                    } else {
                        formData[name] = $input.val();
                    }
                }
            } else if ($input.attr('type') === 'radio') {
                if ($input.is(':checked')) {
                    formData[name] = $input.val();
                }
            } else {
                formData[name] = $input.val();
            }
        });

        // Send AJAX request
        $.ajax({
            url: usttObj.ajax_url,
            type: 'POST',
            data: {
                action: 'ustt_save_settings',
                nonce: usttObj.nonce,
                options: formData
            },
            success: function (response) {
                if (response.success) {
                    showToast(usttObj.strings.saved, 'success');
                } else {
                    showToast(response.data.message || usttObj.strings.error, 'error');
                }
            },
            error: function () {
                showToast(usttObj.strings.error, 'error');
            },
            complete: function () {
                $btn.prop('disabled', false).html(btnHtml);
            }
        });
    }

});
