// Video 1 Scene 4 — Auto-train HERO (5 panes cascading)
// This is where Norami's superpower becomes visible.
//
// Five panes animate in sequence:
//  1. Column normalization        (Mort. Semanal → mort_weekly)
//  2. Column descriptions         (typed italic lines)
//  3. Business glossary           (FCR → Feed Conversion Ratio)
//  4. Row relationships           (foreign-key graph)
//  5. Tool prompts                (sql_tool + python_tool system prompts)
// End beat: giant gold checkmark + "Your assistant is ready."

function V1S4({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      {({ localTime, duration }) => {
        const entryT = Easing.easeOutCubic(Math.min(1, localTime / 0.4));
        const exitStart = duration - 0.3;
        const exitT = localTime > exitStart
          ? Easing.easeInCubic(Math.min(1, (localTime - exitStart) / 0.3))
          : 0;

        return (
          <div style={{
            position: 'absolute', inset: 0,
            background: N2.bg,
            opacity: entryT * (1 - exitT),
          }}>
            <V2Kicker text="step 02 · auto-train" x={60} y={50} />

            <div style={{
              position: 'absolute', left: 60, top: 108,
              fontFamily: N2.serif, fontSize: 52, fontWeight: 350,
              letterSpacing: '-0.025em', lineHeight: 1.02, color: N2.fg,
            }}>
              Teaching itself,{' '}
              <em style={{ color: N2.gold, fontStyle: 'italic' }}>automatically.</em>
            </div>

            {/* 2x3 grid of panes, last cell is a "done" summary */}
            <div style={{
              position: 'absolute',
              left: 60, top: 220, right: 60,
              display: 'grid',
              gridTemplateColumns: '1fr 1fr',
              gridAutoRows: '250px',
              gap: 14,
            }}>
              <NormalizePane    localTime={localTime} delay={0.2} />
              <DescriptionsPane localTime={localTime} delay={1.4} />
              <GlossaryPane     localTime={localTime} delay={3.0} />
              <RelationsPane    localTime={localTime} delay={5.0} />
              <PromptsPane      localTime={localTime} delay={7.2} />
              <ReadyPane        localTime={localTime} delay={10.0} />
            </div>
          </div>
        );
      }}
    </Sprite>
  );
}

// ── Shared pane chrome ────────────────────────────────────────────────────
function AutoPane({ title, delay, localTime, children, status }) {
  const t = Easing.easeOutQuart(Math.min(1, Math.max(0, (localTime - delay) / 0.4)));
  return (
    <div style={{
      background: N2.bgRaised,
      border: `1px solid ${N2.border}`,
      borderRadius: 14,
      padding: '14px 18px',
      fontFamily: N2.sans,
      opacity: t,
      transform: `translateY(${(1 - t) * 14}px)`,
      overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 10,
      }}>
        <div style={{
          fontFamily: N2.mono, fontSize: 10,
          letterSpacing: '0.14em', textTransform: 'uppercase',
          color: N2.fgFaint,
        }}>[ {title} ]</div>
        {status}
      </div>
      <div style={{ flex: 1, overflow: 'hidden' }}>{children}</div>
    </div>
  );
}

function StatusDot({ active }) {
  const t = useTime();
  if (!active) return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontFamily: N2.mono, fontSize: 10,
      color: N2.gold,
    }}>
      <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
        <path d="M3 6l2 2 4-4" stroke={N2.gold} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      done
    </div>
  );
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {[0,1,2].map(i => {
        const phase = (t * 4 + i * 0.3) % 2;
        const o = 0.3 + 0.7 * Math.max(0, Math.sin(phase * Math.PI));
        return <div key={i} style={{
          width: 4, height: 4, borderRadius: 2, background: N2.gold, opacity: o,
        }}/>;
      })}
    </div>
  );
}

