// Promo Video — Main App
// 75-second timeline composed of 8 scenes.

// ─────────────────────────────────────────────────────────────────────────────
// Scene table — start/end seconds + caption tracks per scene
// ─────────────────────────────────────────────────────────────────────────────
const SCENES = [
  { id: 1, start:  0, end:  8, label: 'Cold open',         Component: Scene1ColdOpen },
  { id: 2, start:  8, end: 18, label: 'Why generic failed', Component: Scene2Comparison },
  { id: 3, start: 18, end: 30, label: 'Energy check',      Component: Scene3EnergyCheck },
  { id: 4, start: 30, end: 43, label: 'Hint ladder',       Component: Scene4HintLadder },
  { id: 5, start: 43, end: 53, label: 'Personality',       Component: Scene5Personality },
  { id: 6, start: 53, end: 63, label: 'Parent dashboard',  Component: Scene6Dashboard },
  { id: 7, start: 63, end: 71, label: 'Founder note',      Component: Scene7Founder },
  { id: 8, start: 71, end: 75, label: 'Brand close',       Component: Scene8Close },
];

const DURATION = 75;

// ─────────────────────────────────────────────────────────────────────────────
// CAPTIONS — VO-style subtitle track. Each {start, end, text}.
// ─────────────────────────────────────────────────────────────────────────────
const CAPTIONS = [
  // Scene 1 — Cold open
  { start: 0.8,  end: 4.4,  text: "Most AI tutors hand your kid the answer." },
  { start: 4.6,  end: 8.0,  text: "This one starts with a question." },

  // Scene 2 — Why generic failed
  { start: 8.4,  end: 12.6, text: "Generic AI helpers just did Rina's homework for her." },
  { start: 12.8, end: 17.8, text: "She copied. She didn't learn. We built the opposite." },

  // Scene 3 — Mentor energy check
  { start: 18.3, end: 22.2, text: "Every session opens with Mentor — a 30-second energy check." },
  { start: 22.4, end: 26.4, text: "Green: push hard. Amber: light topic. Red: rest tonight." },
  { start: 26.6, end: 29.8, text: "Sessions adapt to the week she's actually having." },

  // Scene 4 — Hint ladder
  { start: 30.3, end: 34.0, text: "Professor Pi guides with a four-level hint ladder." },
  { start: 34.2, end: 38.6, text: "Always a question. Never the final answer." },
  { start: 38.8, end: 42.8, text: "She does the move herself — that's when it sticks." },

  // Scene 5 — Personality
  { start: 43.3, end: 47.0, text: "Every tutor reads her context first." },
  { start: 47.2, end: 52.8, text: "Chess, piano, cross-country — analogies built around her." },

  // Scene 6 — Parent dashboard
  { start: 53.3, end: 57.4, text: "Parents see exactly what the tutor saw." },
  { start: 57.6, end: 62.8, text: "Including the rest days Mentor recommended." },

  // Scene 7 — Founder
  { start: 63.3, end: 67.2, text: "Built for my daughter Rina, age 12." },
  { start: 67.4, end: 70.8, text: "Now sharing with the first 100 families." },

  // Scene 8 — CTA
  { start: 71.4, end: 74.8, text: "aitutors.me — founding members welcome." },
];

