/* global React */
// TrackPlayer.jsx — Feature 7: bottom player + download

const { useMemo: useMemoP } = React;

function seeded(seed) {
  let s = seed >>> 0;
  return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 0xFFFFFFFF; };
}
function genWaveform(seed, n = 180) {
  const r = seeded(seed);
  const arr = [];
  for (let i = 0; i < n; i++) {
    const t = i / n;
    const env = Math.sin(t * Math.PI) * 0.6 + 0.25;
    const v = (0.35 + r() * 0.65) * env + r() * 0.1;
    arr.push(Math.max(0.08, Math.min(1, v)));
  }
  return arr;
}
function fmtTime(sec) {
  sec = Math.max(0, Math.floor(sec));
  return `${Math.floor(sec/60)}:${(sec%60).toString().padStart(2,'0')}`;
}

function TrackPlayer({ track, playing, progress, onPlay, onSeek, canGenerate, onGenerate, onDownload }) {
  const empty = useMemoP(() => genWaveform(7, 180), []);
  const bars = track?.waveform || empty;
  const dur = track?.length || 0;

  return (
    <div className="player">
      <div className="transport">
        <button className={`play-circ${!track ? ' empty' : ''}`}
                onClick={track ? onPlay : undefined}
                title={track ? (playing ? 'Pause' : 'Play') : 'Generate first'}>
          {playing ? (
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <rect x="4" y="3" width="3" height="10" rx=".5"/><rect x="9" y="3" width="3" height="10" rx=".5"/>
            </svg>
          ) : (
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M5 3.5v9a.5.5 0 00.77.42l7-4.5a.5.5 0 000-.84l-7-4.5A.5.5 0 005 3.5z"/>
            </svg>
          )}
        </button>
        <div className="track-meta">
          <div className="ttl">{track?.title || 'No song yet'}</div>
          <div className="sub">{track?.sub || 'Lyrics → Structure → Style → Generate'}</div>
        </div>
      </div>

      <div className="wave-wrap" style={{ opacity: track ? 1 : .35 }}>
        <PlayerWave bars={bars} progress={progress} onSeek={track ? onSeek : () => {}} />
      </div>

      <span className="timecode">
        {track
          ? <><b>{fmtTime(progress * dur)}</b> / {fmtTime(dur)}</>
          : '—:— / —:—'}
      </span>

      <div className="player-actions">
        <button className="iconbtn" disabled={!track} onClick={onDownload} title="Download MP3">
          <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round">
            <path d="M6.5 2v6.5M6.5 8.5L4 6M6.5 8.5L9 6M2.5 9.5v1.5h8V9.5"/>
          </svg>
        </button>
        <button className="iconbtn" disabled={!track} title="Share">
          <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round">
            <circle cx="3.5" cy="6.5" r="1.5"/><circle cx="9.5" cy="3" r="1.5"/><circle cx="9.5" cy="10" r="1.5"/>
            <path d="M5 5.7l3-1.7M5 7.3l3 1.7"/>
          </svg>
        </button>
        <button className="gen-btn" onClick={onGenerate} disabled={!canGenerate}>
          <span className="star">✦</span>
          {track ? 'Regenerate' : 'Generate'}
        </button>
      </div>
    </div>
  );
}

function PlayerWave({ bars, progress, onSeek }) {
  const ref = React.useRef(null);
  const click = (e) => {
    const r = ref.current.getBoundingClientRect();
    const p = (e.clientX - r.left) / r.width;
    onSeek(Math.max(0, Math.min(1, p)));
  };
  return (
    <div ref={ref} className="player-wave" onClick={click}>
      {bars.map((h, i) => {
        const p = i / bars.length;
        const nearNow = Math.abs(p - progress) < 0.006;
        const isPast = p < progress;
        return <div key={i} className={`bar ${nearNow ? 'now' : isPast ? 'past' : ''}`} style={{ height: `${h * 100}%` }} />;
      })}
    </div>
  );
}

function GenerationOverlay({ step }) {
  const steps = [
    'Reading the structured XML',
    'Selecting the raga & taal',
    'Voicing the singer',
    'Layering instruments',
    'Mixing and mastering',
    'Rendering audio',
  ];
  return (
    <div className="gen-overlay">
      <div className="gen-card">
        <div className="spin" />
        <div className="ttl">Composing</div>
        <div className="sub">Lyria 3 Pro is arranging your song</div>
        <div className="gen-steps">
          {steps.map((s, i) => (
            <div key={s} className={`gen-step ${i < step ? 'done' : i === step ? 'active' : ''}`}>
              <span className="tick">
                {i < step && <svg width="7" height="7" viewBox="0 0 8 8" fill="none" stroke="#fff" strokeWidth="1.6"><path d="M1.5 4l1.5 1.5L6.5 2"/></svg>}
              </span>
              {s}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.TrackPlayer = TrackPlayer;
window.GenerationOverlay = GenerationOverlay;
window.genWaveform = genWaveform;
window.fmtTime = fmtTime;
