// OurSong.jsx — chỉ là floating player ở góc, KHÔNG có section trên trang.
// Collapsed = pill nhỏ như AudioPlayer cũ · Expanded = panel có playlist + controls.

// ─── Inline SVG icons (dùng currentColor để đồng bộ màu site, không rơi vào
// font emoji hệ thống trên iOS/Android). ───────────────────────────────
const Ic = {
  Play: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="currentColor" aria-hidden="true">
      <path d="M7.5 5.2c0-.9 1-1.4 1.7-.9l10 6.8a1.1 1.1 0 0 1 0 1.8l-10 6.8c-.7.5-1.7 0-1.7-.9V5.2z"/>
    </svg>
  ),
  Pause: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="currentColor" aria-hidden="true">
      <rect x="6" y="4.5" width="4" height="15" rx="1.2"/>
      <rect x="14" y="4.5" width="4" height="15" rx="1.2"/>
    </svg>
  ),
  Prev: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="currentColor" aria-hidden="true">
      <rect x="5" y="5" width="2.6" height="14" rx="1"/>
      <path d="M20 6.1v11.8c0 .9-1 1.3-1.7.9l-8.8-5.9a1.1 1.1 0 0 1 0-1.8l8.8-5.9c.7-.5 1.7 0 1.7.9z"/>
    </svg>
  ),
  Next: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="currentColor" aria-hidden="true">
      <path d="M4 6.1v11.8c0 .9 1 1.3 1.7.9l8.8-5.9a1.1 1.1 0 0 0 0-1.8L5.7 5.2C5 4.8 4 5.2 4 6.1z"/>
      <rect x="16.4" y="5" width="2.6" height="14" rx="1"/>
    </svg>
  ),
  Chevron: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="none" stroke="currentColor" strokeWidth="2.2"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M9 6l6 6-6 6"/>
    </svg>
  ),
  Close: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="none" stroke="currentColor" strokeWidth="2"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M6 6l12 12M18 6L6 18"/>
    </svg>
  ),
  VolumeMute: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="none" stroke="currentColor" strokeWidth="1.8"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M4 9.5v5h3l5 3.8V5.7L7 9.5H4z" fill="currentColor" stroke="none"/>
      <path d="M16 10l5 4M21 10l-5 4"/>
    </svg>
  ),
  VolumeLow: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="none" stroke="currentColor" strokeWidth="1.8"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M4 9.5v5h3l5 3.8V5.7L7 9.5H4z" fill="currentColor" stroke="none"/>
      <path d="M15.8 9.6a4 4 0 0 1 0 4.8"/>
    </svg>
  ),
  VolumeHigh: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="none" stroke="currentColor" strokeWidth="1.8"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M4 9.5v5h3l5 3.8V5.7L7 9.5H4z" fill="currentColor" stroke="none"/>
      <path d="M15.8 9.6a4 4 0 0 1 0 4.8M18.5 7a7.5 7.5 0 0 1 0 10"/>
    </svg>
  ),
  Music: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 16} height={p.size || 16}
         fill="none" stroke="currentColor" strokeWidth="1.8"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M9 18V6l10-2v12"/>
      <circle cx="7" cy="18" r="2.2" fill="currentColor" stroke="none"/>
      <circle cx="17" cy="16" r="2.2" fill="currentColor" stroke="none"/>
    </svg>
  ),
};

function fmtTime(s) {
  if (!Number.isFinite(s) || s < 0) return '0:00';
  const m = Math.floor(s / 60);
  const ss = Math.floor(s % 60).toString().padStart(2, '0');
  return `${m}:${ss}`;
}

