// Chapter — Sound Studio.
// Six of the nine picks from the Capabilities page, same cards and same
// transport, plus a link straight into the Sound tab of the studio.
//
// 🔊 SWAPPING THESE: edit EX_SOUND_PICKS. `file` is anything in
// public/product-studio/music-samples/, `img` any still in
// public/product-studio/sound-studio/.
//
// ⚠️ `file` and `img` are separate on purpose: the two folders DISAGREE on slugs.
// Samples are hyphenated from the label (night-drive-1.mp3, wide-open-1.mp3),
// stills come from the id and are not (nightdrive.webp, wideopen.webp).
const EX_SOUND_PICKS = [
  { name: 'Afterhours',  desc: 'Last train, lights low',       file: 'afterhours-1.mp3',  img: 'afterhours' },
  { name: 'Smoke',       desc: 'Low, smoky, half spoken',      file: 'smoke-1.mp3',       img: 'smoke' },
  { name: 'Wide Open',   desc: 'Dusty guitar, big sky',        file: 'wide-open-1.mp3',   img: 'wideopen' },
  { name: 'Night Drive', desc: 'Fast, smooth, propulsive',     file: 'night-drive-1.mp3', img: 'nightdrive' },
  { name: 'Acid',        desc: 'Squelching, a little menacing', file: 'acid-1.mp3',       img: 'acid' },
  { name: 'Steppers',    desc: 'Skipping drums, deep bass',    file: 'steppers-1.mp3',    img: 'steppers' },
];

function exFmtClock(t) {
  if (!t || !isFinite(t)) return '0:00';
  var m = Math.floor(t / 60), s = Math.floor(t % 60);
  return m + ':' + (s < 10 ? '0' : '') + s;
}

