/* global React */

// ===== HERO VARIATION 1: Kinetic Type =====
function HeroKinetic({ onCta }) {
  return (
    <section className="hero hero-1">
      <div className="grid-bg"></div>
      <div className="blob a"></div>
      <div className="blob b"></div>
      <div className="container">
        <span className="eyebrow reveal in">
          <span className="dot"></span>
          <span>Estúdio digital · Disponível para novos projetos</span>
        </span>
        <h1 className="reveal in delay-1">
          A gente <span className="ital">constrói</span><br/>
          o seu{' '}
          <span className="kinetic-word">
            <span className="slot">
              <ul>
                <li>app.</li>
                <li>site.</li>
                <li>MVP.</li>
                <li>sistema.</li>
                <li>app.</li>
              </ul>
            </span>
          </span><br/>
          <span style={{ color: '#9a9a9a' }}>Com</span> <span className="underline">preço justo</span><br/>
          <span style={{ color: '#9a9a9a' }}>e</span> prazo curto.
        </h1>
        <p className="sub reveal in delay-2">
          Apps mobile e sites de alta performance entregues em semanas, não em meses.
          Para startups, empresas e agências que precisam executar rápido sem abrir
          mão de qualidade.
        </p>
        <div className="actions reveal in delay-3">
          <button className="btn btn-primary" onClick={onCta}>
            <span className="dot"></span>
            Solicitar orçamento
          </button>
          <a href="#servicos" className="btn btn-ghost">
            Ver serviços
            <svg className="arrow" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M5 12h14M13 5l7 7-7 7" />
            </svg>
          </a>
        </div>
        <div className="meta-row reveal in delay-4">
          <div className="item">
            <span className="num">48h</span>
            <span className="lab">Resposta · proposta</span>
          </div>
          <div className="item">
            <span className="num">4–8 sem</span>
            <span className="lab">Entrega média MVP</span>
          </div>
          <div className="item">
            <span className="num">100%</span>
            <span className="lab">Código próprio do cliente</span>
          </div>
          <div className="item">
            <span className="num">iOS · Android · Web</span>
            <span className="lab">Stack moderna</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== HERO VARIATION 2: Terminal / Split =====
function HeroTerminal({ onCta }) {
  return (
    <section className="hero hero-2">
      <div className="container">
        <div className="split">
          <div>
            <span className="eyebrow"><span className="dot"></span> Sistemas Club · sistemasclub.com.br</span>
            <h1>
              Do <span className="accent">briefing</span><br/>
              ao <span className="box">deploy</span><br/>
              em semanas.
            </h1>
            <p className="sub">
              A gente projeta, desenvolve e publica apps mobile e sites
              de alta performance. Time enxuto, processo direto, preço
              justo e prazo curto.
            </p>
            <div className="actions">
              <button className="btn btn-primary" onClick={onCta}>
                <span className="dot"></span>
                Solicitar orçamento
              </button>
              <a href="#servicos" className="btn btn-ghost">
                Como funciona
                <svg className="arrow" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M5 12h14M13 5l7 7-7 7" />
                </svg>
              </a>
            </div>
          </div>
          <Terminal />
        </div>
      </div>
    </section>
  );
}

function Terminal() {
  const STAGES = [
    {
      id: 'briefing',
      label: 'Briefing',
      desc: 'Entendendo o problema',
      duration: 1800,
      lines: [
        { type: 'cmd', text: '$ briefing --client "{novo projeto}"' },
        { type: 'out', text: '  ↳ escopo definido', delay: 500 },
        { type: 'out', text: '  ↳ usuário-alvo mapeado', delay: 800 },
        { type: 'ok',  text: '✓ briefing aprovado · proposta enviada em 48h', delay: 1200 },
      ],
    },
    {
      id: 'design',
      label: 'Design',
      desc: 'Wireframes e protótipo',
      duration: 2200,
      lines: [
        { type: 'cmd', text: '$ design --tokens --screens=12' },
        { type: 'out', text: '  ↳ design system definido', delay: 500 },
        { type: 'progress', text: 'gerando telas', delay: 900 },
        { type: 'ok', text: '✓ protótipo navegável · validado pelo cliente', delay: 1700 },
      ],
    },
    {
      id: 'build',
      label: 'Build',
      desc: 'Desenvolvimento iterativo',
      duration: 3000,
      lines: [
        { type: 'cmd', text: '$ build --platforms=ios,android,web' },
        { type: 'out', text: '  compilando módulos........ ', delay: 500, suffix: 'ok' },
        { type: 'out', text: '  integrações pagamento.... ', delay: 1100, suffix: 'ok' },
        { type: 'out', text: '  push & analytics ......... ', delay: 1700, suffix: 'ok' },
        { type: 'ok',  text: '✓ build concluído · 0 erros · 100% coverage', delay: 2400 },
      ],
    },
    {
      id: 'deploy',
      label: 'Deploy',
      desc: 'Publicação nas lojas',
      duration: 1800,
      lines: [
        { type: 'cmd', text: '$ deploy --env=production' },
        { type: 'out', text: '  ↳ App Store · em revisão', delay: 500 },
        { type: 'out', text: '  ↳ Google Play · publicado', delay: 1000 },
        { type: 'ok',  text: '✓ stores aprovaram em 2 dias', delay: 1500 },
      ],
    },
    {
      id: 'live',
      label: 'Live',
      desc: 'Suporte ativo',
      duration: 1200,
      lines: [
        { type: 'cmd', text: '$ monitor --status' },
        { type: 'out', text: '  ↳ uptime 99.9% · usuários ativos: ↑', delay: 400 },
        { type: 'launch', text: '🚀 SEU APP ESTÁ NO AR.', delay: 800 },
      ],
    },
  ];

  const [stageIdx, setStageIdx] = React.useState(-1);  // -1 = idle, 0..4 active, 5 = done
  const [revealedLines, setRevealedLines] = React.useState([]); // [{stageIdx, lineIdx, line}]
  const [stageProgress, setStageProgress] = React.useState(0);
  const [running, setRunning] = React.useState(false);
  const timersRef = React.useRef([]);
  const totalStartRef = React.useRef(0);
  const [elapsed, setElapsed] = React.useState(0);

  const clearTimers = () => {
    timersRef.current.forEach((t) => clearTimeout(t));
    timersRef.current = [];
  };

  const runStage = (i) => {
    if (i >= STAGES.length) {
      setRunning(false);
      setStageIdx(STAGES.length);
      return;
    }
    setStageIdx(i);
    setStageProgress(0);
    const stage = STAGES[i];
    const stageStart = performance.now();

    stage.lines.forEach((line, li) => {
      const t = setTimeout(() => {
        setRevealedLines((prev) => [...prev, { stageIdx: i, lineIdx: li, line }]);
      }, line.delay || 0);
      timersRef.current.push(t);
    });

    // progress ticker for this stage
    const tickProgress = () => {
      const p = Math.min(1, (performance.now() - stageStart) / stage.duration);
      setStageProgress(p);
      if (p < 1 && running !== false) {
        const t = requestAnimationFrame(tickProgress);
        timersRef.current.push({ raf: t });
      }
    };
    tickProgress();

    const next = setTimeout(() => runStage(i + 1), stage.duration);
    timersRef.current.push(next);
  };

  const start = () => {
    clearTimers();
    setRevealedLines([]);
    setStageProgress(0);
    setStageIdx(0);
    setRunning(true);
    totalStartRef.current = performance.now();
    runStage(0);
  };

  const reset = () => {
    clearTimers();
    setRevealedLines([]);
    setStageProgress(0);
    setStageIdx(-1);
    setRunning(false);
    setElapsed(0);
  };

  // elapsed counter
  React.useEffect(() => {
    if (!running) return;
    const id = setInterval(() => {
      setElapsed(Math.floor((performance.now() - totalStartRef.current) / 100));
    }, 100);
    return () => clearInterval(id);
  }, [running]);

  React.useEffect(() => () => clearTimers(), []);

  const totalProgress = stageIdx < 0 ? 0
    : stageIdx >= STAGES.length ? 1
    : (stageIdx + stageProgress) / STAGES.length;

  const done = stageIdx >= STAGES.length;
  const showPhone = stageIdx >= 4; // emerges during Live stage

  return (
    <div className="terminal pipeline-terminal">
      <div className="terminal-bar">
        <div className="lights"><span></span><span></span><span></span></div>
        <div className="title">
          sistemas-club ~ pipeline
          {running && <span className="pl-clock mono">{(elapsed / 10).toFixed(1)}s</span>}
        </div>
        {(running || done) && (
          <button className="pl-reset" onClick={reset} aria-label="Reiniciar">↺</button>
        )}
      </div>

      {/* Emerging phone mockup — slides up & out of terminal during Live stage */}
      <div className={`pl-phone ${showPhone ? 'show' : ''} ${done ? 'done' : ''}`} aria-hidden="true">
        <div className="pl-phone-glow"></div>
        <div className="pl-phone-device">
          <div className="pl-phone-notch"></div>
          <div className="pl-phone-screen">
            <div className="pl-phone-status">
              <span>9:41</span>
              <span className="bars">●●●● 5G</span>
            </div>
            <div className="pl-phone-icon">SC</div>
            <div className="pl-phone-title">Seu App</div>
            <div className="pl-phone-live">
              <span className="dot"></span>
              AO VIVO
            </div>
            <div className="pl-phone-stats">
              <div className="pl-phone-stat">
                <span className="big">1.2k</span>
                <span className="lab">downloads</span>
              </div>
              <div className="pl-phone-stat">
                <span className="big">4.9★</span>
                <span className="lab">avaliação</span>
              </div>
            </div>
            <div className="pl-phone-stores">
              <span className="store"> App Store</span>
              <span className="store"> Play</span>
            </div>
          </div>
        </div>
      </div>

      {/* Pipeline visualization */}
      <div className="pipeline-rail">
        {STAGES.map((s, i) => {
          const state =
            stageIdx > i || done ? 'done' :
            stageIdx === i ? 'active' :
            'pending';
          return (
            <button
              key={s.id}
              className={`pl-stage ${state}`}
              onClick={() => {
                if (stageIdx >= 0) return; // can only click before starting
                start();
              }}
              disabled={stageIdx >= 0}
              title={s.desc}
            >
              <span className="pl-stage-num">0{i + 1}</span>
              <span className="pl-stage-label">{s.label}</span>
              <span className="pl-stage-status">
                {state === 'done' && <span className="check">✓</span>}
                {state === 'active' && <span className="spinner"></span>}
                {state === 'pending' && <span className="dot"></span>}
              </span>
            </button>
          );
        })}
        <div className="pl-rail-track">
          <div className="pl-rail-fill" style={{ width: `${totalProgress * 100}%` }}></div>
        </div>
      </div>

      <div className="terminal-body pipeline-body">
        {stageIdx < 0 ? (
          <div className="pl-idle">
            <div className="pl-idle-glyph">▶</div>
            <div className="pl-idle-title">Rode a esteira de desenvolvimento</div>
            <div className="pl-idle-sub mono">
              // assista 5 etapas do briefing ao deploy
            </div>
            <button className="pl-start" onClick={start}>
              <span className="pl-start-dot"></span>
              Iniciar pipeline
            </button>
          </div>
        ) : (
          <div className="pl-output">
            {revealedLines.map(({ stageIdx: si, lineIdx, line }, k) => (
              <div key={`${si}-${lineIdx}-${k}`} className={`term-line line-${line.type}`}>
                {line.type === 'cmd' && <><span className="term-prompt">$</span> <span className="term-cmd">{line.text.replace(/^\$\s*/, '')}</span></>}
                {line.type === 'out' && <span className="term-out">{line.text}{line.suffix && <span className="term-ok"> {line.suffix}</span>}</span>}
                {line.type === 'ok' && <span className="term-ok">{line.text}</span>}
                {line.type === 'progress' && (
                  <span className="term-out">
                    {line.text}{' '}
                    <span className="inline-bar"><span style={{ width: `${Math.min(100, stageProgress * 100)}%` }}></span></span>
                  </span>
                )}
                {line.type === 'launch' && (
                  <span className="term-launch">{line.text}</span>
                )}
              </div>
            ))}
            {done && (
              <div className="pl-summary">
                <div className="pl-summary-row"><span className="mono lab">// tempo total</span><span>5 etapas concluídas</span></div>
                <div className="pl-summary-row"><span className="mono lab">// na vida real</span><span style={{ color: 'var(--accent-2)' }}>4–8 semanas</span></div>
                <div className="pl-summary-row"><span className="mono lab">// mercado tradicional</span><span style={{ opacity: 0.5 }}>3–6 meses</span></div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ===== HERO VARIATION 3: Editorial Mosaic =====
function HeroMosaic({ onCta }) {
  return (
    <section className="hero hero-3">
      <div className="container">
        <div className="mosaic">
          <div className="tile headline">
            <div>
              <span className="eyebrow" style={{ background: 'rgba(255,255,255,0.08)', borderColor: 'rgba(255,255,255,0.12)', color: '#aaa' }}>
                <span className="dot"></span> Estúdio · 2025
              </span>
              <h1>
                Ideias viram <span className="accent">produto</span><br/>
                em semanas, não<br/>
                em trimestres.
              </h1>
            </div>
            <div className="bottom">
              <p className="sub">
                Apps mobile e sites sob medida, com preço justo, prazo
                curto e qualidade de produto.
              </p>
              <button className="btn btn-primary" onClick={onCta} style={{ background: 'white', color: 'var(--ink)' }}>
                Solicitar orçamento
                <svg className="arrow" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M5 12h14M13 5l7 7-7 7" />
                </svg>
              </button>
            </div>
          </div>
          <div className="tile metric">
            <span className="label">Entrega média</span>
            <div>
              <div className="big">4<sup>–</sup>8</div>
              <span className="label" style={{ marginTop: 8, display: 'block' }}>semanas / MVP</span>
            </div>
          </div>
          <div className="tile cta" onClick={onCta} style={{ cursor: 'pointer' }}>
            <span className="label" style={{ color: 'rgba(255,255,255,0.7)', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase' }}>// próximo passo</span>
            <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', gap: 16 }}>
              <h3>Conte sua ideia.<br/>A gente responde em 48h.</h3>
              <div className="arrow">
                <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M5 12h14M13 5l7 7-7 7" />
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HeroKinetic, HeroTerminal, HeroMosaic });
