// Step 1 focused short — fills in "School information" then advances to Step 2.
// Standalone scene; reuses BRAND, AppFrame, Card primitives from ui.jsx + animations.jsx.

const SCHOOL_NAME = "Sunridge Academy";
const ACADEMIC_YEAR = "2025-26";

// Beat plan (12.5s total):
//  0.0 – 0.7   App frame fades in
//  0.7 – 2.0   "SETUP WIZARD" eyebrow + headline word-stagger
//  2.0 – 2.6   Subtitle
//  2.6 – 3.2   Step strip slides in (6 steps)
//  3.2 – 3.8   School info card slides up
//  3.8 – 4.2   Cursor enters, glides to "School name" input
//  4.2 – 4.4   Click — input focuses (border)
//  4.4 – 6.4   Type "Sunridge Academy" char-by-char
//  6.4 – 6.9   Cursor to Academic year input
//  6.9 – 7.0   Click
//  7.0 – 7.9   Type "2025-26"
//  7.9 – 8.4   Continue button transitions from disabled → active
//  8.4 – 9.2   Cursor moves to Continue
//  9.2 – 9.5   Click — halo pulse
//  9.5 – 10.5  Step 1 ticks complete + green check, Step 2 activates
// 10.5 – 11.5  Header chrome fills in "Sunridge Academy"
// 11.5 – 12.5  Hold then fade

