// Step 6 — Review. Stat tiles only (Almost there + Blockers cards omitted per user).
const STEP6_FRAME = { x: 192, y: 48, w: 1536, h: 984 };

// Beat plan (~7s):
//  0.0 – 0.4   Scene fades in (all steps ✓, Step 6 active)
//  0.4 – 1.0   Step strip slides in with all checks
//  1.0 – 1.8   Tile row 1 cascades (School, Classes, Periods)
//  1.6 – 2.4   Tile row 2 cascades (Subjects, Teachers, Coverage)
//  2.4 – 4.0   Hold to read
//  4.0 – 4.6   Cursor glides to "Finish setup"
//  4.6 – 4.9   Click + halo
//  4.9 – 6.0   Big confetti-ish celebration; button copy could shift
//  6.0 – 7.0   Hold then fade

function StepStripStep6() {
  const steps = ['School', 'Classes', 'Periods', 'Subjects', 'Teachers', 'Review'];
  return (
    <div style={{
      display: 'flex', alignItems: 'center',
      background: '#fff', border: `1px solid ${BRAND.border}`,
      borderRadius: 14, padding: '18px 24px',
    }}>
      {steps.map((s, i) => {
        const isDone = i <= 4;
        const isActive = i === 5;
        return (
          <React.Fragment key={s}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                width: 26, height: 26, borderRadius: 999,
                background: isDone ? BRAND.greenSoft : (isActive ? BRAND.green : '#f1efe8'),
                color: isDone ? BRAND.green : (isActive ? '#fff' : BRAND.inkSub),
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12, fontWeight: 700,
              }}>
                {isDone ? (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5 11-12"/></svg>
                ) : (i + 1)}
              </div>
              <span style={{
                fontSize: 14,
                fontWeight: isActive ? 700 : 500,
                color: isDone || isActive ? BRAND.ink : BRAND.inkSub,
                whiteSpace: 'nowrap',
              }}>{s}</span>
            </div>
            {i < steps.length - 1 && (
              <div style={{
                flex: 1, height: 1,
                background: BRAND.greenMid,
                margin: '0 14px',
              }}/>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function ReviewTile({ icon, iconBg, iconStroke, label, value, sub, chips, opacity = 1, scale = 1 }) {
  return (
    <div style={{
      opacity, transform: `scale(${scale})`,
      transformOrigin: 'center',
      background: '#fff',
      border: `1px solid ${BRAND.border}`,
      borderRadius: 14,
      padding: '22px 24px',
      boxShadow: BRAND.shadow,
      minHeight: 170,
      display: 'flex', flexDirection: 'column',
      transition: 'opacity 240ms, transform 240ms',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <div style={{
          width: 42, height: 42, borderRadius: 11,
          background: iconBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {icon}
        </div>
        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: '0.14em',
          textTransform: 'uppercase', color: BRAND.inkSub,
        }}>{label}</div>
      </div>
      <div style={{ fontSize: 24, fontWeight: 700, color: BRAND.ink, letterSpacing: '-0.02em' }}>{value}</div>
      {sub && <div style={{ fontSize: 14, color: BRAND.inkSoft, marginTop: 4 }}>{sub}</div>}
      {chips && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 12 }}>
          {chips.map(c => (
            <span key={c} style={{
              fontSize: 12, fontWeight: 600, color: BRAND.ink,
              padding: '4px 10px', borderRadius: 6,
              background: '#f1efe8',
              whiteSpace: 'nowrap',
            }}>{c}</span>
          ))}
        </div>
      )}
    </div>
  );
}

function Step6Video({ start = 0 }) {
  const t = useTime();
  const lt = t - start;

  const fadeIn = interpolate([0, 0.4], [0, 1], Easing.easeOutCubic)(lt);
  const fadeOut = interpolate([6.5, 7.0], [1, 0], Easing.easeInCubic)(lt);
  const sceneOp = fadeIn * fadeOut;

  const stripOp = interpolate([0.4, 1.0], [0, 1], Easing.easeOutCubic)(lt);
  const stripY  = interpolate([0.4, 1.0], [16, 0], Easing.easeOutCubic)(lt);

  // Tiles cascade in
  const tileEntry = (i) => ({
    op:    interpolate([1.0 + i*0.12, 1.4 + i*0.12], [0, 1], Easing.easeOutCubic)(lt),
    scale: interpolate([1.0 + i*0.12, 1.4 + i*0.12], [0.92, 1], Easing.easeOutBack)(lt),
  });

  // Continue / Finish click
  const finishClickT = 4.6;
  const finishHot = lt > 4.2 && lt < 4.9;
  const clkT = (lt - finishClickT) / 0.18;
  const clickSquish = clkT > 0 && clkT < 1 ? 0.05 * Math.sin(clkT * Math.PI) : 0;
  const haloOp = interpolate([finishClickT, finishClickT + 0.3, finishClickT + 0.9], [0, 0.8, 0], Easing.easeOutCubic)(lt);
  const haloScale = interpolate([finishClickT, finishClickT + 0.9], [1, 2.4], Easing.easeOutCubic)(lt);

  // Celebration check mark icon "✓ Setup complete" appears after click
  const celebOp = interpolate([finishClickT + 0.2, finishClickT + 0.7], [0, 1], Easing.easeOutBack)(lt);
  const celebScale = interpolate([finishClickT + 0.2, finishClickT + 0.7], [0.6, 1], Easing.easeOutBack)(lt);

  // Cursor
  const path = [
    { t: 3.4, x: 1740, y: 1100 },
    { t: 4.4, x: 1600, y: 995 },   // Finish setup button
    { t: 4.6, x: 1600, y: 995 },
    { t: 7.0, x: 1600, y: 995 },
  ];
  const cur = (() => {
    if (lt < path[0].t) return { x: path[0].x, y: path[0].y, op: 0 };
    if (lt >= path[path.length-1].t) return { x: path[path.length-1].x, y: path[path.length-1].y, op: 1 };
    for (let i = 0; i < path.length - 1; i++) {
      if (lt >= path[i].t && lt <= path[i+1].t) {
        const seg = (lt - path[i].t) / (path[i+1].t - path[i].t || 1);
        const e = Easing.easeInOutCubic(seg);
        return { x: path[i].x + (path[i+1].x - path[i].x) * e, y: path[i].y + (path[i+1].y - path[i].y) * e, op: 1 };
      }
    }
    return { x: path[0].x, y: path[0].y, op: 1 };
  })();
  const cursorFadeOut = interpolate([5.8, 6.4], [1, 0], Easing.easeInCubic)(lt);
  const cursorOp = cur.op * cursorFadeOut;
  const settle = lt > finishClickT && lt < finishClickT + 0.4
    ? Math.sin((lt - finishClickT) * 30) * 1.5 * Math.exp(-(lt - finishClickT) * 8) : 0;

  // Confetti particles
  const confetti = React.useMemo(() => {
    const arr = [];
    for (let i = 0; i < 24; i++) {
      const angle = (i / 24) * Math.PI * 2 + Math.random() * 0.2;
      const dist = 280 + Math.random() * 220;
      const colors = ['#10b981', '#3b82f6', '#f59e0b', '#ec4899', '#8b5cf6', '#ef4444', '#14b8a6'];
      arr.push({
        angle, dist,
        size: 6 + Math.random() * 8,
        color: colors[Math.floor(Math.random() * colors.length)],
        delay: Math.random() * 0.2,
      });
    }
    return arr;
  }, []);

  const tiles = [
    {
      label: 'School',
      iconBg: BRAND.greenSoft, iconStroke: BRAND.green,
      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={BRAND.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 21h18M5 21V7l7-4 7 4v14M9 9h.01M15 9h.01M9 13h.01M15 13h.01M9 17h.01M15 17h.01"/></svg>,
      value: 'Sunridge Academy', sub: '2025-26',
    },
    {
      label: 'Classes',
      iconBg: '#fef3c7', iconStroke: '#d97706',
      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 10L12 5 2 10l10 5 10-5z"/><path d="M6 12v5c0 1 3 3 6 3s6-2 6-3v-5"/></svg>,
      value: '1 class', sub: '1 section', chips: ['Class 1'],
    },
    {
      label: 'Periods',
      iconBg: BRAND.greenSoft, iconStroke: BRAND.green,
      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={BRAND.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
      value: '8 regular', sub: '5-day week',
    },
    {
      label: 'Subjects',
      iconBg: BRAND.greenSoft, iconStroke: BRAND.green,
      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={BRAND.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 3h6a4 4 0 014 4v14a3 3 0 00-3-3H2z"/><path d="M22 3h-6a4 4 0 00-4 4v14a3 3 0 013-3h7z"/></svg>,
      value: '5 subjects', sub: '2 class-subject mappings',
      chips: ['Mathematics', 'English', 'Social Studies', 'Science', 'Art'],
    },
    {
      label: 'Teachers',
      iconBg: BRAND.greenSoft, iconStroke: BRAND.green,
      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={BRAND.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>,
      value: '1 teacher', sub: '1 assignment · 1 period / week',
    },
    {
      label: 'Coverage',
      iconBg: BRAND.greenSoft, iconStroke: BRAND.green,
      icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={BRAND.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9 12l2 2 4-4"/></svg>,
      value: '100%', sub: 'All classes covered',
    },
  ];

  const isClicked = lt > finishClickT;
  const buttonLabel = isClicked ? 'Generating timetable…' : 'Finish setup';

  return (
    <div style={{ position: 'absolute', inset: 0, opacity: sceneOp }}>
      <AppFrame x={STEP6_FRAME.x} y={STEP6_FRAME.y} width={STEP6_FRAME.w} height={STEP6_FRAME.h}>
        <ChromeStep2/>

        <div style={{ padding: '24px 48px' }}>
          {/* Step strip */}
          <div style={{ opacity: stripOp, transform: `translateY(${stripY}px)` }}>
            <StepStripStep6/>
          </div>

          {/* Stat tiles (2 rows × 3) */}
          <div style={{
            marginTop: 24,
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18,
          }}>
            {tiles.map((tile, i) => {
              const e = tileEntry(i);
              return (
                <ReviewTile key={tile.label} {...tile} opacity={e.op} scale={e.scale}/>
              );
            })}
          </div>

          {/* Footer */}
          <div style={{ height: 1, background: BRAND.borderSoft, marginTop: 28 }}/>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginTop: 16,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 6,
              color: BRAND.inkSub, fontSize: 15, fontWeight: 500,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
              Back
            </div>
            <div style={{ position: 'relative' }}>
              {/* Confetti */}
              {lt >= finishClickT && confetti.map((p, i) => {
                const pt = (lt - finishClickT - p.delay) / 1.2;
                if (pt <= 0 || pt >= 1) return null;
                const ease = Easing.easeOutCubic(pt);
                const x = Math.cos(p.angle) * p.dist * ease;
                const y = Math.sin(p.angle) * p.dist * ease + (pt * pt * 200); // gravity
                return (
                  <div key={i} style={{
                    position: 'absolute',
                    left: '50%', top: '50%',
                    width: p.size, height: p.size,
                    background: p.color,
                    borderRadius: 2,
                    transform: `translate(${x}px, ${y}px) rotate(${pt * 720}deg)`,
                    opacity: 1 - pt,
                    pointerEvents: 'none',
                  }}/>
                );
              })}
              {/* Halo */}
              <div style={{
                position: 'absolute', inset: 0,
                borderRadius: 10, background: BRAND.greenSoft,
                opacity: haloOp, transform: `scale(${haloScale})`, pointerEvents: 'none',
              }}/>
              {/* Button */}
              <div style={{
                position: 'relative',
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '12px 22px', borderRadius: 10,
                background: BRAND.green, color: '#fff',
                fontSize: 15, fontWeight: 600,
                transform: `scale(${1 - clickSquish})`,
                boxShadow: finishHot
                  ? `0 0 0 8px ${BRAND.greenSoft}, 0 8px 24px rgba(4,120,87,0.32)`
                  : '0 2px 6px rgba(4,120,87,0.18)',
                transition: 'box-shadow 200ms',
                whiteSpace: 'nowrap',
              }}>
                {isClicked && (
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    transform: `scale(${celebScale})`, opacity: celebOp,
                  }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5 11-12"/></svg>
                  </div>
                )}
                {buttonLabel}
                {!isClicked && (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Cursor */}
        {cursorOp > 0 && (
          <div style={{
            position: 'absolute',
            left: cur.x - STEP6_FRAME.x,
            top: cur.y - STEP6_FRAME.y + settle,
            pointerEvents: 'none',
          }}>
            <Cursor x={0} y={0} opacity={cursorOp}/>
          </div>
        )}
      </AppFrame>
    </div>
  );
}

function Step6App({ loop = true, persistKey = "step6video" }) {
  return (
    <Stage width={1920} height={1080} duration={7} background={BRAND.bg} loop={loop} persistKey={persistKey}>
      <Step6Video start={0}/>
    </Stage>
  );
}

Object.assign(window, { Step6Video, Step6App });

if (!window.__STEP6_NO_AUTOMOUNT) {
  ReactDOM.createRoot(document.getElementById('root')).render(<Step6App/>);
}