// 1) Normalization
function NormalizePane({ localTime, delay }) {
  const rows = [
    { from: 'Weekly Mort.',          to: 'mort_weekly',    unit: 'count' },
    { from: 'Avg Weight (gr)',       to: 'avg_weight_gr',  unit: 'grams' },
    { from: 'FCR',                   to: 'fcr',            unit: 'ratio' },
    { from: 'Biomass (kg)',          to: 'biomass_kg',     unit: 'kg' },
    { from: 'Sampling Date',         to: 'sampling_date',  unit: 'date' },
  ];
  const active = localTime > delay && localTime < delay + 1.2;
  return (
    <AutoPane title="normalize columns" delay={delay} localTime={localTime} status={<StatusDot active={active}/>}>
      {rows.map((r, i) => {
        const ra = Math.min(1, Math.max(0, (localTime - delay - 0.1 - i * 0.12) / 0.3));
        return (
          <div key={r.to} style={{
            display: 'grid', gridTemplateColumns: '1fr 18px 1fr 60px',
            alignItems: 'center', gap: 8, padding: '4px 0',
            fontFamily: N2.mono, fontSize: 11,
            opacity: ra,
            transform: `translateX(${(1 - ra) * 8}px)`,
          }}>
            <div style={{ color: N2.fgFaint }}>{r.from}</div>
            <div style={{ color: N2.gold, textAlign: 'center' }}>→</div>
            <div style={{ color: N2.fg, fontWeight: 500 }}>{r.to}</div>
            <div style={{
              fontSize: 9, padding: '1px 6px',
              background: 'rgba(184,146,74,0.12)', color: N2.goldSoft,
              borderRadius: 3, textAlign: 'center',
              letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>{r.unit}</div>
          </div>
        );
      })}
    </AutoPane>
  );
}

// 2) Descriptions — italic Sectra lines type in
function DescriptionsPane({ localTime, delay }) {
  const rows = [
    { col: 'mort_weekly',    desc: 'Weekly fish mortality per cage' },
    { col: 'avg_weight_gr',  desc: 'Average fish weight at sampling' },
    { col: 'fcr',            desc: 'Feed conversion ratio (kg feed / kg gain)' },
    { col: 'biomass_kg',     desc: 'Live-weight inventory per center' },
  ];
  const active = localTime > delay && localTime < delay + 1.5;
  return (
    <AutoPane title="column descriptions" delay={delay} localTime={localTime} status={<StatusDot active={active}/>}>
      {rows.map((r, i) => {
        const rowStart = delay + 0.2 + i * 0.32;
        const typeT = Math.min(1, Math.max(0, (localTime - rowStart) / 0.3));
        const chars = Math.floor(typeT * r.desc.length);
        return (
          <div key={r.col} style={{
            padding: '5px 0',
            opacity: Math.min(1, Math.max(0, (localTime - rowStart) / 0.15)),
          }}>
            <div style={{ fontFamily: N2.mono, fontSize: 10, color: N2.fgMuted, marginBottom: 2 }}>
              {r.col}
            </div>
            <div style={{
              fontFamily: N2.serif, fontSize: 15, fontStyle: 'italic',
              color: N2.gold, lineHeight: 1.25, letterSpacing: '-0.005em',
            }}>
              {r.desc.slice(0, chars)}
              {typeT > 0 && typeT < 1 && (
                <span style={{
                  display: 'inline-block', width: 1.5, height: 14,
                  background: N2.gold, marginLeft: 1,
                  verticalAlign: 'text-bottom',
                }}/>
              )}
            </div>
          </div>
        );
      })}
    </AutoPane>
  );
}

// 3) Business glossary
function GlossaryPane({ localTime, delay }) {
  const terms = [
    { term: 'FCR',         def: 'Feed Conversion Ratio' },
    { term: 'Biomass',     def: 'Live-weight inventory' },
    { term: 'Center',      def: 'Production cage unit' },
    { term: 'Farmgate',    def: 'Wholesale reference price' },
    { term: 'Cycle',       def: 'Full grow-out period (~16mo)' },
    { term: 'EBITDA',      def: 'Operating earnings pre-D&A' },
  ];
  const active = localTime > delay && localTime < delay + 1.6;
  return (
    <AutoPane title="business glossary" delay={delay} localTime={localTime} status={<StatusDot active={active}/>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 14px' }}>
        {terms.map((t, i) => {
          const ta = Math.min(1, Math.max(0, (localTime - delay - 0.2 - i * 0.14) / 0.3));
          return (
            <div key={t.term} style={{
              display: 'flex', alignItems: 'baseline', gap: 8,
              opacity: ta,
              transform: `translateY(${(1 - ta) * 6}px)`,
            }}>
              <div style={{
                fontFamily: N2.mono, fontSize: 12, color: N2.fg, fontWeight: 600,
              }}>{t.term}</div>
              <div style={{
                fontFamily: N2.sans, fontSize: 11, color: N2.fgSubtle,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>{t.def}</div>
            </div>
          );
        })}
      </div>
    </AutoPane>
  );
}

// 4) Row relationships
function RelationsPane({ localTime, delay }) {
  const active = localTime > delay && localTime < delay + 1.8;
  // Draw a tiny 3-table graph
  const nodes = [
    { id: 'mortality',      x: 40,  y: 80,  w: 110 },
    { id: 'centers',        x: 220, y: 30,  w: 90 },
    { id: 'samplings',      x: 220, y: 140, w: 100 },
  ];
  const edges = [
    { from: 'mortality', to: 'centers',    label: 'center_code → id',  delay: 0.3 },
    { from: 'mortality', to: 'samplings',  label: 'id → mort_id',       delay: 0.9 },
  ];

  return (
    <AutoPane title="row relationships" delay={delay} localTime={localTime} status={<StatusDot active={active}/>}>
      <svg width="100%" height="100%" viewBox="0 0 360 190" style={{ overflow: 'visible' }}>
        {edges.map((e, i) => {
          const from = nodes.find(n => n.id === e.from);
          const to = nodes.find(n => n.id === e.to);
          const x1 = from.x + from.w;
          const y1 = from.y + 14;
          const x2 = to.x;
          const y2 = to.y + 14;
          const ea = Math.min(1, Math.max(0, (localTime - delay - e.delay) / 0.4));
          return (
            <g key={i} opacity={ea}>
              <path
                d={`M ${x1} ${y1} C ${(x1+x2)/2} ${y1}, ${(x1+x2)/2} ${y2}, ${x2} ${y2}`}
                stroke={N2.gold} strokeWidth="1.2" fill="none"
                strokeDasharray="3 3"
              />
              <text x={(x1+x2)/2} y={(y1+y2)/2 - 4} textAnchor="middle"
                fontFamily={N2.mono} fontSize="8" fill={N2.goldSoft}>
                {e.label}
              </text>
            </g>
          );
        })}
        {nodes.map((n, i) => {
          const na = Math.min(1, Math.max(0, (localTime - delay - 0.1 - i * 0.12) / 0.3));
          return (
            <g key={n.id} opacity={na} transform={`translate(${n.x}, ${n.y})`}>
              <rect width={n.w} height={28} rx={6}
                fill={N2.bgCard} stroke={N2.borderStrong} strokeWidth="1"/>
              <text x={n.w / 2} y={18} textAnchor="middle"
                fontFamily={N2.mono} fontSize="11" fill={N2.fg} fontWeight="500">
                {n.id}
              </text>
            </g>
          );
        })}
      </svg>
    </AutoPane>
  );
}

// 5) Tool prompts
function PromptsPane({ localTime, delay }) {
  const sqlText = 'You query Production_Q3 + postgres.mortality.\nJoin on center_code=id. Units: kg, grams.';
  const pyText  = 'You analyze trends in mort_weekly, fcr.\nUse pandas. Reference glossary terms.';

  const sqlT = Math.min(1, Math.max(0, (localTime - delay - 0.2) / 1.0));
  const pyT  = Math.min(1, Math.max(0, (localTime - delay - 1.1) / 1.0));
  const active = localTime > delay && localTime < delay + 2.2;

  const typed = (text, prog) => text.slice(0, Math.floor(prog * text.length));

  return (
    <AutoPane title="tool prompts" delay={delay} localTime={localTime} status={<StatusDot active={active}/>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <CodeBlock label="[sql_tool]" text={typed(sqlText, sqlT)} opacity={Math.min(1, sqlT * 5)}/>
        <CodeBlock label="[python_tool]" text={typed(pyText, pyT)} opacity={Math.min(1, pyT * 5)}/>
      </div>
    </AutoPane>
  );
}

function CodeBlock({ label, text, opacity }) {
  return (
    <div style={{
      background: 'rgba(0,0,0,0.35)',
      border: `1px solid ${N2.border}`,
      borderRadius: 8,
      padding: '8px 10px',
      opacity,
    }}>
      <div style={{
        fontFamily: N2.mono, fontSize: 9, color: N2.gold,
        letterSpacing: '0.08em', marginBottom: 4,
      }}>{label}</div>
      <div style={{
        fontFamily: N2.mono, fontSize: 10, color: N2.fgMuted,
        lineHeight: 1.35, whiteSpace: 'pre-wrap',
      }}>{text}</div>
    </div>
  );
}

// 6) Ready summary pane
function ReadyPane({ localTime, delay }) {
  const t = Easing.easeOutBack(Math.min(1, Math.max(0, (localTime - delay) / 0.6)));
  const tUse = useTime();
  const glow = 0.8 + Math.sin(tUse * 2) * 0.2;

  return (
    <div style={{
      background: 'radial-gradient(circle at center, rgba(184,146,74,0.15), rgba(184,146,74,0.02))',
      border: `1.5px solid ${N2.gold}`,
      borderRadius: 14,
      padding: '18px',
      fontFamily: N2.sans,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      gap: 10,
      opacity: t,
      transform: `scale(${0.9 + t * 0.1})`,
      boxShadow: `0 0 40px rgba(184,146,74,${glow * 0.25})`,
    }}>
      <div style={{
        width: 54, height: 54, borderRadius: '50%',
        background: N2.gold,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="26" height="26" viewBox="0 0 26 26" fill="none">
          <path d="M6 13l5 5 10-10" stroke={N2.bg} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
      <div style={{
        fontFamily: N2.serif, fontSize: 26, fontWeight: 350,
        color: N2.fg, textAlign: 'center', lineHeight: 1.15,
        letterSpacing: '-0.02em',
      }}>
        Your assistant<br/>
        <em style={{ color: N2.gold, fontStyle: 'italic' }}>is ready.</em>
      </div>
    </div>
  );
}

Object.assign(window, { V1S4 });
