// AI animation variations — v2, more distinct & novel. Each one uses a
// different visual metaphor for what the AI is doing, tied to construction
// data so they read as real product moments, not generic chatbot UI.

function AIAnimationsPage() {
  return (
    <div style={{
      width: '100%', height: '100%', background: C.bg, color: C.ink,
      fontFamily: C.sans, fontSize: 13, padding: 20, overflow: 'hidden',
      display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
      gridAutoRows: 'minmax(0, 1fr)', gap: 14, alignContent: 'start',
    }}>
      <AnimExtract />
      <AnimConstellation />
      <AnimMorphForm />
      <AnimCitations />
      <AnimRewrite />
      <AnimGanttWrite />
      <AnimParticles />
      <AnimReceiptParse />
      <AnimMagicSelect />
      <AnimChipsCascade />
      <AnimBlueprintTrace />
      <AnimLiquidBrief />

      <style>{`
        @keyframes aiFadeUp { 0% { opacity: 0; transform: translateY(6px) } 100% { opacity: 1; transform: translateY(0) } }
        @keyframes aiFadeIn { 0% { opacity: 0 } 100% { opacity: 1 } }
        @keyframes aiBlink { 50% { opacity: 0 } }
        @keyframes aiPulse { 0%,100% { opacity: 1 } 50% { opacity: 0.35 } }
        @keyframes aiPing { 0% { transform: scale(1); opacity: 0.7 } 80% { transform: scale(2); opacity: 0 } 100% { opacity: 0 } }
        @keyframes aiSpin { to { transform: rotate(360deg) } }
        @keyframes aiDash { to { stroke-dashoffset: -40 } }
        @keyframes aiShimmer { 0% { background-position: -200% 0 } 100% { background-position: 200% 0 } }
        @keyframes aiDrawBar { 0% { width: 0 } 100% { width: var(--w) } }
        @keyframes aiSparkle { 0%,100% { opacity: 0; transform: scale(0.3) } 50% { opacity: 1; transform: scale(1) } }
        @keyframes aiFloat { 0%,100% { transform: translate(0,0) } 50% { transform: translate(2px,-3px) } }
      `}</style>
    </div>
  );
}

function Shell({ label, sub, children, dark, accent }) {
  return (
    <div style={{
      background: dark ? '#0c111b' : C.panel,
      color: dark ? '#e6edf7' : C.ink,
      border: `1px solid ${dark ? '#1a2233' : C.line}`,
      borderRadius: 12, padding: 14,
      display: 'flex', flexDirection: 'column', gap: 10,
      position: 'relative', overflow: 'hidden', minHeight: 0,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <div style={{ fontSize: 10, color: dark ? '#7388a8' : C.ink3, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>{label}</div>
        <div style={{ fontSize: 11, color: dark ? '#99a8c0' : C.ink2, flex: 1 }}>{sub}</div>
        {accent && <div style={{ width: 6, height: 6, borderRadius: '50%', background: accent, animation: 'aiPulse 1.6s ease-in-out infinite' }} />}
      </div>
      <div style={{ flex: 1, minHeight: 0, position: 'relative' }}>{children}</div>
    </div>
  );
}

// ── 1. Invoice extraction: image → structured fields ──────────
function AnimExtract() {
  const [k, setK] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setK((v) => (v + 1) % 6), 900); return () => clearInterval(t); }, []);
  const fields = [
    ['Vendor','Brannigan Concrete'],
    ['Invoice','INV-1142'],
    ['Amount','$184,220'],
    ['Due','Apr 25'],
    ['PO match','PO-0338'],
  ];
  return (
    <Shell label="Parse" sub="Photo → structured invoice" accent={C.blue}>
      <div style={{ display: 'grid', gridTemplateColumns: '88px 1fr', gap: 12, height: '100%' }}>
        <div style={{ background: `repeating-linear-gradient(135deg, #c4bfb0 0 6px, #b6b1a4 6px 12px)`, borderRadius: 6, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: 8, left: 6, right: 6, height: 3, background: '#fff', opacity: 0.8 }} />
          <div style={{ position: 'absolute', top: 16, left: 6, width: 40, height: 2, background: '#fff', opacity: 0.6 }} />
          {fields.map((_, i) => (
            <div key={i} style={{
              position: 'absolute', top: 28 + i * 8, left: 6, width: 50, height: 2,
              background: i < k ? 'rgba(37,99,235,0.9)' : '#fff', opacity: i < k ? 1 : 0.4,
              transition: 'all 300ms',
            }} />
          ))}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, justifyContent: 'center' }}>
          {fields.map(([k_, v], i) => (
            <div key={i} style={{
              display: 'flex', fontSize: 11, opacity: i < k ? 1 : 0,
              transform: i < k ? 'translateY(0)' : 'translateY(6px)',
              transition: 'all 400ms cubic-bezier(.2,.8,.2,1)',
            }}>
              <span style={{ width: 62, color: C.ink3, fontSize: 10, letterSpacing: '0.02em' }}>{k_}</span>
              <span style={{ fontFamily: C.mono, fontWeight: 500 }}>{v}</span>
              {i === k - 1 && <span style={{ marginLeft: 6, width: 4, height: 4, borderRadius: '50%', background: C.blue }} />}
            </div>
          ))}
        </div>
      </div>
    </Shell>
  );
}