function OurSong() {
  const songs = (useLL('songs') || []).filter(s => s && s.audio);
  const audioRef = React.useRef(null);
  const [idx, setIdx] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);
  const [time, setTime] = React.useState(0);
  const [duration, setDuration] = React.useState(0);
  const [volume, setVolume] = React.useState(0.1);   // âm lượng khởi tạo 10%
  const [expanded, setExpanded] = React.useState(false);

  const current = songs[idx] || null;

  // Autoplay ngay khi mở site. Trình duyệt chặn autoplay có tiếng thì
  // fallback: chờ tương tác đầu tiên (click/touch/scroll/keydown) rồi play.
  React.useEffect(() => {
    if (!songs.length) return;
    const a = audioRef.current;
    if (!a) return;

    let armed = true;
    const tryPlay = () => {
      if (!armed) return;
      const p = a.play();
      if (p && typeof p.then === 'function') {
        p.then(() => { armed = false; setPlaying(true); cleanup(); })
         .catch(() => { /* chờ user gesture */ });
      }
    };
    const onGesture = () => { tryPlay(); };
    const cleanup = () => {
      window.removeEventListener('pointerdown', onGesture);
      window.removeEventListener('keydown', onGesture);
      window.removeEventListener('touchstart', onGesture);
      window.removeEventListener('scroll', onGesture);
    };

    tryPlay();
    window.addEventListener('pointerdown', onGesture, { once: false });
    window.addEventListener('keydown', onGesture, { once: false });
    window.addEventListener('touchstart', onGesture, { once: false, passive: true });
    window.addEventListener('scroll', onGesture, { once: false, passive: true });

    return () => { armed = false; cleanup(); };
  }, [songs.length]);

  // Playlist đổi → kéo idx về trong tầm
  React.useEffect(() => {
    if (idx >= songs.length) setIdx(0);
  }, [songs.length]);

  // Đổi src khi đổi bài
  React.useEffect(() => {
    const a = audioRef.current;
    if (!a || !current) return;
    if (a.src !== current.audio) {
      a.src = current.audio;
      a.load();
      if (playing) a.play().catch(() => setPlaying(false));
    }
  }, [current?.audio]);

  // Sync play/pause với element
  React.useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    if (playing) a.play().catch(() => setPlaying(false));
    else a.pause();
  }, [playing]);

  // Áp dụng volume
  React.useEffect(() => {
    const a = audioRef.current;
    if (a) a.volume = volume;
  }, [volume]);

  const toggle = () => setPlaying(p => !p);
  const next = () => { if (!songs.length) return; setIdx(i => (i + 1) % songs.length); setPlaying(true); };
  const prev = () => { if (!songs.length) return; setIdx(i => (i - 1 + songs.length) % songs.length); setPlaying(true); };
  const select = (i) => {
    if (i === idx) { setPlaying(p => !p); return; }
    setIdx(i); setPlaying(true);
  };
  const seek = (v) => {
    const a = audioRef.current;
    if (!a || !Number.isFinite(duration)) return;
    a.currentTime = (v / 100) * duration;
    setTime(a.currentTime);
  };

  if (!songs.length) return null;

  return (
    <>
      <audio
        ref={audioRef}
        preload="metadata"
        onTimeUpdate={e => setTime(e.currentTarget.currentTime)}
        onLoadedMetadata={e => setDuration(e.currentTarget.duration)}
        onEnded={next}
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
      />

      {ReactDOM.createPortal(
        expanded ? (
          <SongPanel
            songs={songs}
            idx={idx}
            current={current}
            playing={playing}
            time={time}
            duration={duration}
            volume={volume}
            onCollapse={() => setExpanded(false)}
            onToggle={toggle}
            onNext={next}
            onPrev={prev}
            onSelect={select}
            onSeek={seek}
            onVolume={setVolume}
          />
        ) : (
          <SongPill
            song={current}
            playing={playing}
            onExpand={() => setExpanded(true)}
            onToggle={toggle}
            onNext={next}
          />
        ),
        document.body
      )}
    </>
  );
}

// ─── Collapsed pill ──────────────────────────────────────────────
function SongPill({ song, playing, onExpand, onToggle, onNext }) {
  if (!song) return null;
  return (
    <div className="song-pill" onClick={onExpand} role="button" aria-label="Mở trình phát nhạc">
      <div className={`song-pill-cover ${playing ? 'spinning' : ''}`}>
        {song.cover
          ? <img src={song.cover} alt=""/>
          : <span className="song-pill-fallback"><Ic.Music size={18}/></span>}
      </div>
      <div className="song-pill-text">
        <div className="song-pill-title">{song.title || 'Our Song'}</div>
        <div className="song-pill-artist">
          {playing ? 'now playing' : (song.artist || 'tap to play')}
        </div>
      </div>
      <div className="song-pill-ctrls">
        <button type="button" className="primary"
          onClick={(e) => { e.stopPropagation(); onToggle(); }}
          aria-label={playing ? 'Tạm dừng' : 'Phát'}>
          {playing ? <Ic.Pause size={13}/> : <Ic.Play size={13}/>}
        </button>
        <button type="button"
          onClick={(e) => { e.stopPropagation(); onNext(); }}
          aria-label="Bài kế"><Ic.Chevron size={16}/></button>
      </div>
    </div>
  );
}

