/**
 * waveformPlayer  — Alpine.js data component
 *
 * Usage:
 *   <div x-data="waveformPlayer('{{ route('recordings.stream', $rec) }}')"
 *        x-init="init()" @destroy="cleanup()">
 *     …
 *   </div>
 *
 * WaveSurfer is dynamically imported the first time the user clicks play,
 * so it never adds to the initial JS bundle weight.
 */
export function waveformPlayer(audioUrl) {
    return {
        audioUrl,

        // ── State ────────────────────────────────────────────────────────────
        ws:          null,   // WaveSurfer instance
        playing:     false,
        loading:     false,
        ready:       false,
        error:       false,
        currentTime: '00:00',
        totalTime:   '00:00',

        // ── Lifecycle ────────────────────────────────────────────────────────

        init() {
            // Return a cleanup fn — Alpine.js v3 calls this when the element
            // is removed from the DOM, ensuring WaveSurfer is properly destroyed.
            return () => this.cleanup();
        },

        cleanup() {
            if (this.ws) {
                try { this.ws.destroy(); } catch { /* ignore */ }
                this.ws = null;
            }
        },

        // ── Public API ───────────────────────────────────────────────────────

        async toggle() {
            if (this.error) return;

            if (!this.ws) {
                await this._setup();
            }

            if (!this.ready) return;  // still loading

            this.ws.playPause();
            this.playing = this.ws.isPlaying();
        },

        // ── Internal ─────────────────────────────────────────────────────────

        async _setup() {
            this.loading = true;

            try {
                const { default: WaveSurfer } = await import('wavesurfer.js');

                this.ws = WaveSurfer.create({
                    container:     this.$refs.waveform,
                    url:           this.audioUrl,
                    waveColor:     '#94a3b8',
                    progressColor: '#2563eb',
                    cursorColor:   '#2563eb',
                    height:        28,
                    barWidth:      2,
                    barGap:        1,
                    barRadius:     2,
                    normalize:     true,
                    interact:      true,
                });

                this.ws.on('ready', () => {
                    this.ready    = true;
                    this.loading  = false;
                    this.totalTime = this._fmt(this.ws.getDuration());

                    // Auto-play once loaded (user already clicked)
                    this.ws.play();
                    this.playing = true;
                });

                this.ws.on('timeupdate', (t) => {
                    this.currentTime = this._fmt(t);
                });

                this.ws.on('seeking', (t) => {
                    this.currentTime = this._fmt(t);
                });

                this.ws.on('finish', () => {
                    this.playing = false;
                });

                this.ws.on('error', (err) => {
                    console.error('[WaveSurfer]', err);
                    this.loading = false;
                    this.error   = true;
                });

            } catch (err) {
                console.error('[waveformPlayer] Failed to load WaveSurfer:', err);
                this.loading = false;
                this.error   = true;
            }
        },

        _fmt(seconds) {
            const s = Math.floor(seconds ?? 0);
            return String(Math.floor(s / 60)).padStart(2, '0')
                 + ':' + String(s % 60).padStart(2, '0');
        },
    };
}
