// Step 3 — Periods. Working days + Periods per class.
const STEP3_FRAME = { x: 192, y: 48, w: 1536, h: 984 };

// Beat plan (~9s):
//  0.0 – 0.4   Scene fades in (chrome populated, Step 1 ✓, Step 2 ✓, Step 3 active)
//  0.4 – 1.0   Step strip slides in
//  1.0 – 1.6   Working days card slides up (5-day pre-selected)
//  1.6 – 2.5   Cursor glides to "6-day week" → click → Sat highlights green
//  2.5 – 3.0   Periods per class card slides up (table with Class 1 row)
//  3.0 – 3.8   Cursor moves to + button on regular periods
//  3.8 – 4.2   Click + → 8 increments to 9
//  4.2 – 4.6   Click + again → 9 → 10
//  4.6 – 5.4   Cursor glides to Continue (now active green)
//  5.4 – 5.7   Click Continue — halo pulse
//  5.7 – 6.6   Step 3 ticks ✓, Step 4 activates
//  6.6 – 8.0   Hold on populated state
//  8.0 – 8.5   Fade out

const STEP3_DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

function StepStripStep3({ step3DoneT = 0, step4ActiveT = 0 }) {
  const steps = ['School', 'Classes', 'Periods', 'Subjects', 'Teachers', 'Review'];
  const step3Done = step3DoneT > 0.5;
  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 <= 1 || (i === 2 && step3Done);
        const isActive = i === 2 ? !step3Done : (i === 3 ? step3Done : false);
        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,
                transition: 'background 240ms, color 240ms',
              }}>
                {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: (i < 2 || (i === 2 && step3Done)) ? BRAND.greenMid : BRAND.borderSoft,
                margin: '0 14px',
                transition: 'background 240ms',
              }}/>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Same chrome as step 2 (Sunridge Academy, Trial · 6d left)
function ChromeStep3() {
  return <ChromeStep2/>; // reuse from step2-video.jsx (exported to window)
}

function DayChip({ label, selected, justAdded, opacity = 1 }) {
  return (
    <div style={{
      opacity,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      padding: '12px 28px',
      borderRadius: 10,
      background: selected ? BRAND.greenSofter : '#fff',
      border: `1px solid ${selected ? BRAND.greenMid : BRAND.border}`,
      color: selected ? BRAND.green : BRAND.inkSoft,
      fontSize: 15, fontWeight: 600,
      transform: `scale(${justAdded ? 1.06 : 1})`,
      boxShadow: justAdded ? `0 0 0 4px ${BRAND.greenSoft}` : 'none',
      transition: 'background 200ms, border-color 200ms, color 200ms, transform 280ms cubic-bezier(.4,1.6,.6,1), box-shadow 280ms',
    }}>{label}</div>
  );
}

function ToggleChip({ label, selected, justSelected, opacity = 1 }) {
  return (
    <div style={{
      opacity,
      display: 'inline-flex', alignItems: 'center',
      padding: '12px 18px',
      borderRadius: 10,
      background: selected ? BRAND.greenSofter : '#fff',
      border: `1px solid ${selected ? BRAND.greenMid : BRAND.border}`,
      color: selected ? BRAND.green : BRAND.ink,
      fontSize: 14, fontWeight: 600,
      whiteSpace: 'nowrap',
      transform: `scale(${justSelected ? 1.04 : 1})`,
      boxShadow: justSelected ? `0 0 0 4px ${BRAND.greenSoft}` : 'none',
      transition: 'all 240ms',
    }}>{label}</div>
  );
}