// ── 2. Constellation — data points forming an answer ─────────
function AnimConstellation() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => { const id = setInterval(() => setT((v) => (v + 1) % 60), 80); return () => clearInterval(id); }, []);
  const nodes = [
    [30, 40], [80, 25], [140, 60], [200, 35], [250, 80], [320, 45],
    [60, 90], [120, 115], [190, 100], [260, 130], [330, 110],
    [90, 150], [170, 160], [240, 175], [310, 160],
  ];
  const active = Math.min(nodes.length, Math.floor(t * nodes.length / 40));
  return (
    <Shell label="Correlate" sub="Connecting 312 data points" dark accent="#6ea7ff">
      <svg viewBox="0 0 360 200" style={{ width: '100%', height: '100%' }}>
        {nodes.map((n, i) => nodes.map((m, j) => {
          if (j <= i || i >= active || j >= active) return null;
          const dx = n[0] - m[0], dy = n[1] - m[1];
          if (Math.sqrt(dx*dx + dy*dy) > 100) return null;
          return <line key={`${i}-${j}`} x1={n[0]} y1={n[1]} x2={m[0]} y2={m[1]} stroke="#6ea7ff" strokeWidth="0.5" opacity="0.35" />;
        }))}
        {nodes.map((n, i) => (
          <g key={i} opacity={i < active ? 1 : 0.15} style={{ transition: 'opacity 400ms' }}>
            <circle cx={n[0]} cy={n[1]} r={i === active - 1 ? 4 : 2.2} fill="#6ea7ff" />
            {i === active - 1 && <circle cx={n[0]} cy={n[1]} r="10" fill="none" stroke="#6ea7ff" strokeWidth="1" opacity="0.6" />}
          </g>
        ))}
        <text x="180" y="196" fill="#8ca0c0" fontSize="9" fontFamily="monospace" textAnchor="middle">
          linking invoices · daily logs · POs
        </text>
      </svg>
    </Shell>
  );
}

