// "See it run": the walkthrough player, then one tab per team with that team's player.
// Styles: home-v2/watch.css. Each player is a poster until Play; the first Play loads Wistia's player script,
// and a tab press starts that team's video. Evergreen cuts only: no partner, customer or investor name anywhere here.
// Sam, 2026-11-18: the word is "walkthrough", never "demo"; no length badge on a player.

const WATCH_POSTER = (hash) => `https://embed-ssl.wistia.com/deliveries/${hash}.jpg?image_crop_resized=1600x900`;

const WATCH_WALKTHROUGH = {
  id: '1sdbe2j4w6',
  title: 'The EightbyZero walkthrough',
  poster: WATCH_POSTER('98b27ff4b373ff5acbed5a0117bf35ba'),
};

// One entry per team. `id` is the Wistia media id of the evergreen cut.
const WATCH_TEAMS = [
  { id: 'r00bmqb3ww', title: 'The New Cost of Entry', poster: WATCH_POSTER('3f9962dcb273f5fb3d7e86d0091a67e0803f466a'),
    who: 'Sales executives and underwriters',
    what: 'Connecting to any HR system puts your proposal on the broker’s shortlist. See the RFPs it opens and what they are worth.',
    proof: '4 in 10 employers would change carriers if theirs could not connect to their benefit technology platform', src: 'LIMRA, 2025' },
  { id: '19d45k90hq', title: 'The Employer Experience', poster: WATCH_POSTER('042554d4135a5d17565d9ea5251429d41ba91a59'),
    who: 'Teams selling to employer HR leads',
    what: 'Employers get one guided flow on any HR system, so the integration work stays off their HR team.',
    proof: 'Invite · Discover · Connect · Monitor', src: '' },
  { id: '9hh020dg6a', title: 'The Repeatable Implementation', poster: WATCH_POSTER('bb76e230e26ebeb67c2f6c7a46d6a8ecf7e3a3ab'),
    who: 'Implementation and enrollment teams',
    what: 'Capture requirements once and reuse them for every employer, so cases are ready before the plan year starts.',
    proof: 'Connected · Validated · Monitored', src: '' },
  { id: '6t8hm1h1bf', title: 'After The Sale', poster: WATCH_POSTER('7a8f8afabbb5681e45e79bf93d509ffd50f14617'),
    who: 'Billing, claims and administration teams',
    what: 'Hires, pay changes and leaves reach billing and claim files on the day they happen, in both directions.',
    proof: 'Accurate, timely data, long after the sale', src: '' },
];

const watchLoaded = {};
function loadWistia(id) {
  if (!watchLoaded.player) {
    watchLoaded.player = true;
    const s = document.createElement('script');
    s.src = 'https://fast.wistia.com/player.js'; s.async = true;
    document.head.appendChild(s);
  }
  if (!watchLoaded[id]) {
    watchLoaded[id] = true;
    const m = document.createElement('script');
    m.src = `https://fast.wistia.com/embed/${id}.js`; m.async = true; m.type = 'module';
    document.head.appendChild(m);
  }
}

function WatchPlayIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M6 3.5v17a1 1 0 0 0 1.5.86l14-8.5a1 1 0 0 0 0-1.72l-14-8.5A1 1 0 0 0 6 3.5z" />
    </svg>
  );
}

// Poster, then the Wistia element over it once playing.
function WatchStage({ video, playing, onPlay, panelId, role, labelledby }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!playing) return;
    loadWistia(video.id);
    const el = ref.current;
    if (window.customElements && el) {
      window.customElements.whenDefined('wistia-player').then(() => {
        try {
          const started = el.play && el.play();
          if (started && started.catch) started.catch(() => { /* autoplay refused: the poster stays and the viewer's own press starts it */ });
        } catch (e) { /* same: the viewer's own press starts it */ }
      });
    }
  }, [playing, video.id]);
  return (
    <div className="watch-stage" data-playing={String(playing)} id={panelId} role={role} aria-labelledby={labelledby}>
      <img alt="" src={video.poster} loading="lazy" />
      {playing
        ? <wistia-player key={video.id} ref={ref} media-id={video.id} aspect="1.7777777777777777" style={{ position: 'absolute', inset: 0 }} />
        : <button type="button" className="watch-play" aria-label={`Play ${video.title}`} onClick={onPlay}><span><WatchPlayIcon /></span></button>}
    </div>
  );
}

function WatchSection() {
  const [walkPlaying, setWalkPlaying] = React.useState(false);
  const [st, setSt] = React.useState({ cur: 0, playing: false });
  const team = WATCH_TEAMS[st.cur];

  const pick = (i, focus) => {
    setSt({ cur: i, playing: true });
    if (focus) setTimeout(() => { const b = document.getElementById('watch-tab-' + i); if (b) b.focus(); }, 0);
  };
  const onKey = (e) => {
    const d = (e.key === 'ArrowDown' || e.key === 'ArrowRight') ? 1 : (e.key === 'ArrowUp' || e.key === 'ArrowLeft') ? -1 : 0;
    if (d) { e.preventDefault(); pick((st.cur + d + WATCH_TEAMS.length) % WATCH_TEAMS.length, true); }
  };

  return (
    <section className="watch" id="see-it-run" aria-labelledby="watch-h">
      <div className="container">
        <div className="watch-head">
          <span className="eyebrow">See it run</span>
          <h2 id="watch-h">Watch the layer connect.<br />Start with the walkthrough.</h2>
          <p className="watch-lede"><BN /> connecting an employer to a carrier. Below it, the use cases for each team it supports.</p>
        </div>

        <div className="watch-lead">
          <WatchStage video={WATCH_WALKTHROUGH} playing={walkPlaying} onPlay={() => setWalkPlaying(true)} />
        </div>

        <div className="watch-who">
          <span className="eyebrow">Who 8/0 supports</span>
          <h2>Who is <BN /> for?</h2>
          <p className="watch-lede"><BN /> has every team&rsquo;s back, sales to billing. Pick yours to see how it covers your part of the work.</p>
        </div>

        <div className="watch-deck">
          <div className="watch-tabs" role="tablist" aria-label="Teams" aria-orientation="vertical">
            {WATCH_TEAMS.map((t, i) => {
              const on = i === st.cur;
              return (
                <button key={t.id} type="button" role="tab" id={`watch-tab-${i}`} className="watch-tab"
                  aria-selected={String(on)} aria-controls="watch-panel" tabIndex={on ? 0 : -1}
                  onClick={() => pick(i, false)} onKeyDown={onKey}>
                  <span className="who">{t.who}</span>
                  <span className="what">{t.what}</span>
                  <span className="proof">{t.proof}{t.src ? <small>{t.src}</small> : null}</span>
                </button>
              );
            })}
          </div>
          <WatchStage video={team} playing={st.playing} panelId="watch-panel" role="tabpanel" labelledby={`watch-tab-${st.cur}`}
            onPlay={() => setSt({ cur: st.cur, playing: true })} />
          <div className="watch-cap">
            <p>{team.what}</p>
            <div className="proof">{team.proof}{team.src ? <small>{team.src}</small> : null}</div>
          </div>
        </div>
      </div>
    </section>
  );
}
