// ad.jsx — root composition: Stage + scenes wired to the timeline.
// Globals: Stage, Sprite, useTime, useTimeline, Easing, clamp,
//   SceneHook, SceneProblem, SceneTurn, SceneReveal, ScenePrice, SceneFeatures, SceneCTA.

// Scene timings (seconds)
const SCENES = [
  { start:  0.0, end:  4.0, comp: SceneHook },
  { start:  4.0, end: 14.0, comp: SceneProblem },
  { start: 14.0, end: 19.0, comp: SceneTurn },
  { start: 19.0, end: 28.0, comp: SceneReveal },
  { start: 28.0, end: 38.0, comp: ScenePrice },
  { start: 38.0, end: 50.0, comp: SceneFeatures },
  { start: 50.0, end: 56.0, comp: SceneCTA },
];

const DURATION = 56;

function TimeLabeler() {
  const t = useTime();
  React.useEffect(() => {
    const el = document.querySelector('[data-ad-root]');
    if (el) el.setAttribute('data-screen-label', `t=${String(Math.floor(t)).padStart(2, '0')}s`);
  }, [t]);
  return null;
}

// ── AudioSync — keeps audio in step with the timeline play/pause ─────────────
function AudioSync({ audioRef }) {
  const { playing } = useTimeline();
  React.useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) audio.play().catch(() => {});
    else audio.pause();
  }, [playing]);
  return null;
}

