/* global React */
const { useState, useEffect, useRef, useCallback } = React;

// ── 5 cenas de agentes customizados ──
// Simulando sessão interativa do Claude Code (já dentro do `claude`)
// Slash commands customizados criados em .claude/commands/
const SCENES = [
  {
    title: 'claude · ~/pagamentos',
    caption: '01 · Agente de refatoração',
    lines: [
      { type: 'cmd', text: '/refatorar billing-core --manter-contratos-publicos' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/refatorar.md' },
      { type: 'out', text: '⟡ Guardrails:  nunca alterar tabelas em prod  manter interface pública' },
      { type: 'out', text: 'Lendo  23 arquivos  contracts/*.ts  billing/*.ts' },
      { type: 'ok',  text: '✓ Plano: 4 etapas · 3 módulos extraídos · 187 testes passando' },
      { type: 'ok',  text: '↳ PR draft criado → #412 "refactor: billing-core extraction"' },
    ]
  },
  {
    title: 'claude · ~/api-gateway',
    caption: '02 · Agente de code review',
    lines: [
      { type: 'cmd', text: '/revisar-pr HEAD~5..HEAD --regras team-style.md' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/revisar-pr.md  +  guardrails.yml' },
      { type: 'out', text: 'Analisando  12 arquivos alterados  47 funções tocadas' },
      { type: 'warn', text: '⚠ 2 violações de estilo · 1 query N+1 em  UserRepo.list:42' },
      { type: 'warn', text: '⚠ Token de API exposto em  config/dev.ts:18  → bloqueado por guardrail' },
      { type: 'ok',  text: '✓ Correções aplicadas · commit amend feito' },
      { type: 'ok',  text: '↳ Review aprovado → ver  .claude/review-latest.md' },
    ]
  },
  {
    title: 'claude · ~/checkout-svc',
    caption: '03 · Guardrail: path absoluto bloqueado',
    lines: [
      { type: 'cmd', text: '/commit --pre-check' },
      { type: 'out', text: '⚙ Executando hooks de pré-commit…' },
      { type: 'err',  text: '✗ GUARDRAIL VIOLADO  Prevent hardcoded absolute paths in scripts and source files' },
      { type: 'warn', text: '⚠ Encontrado em  scripts/deploy.sh:14  →  /home/rafael/bin/node' },
      { type: 'warn', text: '⚠ Encontrado em  src/config.ts:8  →  /usr/local/data/cache' },
      { type: 'out', text: 'Corrigindo automaticamente…  $HOME/bin/node  $XDG_CACHE_HOME/data' },
      { type: 'ok',  text: '✓ 2 paths absolutos substituídos por variáveis de ambiente' },
      { type: 'ok',  text: '↳ Commit liberado · guardrail satisfeito' },
    ]
  },
  {
    title: 'claude · ~/frontend',
    caption: '04 · QA visual automatizado',
    lines: [
      { type: 'cmd', text: '/qa-visual --pagina checkout --viewport 1440,900' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/qa-visual.md  +  chrome headless' },
      { type: 'img', variant: 'before' },
      { type: 'err',  text: '✗ Artefato visual: botão "Finalizar" cortado em 12px na borda direita' },
      { type: 'warn', text: '⚠ Causa:  padding-right: 0  em  .checkout-cta  → faltando 16px' },
      { type: 'out', text: 'Corrigindo  src/components/CheckoutCTA.tsx:34  → padding: 0 16px' },
      { type: 'img', variant: 'after' },
      { type: 'ok',  text: '✓ Agente QA: layout validado · 0 artefatos · diff visual limpo' },
    ]
  },
  {
    title: 'claude · ~/produto',
    caption: '05 · PRD → decomposição por complexidade',
    lines: [
      { type: 'cmd', text: '/planejar @docs/prd-checkout-v2.md' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/planejar.md' },
      { type: 'out', text: 'Analisando PRD:  docs/prd-checkout-v2.md  (2.400 palavras · 14 requisitos)' },
      { type: 'warn', text: '⚠ Complexidade alta detectada: 3 requisitos cross-domain · 2 integrações externas' },
      { type: 'out', text: 'Acionando subagente  decompositor  → quebrando em problemas menores…' },
      { type: 'ok',  text: '✓ 14 requisitos → 6 épicos · 23 tasks independentes' },
      { type: 'ok',  text: '↳ Plano salvo em  .claude/plans/checkout-v2.md  → 3 tasks prontas pra sprint' },
    ]
  },
  {
    title: 'claude · ~/infra',
    caption: '06 · Agente de on-call',
    lines: [
      { type: 'cmd', text: '/oncall "P1 — checkout 500 desde 14h"' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/oncall.md  +  runbook.md' },
      { type: 'out', text: 'Investigando:  logs  métricas  deploys recentes' },
      { type: 'out', text: 'Correlação:  deploy 14:02  →  flag billing.v2 ativada' },
      { type: 'warn', text: '⚠ 342 erros/min em  /api/checkout  → NullRef em BillingAdapter' },
      { type: 'ok',  text: '✓ Causa raiz: flag sem fallback no adapter legado' },
      { type: 'ok',  text: '↳ Rollback executado · erros zeraram em 47s · postmortem criado' },
    ]
  },
  {
    title: 'claude · ~/plataforma',
    caption: '07 · Agente de migração',
    lines: [
      { type: 'cmd', text: '/migrar hadoop-to-snowflake --tabelas faturamento --zero-downtime' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/migrar.md  +  schemas.yml' },
      { type: 'out', text: 'Inventário:  18 tabelas  4 DAGs Airflow  2.3M registros/dia' },
      { type: 'out', text: '⟡ Guardrails:  validar schema  manter lineage' },
      { type: 'warn', text: '⚠ Coluna fiscal_id: encoding incompatível → conversão UTF-8' },
      { type: 'ok',  text: '✓ DAGs reescritas: Airflow → dbt + Snowpipe · paridade ok' },
      { type: 'ok',  text: '↳ Dry-run pronto → relatório em  .claude/migration.md' },
    ]
  },
  {
    title: 'claude · ~/checkout-svc',
    caption: '08 · Agente de testes',
    lines: [
      { type: 'cmd', text: '/gerar-testes checkout --cenarios-de-borda --sem-mock-de-banco' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/gerar-testes.md' },
      { type: 'out', text: 'Mapeando fluxo:  cart → payment → confirmation → webhook' },
      { type: 'out', text: '⟡ Guardrails:  usar test-containers  timeout 30s' },
      { type: 'ok',  text: '✓ 14 testes gerados · 3 cenários de borda encontrados' },
      { type: 'warn', text: '⚠ Caso novo: cupom expirado + retry → cobrança dupla' },
      { type: 'ok',  text: '↳ Fix sugerido em  checkout/apply-coupon.ts:67' },
    ]
  },
];

// ── Typing effect ──
function useTypingAnimation(scenes, typingSpeed = 32, lineDelay = 900, sceneDelay = 8500) {
  const [sceneIdx, setSceneIdx] = useState(0);
  const [visibleLines, setVisibleLines] = useState([]);
  const [typingLineIdx, setTypingLineIdx] = useState(0);
  const [typingCharIdx, setTypingCharIdx] = useState(0);
  const [phase, setPhase] = useState('typing'); // 'typing' | 'waiting' | 'transition'
  const timerRef = useRef(null);

  const scene = scenes[sceneIdx];
  const totalLines = scene.lines.length;

  // reset on scene change
  useEffect(() => {
    setVisibleLines([]);
    setTypingLineIdx(0);
    setTypingCharIdx(0);
    setPhase('typing');
  }, [sceneIdx]);

  useEffect(() => {
    if (phase === 'typing') {
      if (typingLineIdx >= totalLines) {
        setPhase('waiting');
        return;
      }
      const line = scene.lines[typingLineIdx];
      const isCmd = line.type === 'cmd';
      const fullText = line.text;

      if (isCmd) {
        if (typingCharIdx <= fullText.length) {
          timerRef.current = setTimeout(() => {
            setVisibleLines(prev => {
              const copy = [...prev];
              copy[typingLineIdx] = { ...line, text: fullText.slice(0, typingCharIdx), typing: typingCharIdx < fullText.length };
              return copy;
            });
            setTypingCharIdx(c => c + 1);
          }, typingCharIdx === 0 ? lineDelay : typingSpeed + Math.random() * 22);
        } else {
          timerRef.current = setTimeout(() => {
            setTypingLineIdx(i => i + 1);
            setTypingCharIdx(0);
          }, lineDelay);
        }
      } else {
        timerRef.current = setTimeout(() => {
          setVisibleLines(prev => {
            const copy = [...prev];
            copy[typingLineIdx] = { ...line, typing: false };
            return copy;
          });
          setTimeout(() => {
            setTypingLineIdx(i => i + 1);
            setTypingCharIdx(0);
          }, 180);
        }, lineDelay * 0.65);
      }
    } else if (phase === 'waiting') {
      timerRef.current = setTimeout(() => {
        setPhase('transition');
      }, sceneDelay);
    } else if (phase === 'transition') {
      timerRef.current = setTimeout(() => {
        setSceneIdx(i => (i + 1) % scenes.length);
      }, 700);
    }

    return () => clearTimeout(timerRef.current);
  }, [phase, typingLineIdx, typingCharIdx, sceneIdx]);

  return { scene, sceneIdx, visibleLines, phase, setSceneIdx: (i) => { setSceneIdx(i); } };
}

// ── Terminal component ──
function AnimatedTerminal() {
  const { scene, sceneIdx, visibleLines, phase, setSceneIdx } = useTypingAnimation(SCENES, 24, 500, 3500);

  const renderTag = (text) => {
    return text.split('  ').map((part, i) => {
      if (i % 2 === 1) return <span key={i} className="term-tag">{part}</span>;
      return <span key={i}>{part}</span>;
    });
  };

  const renderScreenshot = (variant) => {
    const isBefore = variant === 'before';
    return (
      <div className="term-screenshot" style={{margin: '8px 0 8px 22px'}}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6,
          fontFamily: '"Geist Mono", monospace', fontSize: 10, letterSpacing: '.08em',
          color: '#9d9b97', textTransform: 'uppercase'
        }}>
          <span>📸</span>
          <span>{isBefore ? 'checkout-before.png' : 'checkout-after.png'}</span>
          <span style={{
            background: isBefore ? 'rgba(224,90,90,.15)' : 'rgba(127,185,138,.15)',
            color: isBefore ? '#e05a5a' : '#7fb98a',
            padding: '1px 6px', borderRadius: 3, fontSize: 9
          }}>{isBefore ? 'ARTEFATO' : 'CORRIGIDO'}</span>
        </div>
        <svg viewBox="0 0 360 90" style={{
          width: '100%', maxWidth: 320, height: 'auto',
          border: '1px solid rgba(255,255,255,.08)', borderRadius: 4,
          background: '#1a1a1a', display: 'block'
        }}>
          {/* mini page mockup */}
          <rect x="0" y="0" width="360" height="14" fill="#111" />
          <circle cx="8" cy="7" r="2" fill="#3a3a3a" />
          <circle cx="16" cy="7" r="2" fill="#3a3a3a" />
          <circle cx="24" cy="7" r="2" fill="#3a3a3a" />
          <rect x="60" y="4" width="80" height="6" rx="3" fill="#222" />
          {/* nav bar */}
          <rect x="12" y="20" width="40" height="4" rx="1" fill="#333" />
          <rect x="280" y="20" width="30" height="4" rx="1" fill="#333" />
          <rect x="316" y="20" width="30" height="4" rx="1" fill="#333" />
          {/* content area */}
          <rect x="12" y="32" width="120" height="6" rx="1" fill="#2a2a2a" />
          <rect x="12" y="42" width="200" height="3" rx="1" fill="#222" />
          <rect x="12" y="48" width="180" height="3" rx="1" fill="#222" />
          {/* product card */}
          <rect x="12" y="58" width="60" height="24" rx="2" fill="#222" />
          <rect x="80" y="58" width="60" height="24" rx="2" fill="#222" />
          <rect x="148" y="58" width="60" height="24" rx="2" fill="#222" />
          {/* CTA button - the key element */}
          {isBefore ? (
            <>
              <rect x="280" y="60" width="78" height="20" rx="4" fill="#D97757" />
              {/* red dashed border showing the clipped area */}
              <rect x="346" y="58" width="14" height="24" fill="rgba(224,90,90,.25)" stroke="#e05a5a" strokeWidth=".8" strokeDasharray="2 1" />
              <line x1="346" y1="56" x2="346" y2="84" stroke="#e05a5a" strokeWidth=".6" strokeDasharray="2 2" />
              {/* annotation arrow */}
              <text x="320" y="54" fill="#e05a5a" fontSize="5" textAnchor="middle" fontFamily="monospace">cortado →</text>
            </>
          ) : (
            <>
              <rect x="280" y="60" width="68" height="20" rx="4" fill="#D97757" />
              {/* green check near button */}
              <circle cx="272" cy="70" r="5" fill="none" stroke="#7fb98a" strokeWidth=".7" />
              <text x="272" y="72" fill="#7fb98a" fontSize="6" textAnchor="middle" fontFamily="monospace">✓</text>
            </>
          )}
        </svg>
      </div>
    );
  };

  const renderCmd = (text) => {
    const lines = text.split('\n');
    return lines.map((line, i) => (
      <span key={i}>
        {i > 0 && <br />}
        {i > 0 && <span style={{color: 'var(--dim)', userSelect:'none'}}>{'  '}</span>}
        {line}
      </span>
    ));
  };

  return (
    <div className="term" aria-hidden="true" style={{ opacity: phase === 'transition' ? 0 : 1, transition: 'opacity .6s ease' }}>
      <span className="term-caption">{scene.caption}</span>
      <div className="term-head">
        <span className="term-dot"></span>
        <span className="term-dot"></span>
        <span className="term-dot"></span>
        <span className="term-title">{scene.title}</span>
      </div>
      <div className="term-body" style={{ minHeight: 340 }}>
        {visibleLines.map((line, i) => {
          if (!line) return null;
          if (line.type === 'img') {
            return <div key={i}>{renderScreenshot(line.variant)}</div>;
          }
          if (line.type === 'cmd') {
            return (
              <div className="term-line" key={i} style={{alignItems: 'flex-start'}}>
                <span className="term-prompt" style={{marginTop: 2}}>›</span>
                <span className="term-cmd" style={{whiteSpace: 'pre-wrap'}}>
                  {renderCmd(line.text)}
                  {line.typing && <span className="cursor"></span>}
                </span>
              </div>
            );
          }
          const cls = line.type === 'ok' ? 'term-out ok' : line.type === 'warn' ? 'term-out warn' : line.type === 'err' ? 'term-out err' : 'term-out';
          return (
            <div className={cls} key={i} style={{ marginTop: i > 0 && visibleLines[i-1]?.type === 'cmd' ? 8 : 3 }}>
              {renderTag(line.text)}
            </div>
          );
        })}
        {phase === 'waiting' && (
          <div className="term-line" style={{ marginTop: 14 }}>
            <span className="term-prompt">›</span>
            <span className="term-cmd"><span className="cursor"></span></span>
          </div>
        )}
      </div>
      <div className="term-pips">
        {SCENES.map((_, i) => (
          <button
            key={i}
            className={'term-pip' + (i === sceneIdx ? ' active' : '')}
            onClick={() => setSceneIdx(i)}
            aria-label={`Cena ${i + 1}`}
          ></button>
        ))}
      </div>
    </div>
  );
}

window.AnimatedTerminal = AnimatedTerminal;
