// ─────────────────────────────────────────────────────────────
// NATIONAL VA LOANS — VIDEO PLAYER
// Reads window.VIDEO (defined in each video's HTML file) and builds the timeline,
// scene timing, narration cues, ducked music and the corner label automatically.
// ─────────────────────────────────────────────────────────────
function buildTimeline(video) {
  let t = 0;
  const scenes = video.scenes.map((s, i) => {
    const start = t;
    t += s.duration;
    return { ...s, start, end: t, label: s.label || `${String(i + 1).padStart(2, '0')} ${s.layout}` };
  });
  const cues = scenes
    .filter((s) => s.voice && s.voiceLength)
    .map((s) => ({ src: s.voice, at: s.start + (s.voiceDelay ?? 0.8), len: s.voiceLength }));
  return { scenes, cues, total: t };
}

function CornerLabel({ text, from, to }) {
  const t = useTime();
  if (!text) return null;
  return (
    <div style={{ position: 'absolute', right: 60, top: 50, fontSize: 22, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(120,135,160,0.9)', opacity: t > from && t < to ? 1 : 0, transition: 'opacity .4s' }}>
      {text}
    </div>
  );
}

function NVLVideo({ video }) {
  const { scenes, cues, total } = React.useMemo(() => buildTimeline(video), [video]);
  const first = scenes[0], last = scenes[scenes.length - 1];
  return (
    <Stage width={1920} height={1080} duration={total} background={NVL_BRAND.colors.paper} persistKey={video.id || 'nvlvideo'}>
      {scenes.map((s) => {
        const L = NVL_LAYOUTS[s.layout];
        if (!L) { console.warn('Unknown layout:', s.layout); return null; }
        return <Sprite key={s.start} start={s.start} end={s.end}><L s={s} /></Sprite>;
      })}
      <CornerLabel text={video.cornerLabel} from={first.end} to={last.start} />
      <Soundtrack cues={cues} total={total}
        music={video.music ? { src: video.music, len: video.musicLength || total, full: video.musicVolume ?? 0.5, duck: video.musicDuck ?? 0.16, loop: !!video.musicLoop } : null} />
    </Stage>
  );
}

Object.assign(window, { NVLVideo, buildTimeline });