// ─────────────────────────────────────────────────────────────────────────────
// SubtitleBar — bottom-center caption band, fades per CAPTIONS table.
// ─────────────────────────────────────────────────────────────────────────────
function SubtitleBar({ enabled = true }) {
  const t = useTime();
  if (!enabled) return null;
  const active = CAPTIONS.find(c => t >= c.start && t < c.end);
  const fade = active
    ? Math.min(
        Math.min(1, (t - active.start) / 0.25),
        Math.min(1, (active.end - t) / 0.3)
      )
    : 0;
  if (!active || fade <= 0) return null;
  return (
    <div style={{
      position: 'absolute',
      left: '50%', bottom: 56,
      transform: 'translateX(-50%)',
      opacity: fade,
      maxWidth: 1300,
      padding: '18px 32px',
      background: 'oklch(0.12 0.04 254 / 0.92)',
      color: palette.onDark,
      borderRadius: 12,
      fontFamily: fonts.sans,
      fontSize: 32,
      fontWeight: 400,
      letterSpacing: '-0.005em',
      lineHeight: 1.3,
      textAlign: 'center',
      backdropFilter: 'blur(8px)',
      WebkitBackdropFilter: 'blur(8px)',
      boxShadow: '0 12px 40px -16px rgba(0,0,0,0.5)',
      zIndex: 60,
      pointerEvents: 'none',
    }}>
      {active.text}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SceneChapters — horizontal chapter strip rendered at top of canvas.
// Clickable; shows progress within each chapter.
// ─────────────────────────────────────────────────────────────────────────────
function SceneChapters() {
  const { time, setTime, duration } = useTimeline();
  return (
    <div style={{
      position: 'absolute',
      top: 20, left: 80, right: 80,
      display: 'flex', gap: 6,
      zIndex: 60,
      pointerEvents: 'auto',
    }}>
      {SCENES.map(s => {
        const inside = time >= s.start && time < s.end;
        const past = time >= s.end;
        const w = ((s.end - s.start) / duration) * 100;
        const localProg = inside ? (time - s.start) / (s.end - s.start) : (past ? 1 : 0);
        return (
          <button
            key={s.id}
            onClick={() => setTime(s.start + 0.05)}
            title={`${String(s.id).padStart(2, '0')} · ${s.label}`}
            style={{
              flex: `${w} 1 0`,
              height: 4,
              background: 'oklch(0.4 0.04 254 / 0.25)',
              border: 0, padding: 0,
              borderRadius: 2,
              cursor: 'pointer',
              position: 'relative',
              overflow: 'hidden',
            }}
          >
            <span style={{
              position: 'absolute', inset: 0,
              width: `${localProg * 100}%`,
              background: inside ? palette.accent : (past ? palette.accentDeep : 'transparent'),
              borderRadius: 'inherit',
              transition: 'width 60ms linear',
            }} />
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// VideoCanvas — composes all the scenes within a Stage.
// ─────────────────────────────────────────────────────────────────────────────
function VideoCanvas({ tweaks }) {
  return (
    <React.Fragment>
      <SceneChapters />
      {SCENES.map(({ id, start, end, Component }) => (
        <Sprite key={id} start={start} end={end}>
          <Component />
        </Sprite>
      ))}
      <SubtitleBar enabled={tweaks.captions} />
    </React.Fragment>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PromoTweaks — TweaksPanel with caption toggle + scene jump
// ─────────────────────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "captions": true
}/*EDITMODE-END*/;

function PromoTweaks({ tweaks, setTweak, onJump }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Captions">
        <TweakToggle
          label="Show subtitles"
          value={tweaks.captions}
          onChange={(v) => setTweak('captions', v)}
        />
      </TweakSection>
      <TweakSection label="Jump to scene">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
          {SCENES.map(s => (
            <button
              key={s.id}
              onClick={() => onJump(s.start)}
              style={{
                fontFamily: '"Geist Mono", ui-monospace, monospace',
                fontSize: 11,
                letterSpacing: '0.04em',
                padding: '8px 10px',
                background: '#fff',
                border: '1px solid #e5e0d4',
                borderRadius: 6,
                color: '#26323f',
                cursor: 'pointer',
                textAlign: 'left',
                lineHeight: 1.3,
              }}
            >
              <span style={{ color: 'oklch(0.42 0.135 150)' }}>0{s.id}</span>
              <span style={{ display: 'block', fontSize: 12, fontFamily: 'inherit', marginTop: 2, color: '#26323f' }}>
                {s.label}
              </span>
            </button>
          ))}
        </div>
      </TweakSection>
      <TweakSection label="Tip">
        <div style={{ fontSize: 12, color: '#6b6458', lineHeight: 1.45 }}>
          Press <strong>space</strong> to play/pause, <strong>←/→</strong> to step, <strong>0</strong> to restart.
        </div>
      </TweakSection>
    </TweaksPanel>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// App — owns tweaks state, wires Stage + jump.
// ─────────────────────────────────────────────────────────────────────────────
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  // Lift seek control out of Stage so the Tweaks panel can jump
  const [seekTarget, setSeekTarget] = React.useState(null);

  return (
    <React.Fragment>
      <Stage
        width={1920}
        height={1080}
        duration={DURATION}
        background={palette.paper}
        loop={true}
        autoplay={true}
        persistKey="aitutors-promo"
      >
        <VideoCanvas tweaks={tweaks} />
        <SeekListener target={seekTarget} clear={() => setSeekTarget(null)} />
      </Stage>
      <PromoTweaks
        tweaks={tweaks}
        setTweak={setTweak}
        onJump={(t) => setSeekTarget(t + 0.05)}
      />
    </React.Fragment>
  );
}

// Inside the Stage's TimelineContext, a child can call setTime.
// This component watches a `target` prop and applies it via setTime.
function SeekListener({ target, clear }) {
  const { setTime } = useTimeline();
  React.useEffect(() => {
    if (target != null) {
      setTime(target);
      clear();
    }
  }, [target]);
  return null;
}

// Mount
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