// ── 3. Form assembling itself ────────────────────────────────
function AnimMorphForm() {
  const [k, setK] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setK((v) => (v + 1) % 5), 700); return () => clearInterval(t); }, []);
  const fields = [
    ['To',     'rcalloway@calloway.co'],
    ['Subject','CO-017 · Low-E glazing · ready to sign'],
    ['Body',   "Hi Ruth — gentle nudge. Quote + drawings attached."],
    ['Attach', '2 files · 184 KB'],
  ];
  return (
    <Shell label="Draft" sub="Nudge email, composing live" accent={C.indigo}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '4px 2px' }}>
        {fields.map(([lab, val], i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '52px 1fr',
            gap: 8, fontSize: 11,
            opacity: i < k ? 1 : 0.15,
            transform: i < k ? 'translateY(0)' : 'translateY(4px)',
            transition: 'all 500ms cubic-bezier(.2,.8,.2,1)',
          }}>
            <span style={{ color: C.ink3, letterSpacing: '0.02em' }}>{lab}</span>
            <span style={{
              background: i === k - 1 ? `linear-gradient(90deg, ${C.blueSoft} 0, transparent)` : 'transparent',
              borderBottom: `1px dashed ${i < k ? C.line : 'transparent'}`,
              paddingBottom: 2, fontFamily: lab === 'Body' ? C.sans : C.mono,
              color: C.ink, transition: 'background 400ms',
            }}>{val}{i === k - 1 && <span style={{ display: 'inline-block', width: 2, height: 10, background: C.blue, marginLeft: 1, verticalAlign: 'text-bottom', animation: 'aiBlink 1s steps(2) infinite' }} />}</span>
          </div>
        ))}
      </div>
      <div style={{ position: 'absolute', bottom: 0, right: 0, display: 'flex', gap: 6, opacity: k >= 4 ? 1 : 0, transition: 'opacity 400ms' }}>
        <span style={{ padding: '3px 8px', fontSize: 10, background: C.ink, color: '#fff', borderRadius: 4 }}>Send</span>
        <span style={{ padding: '3px 8px', fontSize: 10, border: `1px solid ${C.line}`, borderRadius: 4 }}>Edit</span>
      </div>
    </Shell>
  );
}

// ── 4. Citations — source cards cascading behind a quote ─────
function AnimCitations() {
  return (
    <Shell label="Ground" sub="Answer with sources">
      <div style={{ fontSize: 12, lineHeight: 1.5 }}>
        Framing is <b>62%</b> complete
        <sup style={{ color: C.blue, fontSize: 9, fontFamily: C.mono, padding: '0 2px' }}>[1]</sup>
        · 3.4% over budget on slab B
        <sup style={{ color: C.blue, fontSize: 9, fontFamily: C.mono, padding: '0 2px' }}>[2]</sup>
        <sup style={{ color: C.blue, fontSize: 9, fontFamily: C.mono, padding: '0 2px' }}>[3]</sup>
      </div>
      <div style={{ position: 'absolute', bottom: 10, left: 14, right: 14, display: 'flex', gap: 6 }}>
        {[
          ['01','Daily log Apr 21','47 photos · stud count'],
          ['02','INV-1142','Brannigan · $184K'],
          ['03','PO-0338','232 cy vs 240 cy'],
        ].map((s, i) => (
          <div key={i} style={{
            flex: 1, padding: '8px 10px', background: C.bg, border: `1px solid ${C.line}`,
            borderLeft: `3px solid ${C.blue}`, borderRadius: 6, fontSize: 10,
            animation: `aiFadeUp 500ms ${i * 150}ms both`,
          }}>
            <div style={{ fontFamily: C.mono, color: C.blue, fontSize: 9 }}>[{s[0]}]</div>
            <div style={{ fontWeight: 500 }}>{s[1]}</div>
            <div style={{ color: C.ink3 }}>{s[2]}</div>
          </div>
        ))}
      </div>
    </Shell>
  );
}

