function MusicPlayer() {
  const TRACKS = [
    { src: 'track-3.mp3', name: 'خرطوم ياريتكو' },   // opener
    { src: 'track-1.mp3', name: 'خرطوم مسموع'  },
    { src: 'track-4.mp3', name: 'خرطوم واحد'   },
  ];

  const audioRef = React.useRef(null);
  const rootRef  = React.useRef(null);
  const { t } = React.useContext(LangContext);

  const [track, setTrack] = React.useState(() => {
    const saved = parseInt(localStorage.getItem('music_track') || '0', 10);
    return Number.isFinite(saved) && saved >= 0 && saved < 3 ? saved : 0;
  });
  const [playing, setPlaying] = React.useState(false);
  const [volume, setVolume] = React.useState(() => {
    const saved = parseFloat(localStorage.getItem('music_vol'));
    return Number.isFinite(saved) ? Math.max(0, Math.min(1, saved)) : 0.6;
  });
  const [locked, setLocked]     = React.useState(false);
  const [expanded, setExpanded] = React.useState(false);
  const [curTime, setCurTime]   = React.useState(0);
  const [duration, setDuration] = React.useState(0);
  const [speed, setSpeed]       = React.useState(() => {
    const saved = parseFloat(localStorage.getItem('music_speed'));
    return [1, 1.5, 2].includes(saved) ? saved : 1;
  });

  React.useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    audio.volume = volume;
    audio.playbackRate = speed;
    audio.loop = false;

    let cancelled = false;
    const tryPlay = () => audio.play();

    tryPlay()
      .then(() => { if (!cancelled) { setPlaying(true); setLocked(false); } })
      .catch(() => {
        if (cancelled) return;
        setLocked(true);
        const unlock = () => {
          audio.play()
            .then(() => { setPlaying(true); setLocked(false); })
            .catch(() => {});
          window.removeEventListener('click',      unlock, true);
          window.removeEventListener('keydown',    unlock, true);
          window.removeEventListener('touchstart', unlock, true);
        };
        window.addEventListener('click',      unlock, true);
        window.addEventListener('keydown',    unlock, true);
        window.addEventListener('touchstart', unlock, true);
      });

    const onPause = () => setPlaying(false);
    const onPlay  = () => setPlaying(true);
    const onEnded = () => setTrack((i) => (i + 1) % TRACKS.length);
    const onTime  = () => setCurTime(audio.currentTime || 0);
    const onMeta  = () => setDuration(audio.duration || 0);
    setCurTime(0);
    setDuration(0);
    audio.addEventListener('pause',          onPause);
    audio.addEventListener('play',           onPlay);
    audio.addEventListener('ended',          onEnded);
    audio.addEventListener('timeupdate',     onTime);
    audio.addEventListener('loadedmetadata', onMeta);
    audio.addEventListener('durationchange', onMeta);

    return () => {
      cancelled = true;
      audio.removeEventListener('pause',          onPause);
      audio.removeEventListener('play',           onPlay);
      audio.removeEventListener('ended',          onEnded);
      audio.removeEventListener('timeupdate',     onTime);
      audio.removeEventListener('loadedmetadata', onMeta);
      audio.removeEventListener('durationchange', onMeta);
    };
  }, [track]);

  React.useEffect(() => {
    if (audioRef.current) audioRef.current.volume = volume;
    localStorage.setItem('music_vol', String(volume));
  }, [volume]);

  React.useEffect(() => {
    localStorage.setItem('music_track', String(track));
  }, [track]);

  React.useEffect(() => {
    if (audioRef.current) audioRef.current.playbackRate = speed;
    localStorage.setItem('music_speed', String(speed));
  }, [speed]);

  React.useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    let didWePause = false;
    const onOpen = () => {
      if (!audio.paused) {
        audio.pause();
        didWePause = true;
      }
    };
    const onClose = () => {
      if (didWePause) {
        audio.play().then(() => setPlaying(true)).catch(() => {});
        didWePause = false;
      }
    };
    window.addEventListener('memorial:open',  onOpen);
    window.addEventListener('memorial:close', onClose);
    return () => {
      window.removeEventListener('memorial:open',  onOpen);
      window.removeEventListener('memorial:close', onClose);
    };
  }, []);

  React.useEffect(() => {
    if (!expanded) return;
    const onKey = (e) => { if (e.key === 'Escape') setExpanded(false); };
    const onDown = (e) => {
      if (rootRef.current && !rootRef.current.contains(e.target)) setExpanded(false);
    };
    window.addEventListener('keydown', onKey);
    window.addEventListener('mousedown', onDown);
    window.addEventListener('touchstart', onDown, { passive: true });
    return () => {
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('mousedown', onDown);
      window.removeEventListener('touchstart', onDown);
    };
  }, [expanded]);

  const togglePlay = () => {
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) { audio.pause(); setPlaying(false); }
    else { audio.play().then(() => setPlaying(true)).catch(() => {}); }
    window.__playClick?.();
  };

  const pickTrack = (i) => {
    setTrack(i);
    window.__playClick?.();
  };

  const nextTrack = () => { setTrack((i) => (i + 1) % TRACKS.length); window.__playClick?.(); };
  const prevTrack = () => { setTrack((i) => (i - 1 + TRACKS.length) % TRACKS.length); window.__playClick?.(); };

  const SPEEDS = [1, 1.5, 2];
  const cycleSpeed = () => {
    setSpeed((s) => {
      const i = SPEEDS.indexOf(s);
      return SPEEDS[(i + 1) % SPEEDS.length];
    });
    window.__playClick?.();
  };
  const speedLabel = (s) => `${Number.isInteger(s) ? s : s.toFixed(1)}x`;

  const stepVol = (delta) => {
    setVolume((v) => {
      const next = Math.max(0, Math.min(1, v + delta));
      return Math.round(next * 10) / 10;
    });
    window.__playClick?.();
  };

  const fmtTime = (s) => {
    if (!Number.isFinite(s) || s < 0) return '0:00';
    const m = Math.floor(s / 60);
    const sec = Math.floor(s % 60);
    return `${m}:${sec < 10 ? '0' : ''}${sec}`;
  };

  const onProgressClick = (e) => {
    const audio = audioRef.current;
    if (!audio || !Number.isFinite(duration) || duration <= 0) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const pct = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    audio.currentTime = pct * duration;
    setCurTime(audio.currentTime);
    window.__playClick?.();
  };

  const onVolBarClick = (e) => {
    const el = e.currentTarget;
    const rect = el.getBoundingClientRect();
    const pct = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    setVolume(Math.round(pct * 10) / 10);
    window.__playClick?.();
  };

  const toggleExpand = () => {
    setExpanded((v) => !v);
    window.__playClick?.();
  };

  const cur = TRACKS[track];
  const pct = Math.round(volume * 100);
  const muted = volume === 0;
  const hint = (t && t.musicTapToPlay) || '♪ TAP TO PLAY';

  const progressPct = duration > 0 ? Math.min(100, (curTime / duration) * 100) : 0;
  const remaining   = duration > 0 ? Math.max(0, duration - curTime) : 0;

  return (
    <div
      ref={rootRef}
      className={`music-player ${playing ? 'is-playing' : 'is-paused'} ${locked ? 'is-locked' : ''} ${muted ? 'is-muted' : ''} ${expanded ? 'is-open' : 'is-closed'}`}
    >
      <audio ref={audioRef} src={cur.src} loop preload="auto" />

      {locked && !expanded && <span className="music-player__hint mono">{hint}</span>}

      <button
        type="button"
        className="music-player__fab"
        onClick={toggleExpand}
        onMouseEnter={() => window.__playHover?.()}
        data-hover
        aria-label={expanded ? 'Close music player' : 'Open music player'}
        aria-expanded={expanded}
        title={expanded ? 'Close' : cur.name}
      >
        <span className="music-player__fab-ring" aria-hidden="true" />
        <span className="music-player__fab-core">
          {playing ? (
            <span className="music-player__eq" aria-hidden="true">
              <span></span><span></span><span></span><span></span>
            </span>
          ) : (
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M8 5v14l11-7z"/>
            </svg>
          )}
        </span>
      </button>

      <div className="music-player__panel" role="dialog" aria-label="Music player" aria-hidden={!expanded}>
        <div className="music-player__panel-head">
          <span className="music-player__panel-kicker mono">NOW PLAYING</span>
          <button
            type="button"
            className="music-player__close"
            onClick={() => { setExpanded(false); window.__playClick?.(); }}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label="Close"
            title="Close"
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M6 6l12 12M18 6L6 18"/>
            </svg>
          </button>
        </div>

        <div className="music-player__now">
          <span className="music-player__now-title">{cur.name}</span>
          <span className="music-player__now-meta mono">
            TRACK {String(track + 1).padStart(2, '0')} / {String(TRACKS.length).padStart(2, '0')}
          </span>
        </div>

        <div className="music-player__progress">
          <div
            className="music-player__progress-bar"
            role="slider"
            tabIndex={0}
            aria-label="Track progress"
            aria-valuemin="0"
            aria-valuemax={Math.round(duration) || 0}
            aria-valuenow={Math.round(curTime) || 0}
            onClick={onProgressClick}
            onKeyDown={(e) => {
              const audio = audioRef.current;
              if (!audio || !Number.isFinite(duration) || duration <= 0) return;
              if (e.key === 'ArrowLeft')  { e.preventDefault(); audio.currentTime = Math.max(0, audio.currentTime - 5); }
              if (e.key === 'ArrowRight') { e.preventDefault(); audio.currentTime = Math.min(duration, audio.currentTime + 5); }
            }}
            title="Seek"
          >
            <div className="music-player__progress-fill" style={{ width: `${progressPct}%` }} />
            <div className="music-player__progress-thumb" style={{ left: `${progressPct}%` }} />
          </div>
          <div className="music-player__times mono">
            <span className="music-player__time">{fmtTime(curTime)}</span>
            <span className="music-player__time music-player__time--rem">-{fmtTime(remaining)}</span>
          </div>
        </div>

        <div className="music-player__controls">
          <button
            type="button"
            className="music-player__ctrl"
            onClick={prevTrack}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label="Previous track"
            title="Previous"
          >
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M6 5h2v14H6zM20 5v14l-11-7z"/>
            </svg>
          </button>

          <button
            type="button"
            className="music-player__play"
            onClick={togglePlay}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label={playing ? 'Pause music' : 'Play music'}
            title={playing ? 'Pause' : 'Play'}
          >
            {playing ? (
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <rect x="6"  y="5" width="4" height="14" rx="1"/>
                <rect x="14" y="5" width="4" height="14" rx="1"/>
              </svg>
            ) : (
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M8 5v14l11-7z"/>
              </svg>
            )}
          </button>

          <button
            type="button"
            className="music-player__ctrl"
            onClick={nextTrack}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label="Next track"
            title="Next"
          >
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <path d="M16 5h2v14h-2zM4 5v14l11-7z"/>
            </svg>
          </button>

          <button
            type="button"
            className={`music-player__speed mono ${speed === 1 ? '' : 'is-boosted'}`}
            onClick={cycleSpeed}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label={`Playback speed ${speedLabel(speed)}, click to change`}
            title={`Speed · ${speedLabel(speed)}`}
          >
            {speedLabel(speed)}
          </button>
        </div>

        <div className="music-player__vol">
          <button
            type="button"
            className="music-player__vol-btn"
            onClick={() => stepVol(-0.1)}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label="Volume down"
            title="Volume down"
          >
            {muted ? (
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M11 5 6 9H3v6h3l5 4z"/><path d="M22 9l-6 6M16 9l6 6"/>
              </svg>
            ) : (
              <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <rect x="5" y="11" width="14" height="2" rx="1"/>
              </svg>
            )}
          </button>

          <div
            className="music-player__vol-bar"
            role="slider"
            tabIndex={0}
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow={pct}
            aria-label={`Volume ${pct}%`}
            title={`${pct}%`}
            onClick={onVolBarClick}
            onKeyDown={(e) => {
              if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { e.preventDefault(); stepVol(-0.1); }
              if (e.key === 'ArrowRight' || e.key === 'ArrowUp')  { e.preventDefault(); stepVol(+0.1); }
            }}
          >
            <div className="music-player__vol-fill" style={{ width: `${pct}%` }} />
            <div className="music-player__vol-thumb" style={{ left: `${pct}%` }} />
          </div>

          <button
            type="button"
            className="music-player__vol-btn"
            onClick={() => stepVol(0.1)}
            onMouseEnter={() => window.__playHover?.()}
            data-hover
            aria-label="Volume up"
            title="Volume up"
          >
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
              <rect x="5"  y="11" width="14" height="2" rx="1"/>
              <rect x="11" y="5"  width="2"  height="14" rx="1"/>
            </svg>
          </button>

          <span className="music-player__vol-pct mono">{pct}%</span>
        </div>

        <ul className="music-player__list">
          {TRACKS.map((tr, i) => (
            <li key={tr.src}>
              <button
                type="button"
                className={`music-player__item ${i === track ? 'is-active' : ''}`}
                onClick={() => pickTrack(i)}
                onMouseEnter={() => window.__playHover?.()}
                data-hover
                aria-current={i === track ? 'true' : 'false'}
                title={tr.name}
              >
                <span className="music-player__item-num mono">
                  {String(i + 1).padStart(2, '0')}
                </span>
                <span className="music-player__item-name">{tr.name}</span>
                <span className="music-player__item-state" aria-hidden="true">
                  {i === track && playing ? (
                    <span className="music-player__eq music-player__eq--sm">
                      <span></span><span></span><span></span>
                    </span>
                  ) : i === track ? (
                    <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                      <path d="M8 5v14l11-7z"/>
                    </svg>
                  ) : null}
                </span>
              </button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

window.MusicPlayer = MusicPlayer;
