/**
 * Seazonify Customizer Preview
 * Real-time reactive preview without page refresh
 */

(function($, wp) {
    'use strict';
    
    // Listen for customizer ready
    wp.customize.bind('preview-ready', function() {

        // Listen for internal enable/disable
        wp.customize('seazonify_settings[enabled]', function(value) {
            value.bind(function(isEnabled) {
                if (!isEnabled) {
                    removeSeazonify();
                } else {
                    applyEffects();
                }
            });
        });

        // Listen for direct messages from the control pane (faster and more direct)
        wp.customize.preview.bind('seazonify-update-effects', function(data) {
            applyEffects(data, true); // Force apply even if globally disabled
        });

        // Toggle controller button visibility instantly
        wp.customize('seazonify_settings[show_controller]', function(value) {
            value.bind(function(show) {
                const $btn = $('.szfy-sidebar-btn');
                if ($btn.length) {
                    if (show) $btn.show();
                    else $btn.hide();
                }
            });
        });
    });

    /**
     * Apply effects dynamically by injecting the controller script
     * @param {Object} data Selection data (optional)
     * @param {Boolean} force Force apply even if globally disabled (Customizer preview)
     */
    function applyEffects(data, force = false) {
        const isEnabled = wp.customize('seazonify_settings[enabled]').get();
        if (!isEnabled && !force) {
            return;
        }

        // If no data passed, get from Customizer settings
        if (!data) {
            data = {
                visual: wp.customize('seazonify_settings[visual_effect]').get(),
                audio: wp.customize('seazonify_settings[audio_effect]').get(),
                combo: wp.customize('seazonify_settings[combo_effect]').get()
            };
        }

        // Remove existing scripts/effects first
        removeSeazonify();

        // If nothing selected, just return
        if (!data.visual && !data.audio && !data.combo) {
            return;
        }

        // Get direct URLs if provided, otherwise fallback to guessing
        const getAssetUrl = (id, type, providedUrl) => {
            if (providedUrl) return providedUrl;
            if (!id) return null;
            // Use the absolute effects_url passed from PHP
            return `${seazonify_preview_data.effects_url}${type}/${id}.js`;
        };

        const script = document.createElement('script');
        script.id = 'seazonify-live-controller';
        script.src = seazonify_preview_data.controller_url;
        script.defer = true;
        script.setAttribute('crossorigin', 'anonymous');

        if (data.visual) {
            const visualUrl = getAssetUrl(data.visual, 'visual', data.visualUrl);
            if (visualUrl) script.setAttribute('visual', visualUrl);
        }
        
        if (data.audio) {
            const audioUrl = getAssetUrl(data.audio, 'audio', data.audioUrl);
            if (audioUrl) script.setAttribute('audio', audioUrl);
        }

        document.body.appendChild(script);
    }

    /**
     * Remove Seazonify scripts and DOM elements
     */
    function removeSeazonify() {
        // Remove the script tag
        $('#seazonify-live-controller').remove();
        
        // Remove common Seazonify DOM elements
        // Usually effects use these classes/IDs
        $('.seazonify-visual-container, .seazonify-audio-container, #seazonify-canvas').remove();
        
        // Stop any playing audio
        if (window.SeazonifyAudio) {
            try { window.SeazonifyAudio.stop(); } catch(e) {}
        }

        // Clean up global instances if they exist
        window.SeazonifyVisual = null;
        window.SeazonifyAudio = null;
        window.SeazonifyCombo = null;

    }
    
})(jQuery, wp);
