// Case.jsx — R$ 259k → R$ 93k storytelling
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

function useInView(ref, threshold = 0.35) {
  const [seen, setSeen] = useStateC(false);
  useEffectC(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold });
    io.observe(el);
    return () => io.disconnect();
  }, [ref]);
  return seen;
}

function AnimatedNumber({ to, prefix = '', duration = 1400, from = 0 }) {
  const ref = useRefC(null);
  const seen = useInView(ref);
  const [val, setVal] = useStateC(from);
  useEffectC(() => {
    if (!seen) return;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(from + (to - from) * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [seen, to, from, duration]);
  return <span ref={ref}>{prefix}{val.toLocaleString('pt-BR')}</span>;
}

function CaseSection() {
  const barsRef = useRefC(null);
  const [barsIn, setBarsIn] = useStateC(false);
  useEffectC(() => {
    const el = barsRef.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setBarsIn(true); io.disconnect(); } }, { threshold: 0.6 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <section id="case">
      <div className="wrap">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
          <div>
            <span className="q-eyebrow">Case Real · Prova Concreta</span>
            <h2 style={{ marginTop: 18, maxWidth: 900 }}>
              De R$ 259 mil<br />
              para <span className="grad-text-sheen">R$ 93 mil.</span><br />
              Dentro da lei.
            </h2>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <span className="badge">Supermercado</span>
            <span className="badge">Impugnação</span>
            <span className="badge badge-sig badge-dot">100% legal</span>
          </div>
        </div>

        {/* 2-column: left narrative card, right big number viz */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.15fr', gap: 2, background: 'var(--border)' }} className="case-grid">
          {/* LEFT NARRATIVE */}
          <div style={{ background: 'var(--bg2)', padding: 48, display: 'flex', flexDirection: 'column', gap: 24, minHeight: 520 }}>
            <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 44, height: 44,
                border: '1px solid var(--border-sig)',
                background: 'var(--signal-dim)',
                color: 'var(--signal)',
                fontFamily: 'var(--font-mono)',
                fontSize: '0.85rem', fontWeight: 700,
                letterSpacing: '0.06em',
              }}>01</span>
              <div>
                <div className="q-micro" style={{ color: 'var(--signal)' }}>Contexto</div>
                <div style={{ fontFamily: 'var(--display-stack)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '-0.01em', fontSize: '1.15rem', marginTop: 4 }}>Autuação fiscal pesada</div>
              </div>
            </div>
            <p style={{ color: 'var(--t2)' }}>
              Um supermercado recebeu uma autuação fiscal de <strong style={{ color: 'var(--white)' }}>R$ 259.000</strong>. O cenário parecia fechado: pagar ou contestar sem base técnica.
            </p>

            <div style={{ display: 'flex', gap: 18, alignItems: 'center', marginTop: 12 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 44, height: 44,
                border: '1px solid var(--border-sig)',
                background: 'var(--signal-dim)',
                color: 'var(--signal)',
                fontFamily: 'var(--font-mono)',
                fontSize: '0.85rem', fontWeight: 700,
                letterSpacing: '0.06em',
              }}>02</span>
              <div>
                <div className="q-micro" style={{ color: 'var(--signal)' }}>Ação</div>
                <div style={{ fontFamily: 'var(--display-stack)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '-0.01em', fontSize: '1.15rem', marginTop: 4 }}>Análise centavo a centavo</div>
              </div>
            </div>
            <p style={{ color: 'var(--t2)' }}>
              A Business Control analisou cada linha do auto de infração, identificou <strong style={{ color: 'var(--white)' }}>erros no cálculo dos impostos</strong> e conduziu a impugnação do início ao fim.
            </p>

            <div style={{ display: 'flex', gap: 18, alignItems: 'center', marginTop: 12 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 44, height: 44,
                border: '1px solid var(--signal)',
                background: 'var(--signal)',
                color: 'var(--black)',
                fontFamily: 'var(--font-mono)',
                fontSize: '0.85rem', fontWeight: 700,
                letterSpacing: '0.06em',
              }}>03</span>
              <div>
                <div className="q-micro" style={{ color: 'var(--signal)' }}>Resultado</div>
                <div style={{ fontFamily: 'var(--display-stack)', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '-0.01em', fontSize: '1.15rem', marginTop: 4 }}>R$ 166 mil no caixa</div>
              </div>
            </div>
            <p style={{ color: 'var(--t2)' }}>
              Cento e sessenta e seis mil reais que ficaram na operação. Não é promessa: é o que acontece quando contabilidade é tratada como <strong style={{ color: 'var(--white)' }}>estratégia</strong>.
            </p>
          </div>

          {/* RIGHT NUMBERS VIZ */}
          <div style={{ background: 'var(--bg2)', padding: 48, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden' }}>
            <div className="orb orb-sig" style={{ width: 420, height: 420, top: -120, right: -120, opacity: 0.35 }} />

            <div style={{ position: 'relative', zIndex: 2 }}>
              <div className="q-micro" style={{ color: 'var(--t3)', marginBottom: 16 }}>Autuação original</div>
              <div style={{
                fontFamily: 'var(--display-stack)',
                fontSize: 'clamp(2.2rem, 4vw, 3.4rem)',
                fontWeight: 900,
                color: 'var(--t2)',
                textDecoration: 'line-through',
                textDecorationColor: 'var(--signal)',
                textDecorationThickness: '3px',
                letterSpacing: '-0.02em',
                lineHeight: 1,
              }}>
                R$ <AnimatedNumber to={259000} from={0} duration={1500} />
              </div>

              {/* bar viz */}
              <div style={{ marginTop: 32 }} ref={barsRef}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                  <span className="q-micro">Antes</span>
                  <span className="q-micro" style={{ color: 'var(--t3)' }}>100%</span>
                </div>
                <div className="bar" style={{ height: 14, marginBottom: 16 }}>
                  <div className="bar-fill" style={{ background: 'var(--t4)', width: barsIn ? '100%' : '0%', transition: 'width 1s cubic-bezier(0.4,0,0.2,1) 0.15s' }} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                  <span className="q-micro" style={{ color: 'var(--signal)' }}>Depois</span>
                  <span className="q-micro" style={{ color: 'var(--signal)' }}>36%</span>
                </div>
                <div className="bar" style={{ height: 14 }}>
                  <div className="bar-fill" style={{ width: barsIn ? '36%' : '0%', boxShadow: '0 0 18px var(--signal)', transition: 'width 1.2s cubic-bezier(0.4,0,0.2,1) 0.45s' }} />
                </div>
              </div>
            </div>

            <div style={{ position: 'relative', zIndex: 2, marginTop: 48 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
                <span className="q-micro" style={{ color: 'var(--signal)' }}>Valor final</span>
                <span style={{ height: 1, flex: 1, background: 'var(--border)' }} />
                <span className="q-micro" style={{ color: 'var(--signal)' }}>redução 64%</span>
              </div>
              <div style={{
                fontFamily: 'var(--display-stack)',
                fontSize: 'clamp(3.2rem, 8vw, 6.4rem)',
                fontWeight: 900,
                background: 'var(--grad-copper-sheen)',
                backgroundSize: '200% 100%',
                WebkitBackgroundClip: 'text',
                backgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                color: 'transparent',
                letterSpacing: '-0.04em',
                lineHeight: 0.9,
                animation: 'sheen 6s ease-in-out infinite',
                filter: 'drop-shadow(0 0 40px var(--signal-glow))',
              }}>
                R$ <AnimatedNumber to={93000} from={259000} duration={1800} />
              </div>

              <div style={{
                marginTop: 28, paddingTop: 20,
                borderTop: '1px solid var(--border)',
                display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20,
              }}>
                <div>
                  <div className="q-micro">Economia real</div>
                  <div style={{ fontFamily: 'var(--display-stack)', fontWeight: 900, fontSize: '1.8rem', color: 'var(--white)', marginTop: 6, letterSpacing: '-0.02em' }}>
                    R$ <AnimatedNumber to={166000} from={0} duration={2000} />
                  </div>
                </div>
                <div>
                  <div className="q-micro">Prazo</div>
                  <div style={{ fontFamily: 'var(--display-stack)', fontWeight: 900, fontSize: '1.8rem', color: 'var(--white)', marginTop: 6, letterSpacing: '-0.02em' }}>
                    7 meses
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .case-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

window.CaseSection = CaseSection;
window.AnimatedNumber = AnimatedNumber;