// ── 5. Inline rewrite with strikethrough → new text ──────────
function AnimRewrite() {
  return (
    <Shell label="Rewrite" sub="Tone: polished" accent={C.mint}>
      <div style={{ fontSize: 12, lineHeight: 1.6, padding: '4px 2px' }}>
        <span style={{ textDecoration: 'line-through', color: C.ink4, background: '#fee2e2', padding: '1px 3px', borderRadius: 2 }}>
          yo ruth, pls sign the glazing thing asap ok?
        </span>
        <br/>
        <span style={{
          display: 'inline-block', marginTop: 6,
          background: C.mintSoft, color: C.ink, padding: '2px 4px', borderRadius: 2,
          animation: 'aiFadeUp 600ms 400ms both',
        }}>
          Ruth — a gentle reminder that CO-017 is ready for your signature whenever convenient.
        </span>
      </div>
      <div style={{ position: 'absolute', bottom: 10, right: 14, display: 'flex', gap: 6 }}>
        {['Shorter','Longer','More formal','Casual'].map(t => (
          <span key={t} style={{ padding: '2px 7px', fontSize: 9, border: `1px solid ${C.line}`, borderRadius: 999, background: t === 'More formal' ? C.mintSoft : C.panel, color: t === 'More formal' ? C.mint : C.ink2 }}>{t}</span>
        ))}
      </div>
    </Shell>
  );
}

// ── 6. Gantt bars being drawn live ───────────────────────────
function AnimGanttWrite() {
  const [k, setK] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setK((v) => (v + 1) % 6), 700); return () => clearInterval(t); }, []);
  const rows = [
    ['Site prep',   10, 14, C.ink],
    ['Foundation',  24, 18, C.ink],
    ['Framing',     42, 22, C.blue],
    ['MEP rough',   64, 14, C.blue],
    ['Envelope',    78, 12, C.ink3],
  ];
  return (
    <Shell label="Plan" sub="Generating 4-phase schedule">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingTop: 6 }}>
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 8, fontSize: 10, alignItems: 'center', opacity: i < k ? 1 : 0.25, transition: 'opacity 400ms' }}>
            <span>{r[0]}</span>
            <div style={{ position: 'relative', height: 10, background: C.line2, borderRadius: 2 }}>
              <div style={{
                position: 'absolute', top: 0, bottom: 0, left: `${r[1]}%`,
                width: i < k ? `${r[2]}%` : '0%', background: r[3],
                transition: 'width 600ms cubic-bezier(.2,.8,.2,1)',
              }} />
              {i === k - 1 && <div style={{ position: 'absolute', top: -1, bottom: -1, left: `calc(${r[1] + r[2]}% - 1px)`, width: 2, background: C.blue }} />}
            </div>
          </div>
        ))}
      </div>
    </Shell>
  );
}

// ── 7. Particles converging into a number ────────────────────
function AnimParticles() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => { const id = setInterval(() => setT((v) => (v + 1) % 100), 60); return () => clearInterval(id); }, []);
  const prog = (t % 60) / 60;
  const particles = Array.from({ length: 24 }).map((_, i) => {
    const ang = (i / 24) * Math.PI * 2;
    const r = 80 * (1 - prog);
    return { x: 180 + Math.cos(ang) * r, y: 95 + Math.sin(ang) * r, o: prog };
  });
  return (
    <Shell label="Aggregate" sub="Rolling up 12 projects → 1 number" dark>
      <svg viewBox="0 0 360 190" style={{ width: '100%', height: '100%' }}>
        {particles.map((p, i) => (
          <circle key={i} cx={p.x} cy={p.y} r="2" fill="#6ea7ff" opacity={p.o * 0.8 + 0.2} />
        ))}
        <text x="180" y="100" fill="#e6edf7" fontSize="32" fontWeight="600" textAnchor="middle" letterSpacing="-0.02em" style={{ opacity: prog * prog }}>$5.27M</text>
        <text x="180" y="120" fill="#8ca0c0" fontSize="10" textAnchor="middle" style={{ opacity: prog }}>portfolio revenue YTD</text>
      </svg>
    </Shell>
  );
}

