/**
 * Seazonify Customizer Controls
 * With progressive loading and smart client-side search
 */

(function($, wp) {
    'use strict';
    
    // Current selections (only one per type)
    let selectedVisual = '';
    let selectedAudio = '';
    let selectedCombo = seazonifyEffects.selected_combo || '';
    
    // Global cache for effect details (to look up URLs for preview)
    const effectsCache = {};
    
    // Loaded effects (all effects loaded so far)
    let loadedEffects = {
        visual: [],
        audio: [],
        combos: []
    };
    
    // Pagination state
    let currentPage = {
        visual: 0,
        audio: 0,
        combos: 0
    };
    
    let totalPages = {
        visual: 1,
        audio: 1,
        combos: 1
    };
    
    let isLoading = {
        visual: false,
        audio: false,
        combos: false
    };
    
    // Search state
    let searchQuery = '';
    let searchPage = {
        visual: 1,
        audio: 1,
        combos: 1
    };
    let isSearching = false;
    
    // Wait for customizer to be ready
    // Use the official WordPress Customizer pattern to wait for the section
    wp.customize.section('seazonify_section', function(section) {
        
        // Build the custom interface when section is expanded
        section.expanded.bind(function(isExpanded) {
            if (isExpanded && !section.customInterfaceBuilt) {
                buildCustomInterface(section);
                section.customInterfaceBuilt = true;
            }
        });
    });
    
    function buildCustomInterface(section) {
        const $section = $('#accordion-section-seazonify_section .accordion-section-content');
        
        // Hide default controls
        $('#customize-control-seazonify_visual_effect, #customize-control-seazonify_audio_effect, #customize-control-seazonify_combo_effect').hide();
        
        // Get current settings
        const visualSetting = wp.customize('seazonify_settings[visual_effect]');
        const audioSetting = wp.customize('seazonify_settings[audio_effect]');
        const comboSetting = wp.customize('seazonify_settings[combo_effect]');
        
        // Get current selections
        selectedVisual = visualSetting.get() || '';
        selectedAudio = audioSetting.get() || '';
        selectedCombo = comboSetting.get() || '';
        
        // Load initial effects from localized data
        loadedEffects.visual = seazonifyEffects.visual || [];
        loadedEffects.audio = seazonifyEffects.audio || [];
        loadedEffects.combos = seazonifyEffects.combos || [];
        
        // Set total pages from localized pagination data
        totalPages.visual = parseInt(seazonifyPagination.visual) || 1;
        totalPages.audio = parseInt(seazonifyPagination.audio) || 1;
        totalPages.combos = parseInt(seazonifyPagination.combos) || 1;
        
        // Create 3-tab interface HTML with search
        const html = `
            <div class="seazonify-customizer-interface">
                <div class="seazonify-description-area">
                    <p class="seazonify-plain-description">Seazonify empowers your WordPress site with high-performance seasonal visual and audio effects designed to increase visitor engagement and delight your audience throughout the year.</p>
                </div>
                <div class="seazonify-search-box">
                    <input type="text" id="seazonify-search-input" placeholder="Search effects..." />
                    <svg class="search-icon" viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                </div>

                <div class="seazonify-tabs">
                    <div class="seazonify-tab active" data-tab="visual">Visual</div>
                    <div class="seazonify-tab" data-tab="audio">Audio</div>
                    <div class="seazonify-tab" data-tab="combos">Combos</div>
                </div>

                <div class="seazonify-panes">
                    <div class="seazonify-pane active" data-pane="visual">
                        <div class="seazonify-effects-list" id="seazonify-visual-list" data-type="visual"></div>
                        <div class="seazonify-loading-more" id="seazonify-visual-loading" style="display:none;">Loading more...</div>
                    </div>
                    <div class="seazonify-pane" data-pane="audio">
                        <div class="seazonify-effects-list" id="seazonify-audio-list" data-type="audio"></div>
                        <div class="seazonify-loading-more" id="seazonify-audio-loading" style="display:none;">Loading more...</div>
                    </div>
                    <div class="seazonify-pane" data-pane="combos">
                        <div class="seazonify-effects-list" id="seazonify-combos-list" data-type="combos"></div>
                        <div class="seazonify-loading-more" id="seazonify-combos-loading" style="display:none;">Loading more...</div>
                    </div>
                </div>
            </div>
        `;
        
        // Insert after the enable control so the toggle is on top
        $('#customize-control-seazonify_enabled').after(html);
        
        // Render initial loading state for the active tab
        renderEffects('visual', [], false, true);
        
        // Initial marker check
        updateTabMarkers();
        
        // ONLY load the active tab initially (visual)
        loadMoreEffects('visual');
        
        // Tab switching - use event delegation
        $(document).on('click', '.seazonify-tab', function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            
            const tab = $(this).data('tab');
            
            $('.seazonify-tab').removeClass('active');
            $(this).addClass('active');
            $('.seazonify-pane').removeClass('active');
            $(`.seazonify-pane[data-pane="${tab}"]`).addClass('active');
            
            // Trigger search or initial load for the new tab
            try {
                const $targetList = $(`#seazonify-${tab}-list`);

                if (isSearching && searchQuery) {
                    renderEffects(tab, [], false, true);
                    searchPage[tab] = 0;
                    executeSearch(tab, searchQuery);
                } else if (loadedEffects[tab].length === 0) {
                    // ABSOLUTE FORCE: Ensure call is never skipped for the first visit
                    isLoading[tab] = false; 
                    currentPage[tab] = 0; 
                    renderEffects(tab, [], false, true); 
                    loadMoreEffects(tab);
                }
            } catch (err) {
                loadMoreEffects(tab);
            }
            
            return false;
        });
        
        // Search functionality
        $('#seazonify-search-input').on('input', debounce(handleSearch, 300));
        
        // Infinite scroll for each list
        $('.seazonify-effects-list').on('scroll', function() {
            const $list = $(this);
            const type = $list.data('type');
            
            // Check if scrolled near bottom (80%)
            const scrollTop = $list.scrollTop();
            const scrollHeight = $list[0].scrollHeight;
            const clientHeight = $list.height();
            
            if (scrollTop + clientHeight >= scrollHeight * 0.8) {
                if (searchQuery) {
                    loadMoreSearchResults(type);
                } else {
                    loadMoreEffects(type);
                }
            }
        });
    }
    
    function renderEffects(type, effects, append = false, isInitial = false) {
        const listId = `#seazonify-${type}-list`;
        const $list = $(listId);
        
        if (!append) {
            $list.empty();
        }
        
        if (effects.length === 0 && !append) {
            if (isInitial) {
                $list.html('<div class="seazonify-loading"><div class="spinner"></div><p>Loading effects...</p></div>');
            } else {
                $list.html('<p class="seazonify-no-effects">No effects available</p>');
            }
            return;
        }
        
        effects.forEach(effect => {
            // Cache the effect for preview lookups
            effectsCache[effect.id] = effect;
            
            let isSelected = false;
            if (type === 'visual') isSelected = String(selectedVisual) === String(effect.id);
            else if (type === 'audio') isSelected = String(selectedAudio) === String(effect.id);
            else if (type === 'combos') isSelected = String(selectedCombo) === String(effect.id);
            
            // Premium Card Structure mirroring Workspace
            const $card = $('<div class="seazonify-effect-card"></div>')
                .toggleClass('selected', isSelected)
                .attr('data-effect-id', effect.id)
                .attr('data-effect-type', type);

            const $cardTop = $('<div class="card-top"></div>');

            // Preview Area (Image or Icon)
            const $preview = $('<div class="effect-visual-preview"></div>');
            if (effect.thumbnail) {
                $preview.append(`<img src="${effect.thumbnail}" alt="${effect.name}" />`);
            } else {
                $preview.append(`<span class="effect-icon-fallback">${effect.icon || '✨'}</span>`);
            }

            // Info Area
            const $info = $('<div class="effect-info"></div>');
            $info.append(`<div class="effect-name">${effect.name}</div>`);
            $info.append(`<div class="effect-description">${effect.description || ''}</div>`);

            // Selection Checkmark
            const $check = $('<div class="effect-select-icon"></div>');
            if (isSelected) {
                // Check circle icon matching Workspace
                $check.html('<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>');
            }

            $cardTop.append($preview).append($info).append($check);

            // Metadata Row (Match Workspace: Author, Rating, Info Icon with Tag Tooltip)
            const $cardBottom = $('<div class="card-bottom effect-meta"></div>');
            const $metaLeft = $('<div class="meta-left"></div>');
            
            // Author
            $metaLeft.append(`<span class="meta-author">${effect.author || 'Seazonify'}</span>`);
            
            // Rating
            const ratingNumber = parseFloat(effect.rating);
            const ratingText = (ratingNumber > 0) ? ratingNumber.toFixed(1) : 'New';
            $metaLeft.append(`<span class="meta-rating"><svg class="rating-star" viewBox="0 0 24 24" width="12" height="12"><path fill="currentColor" stroke="none" d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"></path></svg>${ratingText}</span>`);

            // Info Icon & Tag Tooltip (Right side)
            const $metaRight = $('<div class="meta-right"></div>');
            const $infoWrapper = $('<div class="effect-info-wrapper"></div>');
            const $infoIcon = $('<div class="info-icon"><svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg></div>');
            
            const $metaTags = $('<div class="meta-tags-tooltip"></div>');
            const tagsList = (effect.tags && Array.isArray(effect.tags) && effect.tags.length > 0) ? effect.tags : [type === 'combos' ? 'combo' : type];
            
            tagsList.forEach(tag => {
                $metaTags.append(`<span class="tag">${tag}</span>`);
            });

            $infoWrapper.append($infoIcon).append($metaTags);
            $metaRight.append($infoWrapper);

            $cardBottom.append($metaLeft).append($metaRight);
            $card.append($cardTop).append($cardBottom);
            
            $card.on('click', function() {
                toggleEffect(effect.id, type);
            });
            
            $list.append($card);
        });
    }
    
    function loadMoreEffects(type) {
        // Special case: if we have 0 effects, always allow loading the first page once
        const isFirstLoad = (loadedEffects[type].length === 0 && currentPage[type] === 0);
        
        // Don't load if already loading or no more pages (unless it's the very first load)
        if (isLoading[type] || (!isFirstLoad && currentPage[type] >= totalPages[type] && totalPages[type] > 0)) {
            return;
        }
        
        isLoading[type] = true;
        
        // Only show "Loading more..." at bottom if not the first page
        if (currentPage[type] > 0) {
            $(`#seazonify-${type}-loading`).show();
        }
        
        const nextPage = (currentPage[type] || 0) + 1;
        
        $.ajax({
            url: seazonifyAjax.ajax_url,
            type: 'POST',
            cache: false, // Manual jQuery cache bust
            data: {
                action: 'seazonify_load_page',
                type: type,
                page: nextPage,
                nonce: seazonifyAjax.nonce,
                _cache_bust: Date.now() // Forced unique request ID
            },
            success: function(response) {
                if (response.success) {
                    // Add to loaded effects
                    loadedEffects[type] = loadedEffects[type].concat(response.data.effects);
                    
                    // Render new effects (append if not first page)
                    renderEffects(type, response.data.effects, currentPage[type] > 0);
                    
                    // Update page counter
                    currentPage[type] = nextPage;
                    
                    // Update total pages if returned
                    if (response.data.total_pages) {
                        totalPages[type] = response.data.total_pages;
                    }
                }
            },
            error: function(xhr, status, error) {
            },
            complete: function() {
                isLoading[type] = false;
                $(`#seazonify-${type}-loading`).hide();
            }
        });
    }
    
    function handleSearch() {
        searchQuery = $('#seazonify-search-input').val().trim();
        const activeTab = $('.seazonify-tab.active').data('tab');
        
        if (!searchQuery) {
            // No search query - restore original loaded effects for ALL tabs
            isSearching = false;
            ['visual', 'audio', 'combos'].forEach(type => {
                renderEffects(type, loadedEffects[type]);
            });
            return;
        }
        
        isSearching = true;
        
        // Clear only the current tab and show loading
        const $list = $(`#seazonify-${activeTab}-list`);
        $list.html('<div class="seazonify-loading"><div class="spinner"></div><p>Searching effects...</p></div>');
        
        // Reset search pages for this query
        searchPage[activeTab] = 0; // Will be incremented in searchInNextPage
        
        executeSearch(activeTab, searchQuery);
    }
    
    function executeSearch(type, query) {
        // Don't load if already loading or no more pages
        if (isLoading[type] || (searchPage[type] > 0 && searchPage[type] >= totalPages[type])) {
            return;
        }
        
        isLoading[type] = true;
        const nextPage = (searchPage[type] || 0) + 1;
        $(`#seazonify-${type}-loading`).show();
        
        $.ajax({
            url: seazonifyAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'seazonify_search_effects',
                type: type,
                page: nextPage,
                query: query,
                nonce: seazonifyAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data.effects) {
                    // Render effects (append if page > 1)
                    renderEffects(type, response.data.effects, nextPage > 1);
                    
                    searchPage[type] = nextPage;
                    totalPages[type] = response.data.total_pages || 1;
                    
                    if (response.data.effects.length === 0 && nextPage === 1) {
                         $(`#seazonify-${type}-list`).html('<p class="seazonify-no-effects">No matches found for "' + query + '"</p>');
                    }
                }
            },
            complete: function() {
                isLoading[type] = false;
                $(`#seazonify-${type}-loading`).hide();
            }
        });
    }
    

    
    function searchInNextPage(type) {
        if (!isSearching || !searchQuery) return;
        executeSearch(type, searchQuery);
    }
    
    function loadMoreSearchResults(type) {
        executeSearch(type, searchQuery);
    }
    
    function toggleEffect(effectId, type) {
        
        if (type === 'combos' || type === 'combo') {
            if (String(selectedCombo) === String(effectId)) {
                selectedCombo = '';
            } else {
                selectedCombo = effectId;
                selectedVisual = '';
                selectedAudio = '';
            }
        } else if (type === 'visual') {
            if (String(selectedVisual) === String(effectId)) {
                selectedVisual = '';
            } else {
                selectedVisual = effectId;
                selectedCombo = ''; // Combo is exclusive
            }
        } else if (type === 'audio') {
            if (String(selectedAudio) === String(effectId)) {
                selectedAudio = '';
            } else {
                selectedAudio = effectId;
                selectedCombo = ''; // Combo is exclusive
            }
        }
        
        // Update WordPress settings
        wp.customize('seazonify_settings[enabled]').set(true);
        wp.customize('seazonify_settings[visual_effect]').set(selectedVisual);
        wp.customize('seazonify_settings[audio_effect]').set(selectedAudio);
        wp.customize('seazonify_settings[combo_effect]').set(selectedCombo);
        
        // Update UI for ALL cards
        updateAllCards();
        
        // Update tab markers
        updateTabMarkers();
        
        // Notify preview
        notifyPreview();
    }
    
    function updateAllCards() {
        $('.seazonify-effect-card').each(function() {
            const $card = $(this);
            const effectId = $card.data('effect-id');
            const effectType = $card.data('effect-type');
            
            let isSelected = false;
            if (effectType === 'visual') isSelected = String(effectId) === String(selectedVisual);
            else if (effectType === 'audio') isSelected = String(effectId) === String(selectedAudio);
            else if (effectType === 'combos') isSelected = String(effectId) === String(selectedCombo);
            
            $card.toggleClass('selected', isSelected);
        });
    }

    function updateTabMarkers() {
        $('.seazonify-tab').each(function() {
            const $tab = $(this);
            const tabType = $tab.data('tab');
            let hasSelection = false;
            
            if (tabType === 'visual') hasSelection = !!selectedVisual;
            else if (tabType === 'audio') hasSelection = !!selectedAudio;
            else if (tabType === 'combos') hasSelection = !!selectedCombo;
            
            $tab.toggleClass('has-selection', hasSelection);
        });
    }
    
    function notifyPreview() {
        // Send current selections to preview
        // To ensure the script is flawlessly injected into the live page without
        // DOM timing issues, we rely on the PHP injection by refreshing the preview frame.
        if (wp.customize && wp.customize.previewer && typeof wp.customize.previewer.refresh === 'function') {
            wp.customize.previewer.refresh();
        }
    }
    
    // Debounce helper
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
})(jQuery, wp);