function ExSound() {
  // One <audio> for the chapter. Six separate elements would play over each other.
  const [playing, setPlaying] = React.useState(null);
  const [pos, setPos] = React.useState(0);
  const [dur, setDur] = React.useState(0);
  const ref = React.useRef(null);

  React.useEffect(function () {
    var el = ref.current; if (!el) return;
    function onTime() { setPos(el.currentTime || 0); }
    function onMeta() { setDur(el.duration || 0); }
    function onEnd() { setPlaying(null); setPos(0); }
    el.addEventListener('timeupdate', onTime);
    el.addEventListener('loadedmetadata', onMeta);
    el.addEventListener('ended', onEnd);
    return function () {
      el.removeEventListener('timeupdate', onTime);
      el.removeEventListener('loadedmetadata', onMeta);
      el.removeEventListener('ended', onEnd);
    };
  }, []);

  function toggle(p) {
    var el = ref.current; if (!el) return;
    if (playing === p.name) { el.pause(); setPlaying(null); return; }
    el.src = '/product-studio/music-samples/' + p.file;
    setPos(0); setDur(0);
    el.play().then(function () { setPlaying(p.name); }).catch(function () { setPlaying(null); });
  }
  function seek(v) { var el = ref.current; if (el) { el.currentTime = v; setPos(v); } }

  return (
    <ExSection
      id="sound"
      chapter="Sound Studio"
      title="Music, cut to your brief."
      kicker="Forty nine moods to pick from, or describe the track you want in your own words. Press play to hear what comes out."
      tone="cocoa"
    >
      <style>{`
        .ex-snd-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
        @media (max-width: 1000px) { .ex-snd-grid { grid-template-columns: repeat(2, 1fr); gap: 14px; } }
        @media (max-width: 560px)  { .ex-snd-grid { grid-template-columns: 1fr; } }
        .ex-snd { display: grid; grid-template-columns: 64px 1fr; gap: 14px; align-items: center;
          padding: 12px; background: rgba(242,236,228,0.06);
          border: 1px solid rgba(242,236,228,0.10); transition: background 200ms; }
        .ex-snd:hover { background: rgba(242,236,228,0.10); }
        .ex-snd-art { width: 64px; height: 64px; overflow: hidden; }
        .ex-snd-art img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .ex-snd-body { min-width: 0; }
        .ex-snd-name { font-family: "La Villa", sans-serif; font-size: 14.5px; color: var(--cream); display: block; }
        .ex-snd-desc { font-family: "La Villa", sans-serif; font-size: 12px; color: rgba(242,236,228,0.55);
          display: block; margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .ex-snd-row { display: flex; align-items: center; gap: 9px; margin-top: 9px; }
        .ex-snd-btn { width: 26px; height: 26px; flex: none; display: grid; place-items: center; cursor: pointer;
          background: transparent; color: var(--cream); border: 1px solid rgba(242,236,228,0.35);
          font-size: 9px; padding: 0; }
        .ex-snd-btn:hover { background: var(--cream); color: #2A2420; }
        .ex-snd.is-on .ex-snd-btn { background: var(--cream); color: #2A2420; }
        .ex-snd-bar { flex: 1; min-width: 0; height: 3px; cursor: pointer; accent-color: var(--cream); }
        .ex-snd-time { font-family: "La Villa", sans-serif; font-size: 10.5px; color: rgba(242,236,228,0.5);
          font-variant-numeric: tabular-nums; min-width: 30px; text-align: right; }
        .ex-snd-cta { display: inline-flex; align-items: center; gap: 10px; margin-top: 40px;
          padding: 14px 26px; border: 1px solid rgba(242,236,228,0.4); color: var(--cream);
          font-family: "La Villa", sans-serif; font-size: 12px; letter-spacing: 0.16em;
          text-transform: uppercase; text-decoration: none; transition: background 200ms, color 200ms, gap 240ms; }
        .ex-snd-cta:hover { background: var(--cream); color: #2A2420; gap: 16px; }
      `}</style>
      <div className="ex-snd-grid">
        {EX_SOUND_PICKS.map(function (p) {
          var on = playing === p.name;
          return (
            <div key={p.name} className={'ex-snd' + (on ? ' is-on' : '')}>
              <span className="ex-snd-art"><img src={'/product-studio/sound-studio/' + p.img + '.webp'} alt="" loading="lazy" /></span>
              <span className="ex-snd-body">
                <span className="ex-snd-name">{p.name}</span>
                <span className="ex-snd-desc">{p.desc}</span>
                <span className="ex-snd-row">
                  <button className="ex-snd-btn" onClick={function () { toggle(p); }}
                    aria-label={(on ? 'Pause ' : 'Play ') + p.name}>{on ? '■' : '▶'}</button>
                  <input className="ex-snd-bar" type="range" min={0} step={0.1}
                    max={on && dur ? dur : 100} value={on ? pos : 0} disabled={!on}
                    onChange={function (e) { seek(Number(e.target.value)); }}
                    aria-label={'Scrub ' + p.name} />
                  <span className="ex-snd-time">{on ? exFmtClock(pos) : exFmtClock(0)}</span>
                </span>
              </span>
            </div>
          );
        })}
      </div>
      {/* ⚠️ "the artists it learned from", never "the artists who played it".
          They were paid for the music the model was TRAINED on. They did not
          perform anyone's track, and saying otherwise is the overclaim that got
          "we shoot it again" cut from the Reshoot copy. */}
      <div style={{ marginTop: 40, paddingTop: 26, borderTop: '1px solid rgba(242,236,228,0.16)', maxWidth: 620 }}>
        <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 15, lineHeight: 1.6, color: 'var(--cream)', margin: 0 }}>
          Trained on licensed music, not scraped music.
        </p>
        <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 13.5, lineHeight: 1.6, color: 'rgba(242,236,228,0.6)', margin: '8px 0 0' }}>
          The artists whose work it learned from opted in, and they are paid when their work features.
        </p>
      </div>

      {/* Straight into the Sound tab, not the studio's front door. The ?tab=
          reader in ProductStudio handles it. */}
      <a className="ex-snd-cta" href={(window.PORTAL_URL || '/dashboard/product-studio') + '?tab=sound'}>
        Cut your own track <span aria-hidden="true">&rarr;</span>
      </a>
      <audio ref={ref} preload="none" />
    </ExSection>
  );
}

Object.assign(window, { ExSound });