// ─── Expanded panel ──────────────────────────────────────────────
function SongPanel({
  songs, idx, current, playing, time, duration, volume,
  onCollapse, onToggle, onNext, onPrev, onSelect, onSeek, onVolume,
}) {
  const seekPct = duration ? (time / duration) * 100 : 0;

  return (
    <>
      <div className="song-panel-backdrop" onClick={onCollapse}/>

      <div className="song-panel" role="dialog" aria-label="Trình phát nhạc">
        <div className="song-panel-head">
          <div className="song-panel-eyebrow">Our Song ♪</div>
          <button type="button" className="song-panel-close"
            onClick={onCollapse} aria-label="Thu gọn"><Ic.Close size={16}/></button>
        </div>

        <div className="song-panel-body">
          <div className={`song-vinyl ${playing ? 'spinning' : ''}`}>
            <div className="song-vinyl-grooves"/>
            <div className="song-cover">
              {current?.cover ? (
                <img src={current.cover} alt="" draggable={false}/>
              ) : (
                <div className="song-cover-fallback">
                  <img src="assets/icons/heart-solid.svg" alt=""/>
                </div>
              )}
            </div>
            <div className="song-vinyl-center"/>
          </div>

          <div className="song-title">{current?.title || '—'}</div>
          <div className="song-artist">{current?.artist || ''}</div>

          <div className="song-seekbar">
            <input
              type="range" min={0} max={100} step={.1}
              value={seekPct}
              onChange={e => onSeek(parseFloat(e.target.value))}
              aria-label="Tua nhạc"
              style={{ '--v': `${seekPct}%` }}
            />
            <div className="song-time">
              <span>{fmtTime(time)}</span>
              <span>{fmtTime(duration)}</span>
            </div>
          </div>

          <div className="song-controls">
            <button type="button" className="song-ctrl" onClick={onPrev} aria-label="Bài trước">
              <Ic.Prev size={16}/>
            </button>
            <button type="button" className="song-ctrl song-play" onClick={onToggle}
              aria-label={playing ? 'Tạm dừng' : 'Phát'}>
              {playing ? <Ic.Pause size={18}/> : <Ic.Play size={18}/>}
            </button>
            <button type="button" className="song-ctrl" onClick={onNext} aria-label="Bài kế">
              <Ic.Next size={16}/>
            </button>
          </div>

          <div className="song-volume">
            <span aria-hidden="true" className="song-volume-icon">
              {volume === 0
                ? <Ic.VolumeMute size={18}/>
                : volume < 0.5
                  ? <Ic.VolumeLow size={18}/>
                  : <Ic.VolumeHigh size={18}/>}
            </span>
            <input
              type="range" min={0} max={1} step={.01}
              value={volume}
              onChange={e => onVolume(parseFloat(e.target.value))}
              aria-label="Âm lượng"
              style={{ '--v': `${volume * 100}%` }}
            />
            <span className="song-volume-val">{Math.round(volume * 100)}%</span>
          </div>
        </div>

        {songs.length > 1 && (
          <div className="song-playlist">
            <div className="song-playlist-label">Danh sách</div>
            <div className="song-playlist-scroll">
              {songs.map((s, i) => (
                <button key={s.id || s.audio || i} type="button"
                  className={`song-item ${i === idx ? 'active' : ''}`}
                  onClick={() => onSelect(i)}>
                  <div className="song-item-num">
                    {i === idx && playing ? (
                      <div className="song-bars" aria-hidden="true">
                        <span/><span/><span/>
                      </div>
                    ) : (
                      String(i + 1).padStart(2, '0')
                    )}
                  </div>
                  <div className="song-item-cover">
                    {s.cover
                      ? <img src={s.cover} alt=""/>
                      : <img src="assets/icons/heart-outline.svg" alt="" style={{ width: 20, height: 20, opacity: .6 }}/>}
                  </div>
                  <div className="song-item-text">
                    <div className="song-item-title">{s.title || 'Untitled'}</div>
                    <div className="song-item-artist">{s.artist || '—'}</div>
                  </div>
                  <div className="song-item-icon">
                    {i === idx && playing ? <Ic.Pause size={12}/> : <Ic.Play size={12}/>}
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </>
  );
}

window.OurSong = OurSong;