// ── 8. Receipt parser — lines highlight then populate table ──
function AnimReceiptParse() {
  const [k, setK] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setK((v) => (v + 1) % 5), 850); return () => clearInterval(t); }, []);
  return (
    <Shell label="Read" sub="Highlighting each line as it parses" accent={C.amber}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, height: '100%' }}>
        <div style={{ background: '#fafaf7', border: `1px solid ${C.line}`, borderRadius: 6, padding: '10px 12px', fontFamily: C.mono, fontSize: 10, lineHeight: 1.8 }}>
          <div>HOME DEPOT #2284</div>
          <div style={{ color: C.ink3 }}>apr 21, 2026 · 09:14</div>
          {[
            ['2X4-8  SPF',  '$4.82', 'x 80'],
            ['#4 REBAR',    '$12.40','x 24'],
            ['TYVEK 9x150', '$189.00','x 1'],
          ].map(([n, p, q], i) => (
            <div key={i} style={{
              padding: '1px 4px',
              background: i === (k - 1) ? `rgba(217,119,6,0.15)` : 'transparent',
              transition: 'background 300ms',
              display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 8,
            }}>
              <span>{n}</span><span>{q}</span><span>{p}</span>
            </div>
          ))}
          <div>─────────────────</div>
          <div>TOTAL  $878.40</div>
        </div>
        <div style={{ fontSize: 10, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 5 }}>
          {[
            ['2×4 SPF ×80','→ Pine Ridge · Framing'],
            ['Rebar #4 ×24','→ PO-0338'],
            ['Tyvek 9×150','→ new SKU'],
          ].map((r, i) => (
            <div key={i} style={{ opacity: i < k ? 1 : 0, transform: i < k ? 'translateX(0)' : 'translateX(-6px)', transition: 'all 400ms', fontFamily: C.mono }}>
              <div style={{ fontWeight: 500 }}>{r[0]}</div>
              <div style={{ color: C.ink3 }}>{r[1]}</div>
            </div>
          ))}
        </div>
      </div>
    </Shell>
  );
}

// ── 9. Magic selection — user highlights text, AI menu appears ─
function AnimMagicSelect() {
  const [t, setT] = React.useState(0);
  React.useEffect(() => { const id = setInterval(() => setT((v) => (v + 1) % 4), 900); return () => clearInterval(id); }, []);
  return (
    <Shell label="Select" sub="Highlight → AI menu appears">
      <div style={{ fontSize: 12, lineHeight: 1.65, padding: '2px 2px' }}>
        The owner requested{' '}
        <span style={{ background: t > 0 ? 'rgba(37,99,235,0.2)' : 'transparent', transition: 'background 300ms', position: 'relative', padding: '1px 2px', borderRadius: 2 }}>
          Low-E glazing across the west facade, pending quote
          {t > 1 && (
            <div style={{
              position: 'absolute', top: -40, left: -10,
              background: C.ink, color: '#fff', borderRadius: 8,
              padding: '4px 6px', display: 'flex', gap: 2,
              animation: 'aiFadeUp 250ms ease-out both',
              whiteSpace: 'nowrap', zIndex: 10,
            }}>
              {['Explain','Quote it','Draft CO','Ask…'].map((a, i) => (
                <span key={i} style={{ padding: '3px 7px', fontSize: 9, background: i === 0 ? 'rgba(255,255,255,0.12)' : 'transparent', borderRadius: 4 }}>{a}</span>
              ))}
            </div>
          )}
        </span>
        {' '}and we are still waiting on{' '}
        <span style={{ color: C.ink3 }}>approval from the board.</span>
      </div>
      {t >= 3 && (
        <div style={{ position: 'absolute', bottom: 10, left: 14, right: 14, padding: 8, background: C.blueSoft, borderRadius: 6, fontSize: 11, animation: 'aiFadeUp 400ms both' }}>
          Drafted CO-017 · $42,180 · 3 sheets attached →
        </div>
      )}
    </Shell>
  );
}