// ─── 6-step variant of the strip used in this video ──────────────────────────
function StepStrip6({ active = 0, completed = [], step1Progress = 0, step2Progress = 0 }) {
  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',
      gap: 0,
    }}>
      {steps.map((s, i) => {
        const isDone = completed.includes(i);
        const isActive = i === active;
        // Smooth color/scale on Step 1 as it ticks complete
        const tickT = i === 0 ? step1Progress : (i === 1 ? step2Progress : 0);
        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',
                transform: `scale(${1 + tickT * 0.08})`,
              }}>
                {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" strokeDasharray="24" strokeDashoffset={24 * (1 - tickT)}/>
                  </svg>
                ) : (i + 1)}
              </div>
              <span style={{
                fontSize: 14,
                fontWeight: isActive ? 700 : 500,
                color: isDone || isActive ? BRAND.ink : BRAND.inkSub,
                whiteSpace: 'nowrap',
                transition: 'all 240ms',
              }}>{s}</span>
            </div>
            {i < steps.length - 1 && (
              <div style={{
                flex: 1, height: 1,
                background: isDone || (i === 0 && tickT > 0.5) ? BRAND.greenMid : BRAND.borderSoft,
                margin: '0 14px',
                transition: 'background 240ms',
              }}/>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ─── Top chrome with smooth header-name fill-in ──────────────────────────────
function ChromeStep1({ schoolName = '', year = '2025-26', trialText = 'Trial · 7d left' }) {
  return (
    <div style={{
      height: 88, padding: '0 36px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      borderBottom: `1px solid ${BRAND.borderSoft}`,
      background: BRAND.bg,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12,
          background: BRAND.greenSoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="24" height="24" 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>
        </div>
        <div>
          <div style={{
            fontSize: 19, fontWeight: 700, color: BRAND.ink,
            lineHeight: 1.1,
            minHeight: 22,
            fontFamily: BRAND.font,
          }}>
            {schoolName || <span style={{ color: BRAND.inkSub, fontWeight: 500 }}>Setup</span>}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5 }}>
            <span style={{ fontSize: 13, color: BRAND.inkSoft, whiteSpace: 'nowrap' }}>{year}</span>
            <span style={{
              fontSize: 11, fontWeight: 600,
              padding: '2px 7px', borderRadius: 6,
              background: '#fef3c7', color: '#92400e',
              whiteSpace: 'nowrap',
            }}>Admin</span>
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          padding: '8px 14px', borderRadius: 999,
          background: BRAND.greenSoft, color: BRAND.green,
          fontSize: 14, fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 8,
          whiteSpace: 'nowrap',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M2 6l5 4 5-7 5 7 5-4-2 13H4z"/></svg>
          {trialText}
        </div>
        {/* Dark mode (moon) */}
        <div style={{
          width: 34, height: 34, borderRadius: 999,
          border: `1px solid ${BRAND.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: BRAND.inkSoft,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 12.79A9 9 0 1 1 11.21 3a7 7 0 0 0 9.79 9.79z"/>
          </svg>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 4,
          padding: '4px 4px 4px 12px', borderRadius: 999,
          border: `1px solid ${BRAND.border}`,
          background: '#fff',
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 999,
            background: BRAND.green, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 600,
          }}>C</div>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={BRAND.inkSub} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M6 9l6 6 6-6"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

// ─── Input field with focus state + typing caret ─────────────────────────────
function TextField({ label, placeholder, value, focused, showCaret = false }) {
  return (
    <div>
      <div style={{
        fontSize: 14, fontWeight: 600, color: BRAND.ink, marginBottom: 8,
      }}>{label}</div>
      <div style={{
        height: 52, padding: '0 16px',
        background: '#fff',
        border: `1px solid ${focused ? BRAND.green : BRAND.border}`,
        borderRadius: 10,
        display: 'flex', alignItems: 'center',
        fontSize: 16, color: value ? BRAND.ink : BRAND.inkSub,
        fontFamily: BRAND.font,
        boxShadow: focused ? `0 0 0 4px ${BRAND.greenSofter}` : 'none',
        transition: 'border-color 160ms, box-shadow 160ms',
      }}>
        {value || placeholder}
        {showCaret && (
          <span style={{
            display: 'inline-block',
            width: 2, height: 22,
            background: BRAND.green,
            marginLeft: 2,
            animation: 'caret-blink 1s steps(1) infinite',
          }}/>
        )}
      </div>
    </div>
  );
}

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

  const fadeIn = interpolate([0, 0.7], [0, 1], Easing.easeOutCubic)(lt);
  const fadeOut = interpolate([11.8, 12.5], [1, 0], Easing.easeInCubic)(lt);
  const sceneOp = fadeIn * fadeOut;

  // Eyebrow + headline + subtitle
  const eyebrowOp = interpolate([0.7, 1.2], [0, 1], Easing.easeOutCubic)(lt);
  const w1 = {
    op: interpolate([1.0, 1.5], [0, 1], Easing.easeOutCubic)(lt),
    y:  interpolate([1.0, 1.5], [20, 0], Easing.easeOutCubic)(lt),
  };
  const w2 = {
    op: interpolate([1.15, 1.65], [0, 1], Easing.easeOutCubic)(lt),
    y:  interpolate([1.15, 1.65], [20, 0], Easing.easeOutCubic)(lt),
  };
  const w3 = {
    op: interpolate([1.3, 1.8], [0, 1], Easing.easeOutCubic)(lt),
    y:  interpolate([1.3, 1.8], [20, 0], Easing.easeOutCubic)(lt),
  };
  const w4 = {
    op: interpolate([1.45, 1.95], [0, 1], Easing.easeOutCubic)(lt),
    y:  interpolate([1.45, 1.95], [20, 0], Easing.easeOutCubic)(lt),
  };

  const subOp = interpolate([2.0, 2.6], [0, 1], Easing.easeOutCubic)(lt);
  const subY  = interpolate([2.0, 2.6], [12, 0], Easing.easeOutCubic)(lt);

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

  const cardOp = interpolate([3.2, 3.8], [0, 1], Easing.easeOutCubic)(lt);
  const cardY  = interpolate([3.2, 3.8], [24, 0], Easing.easeOutCubic)(lt);

  // ── Inputs ────────────────────────────────────────────────────────────────
  // School name focus 4.2–4.4; type 4.4–6.4 (2s for 19 chars ≈ 0.105s/char)
  const nameFocusOn = lt >= 4.2 && lt < 6.6;
  const namePhase = clamp((lt - 4.4) / 2.0, 0, 1);
  const nameChars = Math.floor(namePhase * SCHOOL_NAME.length);
  const nameValue = SCHOOL_NAME.slice(0, nameChars);
  const nameCaret = lt >= 4.4 && lt < 6.4;

  // Academic year focus 6.9–7.95; type 7.0–7.9
  const yearFocusOn = lt >= 6.9 && lt < 8.0;
  const yearPhase = clamp((lt - 7.0) / 0.9, 0, 1);
  const yearChars = Math.floor(yearPhase * ACADEMIC_YEAR.length);
  const yearValue = yearChars > 0 ? ACADEMIC_YEAR.slice(0, yearChars) : '';
  const yearCaret = lt >= 7.0 && lt < 7.9;

  // Continue button activation 7.9 → 8.4
  const continueActive = interpolate([7.9, 8.4], [0, 1], Easing.easeOutCubic)(lt);
  const continueHot = lt > 8.9 && lt < 9.4;
  const clickT = (lt - 9.25) / 0.18;
  const clickSquish = clickT > 0 && clickT < 1 ? 0.05 * Math.sin(clickT * Math.PI) : 0;
  const haloOp = interpolate([9.3, 9.55, 10.0], [0, 0.7, 0], Easing.easeOutCubic)(lt);
  const haloScale = interpolate([9.3, 10.0], [1, 1.6], Easing.easeOutCubic)(lt);

  // Step transitions: step 1 completes at 9.5 → 10.2, step 2 activates 10.0 → 10.5
  const step1Progress = interpolate([9.5, 10.2], [0, 1], Easing.easeOutCubic)(lt);
  const step2Progress = interpolate([10.0, 10.5], [0, 1], Easing.easeOutCubic)(lt);
  const step1Done = lt >= 9.7;
  const activeStep = step1Done ? 1 : 0;
  const completed = step1Done ? [0] : [];

  // Header name fills in 10.5 → 11.3 (echoing what the user typed)
  const headerFill = clamp((lt - 10.5) / 0.8, 0, 1);
  const headerChars = Math.floor(headerFill * SCHOOL_NAME.length);
  const headerName = headerChars > 0 ? SCHOOL_NAME.slice(0, headerChars) : '';
  const headerYear = lt >= 10.5 ? ACADEMIC_YEAR : '2025-26';

  // ── Cursor path ───────────────────────────────────────────────────────────
  // Cursor SVG tip is at its (3, 2) corner, so position the SVG so the tip
  // visibly lands on the Continue button center (~1595, 738).
  const cursorPath = [
    { tIn: 3.6,  tOut: 4.2,  x: 1500, y: 1020 }, // entry from below
    { tIn: 4.2,  tOut: 6.4,  x: 600,  y: 600 },  // School name field
    { tIn: 6.4,  tOut: 6.9,  x: 1260, y: 600 },  // Academic year
    { tIn: 6.9,  tOut: 8.4,  x: 1300, y: 600 },  // tiny drift while typing
    { tIn: 8.4,  tOut: 9.2,  x: 1592, y: 736 },  // Continue button — tip on label
    { tIn: 9.2,  tOut: 12.0, x: 1592, y: 736 },  // hold through click
  ];
  const cur = (() => {
    if (lt < cursorPath[0].tIn) return { x: 1500, y: 1020, op: 0 };
    if (lt > 11.6) return { x: 1592, y: 736, op: 0 };
    for (let i = 0; i < cursorPath.length - 1; i++) {
      const a = cursorPath[i], b = cursorPath[i + 1];
      if (lt >= a.tIn && lt <= b.tIn) {
        const seg = clamp((lt - a.tIn) / (b.tIn - a.tIn || 1), 0, 1);
        const e = Easing.easeInOutCubic(seg);
        return { x: a.x + (b.x - a.x) * e, y: a.y + (b.y - a.y) * e, op: 1 };
      }
    }
    return { x: 1592, y: 736, op: 1 };
  })();

  // Cursor settle wobble after clicking Continue
  const settle = lt > 9.25 && lt < 9.65
    ? Math.sin((lt - 9.25) * 30) * 1.5 * Math.exp(-(lt - 9.25) * 8)
    : 0;

  return (
    <div style={{ position: 'absolute', inset: 0, opacity: sceneOp }}>
      <AppFrame x={FRAME.x} y={FRAME.y} width={FRAME.w} height={FRAME.h}>
        <ChromeStep1
          schoolName={headerName}
          year={headerYear}
          trialText="Trial · 7d left"
        />

        <div style={{ padding: '36px 56px' }}>
          {/* Eyebrow */}
          <div style={{
            fontSize: 13, fontWeight: 700, letterSpacing: '0.16em',
            textTransform: 'uppercase', color: BRAND.inkSub,
            opacity: eyebrowOp,
          }}>
            Setup wizard
          </div>

          {/* Headline — word-by-word stagger */}
          <div style={{
            fontSize: 48, fontWeight: 700, color: BRAND.ink,
            letterSpacing: '-0.02em', lineHeight: 1.05,
            marginTop: 12,
            fontFamily: BRAND.font,
          }}>
            <span style={{ display: 'inline-block', opacity: w1.op, transform: `translateY(${w1.y}px)` }}>Let's</span>{' '}
            <span style={{ display: 'inline-block', opacity: w2.op, transform: `translateY(${w2.y}px)` }}>build</span>{' '}
            <span style={{ display: 'inline-block', opacity: w3.op, transform: `translateY(${w3.y}px)` }}>your</span>{' '}
            <span style={{ display: 'inline-block', opacity: w4.op, transform: `translateY(${w4.y}px)` }}>timetable.</span>
          </div>

          {/* Subtitle */}
          <div style={{
            fontSize: 18, color: BRAND.inkSoft, marginTop: 10,
            maxWidth: 800, lineHeight: 1.5,
            opacity: subOp,
            transform: `translateY(${subY}px)`,
          }}>
            Six quick steps. You can leave any time and pick up where you left off — nothing is locked until you publish.
          </div>

          {/* Step strip */}
          <div style={{
            marginTop: 36,
            opacity: stripOp,
            transform: `translateY(${stripY}px)`,
          }}>
            <StepStrip6
              active={activeStep}
              completed={completed}
              step1Progress={step1Progress}
              step2Progress={step2Progress}
            />
          </div>

          {/* School info card */}
          <div style={{
            marginTop: 28,
            opacity: cardOp,
            transform: `translateY(${cardY}px)`,
          }}>
            <Card style={{ padding: '28px 32px' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 24 }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12,
                  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">
                    <path d="M3 21h18M5 21V7l7-4 7 4v14M9 9h.01M15 9h.01M9 13h.01M15 13h.01M9 17h.01M15 17h.01"/>
                  </svg>
                </div>
                <div>
                  <div style={{ fontSize: 20, fontWeight: 700, color: BRAND.ink, letterSpacing: '-0.01em' }}>
                    School information
                  </div>
                  <div style={{ fontSize: 14, color: BRAND.inkSoft, marginTop: 4 }}>
                    The basics. You can change these later from Settings.
                  </div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
                <TextField
                  label="School name"
                  placeholder="e.g. Sunrise Public School"
                  value={nameValue}
                  focused={nameFocusOn}
                  showCaret={nameCaret}
                />
                <TextField
                  label="Academic year"
                  placeholder="2025-26"
                  value={yearValue}
                  focused={yearFocusOn}
                  showCaret={yearCaret}
                />
              </div>
            </Card>
          </div>

          {/* Footer separator */}
          <div style={{ height: 1, background: BRAND.borderSoft, marginTop: 28, opacity: cardOp }}/>

          {/* Footer row */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginTop: 18,
            opacity: cardOp,
          }}>
            <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={{ fontSize: 14, color: BRAND.inkSub }}>
              Changes will be saved on continue
            </div>
            {/* Continue button — transitions from disabled green to active green */}
            <div style={{ position: 'relative' }}>
              {/* Halo pulse on click */}
              <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,
                // Interpolate background from pale to bright
                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',
                opacity: 0.5 + 0.5 * continueActive,
              }}>
                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 (inside frame so it stays clipped) */}
        {cur.op > 0 && (
          <div style={{
            position: 'absolute',
            left: cur.x - FRAME.x,
            top: cur.y - FRAME.y + settle,
            pointerEvents: 'none',
          }}>
            <Cursor x={0} y={0} opacity={cur.op}/>
          </div>
        )}
      </AppFrame>

      {/* Caret keyframes */}
      <style>{`
        @keyframes caret-blink {
          0%, 50% { opacity: 1; }
          50.01%, 100% { opacity: 0; }
        }
      `}</style>
    </div>
  );
}

function Step1App({ loop = true, persistKey = "step1video" }) {
  return (
    <Stage width={1920} height={1080} duration={12.5} background={BRAND.bg} loop={loop} persistKey={persistKey}>
      <Step1Video start={0}/>
    </Stage>
  );
}

Object.assign(window, { Step1Video, Step1App, ChromeStep1, StepStrip6, TextField });

// Default mount (looped, with playback bar). Recording mode mounts via a different entry.
if (!window.__STEP1_NO_AUTOMOUNT) {
  ReactDOM.createRoot(document.getElementById('root')).render(<Step1App/>);
}
