// SECTIONS — Ticker, Metrics, UseCases, Pricing, Footer

function Ticker() {
  const items = [
    'Soja Sorriso/MT · R$ 142,30/sc · ↑ 2.1%',
    'Pluviometria Conquista/BA · 47mm/7d · normal +12%',
    'NDVI Cerrado · 0.74 · vigor estável',
    'Algodão LEM/BA · alerta lagarta · 38 talhões',
    'Milho safrinha · janela ótima 14d',
    'Pronaf B · teto R$ 6.000 · taxa 0.5%',
    'Café Cerrado/MG · R$ 1.840/sc · ↓ 0.4%',
    'Mandioca Quixadá/CE · pico de preço previsto +21d',
  ];
  return (
    <div style={{
      position: 'relative', zIndex: 2,
      borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)',
      background: 'var(--bg-2)',
      overflow: 'hidden',
      padding: '14px 0',
    }}>
      <div style={{ display: 'flex', gap: 48, animation: 'tickerScroll 60s linear infinite', whiteSpace: 'nowrap' }}>
        {[...items, ...items, ...items].map((t, i) => (
          <span key={i} className="mono" style={{ fontSize: 12, color: 'var(--ink-2)', letterSpacing: '0.02em' }}>
            <span style={{ color: 'var(--terra)', marginRight: 8 }}>●</span>{t}
          </span>
        ))}
      </div>
      <style>{`@keyframes tickerScroll { from { transform: translateX(0); } to { transform: translateX(-33.33%); } }`}</style>
    </div>
  );
}

