/**
 * Waveform Progress Bar
 *
 * Renders an SVG waveform inside .mementor-tts-waveform containers.
 * Bar heights are seeded from post ID for deterministic per-post patterns.
 * Foreground layer clips to audio.currentTime for playback progress.
 * Click and drag to seek. Silent fallback to linear on error.
 */
(function() {
    'use strict';

    var BAR_COUNT  = 60;
    var BAR_WIDTH  = 3;
    var BAR_GAP    = 2;
    var BAR_STEP   = BAR_WIDTH + BAR_GAP;
    var SVG_WIDTH  = BAR_COUNT * BAR_STEP - BAR_GAP;
    var SVG_HEIGHT = 32;
    var MIN_HEIGHT = 0.2;
    var SVG_NS     = 'http://www.w3.org/2000/svg';

    // --- Seeded PRNG ---

    function seededRandom(seed) {
        seed = Math.abs(seed) || 1;
        return function() {
            seed = (seed * 16807) % 2147483647;
            return (seed - 1) / 2147483646;
        };
    }

    // --- SVG Builder ---

    function buildSVG(container) {
        var postId = parseInt(container.getAttribute('data-post-id'), 10) || 1;
        var rand = seededRandom(postId);
        var heights = [];
        var i;

        for (i = 0; i < BAR_COUNT; i++) {
            heights.push(MIN_HEIGHT + rand() * (1 - MIN_HEIGHT));
        }

        var svg = document.createElementNS(SVG_NS, 'svg');
        svg.setAttribute('class', 'mementor-tts-waveform-svg');
        svg.setAttribute('viewBox', '0 0 ' + SVG_WIDTH + ' ' + SVG_HEIGHT);
        svg.setAttribute('preserveAspectRatio', 'none');

        var bgGroup = document.createElementNS(SVG_NS, 'g');
        bgGroup.setAttribute('class', 'mementor-tts-waveform-bg');

        var fgGroup = document.createElementNS(SVG_NS, 'g');
        fgGroup.setAttribute('class', 'mementor-tts-waveform-fg');
        fgGroup.style.clipPath = 'inset(0 100% 0 0)';

        for (i = 0; i < BAR_COUNT; i++) {
            var h = Math.round(heights[i] * SVG_HEIGHT);
            var y = SVG_HEIGHT - h;
            var x = i * BAR_STEP;

            var bgRect = document.createElementNS(SVG_NS, 'rect');
            bgRect.setAttribute('x', x);
            bgRect.setAttribute('y', y);
            bgRect.setAttribute('width', BAR_WIDTH);
            bgRect.setAttribute('height', h);
            bgRect.setAttribute('rx', 1.5);
            bgGroup.appendChild(bgRect);

            var fgRect = document.createElementNS(SVG_NS, 'rect');
            fgRect.setAttribute('x', x);
            fgRect.setAttribute('y', y);
            fgRect.setAttribute('width', BAR_WIDTH);
            fgRect.setAttribute('height', h);
            fgRect.setAttribute('rx', 1.5);
            fgGroup.appendChild(fgRect);
        }

        svg.appendChild(bgGroup);
        svg.appendChild(fgGroup);
        container.appendChild(svg);

        return { svg: svg, fgGroup: fgGroup };
    }

    // --- Find audio element ---

    function findAudio(container) {
        var player = container.closest('.mementor-tts-player') ||
                     container.closest('#mementor-tts-sticky-footer') ||
                     container.closest('#tts-sticky-preview') ||
                     container.closest('.mementor-tts-player-container');
        if (player) {
            return player.querySelector('audio');
        }
        return null;
    }

    // --- Seek helpers ---

    function getSeekRatio(e, container) {
        var rect = container.getBoundingClientRect();
        var clientX = e.touches ? e.touches[0].clientX : e.clientX;
        var ratio = (clientX - rect.left) / rect.width;
        return Math.max(0, Math.min(1, ratio));
    }

    function updateClip(fgGroup, pct) {
        fgGroup.style.clipPath = 'inset(0 ' + (100 - pct) + '% 0 0)';
    }

    // --- Fallback to linear ---

    function fallbackToLinear(container) {
        while (container.firstChild) {
            container.removeChild(container.firstChild);
        }
        var bar = document.createElement('div');
        bar.className = 'mementor-tts-progress-bar';
        container.appendChild(bar);
        container.classList.remove('mementor-tts-waveform');
    }

    // --- Bind audio events and seek ---

    function bindAudio(audio, fgGroup, container) {
        audio.addEventListener('timeupdate', function() {
            if (!audio.duration) return;
            updateClip(fgGroup, (audio.currentTime / audio.duration) * 100);
        });

        audio.addEventListener('ended', function() {
            updateClip(fgGroup, 0);
        });

        // Click to seek
        container.addEventListener('click', function(e) {
            if (!audio.duration) return;
            audio.currentTime = getSeekRatio(e, container) * audio.duration;
        });

        // Drag to seek (desktop)
        var dragging = false;

        container.addEventListener('mousedown', function(e) {
            if (!audio.duration) return;
            dragging = true;
            e.preventDefault();
            audio.currentTime = getSeekRatio(e, container) * audio.duration;
        });

        document.addEventListener('mousemove', function(e) {
            if (!dragging || !audio.duration) return;
            var ratio = getSeekRatio(e, container);
            audio.currentTime = ratio * audio.duration;
            updateClip(fgGroup, ratio * 100);
        });

        document.addEventListener('mouseup', function() {
            dragging = false;
        });

        // Touch drag (mobile)
        container.addEventListener('touchstart', function(e) {
            if (!audio.duration) return;
            dragging = true;
            e.preventDefault();
            audio.currentTime = getSeekRatio(e, container) * audio.duration;
        }, { passive: false });

        document.addEventListener('touchmove', function(e) {
            if (!dragging || !audio.duration) return;
            var ratio = getSeekRatio(e, container);
            audio.currentTime = ratio * audio.duration;
            updateClip(fgGroup, ratio * 100);
        });

        document.addEventListener('touchend', function() {
            dragging = false;
        });
    }

    // --- Initialize one container ---

    function initWaveform(container) {
        try {
            // Skip if already initialized
            if (container.querySelector('.mementor-tts-waveform-svg')) return;

            var result = buildSVG(container);
            var fgGroup = result.fgGroup;
            var audio = findAudio(container);

            if (audio) {
                bindAudio(audio, fgGroup, container);
            }
        } catch (err) {
            fallbackToLinear(container);
        }
    }

    // --- Init all waveforms with lazy-load ---

    function init() {
        var containers = document.querySelectorAll('.mementor-tts-waveform');
        if (!containers.length) return;

        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        observer.unobserve(entry.target);
                        initWaveform(entry.target);
                    }
                });
            }, { rootMargin: '200px' });

            containers.forEach(function(c) { observer.observe(c); });
        } else {
            containers.forEach(function(c) { initWaveform(c); });
        }
    }

    // Expose for admin preview
    window.MementorTTSWaveform = { init: initWaveform };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