// ── 10. Suggestion chips cascading in ────────────────────────
function AnimChipsCascade() {
  const [k, setK] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setK((v) => (v + 1) % 8), 300); return () => clearInterval(t); }, []);
  const chips = [
    ['Overbudget POs', C.red],
    ['Open RFIs > 5d', C.amber],
    ['Weather next 7d', C.blue],
    ['Crew overtime', C.amber],
    ['Subs w/o insurance', C.red],
    ['Inspections this week', C.blue],
    ['Draw readiness', C.mint],
  ];
  return (
    <Shell label="Suggest" sub="7 follow-up queries">
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, padding: '4px 2px' }}>
        {chips.map(([t, c], i) => (
          <span key={i} style={{
            padding: '5px 10px', borderRadius: 999, fontSize: 11,
            border: `1px solid ${i < k ? c : C.line}`,
            color: i < k ? c : C.line2,
            background: i < k ? `${c}12` : C.panel,
            opacity: i < k ? 1 : 0,
            transform: i < k ? 'translateY(0) scale(1)' : 'translateY(8px) scale(0.92)',
            transition: 'all 400ms cubic-bezier(.2,.8,.2,1)',
          }}>{t}</span>
        ))}
      </div>
      <div style={{ position: 'absolute', bottom: 10, left: 14, fontSize: 10, color: C.ink3, fontFamily: C.mono }}>
        ↑ ↓ to focus · ↵ to run
      </div>
    </Shell>
  );
}

// ── 11. Blueprint trace — SVG path drawing itself ────────────
function AnimBlueprintTrace() {
  return (
    <Shell label="Sketch" sub="AI-generated floor plan from brief" dark accent="#6ea7ff">
      <svg viewBox="0 0 360 180" style={{ width: '100%', height: '100%' }}>
        <defs>
          <pattern id="grid1" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#1c2536" strokeWidth="0.5" />
          </pattern>
        </defs>
        <rect width="360" height="180" fill="url(#grid1)" />
        <path
          d="M 40 40 L 320 40 L 320 140 L 40 140 Z M 180 40 L 180 140 M 40 90 L 320 90"
          fill="none" stroke="#6ea7ff" strokeWidth="1.8" strokeLinecap="round"
          strokeDasharray="8 4"
          style={{ animation: 'aiDash 1.5s linear infinite' }}
        />
        {/* door arcs */}
        <path d="M 80 40 A 20 20 0 0 1 100 60" fill="none" stroke="#6ea7ff" strokeWidth="1" opacity="0.6" />
        <path d="M 220 90 A 20 20 0 0 0 240 110" fill="none" stroke="#6ea7ff" strokeWidth="1" opacity="0.6" />
        {/* dims */}
        <text x="180" y="30" fill="#8ca0c0" fontSize="9" textAnchor="middle" fontFamily="monospace">54' — Level 2 · 2BR</text>
      </svg>
    </Shell>
  );
}

// ── 12. Liquid daily brief — gradient bg + text type-in ──────
function AnimLiquidBrief() {
  const [k, setK] = React.useState(0);
  const lines = [
    'Framing 62%, on pace.',
    '41 of 44 crew on site.',
    '3 invoices need approval.',
    'One PPE flag at 10:14.',
  ];
  React.useEffect(() => { const t = setInterval(() => setK((v) => (v + 1) % 6), 700); return () => clearInterval(t); }, []);
  return (
    <Shell label="Brief" sub="Daily site summary">
      <div style={{ position: 'absolute', inset: 0, background: `
        radial-gradient(320px 180px at 20% 20%, rgba(110,167,255,0.18), transparent 70%),
        radial-gradient(260px 160px at 85% 80%, rgba(251,191,36,0.14), transparent 70%),
        radial-gradient(200px 140px at 60% 50%, rgba(139,92,246,0.12), transparent 70%)
      `, animation: 'aiFloat 4s ease-in-out infinite' }} />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 6, padding: '6px 4px' }}>
        {lines.map((l, i) => (
          <div key={i} style={{
            fontSize: 13, fontFamily: C.serif, fontStyle: 'italic', letterSpacing: '-0.01em',
            opacity: i < k ? 1 : 0, transform: i < k ? 'translateY(0)' : 'translateY(4px)',
            transition: 'all 400ms',
          }}>— {l}</div>
        ))}
      </div>
    </Shell>
  );
}

Object.assign(window, { AIAnimationsPage });
