// Hero.jsx — motion-first hook
const { useState, useEffect: useEffectHero, useRef: useRefHero } = React;

/* ─── keyframes global (injected once) ─── */
const HERO_CSS = `
  @keyframes heroOrbPulse {
    0%, 100% { transform: scale(1);   opacity: 0.65; }
    50%       { transform: scale(1.1); opacity: 0.9;  }
  }
  @keyframes heroOrbPulse2 {
    0%, 100% { transform: scale(1);    opacity: 0.45; }
    50%       { transform: scale(1.08); opacity: 0.65; }
  }
  @keyframes cardFloat {
    0%, 100% { transform: translateY(0px)   rotate(0deg); }
    33%       { transform: translateY(-8px)  rotate(0.3deg); }
    66%       { transform: translateY(-4px)  rotate(-0.2deg); }
  }
  @keyframes badgePulse {
    0%, 100% { box-shadow: 0 0 0 0 rgba(201,106,59,0); }
    50%       { box-shadow: 0 0 0 8px rgba(201,106,59,0.18); }
  }
  @keyframes sheenLine {
    0%   { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
  }
  @keyframes slideUp {
    from { opacity: 0; transform: translateY(32px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  @keyframes fadeIn {
    from { opacity: 0; }
    to   { opacity: 1; }
  }
  @keyframes scaleIn {
    from { opacity: 0; transform: scale(0.92) translateY(16px); }
    to   { opacity: 1; transform: scale(1) translateY(0); }
  }
  @keyframes badgePop {
    0%   { opacity: 0; transform: translate(50%, -50%) scale(0.6); }
    70%  { transform: translate(50%, -50%) scale(1.08); }
    100% { opacity: 1; transform: translate(50%, -50%) scale(1); }
  }
  @keyframes sweep {
    from { transform: translateX(-120px); }
    to   { transform: translateX(100vw); }
  }
  @keyframes dotBlink {
    0%, 100% { opacity: 1; }
    50%       { opacity: 0.3; }
  }

  .hero-word {
    display: inline-block;
    opacity: 0;
    animation: slideUp 0.7s cubic-bezier(.22,1,.36,1) forwards;
    padding-top: 0.1em;
    padding-bottom: 0.14em;
  }
  .hero-sub-line {
    opacity: 0;
    animation: slideUp 0.6s cubic-bezier(.22,1,.36,1) forwards;
  }
  .hero-kpi {
    opacity: 0;
    animation: slideUp 0.6s cubic-bezier(.22,1,.36,1) forwards;
  }
  .hero-card-wrap {
    opacity: 0;
    animation: scaleIn 0.8s cubic-bezier(.22,1,.36,1) forwards;
  }

  .q1-opt:hover { border-color: var(--signal) !important; background: var(--signal-dim) !important; }
  .q1-opt:hover .arrow { transform: translateX(4px); color: var(--signal); }
  .q1-opt { transition: border-color .2s, background .2s; }

  @media (max-width: 980px) {
    .hero-grid { grid-template-columns: 1fr !important; gap: 40px !important; }
  }
  @media (max-width: 640px) {
    .hero-kpi { grid-template-columns: 1fr 1fr !important; }
    .hero-kpi > div { border-right: none !important; border-bottom: 1px solid var(--border); }
    .hero-kpi > div:nth-child(odd) { border-right: 1px solid var(--border) !important; }
    .hero-kpi > div:last-child { border-bottom: none; }
    .hero-kpi > div:nth-last-child(2) { border-bottom: none; }
  }
`;