function Metrics() {
  const refs = useRef([]);
  const targets = [
    { v: 1847293, label: 'hectares monitorados', fmt: n => n.toLocaleString('pt-BR') },
    { v: 38219, label: 'produtores ativos', fmt: n => n.toLocaleString('pt-BR') },
    { v: 94.2, label: 'precisão de safra', fmt: n => n.toFixed(1) + '%' },
    { v: 412, label: 'recomendações/min', fmt: n => n.toLocaleString('pt-BR') },
  ];
  const [vals, setVals] = useState(targets.map(() => 0));
  const [seen, setSeen] = useState(false);
  const containerRef = useRef(null);

  useEffect(() => {
    if (!containerRef.current) return;
    const obs = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting && !seen) {
        setSeen(true);
        const start = Date.now();
        const dur = 1800;
        const tick = () => {
          const p = Math.min(1, (Date.now() - start) / dur);
          const eased = 1 - Math.pow(1 - p, 3);
          setVals(targets.map(t => t.v * eased));
          if (p < 1) requestAnimationFrame(tick);
        };
        tick();
      }
    }, { threshold: 0.3 });
    obs.observe(containerRef.current);
    return () => obs.disconnect();
  }, [seen]);

  return (
    <section ref={containerRef} style={{ position: 'relative', padding: '120px 32px', zIndex: 2 }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <SectionLabel num="05" title="Em números reais" />
        <div style={{
          marginTop: 48,
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          borderTop: '1px solid var(--line)',
        }}>
          {targets.map((t, i) => (
            <div key={i} style={{ padding: '32px 24px', borderRight: i < 3 ? '1px solid var(--line)' : 'none', borderBottom: '1px solid var(--line)' }}>
              <div className="serif" style={{ fontSize: 'clamp(48px, 5vw, 80px)', lineHeight: 1, letterSpacing: '-0.025em', color: 'var(--ink)' }}>
                {t.fmt(vals[i])}
              </div>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--muted)', textTransform: 'uppercase', marginTop: 12 }}>
                {t.label}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function UseCases() {
  const cases = [
    {
      tag: 'Cooperativa',
      who: 'COAMO · 13 mil produtores',
      title: 'Reduziu perda por veranico em 31% após 2 safras.',
      detail: 'Alertas semanais de janela climática + ajuste de variedade por talhão.',
    },
    {
      tag: 'Pequeno produtor',
      who: 'Sr. Antônio · Quixadá/CE',
      title: 'Triplicou margem na mandioca em 18 meses.',
      detail: 'Agro Amigo mostrou pico de preço para venda + linha de Pronaf adequada.',
    },
    {
      tag: 'Banco',
      who: 'BNB · Crédito Rural',
      title: 'Aprovação de crédito 4× mais rápida com risco menor.',
      detail: 'Score Agro Amigo cruza histórico de produção, NDVI, e clima do município.',
    },
  ];
  return (
    <section id="casos" style={{ position: 'relative', padding: '60px 32px 120px', zIndex: 2 }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <SectionLabel num="06" title="Casos reais" />
        <div style={{ marginTop: 48, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
          {cases.map((c, i) => (
            <article key={i} style={{
              border: '1px solid var(--line)', background: 'var(--paper)',
              padding: 28, display: 'flex', flexDirection: 'column', minHeight: 320,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 32 }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '3px 8px', border: '1px solid var(--line-2)', color: 'var(--ink-2)' }}>
                  {c.tag}
                </span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>0{i+1}/03</span>
              </div>
              <h3 className="serif" style={{ fontSize: 30, lineHeight: 1.05, margin: 0, marginBottom: 12, letterSpacing: '-0.015em' }}>
                {c.title}
              </h3>
              <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, margin: 0 }}>{c.detail}</p>
              <div style={{ marginTop: 'auto', paddingTop: 24, borderTop: '1px dashed var(--line)' }}>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{c.who}</div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function Pricing() {
  const tiers = [
    { name: 'Pequeno produtor', price: 'R$ 0', sub: 'até 50ha · WhatsApp', features: ['Alertas climáticos', '5 perguntas/dia ao Agro Amigo', 'Score básico para Pronaf'] },
    { name: 'Profissional', price: 'R$ 89', sub: 'por mês · até 1.000ha', features: ['Tudo do plano gratuito', 'NDVI semanal de todos talhões', 'Plano de safra com 3 cenários', 'API de mercado + alertas de preço'], featured: true },
    { name: 'Cooperativa / Banco', price: 'sob consulta', sub: 'enterprise', features: ['Modelo dedicado por bioma', 'API + SDK completos', 'White label + integração ERP', 'SLA 99.9% + suporte dedicado'] },
  ];
  return (
    <section id="preços" style={{ position: 'relative', padding: '40px 32px 120px', zIndex: 2 }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <SectionLabel num="07" title="Planos" />
        <h2 className="serif" style={{ marginTop: 24, fontSize: 'clamp(40px, 5vw, 72px)', lineHeight: 1, letterSpacing: '-0.02em', maxWidth: 720 }}>
          Do roçado familiar à cooperativa de <span className="it" style={{ color: 'var(--terra)' }}>13 mil cabeças.</span>
        </h2>

        <div style={{ marginTop: 56, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, border: '1px solid var(--line)' }}>
          {tiers.map((t, i) => (
            <div key={i} style={{
              padding: 32,
              background: t.featured ? 'var(--ink)' : 'var(--paper)',
              color: t.featured ? 'var(--paper)' : 'var(--ink)',
              borderRight: i < 2 ? '1px solid var(--line)' : 'none',
              display: 'flex', flexDirection: 'column', gap: 16,
            }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: t.featured ? 'var(--gold)' : 'var(--muted)' }}>
                {t.name}
              </div>
              <div className="serif" style={{ fontSize: 56, lineHeight: 1, letterSpacing: '-0.02em' }}>
                {t.price}
              </div>
              <div className="mono" style={{ fontSize: 12, color: t.featured ? 'rgba(248,245,236,0.6)' : 'var(--muted)' }}>{t.sub}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: '12px 0 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                {t.features.map((f, k) => (
                  <li key={k} style={{ fontSize: 14, display: 'flex', gap: 10, alignItems: 'baseline' }}>
                    <span style={{ color: t.featured ? 'var(--gold)' : 'var(--terra)' }}>+</span>
                    {f}
                  </li>
                ))}
              </ul>
              <button onClick={() => {
                const msg = i === 0 ? 'Quero começar com o plano gratuito do Agro Amigo.'
                  : i === 1 ? 'Quero o plano Profissional (R$ 89) do Agro Amigo.'
                  : 'Quero falar com vendas sobre o plano enterprise do Agro Amigo.';
                window.open('https://wa.me/5543996261624?text=' + encodeURIComponent('Olá! ' + msg), '_blank', 'noopener');
              }} style={{
                marginTop: 'auto',
                padding: '12px 18px',
                background: t.featured ? 'var(--gold)' : 'var(--ink)',
                color: t.featured ? 'var(--ink)' : 'var(--paper)',
                border: 0, borderRadius: 999,
                fontSize: 14, fontWeight: 500,
              }}>
                {i === 2 ? 'Falar com vendas →' : 'Começar →'}
              </button>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Footer() {
  const [email, setEmail] = React.useState('');
  const sendToWA = () => {
    const text = email
      ? `Olá! Quero acesso ao Agro Amigo. Meu email: ${email}`
      : 'Olá! Quero acesso ao Agro Amigo.';
    window.open('https://wa.me/5543996261624?text=' + encodeURIComponent(text), '_blank', 'noopener');
  };
  return (
    <footer style={{
      position: 'relative', zIndex: 2,
      background: 'var(--ink)', color: 'var(--paper)',
      padding: '100px 32px 40px',
    }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <h2 className="serif" style={{
          fontSize: 'clamp(56px, 8vw, 140px)',
          lineHeight: 0.95, letterSpacing: '-0.025em', margin: 0,
        }}>
          A próxima safra<br/>
          <span className="it" style={{ color: 'var(--gold)' }}>começa hoje.</span>
        </h2>

        <div style={{ marginTop: 64, display: 'flex', alignItems: 'center', gap: 16 }}>
          <input
            value={email}
            onChange={e => setEmail(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') sendToWA(); }}
            placeholder="seu@email.com.br"
            style={{
              flex: 1, maxWidth: 480,
              background: 'transparent',
              border: 0, borderBottom: '1px solid rgba(248,245,236,0.3)',
              padding: '16px 4px', fontSize: 18,
              color: 'var(--paper)', outline: 'none',
            }}
          />
          <button onClick={sendToWA} style={{
            background: 'var(--gold)', color: 'var(--ink)',
            border: 0, padding: '14px 28px', borderRadius: 999,
            fontSize: 15, fontWeight: 500,
          }}>Receber acesso →</button>
        </div>

        <div style={{
          marginTop: 100, paddingTop: 32,
          borderTop: '1px solid rgba(248,245,236,0.15)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          color: 'rgba(248,245,236,0.5)', fontSize: 12,
        }} className="mono">
          <span>Agro Amigo · Inteligência Agrícola Brasileira</span>
          <span>BR · 2026 · feito no campo, para o campo</span>
        </div>
      </div>
    </footer>
  );
}

window.Ticker = Ticker;
window.Metrics = Metrics;
window.UseCases = UseCases;
window.Pricing = Pricing;
window.Footer = Footer;
