jQuery(document).ready(function($) {

    // ------------------------------------------------------------------------
    // 1. Ethereal Web Audio Synth Engine
    // ------------------------------------------------------------------------
    let audioCtx = null;
    let isSoundEnabled = localStorage.getItem('dakidarts_sound_enabled') === 'true';

    // Lazily initialize AudioContext to comply with browser autoplay policies
    function getAudioContext() {
        if (!audioCtx) {
            audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        }
        return audioCtx;
    }

    // Play synthesized high-vibrational celestial chime
    function playCelestialChime(frequency = 587.33, type = 'sine') {
        if (!isSoundEnabled) return;
        try {
            const ctx = getAudioContext();
            if (ctx.state === 'suspended') {
                ctx.resume();
            }

            const now = ctx.currentTime;
            
            // Core Carrier Oscillator
            const osc = ctx.createOscillator();
            osc.type = type;
            osc.frequency.setValueAtTime(frequency, now);
            
            // Frequency modulation sweep for metallic crystal vibe
            osc.frequency.exponentialRampToValueAtTime(frequency * 2, now + 0.08);

            // Resonant Filter
            const filter = ctx.createBiquadFilter();
            filter.type = 'lowpass';
            filter.frequency.setValueAtTime(2000, now);
            filter.frequency.exponentialRampToValueAtTime(300, now + 1.2);

            // Envelope Generator
            const gainNode = ctx.createGain();
            gainNode.gain.setValueAtTime(0, now);
            gainNode.gain.linearRampToValueAtTime(0.25, now + 0.03); // Fast attack
            gainNode.gain.exponentialRampToValueAtTime(0.0001, now + 1.8); // Smooth celestial decay

            // Cosmic Delay Effect
            const delay = ctx.createDelay();
            delay.delayTime.setValueAtTime(0.25, now);
            const delayGain = ctx.createGain();
            delayGain.gain.setValueAtTime(0.12, now);

            // Connect graph
            osc.connect(filter);
            filter.connect(gainNode);
            gainNode.connect(ctx.destination);

            // Feedback loop for space eco
            gainNode.connect(delay);
            delay.connect(delayGain);
            delayGain.connect(ctx.destination);

            osc.start(now);
            osc.stop(now + 2.0);
        } catch (e) {
            console.warn('Web Audio Playback blocked or unsupported.', e);
        }
    }

    // Inject global Sound Toggle buttons on all wrappers
    function initSoundToggles() {
        $('.dakidarts-form-wrapper').each(function() {
            const $wrapper = $(this);
            if ($wrapper.find('.dakidarts-sound-toggle').length === 0) {
                const icon = isSoundEnabled ? '🔊' : '🔇';
                const $btn = $('<div class="dakidarts-sound-toggle" title="Toggle Cosmic Chimes">' + icon + '</div>');
                $wrapper.append($btn);
            }
        });
    }

    // Bind Sound Toggle clicks
    $(document).on('click', '.dakidarts-sound-toggle', function() {
        isSoundEnabled = !isSoundEnabled;
        localStorage.setItem('dakidarts_sound_enabled', isSoundEnabled);
        
        const icon = isSoundEnabled ? '🔊' : '🔇';
        $('.dakidarts-sound-toggle').text(icon);
        
        if (isSoundEnabled) {
            playCelestialChime(523.25, 'triangle'); // Warm chime confirmation
        }
    });

    // ------------------------------------------------------------------------
    // 2. Cosmic Background Particle System (Canvas)
    // ------------------------------------------------------------------------
    function initCosmicParticles() {
        $('.dakidarts-form-wrapper').each(function() {
            const $wrapper = $(this);
            if ($wrapper.find('.dakidarts-cosmic-particles').length === 0) {
                const $canvas = $('<canvas class="dakidarts-cosmic-particles"></canvas>');
                $wrapper.prepend($canvas);
                
                const canvas = $canvas[0];
                const ctx = canvas.getContext('2d');
                let animationFrameId;

                function resize() {
                    canvas.width = $wrapper.outerWidth();
                    canvas.height = $wrapper.outerHeight();
                }

                // Initial resize
                resize();
                $(window).on('resize', resize);

                // Space dust array
                const stars = [];
                const maxStars = 35;
                for (let i = 0; i < maxStars; i++) {
                    stars.push({
                        x: Math.random() * canvas.width,
                        y: Math.random() * canvas.height,
                        radius: Math.random() * 1.5 + 0.2,
                        opacity: Math.random() * 0.7 + 0.1,
                        speed: Math.random() * 0.15 + 0.05
                    });
                }

                function draw() {
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    
                    stars.forEach(star => {
                        ctx.beginPath();
                        ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
                        ctx.fillStyle = `rgba(124, 58, 237, ${star.opacity})`;
                        ctx.shadowBlur = 4;
                        ctx.shadowColor = 'rgba(79, 70, 229, 0.4)';
                        ctx.fill();

                        // Drifting movement
                        star.y -= star.speed;
                        if (star.y < 0) {
                            star.y = canvas.height;
                            star.x = Math.random() * canvas.width;
                        }
                    });

                    animationFrameId = requestAnimationFrame(draw);
                }

                draw();

                // Clean up animation on wrapper destroy if necessary
                $wrapper.data('particles-animation-id', animationFrameId);
            }
        });
    }

    // ------------------------------------------------------------------------
    // 3. Astrological Zodiac Wheel SVG Renderer
    // ------------------------------------------------------------------------
    const zodiacData = [
        { name: 'aries', glyph: '♈' },
        { name: 'taurus', glyph: '♉' },
        { name: 'gemini', glyph: '♊' },
        { name: 'cancer', glyph: '♋' },
        { name: 'leo', glyph: '♌' },
        { name: 'virgo', glyph: '♍' },
        { name: 'libra', glyph: '♎' },
        { name: 'scorpio', glyph: '♏' },
        { name: 'sagittarius', glyph: '♐' },
        { name: 'capricorn', glyph: '♑' },
        { name: 'aquarius', glyph: '♒' },
        { name: 'pisces', glyph: '♓' }
    ];

    function injectZodiacWheel(selectElement, wrapperContainer) {
        const $select = $(selectElement);
        if ($select.length === 0 || $select.data('wheel-injected')) return;
        $select.data('wheel-injected', true).hide(); // Hide raw dropdown

        const currentVal = $select.val() || 'aries';
        
        // Build Wheel HTML
        let wheelHtml = `
            <div class="dakidarts-zodiac-wheel-container">
                <span class="dakidarts-zodiac-wheel-indicator">${currentVal.toUpperCase()}</span>
                <div class="dakidarts-zodiac-wheel-wrapper">
                    <svg viewBox="0 0 200 200">
                        <defs>
                            <radialGradient id="dakidarts-grad" cx="50%" cy="50%" r="50%">
                                <stop offset="0%" stop-color="#4f46e5" />
                                <stop offset="100%" stop-color="#7c3aed" />
                            </radialGradient>
                        </defs>
        `;

        // Generate slices
        const centerX = 100, centerY = 100, radius = 90, innerRadius = 45;
        zodiacData.forEach((sign, i) => {
            const startAngle = (i * 30 - 105) * Math.PI / 180;
            const endAngle = ((i + 1) * 30 - 105) * Math.PI / 180;

            const x1 = centerX + radius * Math.cos(startAngle);
            const y1 = centerY + radius * Math.sin(startAngle);
            const x2 = centerX + radius * Math.cos(endAngle);
            const y2 = centerY + radius * Math.sin(endAngle);

            const x3 = centerX + innerRadius * Math.cos(endAngle);
            const y3 = centerY + innerRadius * Math.sin(endAngle);
            const x4 = centerX + innerRadius * Math.cos(startAngle);
            const y4 = centerY + innerRadius * Math.sin(startAngle);

            const angleCenter = (i * 30 - 90) * Math.PI / 180;
            const textX = centerX + ((radius + innerRadius) / 2) * Math.cos(angleCenter);
            const textY = centerY + ((radius + innerRadius) / 2) * Math.sin(angleCenter) + 5;

            const isActive = sign.name === currentVal ? 'active' : '';

            // Draw donut slice path
            wheelHtml += `
                <path d="M ${x1} ${y1} A ${radius} ${radius} 0 0 1 ${x2} ${y2} L ${x3} ${y3} A ${innerRadius} ${innerRadius} 0 0 0 ${x4} ${y4} Z" 
                      class="dakidarts-wheel-slice ${isActive}" 
                      data-sign="${sign.name}" />
                <text x="${textX}" y="${textY}" text-anchor="middle" class="dakidarts-wheel-glyph">${sign.glyph}</text>
            `;
        });

        // Center celestial hub
        wheelHtml += `
                        <circle cx="${centerX}" cy="${centerY}" r="${innerRadius - 2}" class="dakidarts-wheel-center" />
                        <text x="${centerX}" y="${centerY + 4}" text-anchor="middle" class="dakidarts-wheel-center-text">✦ ORACLE ✦</text>
                    </svg>
                </div>
            </div>
        `;

        const $wheel = $(wheelHtml);
        $select.after($wheel);

        // Bind wheel clicks
        $wheel.find('.dakidarts-wheel-slice').on('click', function() {
            const selectedSign = $(this).data('sign');
            
            $wheel.find('.dakidarts-wheel-slice').removeClass('active');
            $(this).addClass('active');

            $wheel.find('.dakidarts-zodiac-wheel-indicator').text(selectedSign.toUpperCase());
            $select.val(selectedSign).trigger('change');
            
            // Frequencies tuned to celestial bodies (e.g. 523Hz resonant third)
            playCelestialChime(523.25, 'triangle');
        });
    }

    function initZodiacWheels() {
        $('form.dakidarts-form select').each(function() {
            const name = $(this).attr('name') || '';
            if (name.includes('sign') || name.includes('zodiac')) {
                injectZodiacWheel(this);
            }
        });
    }

    // ------------------------------------------------------------------------
    // 4. Interactive Tarot Deck Card Spread Draws
    // ------------------------------------------------------------------------
    function handleTarotDrawSpread($form, endpoint, totalCardsToDraw) {
        const $wrapper = $form.closest('.dakidarts-form-wrapper');
        const $loader = $wrapper.find('.dakidarts-loader-overlay');
        const $result = $wrapper.find('.dakidarts-result');

        // Render card draw board
        $form.stop().fadeOut(300, function() {
            let deckHtml = `
                <div class="dakidarts-tarot-deck-board">
                    <div class="dakidarts-tarot-deck-title">Choose <span class="dakidarts-tarot-draw-count">${totalCardsToDraw}</span> Cards from the Deck</div>
                    <div class="dakidarts-tarot-deck">
            `;

            // Fan 22 Major Arcana cards fanned beautifully
            const cardsCount = 18;
            for (let i = 0; i < cardsCount; i++) {
                const angle = (i - (cardsCount - 1) / 2) * 5; // Rotation step
                const offset = (i - (cardsCount - 1) / 2) * 15; // Positioning fan
                deckHtml += `
                    <div class="dakidarts-deck-card" 
                         style="transform: rotate(${angle}deg) translateX(${offset}px); z-index: ${i + 1}; left: calc(50% - 45px);" 
                         data-index="${i}"></div>
                `;
            }

            deckHtml += `
                    </div>
                </div>
            `;

            const $deckBoard = $(deckHtml);
            $wrapper.append($deckBoard);

            const drawnIndexes = [];

            // Bind card selection
            $deckBoard.find('.dakidarts-deck-card').on('click', function() {
                if ($(this).hasClass('drawn') || drawnIndexes.length >= totalCardsToDraw) return;

                $(this).addClass('drawn');
                drawnIndexes.push($(this).data('index'));

                const frequencies = [440.00, 493.88, 523.25]; // Resonant chord
                const note = frequencies[drawnIndexes.length - 1] || 523.25;
                playCelestialChime(note, 'sine');

                const remaining = totalCardsToDraw - drawnIndexes.length;
                if (remaining > 0) {
                    $deckBoard.find('.dakidarts-tarot-draw-count').text(remaining);
                } else {
                    $deckBoard.find('.dakidarts-tarot-deck-title').text('Analyzing your celestial spread...');
                    
                    // Proceed to send AJAX calculation
                    setTimeout(function() {
                        $deckBoard.fadeOut(300, function() {
                            $deckBoard.remove();
                            $loader.addClass('active');

                            const params = {};
                            $form.serializeArray().forEach(item => {
                                params[item.name] = item.value;
                            });

                            // Inject visual drawn card indexes into API param if required
                            params['drawn_cards'] = drawnIndexes.join(',');

                            $.post(DakidartsAjax.ajax_url, {
                                action: 'dakidarts_numerology_calculate',
                                endpoint: endpoint,
                                params: params,
                                nonce: DakidartsAjax.nonce
                            }, function(response) {
                                if (response.success && response.data && response.data.html) {
                                    $result.html(response.data.html).stop().fadeIn(400);
                                    bindResultReset($form, $result);
                                    initResultsToolbox($result);
                                } else {
                                    alert(response.data || 'An error occurred. Please try again.');
                                    $form.stop().fadeIn(300);
                                }
                            }).fail(function() {
                                alert('A connection error occurred.');
                                $form.stop().fadeIn(300);
                            }).always(function() {
                                $loader.removeClass('active');
                            });
                        });
                    }, 1200);
                }
            });
        });
    }

    // ------------------------------------------------------------------------
    // 5. Results Floating Toolbox (Print, Copy, Voice Synth Oracle)
    // ------------------------------------------------------------------------
    function showToast(message) {
        let $toast = $('.dakidarts-toast');
        if ($toast.length === 0) {
            $toast = $('<div class="dakidarts-toast">✨ <span class="dakidarts-toast-text"></span></div>');
            $('body').append($toast);
        }
        $toast.find('.dakidarts-toast-text').text(message);
        $toast.addClass('active');

        setTimeout(function() {
            $toast.removeClass('active');
        }, 3000);
    }

    function initResultsToolbox($resultContainer) {
        if ($resultContainer.find('.dakidarts-results-toolbox').length > 0) return;

        const toolboxHtml = `
            <div class="dakidarts-results-toolbox">
                <button class="dakidarts-toolbox-btn dakidarts-print-btn" title="Download Report PDF">🖨️ PDF Report</button>
                <button class="dakidarts-toolbox-btn dakidarts-share-btn" title="Copy Shareable Oracle Link">🔗 Share Oracle</button>
                <button class="dakidarts-toolbox-btn dakidarts-voice-btn" title="Listen to Voice Oracle">🔊 Voice Oracle</button>
            </div>
        `;

        $resultContainer.prepend(toolboxHtml);

        // Bind Print/PDF Action
        $resultContainer.find('.dakidarts-print-btn').on('click', function() {
            playCelestialChime(587.33, 'triangle');
            window.print();
        });

        // Bind Clipboard Copy Action
        $resultContainer.find('.dakidarts-share-btn').on('click', function() {
            playCelestialChime(659.25, 'triangle');
            const scoreText = $resultContainer.find('.dakidarts-gauge-number').text() || 'Vibrational Connection';
            const predictionSummary = $resultContainer.find('.dakidarts-horoscope-text').text() || 
                                     $resultContainer.find('.dakidarts-compat-summary p').text() || 
                                     'My celestial oracle prediction reading!';
            
            const shareString = `✦ Astro-Celestial Reading ✦\nConnection Resonance: ${scoreText}\nPrediction: "${predictionSummary.substring(0, 100)}..."\nCalculate yours at: ${window.location.href}`;
            
            navigator.clipboard.writeText(shareString).then(function() {
                showToast('Celestial report link copied to clipboard! ✦');
            }).catch(function() {
                showToast('Unable to copy. Please manually highlight report.');
            });
        });

        // Bind Voice Oracle Synthesizer (Text-To-Speech)
        let isSpeaking = false;
        $resultContainer.find('.dakidarts-voice-btn').on('click', function() {
            if ('speechSynthesis' in window) {
                if (isSpeaking) {
                    window.speechSynthesis.cancel();
                    isSpeaking = false;
                    $(this).html('🔊 Voice Oracle');
                    return;
                }

                playCelestialChime(440.00, 'sine');
                
                const $prediction = $resultContainer.find('.dakidarts-horoscope-text, .dakidarts-compat-summary p, .dakidarts-tarot-overall-meaning p, .dakidarts-card-item');
                let readText = '';
                if ($prediction.length > 0) {
                    readText = $prediction.first().text();
                } else {
                    readText = $resultContainer.text().replace(/[\n\t]/g, ' ').substring(0, 200);
                }

                const utterance = new SpeechSynthesisUtterance(readText);
                utterance.pitch = 1.05; // Slightly high-vibrational pitch
                utterance.rate = 0.95; // Steady, soothing flow

                utterance.onend = function() {
                    isSpeaking = false;
                    $resultContainer.find('.dakidarts-voice-btn').html('🔊 Voice Oracle');
                };

                window.speechSynthesis.speak(utterance);
                isSpeaking = true;
                $(this).html('⏸️ Pause Oracle');
            } else {
                showToast('Voice synthesizer not supported on this browser.');
            }
        });
    }

    // Shared Reset function
    function bindResultReset($form, $result) {
        $result.find('.dakidarts-try-again').off('click').on('click', function(e) {
            e.preventDefault();
            
            // Cancel voice oracle if active
            if ('speechSynthesis' in window) {
                window.speechSynthesis.cancel();
            }

            playCelestialChime(329.63, 'sine'); // Reset tone

            $result.stop().fadeOut(300, function() {
                $result.html('');
                $form.trigger('reset');
                
                // Reset standard elements
                $form.find('.dakidarts-toggle-wrapper').each(function() {
                    $(this).find('.dakidarts-toggle-hidden').val('false');
                    $(this).find('.dakidarts-toggle-option').removeClass('active');
                    $(this).find('.dakidarts-toggle-option[data-value="false"]').addClass('active');
                });

                // Reset zodiac wheels to Aries default
                $form.find('.dakidarts-zodiac-wheel-container').each(function() {
                    const $indicator = $(this).find('.dakidarts-zodiac-wheel-indicator');
                    const $slices = $(this).find('.dakidarts-wheel-slice');
                    $slices.removeClass('active');
                    $(this).find('.dakidarts-wheel-slice[data-sign="aries"]').addClass('active');
                    $indicator.text('ARIES');
                });

                $form.stop().fadeIn(300);
            });
        });
    }

    // ------------------------------------------------------------------------
    // Global Form Interceptor
    // ------------------------------------------------------------------------
    $(document).on('submit', 'form.dakidarts-form', function(e) {
        const $form = $(this);
        const endpoint = $form.data('endpoint') || '';

        // Draw dynamic Tarot cards fan deck instead of instant submit
        if (endpoint.includes('tarot')) {
            e.preventDefault();
            const totalCards = endpoint.includes('three') ? 3 : 1;
            handleTarotDrawSpread($form, endpoint, totalCards);
            return;
        }

        e.preventDefault();
        const $wrapper = $form.closest('.dakidarts-form-wrapper');
        const $loader = $wrapper.find('.dakidarts-loader-overlay');
        const $result = $wrapper.find('.dakidarts-result');

        // Play submit bell
        playCelestialChime(587.33, 'triangle');

        const params = {};
        $form.serializeArray().forEach(item => {
            params[item.name] = item.value;
        });

        $loader.addClass('active');
        $result.stop().fadeOut(200);

        $.post(DakidartsAjax.ajax_url, {
            action: 'dakidarts_numerology_calculate',
            endpoint: endpoint,
            params: params,
            nonce: DakidartsAjax.nonce
        }, function(response) {
            if (response.success && response.data && response.data.html) {
                playCelestialChime(698.46, 'sine'); // Success bell chord
                
                $form.stop().fadeOut(300, function() {
                    $result.html(response.data.html).stop().fadeIn(400);
                    bindResultReset($form, $result);
                    initResultsToolbox($result);
                });
            } else {
                alert(response.data || 'An error occurred. Please try again.');
            }
        }).fail(function() {
            alert('A connection error occurred. Please try again.');
        }).always(function() {
            setTimeout(function() {
                $loader.removeClass('active');
            }, 300);
        });
    });

    // ------------------------------------------------------------------------
    // Initialize Suite On Page Load
    // ------------------------------------------------------------------------
    function bootstrapSuite() {
        initSoundToggles();
        initCosmicParticles();
        initZodiacWheels();
    }

    bootstrapSuite();

    // Re-bind elements when active AJAX actions happen in dynamic widgets/blocks
    $(document).on('dakidarts_blocks_loaded', function() {
        bootstrapSuite();
    });

});