/* ─── KPI counter animado no scroll ─── */
function KpiNum({ target, suffix = '', prefix = '', duration = 1200 }) {
  const ref = useRefHero(null);
  const [v, setV] = useState(0);
  const [seen, setSeen] = useState(false);
  useEffectHero(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  useEffectHero(() => {
    if (!seen) return;
    const t0 = performance.now(); let raf;
    const step = (t) => {
      const p = Math.min(1, (t - t0) / duration);
      setV(Math.round(target * (1 - Math.pow(1 - p, 3))));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [seen]);
  return <span ref={ref}>{prefix}{v}{suffix}</span>;
}

function Hero({ heroStyle = 'embed', onStartDiagnostic }) {
  useEffectHero(() => {
    if (!document.getElementById('hero-styles')) {
      const s = document.createElement('style');
      s.id = 'hero-styles';
      s.textContent = HERO_CSS;
      document.head.appendChild(s);
    }
  }, []);

  return (
    <section id="top" style={{
      paddingTop: 160, paddingBottom: 100,
      borderBottom: '1px solid var(--border)',
      overflow: 'hidden',
      position: 'relative',
    }}>
      {/* orbs — animated */}
      <div className="orb orb-sig" style={{
        width: 820, height: 820, top: -260, right: -200,
        animation: 'heroOrbPulse 8s ease-in-out infinite',
      }} />
      <div className="orb orb-deep" style={{
        width: 520, height: 520, bottom: -280, left: -220,
        animation: 'heroOrbPulse2 11s ease-in-out infinite',
      }} />

      <div className="wrap" style={{ position: 'relative', zIndex: 2 }}>
        <span className="q-eyebrow" style={{ opacity: 0, animation: 'fadeIn 0.5s ease forwards 0.1s' }}>
          Redução e Recuperação Tributária
        </span>

        {heroStyle === 'manifesto' && <HeroManifesto onStart={onStartDiagnostic} />}
        {heroStyle === 'embed'    && <HeroEmbed     onStart={onStartDiagnostic} />}
        {heroStyle === 'ticker'   && <HeroTicker    onStart={onStartDiagnostic} />}
      </div>
    </section>
  );
}

/* ─── EMBED ─── */
function HeroEmbed({ onStart }) {
  const [seg, setSeg] = useState(null);

  const options = [
    { id: 'comercio',  label: 'Comércio',  hint: 'Varejo, atacado, distrib.' },
    { id: 'servicos',  label: 'Serviços',  hint: 'Profissionais, tech, agências' },
    { id: 'industria', label: 'Indústria', hint: 'Manuf., transform., insumos' },
    { id: 'outro',     label: 'Outro',     hint: 'Agro, construção, saúde…' },
  ];

  const handlePick = (id) => {
    setSeg(id);
    setTimeout(() => onStart?.(id), 420);
  };

  /* stagger delays */
  const D = (n) => `${n}s`;

  return (
    <div
      style={{ display: 'grid', gridTemplateColumns: '1.15fr 1fr', gap: 80, alignItems: 'start', marginTop: 36 }}
      className="hero-grid"
    >
      {/* ── LEFT ── */}
      <div>
        {/* H1 — each line slides up with stagger */}
        <h1 style={{ marginBottom: 28, lineHeight: 1.1 }}>
          <span className="hero-word" style={{ animationDelay: D(0.25) }}>Contabilidade</span>
          <br />
          <span className="hero-word" style={{ animationDelay: D(0.38) }}>não é reação.</span>
          <br />
          <span className="hero-word grad-text-sheen" style={{ animationDelay: D(0.52) }}>É ação.</span>
        </h1>

        <p
          className="q-sub q-sub-lg hero-sub-line"
          style={{ maxWidth: 560, marginBottom: 20, animationDelay: D(0.68) }}
        >
          Você está pagando impostos que não deve.<br />
          A gente prova isso.
        </p>

        <p
          className="hero-sub-line"
          style={{ maxWidth: 500, color: 'var(--t2)', marginBottom: 44, animationDelay: D(0.78) }}
        >
          Diagnóstico tributário gratuito para empresários que querem parar de pagar a mais e recuperar o que já saiu.
        </p>

        {/* KPI row */}
        <div
          className="hero-kpi"
          style={{
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0,
            border: '1px solid var(--border)', borderRadius: 'var(--r-1)',
            overflow: 'hidden', maxWidth: 680,
            animationDelay: D(0.9),
          }}
        >
          {[
            { label: 'anos de mercado', node: <span>15<span style={{ fontFamily: 'var(--font-mono)', fontSize: '1.1rem' }}>+</span></span> },
            { label: 'recuperados',     node: <span>R$ <KpiNum target={8} suffix="Mi" duration={1000} /></span> },
            { label: 'impugnações',     node: <KpiNum target={320} suffix="+" duration={1400} /> },
            { label: 'redução média',   node: <KpiNum target={31} suffix="%" duration={1100} /> },
          ].map((s, i) => (
            <div key={i} style={{
              padding: '20px 18px',
              borderRight: i < 3 ? '1px solid var(--border)' : 'none',
              background: 'rgba(0,0,0,0.55)',
              transition: 'background .25s',
            }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--signal-dim)'}
              onMouseLeave={e => e.currentTarget.style.background = 'rgba(0,0,0,0.55)'}
            >
              <div style={{
                fontFamily: 'var(--display-stack)',
                fontSize: '1.75rem', fontWeight: 900,
                letterSpacing: '-0.02em', color: 'var(--white)', lineHeight: 1,
              }}>{s.node}</div>
              <div className="q-micro" style={{ marginTop: 8, color: 'var(--t3)' }}>{s.label}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── RIGHT — diagnostic card ── */}
      <div className="hero-card-wrap" style={{ position: 'relative', animationDelay: D(0.45) }}>

        {/* floating card with breathing animation */}
        <div style={{
          animation: 'cardFloat 7s ease-in-out infinite',
          transformOrigin: 'center center',
        }}>
          <div style={{
            background: 'var(--grad-copper-soft), var(--bg2)',
            backgroundBlendMode: 'overlay',
            border: '1px solid var(--border-sig)',
            borderRadius: 'var(--r-2)',
            padding: 36,
            boxShadow: 'var(--shadow-sig)',
            position: 'relative',
            overflow: 'hidden',
          }}>
            {/* top sheen line — looping */}
            <div style={{
              position: 'absolute', top: 0, left: 0, right: 0, height: 2,
              background: 'var(--grad-copper-sheen)',
              backgroundSize: '200% 100%',
              animation: 'sheen 4s ease-in-out infinite',
            }} />

            {/* header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
              <span className="badge badge-sig badge-dot" style={{ animation: 'badgePulse 3s ease-in-out infinite' }}>
                Diagnóstico ao vivo
              </span>
              <span className="q-micro" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{
                  width: 6, height: 6, borderRadius: '50%',
                  background: 'var(--signal)',
                  boxShadow: '0 0 8px var(--signal)',
                  animation: 'dotBlink 1.8s ease-in-out infinite',
                }} />
                Passo 01 / 05
              </span>
            </div>

            <div className="q-micro" style={{ color: 'var(--signal)', marginBottom: 10 }}>Pergunta 01</div>
            <h3 style={{ fontSize: '1.6rem', marginBottom: 4 }}>Qual é o segmento da sua empresa?</h3>
            <p className="q-small" style={{ color: 'var(--t3)', marginBottom: 22 }}>
              Começamos pelo básico. 3 minutos no total.
            </p>

            <div style={{ display: 'grid', gap: 10 }}>
              {options.map((o) => {
                const active = seg === o.id;
                return (
                  <button
                    key={o.id}
                    onClick={() => handlePick(o.id)}
                    className="q1-opt"
                    style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      padding: '16px 18px',
                      border: `1px solid ${active ? 'var(--signal)' : 'var(--border)'}`,
                      background: active ? 'var(--signal-dim)' : 'var(--bg3)',
                      borderRadius: 'var(--r-1)',
                      textAlign: 'left',
                    }}
                  >
                    <div>
                      <div style={{
                        fontFamily: 'var(--display-stack)',
                        fontWeight: 700, fontSize: '1rem',
                        textTransform: 'uppercase', letterSpacing: '0.02em',
                        color: active ? 'var(--signal)' : 'var(--white)',
                        transition: 'color .2s',
                      }}>{o.label}</div>
                      <div className="q-small" style={{ color: 'var(--t3)', marginTop: 4, fontSize: '0.78rem' }}>{o.hint}</div>
                    </div>
                    <span className="arrow" style={{
                      color: active ? 'var(--signal)' : 'var(--t3)',
                      fontSize: '1.2rem',
                      transform: active ? 'translateX(4px)' : 'none',
                      transition: 'transform .2s, color .2s',
                    }}>→</span>
                  </button>
                );
              })}
            </div>

            <div style={{
              marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--border)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <span className="q-small" style={{ color: 'var(--t3)' }}>
                100% confidencial · Sem compromisso
              </span>
              <div style={{ display: 'flex', gap: 4 }}>
                {[1,2,3,4,5].map(i => (
                  <span key={i} style={{
                    width: 18, height: 3,
                    background: i === 1 ? 'var(--signal)' : 'var(--t5)',
                    borderRadius: 1,
                    boxShadow: i === 1 ? '0 0 8px var(--signal)' : 'none',
                  }} />
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* floating badge — OPORTUNIDADE */}
        <div style={{
          position: 'absolute', right: 0, top: 0,
          transform: 'translate(50%, -50%)',
          background: 'var(--grad-copper)',
          color: '#FFF6EE',
          padding: '10px 16px',
          fontFamily: 'var(--font-mono)',
          fontSize: '0.62rem',
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          borderRadius: 'var(--r-1)',
          fontWeight: 700,
          whiteSpace: 'nowrap',
          boxShadow: 'var(--shadow-sig)',
          animation: 'badgePop 0.7s cubic-bezier(.34,1.5,.64,1) forwards 1s, badgePulse 4s ease-in-out infinite 1.7s',
          opacity: 0,
        }}>
          Oportunidade
        </div>
      </div>
    </div>
  );
}

/* ─── MANIFESTO ─── */
function HeroManifesto({ onStart }) {
  return (
    <div style={{ marginTop: 36 }}>
      <h1 style={{ fontSize: 'clamp(3.2rem, 11vw, 10rem)', marginBottom: 32, letterSpacing: '-0.045em' }}>
        <span className="hero-word" style={{ animationDelay: '0.2s' }}>PAGUE</span><br />
        <span className="hero-word" style={{ animationDelay: '0.32s' }}>O QUE A LEI PEDE.</span><br />
        <span className="hero-word grad-text-sheen" style={{ animationDelay: '0.46s' }}>NEM UM CENTAVO A MAIS.</span>
      </h1>
      <p className="q-sub q-sub-lg hero-sub-line" style={{ maxWidth: 640, marginBottom: 44, animationDelay: '0.62s' }}>
        Diagnóstico tributário gratuito. Em 15 anos, reduzimos a carga fiscal de centenas de empresas, dentro da lei, sem atalhos.
      </p>
      <div className="hero-sub-line" style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap', animationDelay: '0.74s' }}>
        <button className="btn btn-primary btn-lg" onClick={() => onStart?.()}>
          Fazer diagnóstico <span className="arrow">→</span>
        </button>
        <button className="btn btn-ghost" onClick={() => document.getElementById('case')?.scrollIntoView({ behavior: 'smooth' })}>
          Ver case real ↓
        </button>
      </div>
    </div>
  );
}

/* ─── TICKER ─── */
function HeroTicker({ onStart }) {
  return (
    <div style={{ marginTop: 36 }}>
      <h1 style={{ marginBottom: 24 }}>
        <span className="hero-word" style={{ animationDelay: '0.25s' }}>Contabilidade</span><br />
        <span className="hero-word" style={{ animationDelay: '0.38s' }}>não é reação.</span><br />
        <span className="hero-word grad-text-sheen" style={{ animationDelay: '0.52s' }}>É ação.</span>
      </h1>
      <p className="q-sub q-sub-lg hero-sub-line" style={{ maxWidth: 540, marginBottom: 44, animationDelay: '0.66s' }}>
        Diagnóstico tributário para empresários que querem parar de pagar a mais.
      </p>

      {/* live ticker */}
      <div
        className="hero-sub-line"
        style={{
          border: '1px solid var(--border)',
          borderTop: '1px solid var(--border-sig)',
          borderRadius: 'var(--r-1)',
          background: 'var(--bg2)',
          padding: '22px 0',
          overflow: 'hidden',
          marginBottom: 32,
          position: 'relative',
          animationDelay: '0.8s',
        }}
      >
        {/* scanning line */}
        <div style={{
          position: 'absolute', top: -1, left: 0, width: 120, height: 2,
          background: 'var(--signal)',
          boxShadow: '0 0 20px var(--signal)',
          animation: 'sweep 6s linear infinite',
        }} />
        <div style={{
          display: 'flex', gap: 80, whiteSpace: 'nowrap',
          animation: 'tick 30s linear infinite',
          fontFamily: 'var(--font-mono)',
          fontSize: '0.92rem', letterSpacing: '0.1em', textTransform: 'uppercase',
        }}>
          {[
            ['Supermercado SP', '+R$ 166.000', 'Impugnação'],
            ['Indústria PR',    '+R$ 412.000', 'Recuperação'],
            ['Serviços Tech MG','+R$ 88.400',  'Mudança regime'],
            ['Varejo RJ',       '+R$ 234.500', 'Créditos PIS/COFINS'],
            ['Construção GO',   '+R$ 512.000', 'Impugnação'],
            ['Distribuidora BA','+R$ 143.200', 'Planejamento'],
          ].concat([
            ['Supermercado SP', '+R$ 166.000', 'Impugnação'],
            ['Indústria PR',    '+R$ 412.000', 'Recuperação'],
            ['Serviços Tech MG','+R$ 88.400',  'Mudança regime'],
            ['Varejo RJ',       '+R$ 234.500', 'Créditos PIS/COFINS'],
            ['Construção GO',   '+R$ 512.000', 'Impugnação'],
            ['Distribuidora BA','+R$ 143.200', 'Planejamento'],
          ]).map((row, i) => (
            <span key={i} style={{ display: 'inline-flex', gap: 22, alignItems: 'center' }}>
              <span style={{ color: 'var(--t3)' }}>{row[0]}</span>
              <span style={{ color: 'var(--signal)', fontWeight: 700 }}>{row[1]}</span>
              <span style={{ color: 'var(--t2)' }}>{row[2]}</span>
              <span style={{ color: 'var(--signal)' }}>◆</span>
            </span>
          ))}
        </div>
      </div>

      <div className="hero-sub-line" style={{ display: 'flex', gap: 16, flexWrap: 'wrap', animationDelay: '0.95s' }}>
        <button className="btn btn-primary btn-lg" onClick={() => onStart?.()}>
          Descobrir minha oportunidade <span className="arrow">→</span>
        </button>
      </div>
    </div>
  );
}

window.Hero = Hero;