// ── SplashScreen ─────────────────────────────────────────────────────────────
function SplashScreen({ audioRef }) {
  const { setTime, setPlaying } = useTimeline();
  const [elapsed, setElapsed] = React.useState(0);
  const [exiting, setExiting] = React.useState(false);
  const [gone, setGone] = React.useState(false);
  const [btnHover, setBtnHover] = React.useState(false);

  // Local RAF clock drives all splash animations
  React.useEffect(() => {
    const t0 = performance.now();
    let raf;
    const tick = () => {
      setElapsed((performance.now() - t0) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const handlePlay = () => {
    if (exiting) return;
    setExiting(true);
    const audio = audioRef.current;
    if (audio) audio.play().catch(() => {});
    setTime(0);
    setPlaying(true);
    setTimeout(() => setGone(true), 650);
  };

  if (gone) return null;

  // Animation values
  const saplingP  = Easing.easeOutCubic(clamp(elapsed / 3.2, 0, 1));
  const pulse     = 1 + 0.028 * Math.sin(elapsed * 2.8);
  const fi = (delay) => Easing.easeOutCubic(clamp((elapsed - delay) / 0.55, 0, 1));

  const btnScale  = (btnHover ? 1.06 : 1) * pulse;

  return (
    <div
      onClick={handlePlay}
      style={{
        position: 'absolute', inset: 0,
        zIndex: 500,
        background: FS.primary,
        cursor: 'pointer',
        opacity: exiting ? 0 : 1,
        transition: 'opacity 0.6s ease',
        userSelect: 'none',
        overflow: 'hidden',
      }}
    >
      {/* Faint decorative tree — top right */}
      <div style={{
        position: 'absolute', top: -80, right: -100,
        opacity: 0.10 * fi(0.4),
        transform: 'rotate(12deg)',
      }}>
        <Tree size={900} progress={saplingP} color={FS.sapling} accent={FS.primaryMid} />
      </div>

      {/* Subtle radial glow from center */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 70% 55% at 50% 52%, rgba(15,61,46,0.55) 0%, transparent 100%)`,
        pointerEvents: 'none',
      }} />

      {/* ── Brand pill ── */}
      <div style={{
        position: 'absolute', top: 160, left: 0, right: 0,
        display: 'flex', justifyContent: 'center',
        opacity: fi(0.1),
        transform: `translateY(${(1 - fi(0.1)) * 20}px)`,
      }}>
        <div style={{
          padding: '14px 28px',
          borderRadius: 999,
          border: `1.5px solid rgba(163,244,195,0.25)`,
          background: 'rgba(163,244,195,0.07)',
          fontFamily: 'Geist Mono, monospace',
          fontSize: 24,
          fontWeight: 600,
          letterSpacing: '0.16em',
          color: FS.sapling,
          textTransform: 'uppercase',
        }}>
          Made for Sri Lanka 🇱🇰
        </div>
      </div>

      {/* ── Sapling ── */}
      <div style={{
        position: 'absolute', top: 280, left: 0, right: 0,
        display: 'flex', justifyContent: 'center',
      }}>
        <Sapling size={520} progress={saplingP} color={FS.primaryMid} accent={FS.sapling} />
      </div>

      {/* ── Wordmark ── */}
      <div style={{
        position: 'absolute', top: 870, left: 0, right: 0,
        textAlign: 'center',
        padding: '0 80px',
        opacity: fi(0.8),
        transform: `translateY(${(1 - fi(0.8)) * 30}px)`,
      }}>
        <div style={{
          fontFamily: 'Instrument Serif, serif',
          fontSize: 180,
          lineHeight: 0.92,
          letterSpacing: '-0.03em',
          color: FS.surface,
        }}>
          Forest<i style={{ color: FS.sapling }}>Store</i>
        </div>
        <div style={{
          fontFamily: 'Geist, sans-serif',
          fontSize: 42,
          fontWeight: 400,
          color: FS.inverseGreen,
          marginTop: 28,
          lineHeight: 1.3,
          opacity: fi(1.1),
        }}>
          Your store.{' '}
          <i style={{ fontFamily: 'Instrument Serif, serif', color: FS.sapling, fontSize: 48 }}>
            Already grown.
          </i>
        </div>
      </div>

      {/* ── Play button ── */}
      <div style={{
        position: 'absolute', top: 1270, left: 0, right: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 36,
        opacity: fi(1.5),
        transform: `translateY(${(1 - fi(1.5)) * 40}px)`,
      }}>
        {/* Circle */}
        <div
          onMouseEnter={() => setBtnHover(true)}
          onMouseLeave={() => setBtnHover(false)}
          style={{
            width: 220, height: 220,
            borderRadius: 999,
            background: FS.sapling,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transform: `scale(${btnScale})`,
            boxShadow: `0 0 ${btnHover ? 80 : 48}px rgba(163,244,195,${btnHover ? 0.45 : 0.28})`,
            transition: 'box-shadow 0.2s ease',
          }}
        >
          {/* Play triangle */}
          <svg width="72" height="72" viewBox="0 0 72 72" fill="none">
            <path d="M26 18L56 36L26 54V18Z" fill={FS.primary} />
          </svg>
        </div>

        {/* Label */}
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            fontFamily: 'Instrument Serif, serif',
            fontSize: 64,
            color: FS.surface,
            letterSpacing: '-0.02em',
          }}>
            Watch the story
          </div>
          <div style={{
            fontFamily: 'Geist Mono, monospace',
            fontSize: 22,
            fontWeight: 500,
            letterSpacing: '0.14em',
            color: FS.inverseGreen,
            textTransform: 'uppercase',
          }}>
            56 seconds · sound on
          </div>
        </div>
      </div>

      {/* ── Bottom URL ── */}
      <div style={{
        position: 'absolute', bottom: 90, left: 0, right: 0,
        textAlign: 'center',
        opacity: fi(2.0) * 0.65,
        fontFamily: 'Geist Mono, monospace',
        fontSize: 28,
        fontWeight: 500,
        letterSpacing: '0.04em',
        color: FS.sapling,
      }}>
        foreststore.co
      </div>
    </div>
  );
}

// ── Ad root ──────────────────────────────────────────────────────────────────
function Ad() {
  const audioRef = React.useRef(null);

  React.useEffect(() => {
    const audio = new Audio('music.mp3');
    audio.loop = true;
    audio.volume = 0.65;
    audioRef.current = audio;
    return () => { audio.pause(); audio.src = ''; };
  }, []);

  return (
    <div data-ad-root data-screen-label="t=00s" style={{ position: 'absolute', inset: 0 }}>
      <Stage
        width={1080}
        height={1920}
        duration={DURATION}
        background={FS.surface}
        autoplay={false}
        persistKey="foreststore-ad"
      >
        <TimeLabeler />
        <AudioSync audioRef={audioRef} />
        {SCENES.map((s, i) => (
          <Sprite key={i} start={s.start} end={s.end}>
            <s.comp />
          </Sprite>
        ))}
        <SplashScreen audioRef={audioRef} />
      </Stage>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Ad />);
