'use client';

import { useState, useRef, useEffect } from 'react';

interface AudioPlayerProps {
    src: string;
    unlockedSeconds: number; // 2, 4, 7, 11, 16, 30 (or full length)
    startTime?: number; // Start offset in seconds (for curated specials)
    onPlay?: () => void;
    onReplay?: () => void;
    autoPlay?: boolean;
}

export default function AudioPlayer({ src, unlockedSeconds, startTime = 0, onPlay, onReplay, autoPlay = false }: AudioPlayerProps) {
    const audioRef = useRef<HTMLAudioElement>(null);
    const [isPlaying, setIsPlaying] = useState(false);
    const [progress, setProgress] = useState(0);
    const [hasPlayedOnce, setHasPlayedOnce] = useState(false);

    useEffect(() => {
        if (audioRef.current) {
            audioRef.current.pause();
            audioRef.current.currentTime = startTime;
            setIsPlaying(false);
            setProgress(0);
            setHasPlayedOnce(false); // Reset for new segment

            if (autoPlay) {
                const playPromise = audioRef.current.play();
                if (playPromise !== undefined) {
                    playPromise
                        .then(() => {
                            setIsPlaying(true);
                            onPlay?.();
                            setHasPlayedOnce(true);
                        })
                        .catch(error => {
                            console.log("Autoplay prevented:", error);
                            setIsPlaying(false);
                        });
                }
            }
        }
    }, [src, unlockedSeconds, startTime, autoPlay]);

    const togglePlay = () => {
        if (!audioRef.current) return;

        if (isPlaying) {
            audioRef.current.pause();
        } else {
            audioRef.current.play();
            onPlay?.();

            if (hasPlayedOnce) {
                onReplay?.();
            } else {
                setHasPlayedOnce(true);
            }
        }
        setIsPlaying(!isPlaying);
    };

    const handleTimeUpdate = () => {
        if (!audioRef.current) return;

        const current = audioRef.current.currentTime;
        const elapsed = current - startTime;
        const percent = (elapsed / unlockedSeconds) * 100;
        setProgress(Math.min(percent, 100));

        if (elapsed >= unlockedSeconds) {
            audioRef.current.pause();
            audioRef.current.currentTime = startTime;
            setIsPlaying(false);
            setProgress(0);
        }
    };

    return (
        <div className="audio-player">
            <audio
                ref={audioRef}
                src={src}
                onTimeUpdate={handleTimeUpdate}
                onEnded={() => setIsPlaying(false)}
            />

            <div className="player-controls">
                <button onClick={togglePlay} className="play-button">
                    {isPlaying ? (
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" width="24" height="24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5" />
                        </svg>
                    ) : (
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" width="24" height="24" style={{ marginLeft: '4px' }}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z" />
                        </svg>
                    )}
                </button>

                <div className="progress-bar-container">
                    <div
                        className="progress-bar"
                        style={{ width: `${progress}%` }}
                    />
                </div>

                <div style={{ fontFamily: 'monospace', fontSize: '0.875rem', color: '#4b5563' }}>
                    {unlockedSeconds}s
                </div>
            </div>
        </div>
    );
}
