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

/* ─────────────────────────────────────────────
   유틸
───────────────────────────────────────────── */
const pad = (n) => String(Math.floor(n)).padStart(2, '0');
export const fmtTime = (s) => `${pad(s / 60)}:${pad(s % 60)}`;

/* ─────────────────────────────────────────────
   Audio Player (실제 <audio> 기반)
───────────────────────────────────────────── */
const AudioPlayer = ({ audioUrl, totalSec, accentColor }) => {
    const audioRef   = useRef(null);
    const [playing, setPlaying]   = useState(false);
    const [elapsed, setElapsed]   = useState(0);
    const [duration, setDuration] = useState(totalSec ?? 0);
    const [volume, setVolume]     = useState(1);

    /* 실제 오디오가 없으면 가짜 타이머로 폴백 */
    const isFake = !audioUrl;
    const timerRef = useRef(null);

    const total = duration || totalSec || 60;

    const togglePlay = () => {
        if (isFake) {
            if (playing) {
                clearInterval(timerRef.current);
                setPlaying(false);
            } else {
                setPlaying(true);
                timerRef.current = setInterval(() => {
                    setElapsed((e) => {
                        if (e >= total - 1) {
                            clearInterval(timerRef.current);
                            setPlaying(false);
                            return 0;
                        }
                        return e + 1;
                    });
                }, 1000);
            }
            return;
        }
        const el = audioRef.current;
        if (!el) return;
        playing ? el.pause() : el.play();
    };

    const handleSeek = (e) => {
        const rect  = e.currentTarget.getBoundingClientRect();
        const ratio = (e.clientX - rect.left) / rect.width;
        const newTime = ratio * total;
        if (!isFake && audioRef.current) {
            audioRef.current.currentTime = newTime;
        }
        setElapsed(newTime);
    };

    const handleVolumeChange = (e) => {
        const v = Number(e.target.value);
        setVolume(v);
        if (!isFake && audioRef.current) audioRef.current.volume = v;
    };

    useEffect(() => () => clearInterval(timerRef.current), []);

    const progress = (elapsed / total) * 100;

    return (
        <div className="ms-audio-player" style={{ '--player-accent': accentColor }}>
            {!isFake && (
                <audio
                    ref={audioRef}
                    src={audioUrl}
                    onLoadedMetadata={(e) => setDuration(e.target.duration)}
                    onTimeUpdate={(e) => setElapsed(e.target.currentTime)}
                    onPlay={() => setPlaying(true)}
                    onPause={() => setPlaying(false)}
                    onEnded={() => { setPlaying(false); setElapsed(0); }}
                />
            )}
            <button
                type="button"
                className={`ms-player__play ${playing ? 'is-playing' : ''}`}
                onClick={togglePlay}
                aria-label={playing ? '일시정지' : '재생'}
            >
                {playing ? (
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                        <rect x="3" y="2" width="4" height="12" rx="1" />
                        <rect x="9" y="2" width="4" height="12" rx="1" />
                    </svg>
                ) : (
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                        <path d="M4 2l10 6-10 6V2z" />
                    </svg>
                )}
            </button>

            <div className="ms-player__timeline">
                <div className="ms-player__bar" onClick={handleSeek} role="slider"
                     aria-label="재생 위치" aria-valuenow={Math.round(elapsed)} aria-valuemin={0} aria-valuemax={Math.round(total)}>
                    <div className="ms-player__fill" style={{ width: `${progress}%` }} />
                    <div className="ms-player__thumb" style={{ left: `${progress}%` }} />
                </div>
                <div className="ms-player__times">
                    <span>{fmtTime(elapsed)}</span>
                    <span>{fmtTime(total)}</span>
                </div>
            </div>

            <div className="ms-volume">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden>
                    <path d="M2 5h2.5l3-3v10l-3-3H2V5zm8.5-1.5a4.5 4.5 0 010 7" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round"/>
                </svg>
                <input
                    type="range" min={0} max={1} step={0.02} value={volume}
                    onChange={handleVolumeChange}
                    className="ms-volume__slider"
                    aria-label="볼륨"
                />
            </div>
        </div>
    );
};

export default AudioPlayer;