function Stepper({ value, faded = false, plusHot = false, justPlus = false }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      border: `1px solid ${BRAND.border}`,
      borderRadius: 10,
      background: '#fff',
      opacity: faded ? 0.5 : 1,
    }}>
      <div style={{
        width: 38, height: 38,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: BRAND.inkSub,
        fontSize: 18, fontWeight: 500,
      }}>−</div>
      <div style={{
        minWidth: 44, height: 38,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 16, fontWeight: 700, color: BRAND.ink,
        fontVariantNumeric: 'tabular-nums',
        borderLeft: `1px solid ${BRAND.borderSoft}`,
        borderRight: `1px solid ${BRAND.borderSoft}`,
        transform: `scale(${justPlus ? 1.15 : 1})`,
        transition: 'transform 260ms cubic-bezier(.4,1.6,.6,1)',
      }}>{value}</div>
      <div style={{
        width: 38, height: 38,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: BRAND.inkSub,
        fontSize: 18, fontWeight: 500,
        background: plusHot ? BRAND.greenSoft : 'transparent',
        color: plusHot ? BRAND.green : BRAND.inkSub,
        transition: 'background 160ms',
        borderTopRightRadius: 10,
        borderBottomRightRadius: 10,
      }}>+</div>
    </div>
  );
}

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

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

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

  // Working days card
  const wdCardOp = interpolate([1.0, 1.6], [0, 1], Easing.easeOutCubic)(lt);
  const wdCardY  = interpolate([1.0, 1.6], [24, 0], Easing.easeOutCubic)(lt);

  // 6-day toggle: click at 2.2
  const sixDayClickT = 2.2;
  const isSixDay = lt >= sixDayClickT;
  const just6 = lt >= sixDayClickT && lt < sixDayClickT + 0.4;
  const just5 = lt < sixDayClickT && lt > 1.4;
  const satJustAdded = lt >= sixDayClickT && lt < sixDayClickT + 0.6;

  // Periods per class card
  const ppCardOp = interpolate([2.5, 3.0], [0, 1], Easing.easeOutCubic)(lt);
  const ppCardY  = interpolate([2.5, 3.0], [24, 0], Easing.easeOutCubic)(lt);

  // Plus clicks: t=3.9, t=4.3
  const plusClicks = [3.9, 4.3];
  const periodsValue = 8 + plusClicks.filter(ct => lt >= ct).length;
  const plusJust = plusClicks.some(ct => lt >= ct && lt < ct + 0.35);
  const plusHot = plusClicks.some(ct => lt > ct - 0.3 && lt < ct + 0.2);

  // Continue
  const continueActive = interpolate([1.6, 2.0], [0, 1], Easing.easeOutCubic)(lt);
  const continueClickT = 5.5;
  const continueHot = lt > 5.1 && lt < 5.8;
  const clkT = (lt - continueClickT) / 0.18;
  const clickSquish = clkT > 0 && clkT < 1 ? 0.05 * Math.sin(clkT * Math.PI) : 0;
  const haloOp = interpolate([continueClickT, continueClickT + 0.25, continueClickT + 0.7], [0, 0.7, 0], Easing.easeOutCubic)(lt);
  const haloScale = interpolate([continueClickT, continueClickT + 0.7], [1, 1.6], Easing.easeOutCubic)(lt);

  const step3DoneT = interpolate([continueClickT + 0.1, continueClickT + 0.8], [0, 1], Easing.easeOutCubic)(lt);
  const step4ActiveT = interpolate([continueClickT + 0.4, continueClickT + 1.0], [0, 1], Easing.easeOutCubic)(lt);

  // Cursor path (absolute coords on 1920×1080)
  // 6-day toggle at x≈690, y≈360
  // Plus button on Class 1 in periods table: x≈1580, y≈810
  // Continue button: x≈1585, y≈735 (content is short — footer sits higher than step 2)
  const path = [
    { t: 1.4, x: 1740, y: 1080 },           // entry
    { t: 2.0, x: 690, y: 360 },             // hover 6-day toggle
    { t: 2.2, x: 690, y: 360 },             // click
    { t: 3.7, x: 1580, y: 810 },            // glide to plus
    { t: 3.9, x: 1580, y: 810 },            // click
    { t: 4.3, x: 1580, y: 810 },            // click again
    { t: 5.2, x: 1585, y: 735 },            // glide to Continue
    { t: 5.5, x: 1585, y: 735 },            // hold/click
    { t: 8.0, x: 1585, y: 735 },
  ];
  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([7.4, 8.0], [1, 0], Easing.easeInCubic)(lt);
  const cursorOp = cur.op * cursorFadeOut;
  const settle = lt > continueClickT && lt < continueClickT + 0.4
    ? Math.sin((lt - continueClickT) * 30) * 1.5 * Math.exp(-(lt - continueClickT) * 8) : 0;

  // Number of days shown
  const visibleDays = isSixDay ? 6 : 5;
  const daySummary = isSixDay
    ? '6 days per week · Mon, Tue, Wed, Thu, Fri, Sat'
    : '5 days per week · Mon, Tue, Wed, Thu, Fri';

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

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

          {/* Working days card */}
          <div style={{
            marginTop: 18,
            opacity: wdCardOp,
            transform: `translateY(${wdCardY}px)`,
          }}>
            <Card style={{ padding: '22px 26px' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 16 }}>
                <div style={{
                  width: 42, height: 42, borderRadius: 11,
                  background: BRAND.greenSoft,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={BRAND.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="3" y="4" width="18" height="18" rx="2"/>
                    <path d="M16 2v4M8 2v4M3 10h18"/>
                  </svg>
                </div>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: BRAND.ink, letterSpacing: '-0.01em' }}>
                    Working days
                  </div>
                  <div style={{ fontSize: 14, color: BRAND.inkSoft, marginTop: 4, maxWidth: 800 }}>
                    Days the school operates. Most schools run Mon–Fri; many in India also have classes on Saturday.
                  </div>
                </div>
              </div>

              {/* 5/6 day toggle */}
              <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
                <ToggleChip label="5-day week (Mon–Fri)" selected={!isSixDay} justSelected={just5}/>
                <ToggleChip label="6-day week (Mon–Sat)" selected={isSixDay} justSelected={just6}/>
              </div>

              {/* Day chips */}
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {STEP3_DAYS.map(d => {
                  const sel = d !== 'Sat' || isSixDay;
                  const just = d === 'Sat' && satJustAdded;
                  return <DayChip key={d} label={d} selected={sel} justAdded={just}/>;
                })}
              </div>

              <div style={{ fontSize: 13, color: BRAND.inkSoft, marginTop: 12 }}>
                <span style={{ fontWeight: 700, color: BRAND.ink }}>{visibleDays}</span>{' '}{daySummary.slice(daySummary.indexOf(' '))}
              </div>
            </Card>
          </div>

          {/* Periods per class card */}
          <div style={{
            marginTop: 14,
            opacity: ppCardOp,
            transform: `translateY(${ppCardY}px)`,
          }}>
            <Card style={{ padding: '22px 26px' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 18 }}>
                <div style={{
                  width: 42, height: 42, borderRadius: 11,
                  background: BRAND.greenSoft,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  <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>
                </div>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: BRAND.ink, letterSpacing: '-0.01em' }}>
                    Periods per class
                  </div>
                  <div style={{ fontSize: 14, color: BRAND.inkSoft, marginTop: 4, maxWidth: 820 }}>
                    How many teaching periods each class has on a regular day. You can fine-tune individual classes below.
                  </div>
                </div>
              </div>

              {/* Table header */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 200px 200px',
                gap: 16,
                padding: '12px 14px',
                borderBottom: `1px solid ${BRAND.borderSoft}`,
              }}>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: BRAND.inkSub }}>Class</div>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: BRAND.inkSub, textAlign: 'right' }}>Regular</div>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: BRAND.inkSub, textAlign: 'right' }}>Extended</div>
              </div>

              {/* Class 1 row */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 200px 200px',
                gap: 16,
                padding: '18px 14px',
                alignItems: 'center',
              }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: BRAND.ink }}>Class 1</div>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Stepper value={periodsValue} plusHot={plusHot} justPlus={plusJust}/>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Stepper value={periodsValue + 1} faded/>
                </div>
              </div>
            </Card>
          </div>

          {/* Footer */}
          <div style={{ height: 1, background: BRAND.borderSoft, marginTop: 18 }}/>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginTop: 14,
          }}>
            <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' }}>
              <div style={{
                position: 'absolute', inset: 0,
                borderRadius: 10,
                background: BRAND.greenSoft,
                opacity: haloOp,
                transform: `scale(${haloScale})`,
                pointerEvents: 'none',
              }}/>
              <div style={{
                position: 'relative',
                display: 'inline-flex', alignItems: 'center', gap: 6,
                padding: '12px 22px', borderRadius: 10,
                background: continueActive > 0.5 ? BRAND.green : '#9bcdb6',
                color: '#fff',
                fontSize: 15, fontWeight: 600,
                transform: `scale(${1 - clickSquish})`,
                boxShadow: continueHot
                  ? `0 0 0 8px ${BRAND.greenSoft}, 0 8px 20px rgba(4,120,87,0.28)`
                  : continueActive > 0.5 ? '0 2px 6px rgba(4,120,87,0.18)' : 'none',
                transition: 'background 320ms, box-shadow 200ms',
              }}>
                Continue
                <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 - STEP3_FRAME.x,
            top: cur.y - STEP3_FRAME.y + settle,
            pointerEvents: 'none',
          }}>
            <Cursor x={0} y={0} opacity={cursorOp}/>
          </div>
        )}
      </AppFrame>
    </div>
  );
}

function Step3App({ loop = true, persistKey = "step3video" }) {
  return (
    <Stage width={1920} height={1080} duration={8.5} background={BRAND.bg} loop={loop} persistKey={persistKey}>
      <Step3Video start={0}/>
    </Stage>
  );
}

Object.assign(window, { Step3Video, Step3App });

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