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

// ── 6 cenas: MMC + IA em engagements reais ──
const MMC_SCENES = [
  {
    title: 'mmc · tech-dd',
    caption: '01 · Due diligence com IA',
    lines: [
      { type: 'cmd', text: '/dd-scan --repo target-fintech --prazo 5d' },
      { type: 'out', text: '⚙ Carregando  .claude/commands/dd-scan.md  +  checklist-investidor.yml' },
      { type: 'out', text: 'Escaneando:  847 arquivos  12 serviços  3 databases  2 filas' },
      { type: 'warn', text: '⚠ Tech debt crítico: 23% do codebase sem cobertura de testes' },
      { type: 'warn', text: '⚠ Dependência vulnerável:  CVE-2024-38816  em 3 serviços core' },
      { type: 'ok',  text: '✓ Relatório executivo gerado → dd-report-target-v1.pdf' },
      { type: 'ok',  text: '↳ 47 findings · 3 blockers · recomendação: proceed with conditions' },
    ]
  },
  {
    title: 'mmc · migração-aws',
    caption: '02 · Migração zero-downtime',
    lines: [
      { type: 'cmd', text: '/migration-plan --from ovhcloud --to aws --contracts 60k' },
      { type: 'out', text: '⚙ Analisando infraestrutura atual…' },
      { type: 'out', text: 'Inventário:  14 serviços  60.247 contratos  15 integrações' },
      { type: 'out', text: '⟡ Guardrails:  zero downtime  compliance SUSEP  rollback <5min' },
      { type: 'ok',  text: '✓ Plano de migração: 4 fases · 12 meses · sem janela' },
      { type: 'ok',  text: '↳ migration-plan-v1.md  pronto para validação com o time' },
    ]
  },
  {
    title: 'mmc · data-eng',
    caption: '03 · Modernização de pipeline',
    lines: [
      { type: 'cmd', text: '/modernizar-pipeline --from hadoop-hive --to snowflake-trino' },
      { type: 'out', text: '⚙ Carregando  schemas.yml  +  lineage-map.json' },
      { type: 'out', text: 'Inventário:  18 tabelas  4 DAGs Airflow  2.3M registros/dia' },
      { type: 'warn', text: '⚠ Coluna fiscal_id: encoding incompatível → conversão UTF-8 necessária' },
      { type: 'out', text: 'Reescrevendo DAGs:  Hive HQL → Trino SQL + dbt models' },
      { type: 'ok',  text: '✓ DAGs migradas · paridade de dados validada · NiFi configurado' },
      { type: 'ok',  text: '↳ Queries que levavam horas agora executam em minutos' },
    ]
  },
  {
    title: 'mmc · arch-review',
    caption: '04 · Revisão de arquitetura',
    lines: [
      { type: 'cmd', text: '/arch-review --stack insurtech-backoffice --focus integrações' },
      { type: 'out', text: '⚙ Carregando contexto:  InsurTech · pipeline de seguros · 6 parceiros' },
      { type: 'out', text: 'Analisando:  8 microsserviços  4 integrações externas  2 databases' },
      { type: 'warn', text: '⚠ Gargalo: fila de processamento sem dead letter queue' },
      { type: 'warn', text: '⚠ Acoplamento: 3 serviços compartilhando schema de persistência' },
      { type: 'ok',  text: '✓ Proposta: 5 serviços consolidados · DLQ + retry pattern' },
      { type: 'ok',  text: '↳ arch-proposal-v1.md  → revisão com CTO na segunda' },
    ]
  },
  {
    title: 'mmc · turnaround',
    caption: '05 · Reorganização de time',
    lines: [
      { type: 'cmd', text: '/team-assessment --org fintech-b2b --headcount 20' },
      { type: 'out', text: '⚙ Mapeando  skills matrix  ownership  delivery metrics' },
      { type: 'out', text: '20 engenheiros · 3 squads · 0 tech leads seniores identificados' },
      { type: 'warn', text: '⚠ 4 áreas de produto sem ownership técnico definido' },
      { type: 'warn', text: '⚠ Lead time médio: 23 dias — benchmark do setor: 8 dias' },
      { type: 'ok',  text: '✓ Proposta: 4 verticais · 2 líderes a contratar · rituais redesenhados' },
      { type: 'ok',  text: '↳ Estimativa de impacto: lead time → 10 dias em 90 dias' },
    ]
  },
  {
    title: 'mmc · pós-aquisição',
    caption: '06 · Integração técnica M&A',
    lines: [
      { type: 'cmd', text: '/post-acquisition --target studio-acquired --acquirer nasdaq-co' },
      { type: 'out', text: '⚙ Carregando  integration-playbook.md  +  org-chart.yml' },
      { type: 'out', text: 'Mapeando:  40+ pessoas  2 stacks  3 produtos  800K DAU' },
      { type: 'out', text: '⟡ Prioridades:  retenção de talentos  unificação de deploy  SLA único' },
      { type: 'warn', text: '⚠ 2 serviços críticos sem documentação de runbook' },
      { type: 'ok',  text: '✓ Plano de integração: 6 meses · 4 workstreams · 0 churn técnico' },
      { type: 'ok',  text: '↳ Week 1: runbooks + on-call unificado · deploy pipeline comum' },
    ]
  },
];

// ── Typing animation hook ──
function useTerminalAnimation(scenes, typingSpeed = 28, lineDelay = 600, sceneDelay = 4000) {
  const [sceneIdx, setSceneIdx] = useState(0);
  const [visibleLines, setVisibleLines] = useState([]);
  const [typingLineIdx, setTypingLineIdx] = useState(0);
  const [typingCharIdx, setTypingCharIdx] = useState(0);
  const [phase, setPhase] = useState('typing');
  const timerRef = useRef(null);

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

  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() * 18);
        } 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);
          }, 150);
        }, lineDelay * 0.55);
      }
    } else if (phase === 'waiting') {
      timerRef.current = setTimeout(() => setPhase('transition'), sceneDelay);
    } else if (phase === 'transition') {
      timerRef.current = setTimeout(() => {
        setSceneIdx(i => (i + 1) % scenes.length);
      }, 600);
    }
    return () => clearTimeout(timerRef.current);
  }, [phase, typingLineIdx, typingCharIdx, sceneIdx]);

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

// ── Render helpers ──
function renderTag(text) {
  return text.split('  ').map((part, i) => {
    if (i % 2 === 1) return React.createElement('span', { key: i, className: 'term-tag' }, part);
    return React.createElement('span', { key: i }, part);
  });
}

// ── Terminal component ──
function MMCTerminal() {
  const { scene, sceneIdx, visibleLines, phase, setSceneIdx } = useTerminalAnimation(MMC_SCENES, 24, 500, 3500);

  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">
        {visibleLines.map((line, i) => {
          if (!line) return null;
          if (line.type === 'cmd') {
            return (
              <div className="term-line" key={i}>
                <span className="term-prompt">›</span>
                <span className="term-cmd">
                  {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">
        {MMC_SCENES.map((_, i) => (
          <button
            key={i}
            className={'term-pip' + (i === sceneIdx ? ' active' : '')}
            onClick={() => setSceneIdx(i)}
            aria-label={'Cena ' + (i + 1)}
          ></button>
        ))}
      </div>
    </div>
  );
}

window.MMCTerminal = MMCTerminal;
