/* Sections: Metrics bar · Pain comparison · Bento features · How-it-works · Quote */

/* ══════════ METRICS BAR (4 proof stats + fake brand logos) ══════════ */
const MbIcMsg = () => (
  <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12z"/>
  </svg>
);
const MbIcUsers = () => (
  <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="9" cy="8" r="3.5"/><path d="M2.5 20c.6-3.5 3.4-5.5 6.5-5.5s5.9 2 6.5 5.5"/><circle cx="17" cy="9" r="2.7"/><path d="M21.5 18c-.4-2.4-2.2-3.8-4.5-3.8"/>
  </svg>
);
const MbIcCheck = () => (
  <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/><path d="M8.5 15.5l2.2 2.2L15.5 13"/>
  </svg>
);
const MbIcMoney = () => (
  <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 17l6-6 4 4 8-8"/><path d="M15 7h6v6"/>
  </svg>
);

const FAKE_BRANDS = [
  { mark: 'circle',  name: 'Lume Clinic' },
  { mark: 'tri',     name: 'Nova Med' },
  { mark: 'square',  name: 'Bauer Estética' },
  { mark: 'plus',    name: 'Klima Saúde' },
  { mark: 'ring',    name: 'Vetor Co.' },
  { mark: 'diamond', name: 'Orva Brasil' },
  { mark: 'bars',    name: 'Petra Group' },
  { mark: 'wave',    name: 'Atlan Tech' },
];

const BrandMark = ({ kind }) => {
  const props = { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'currentColor' };
  if (kind === 'circle')  return <svg {...props}><circle cx="12" cy="12" r="8"/></svg>;
  if (kind === 'tri')     return <svg {...props}><path d="M12 4l8 14H4z"/></svg>;
  if (kind === 'square')  return <svg {...props}><rect x="5" y="5" width="14" height="14" rx="2"/></svg>;
  if (kind === 'plus')    return <svg {...props} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>;
  if (kind === 'ring')    return <svg {...props} fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="12" cy="12" r="7"/></svg>;
  if (kind === 'diamond') return <svg {...props}><path d="M12 3l9 9-9 9-9-9z"/></svg>;
  if (kind === 'bars')    return <svg {...props}><rect x="4" y="13" width="3" height="7" rx="1"/><rect x="10.5" y="9" width="3" height="11" rx="1"/><rect x="17" y="5" width="3" height="15" rx="1"/></svg>;
  if (kind === 'wave')    return <svg {...props} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M3 14c3 0 3-4 6-4s3 4 6 4 3-4 6-4"/></svg>;
  return null;
};

const INTEGRATIONS_BASE = '../../assets/integrations';
const INTEGRATIONS = [
  'whatsapp-icon.svg',
  'instagram-official.svg',
  'meta-icon.svg',
  'messenger.svg',
  'telegram.svg',
  'google-calendar.svg',
  'google-meet.svg',
  'monday-icon.svg',
  'salesforce.svg',
  'slack-icon.svg',
  'shopify.svg',
  'stripe.svg',
  'twilio-icon.svg',
  'active-campaign-icon.svg',
];

const MetricsBar = () => (
  <section className="metrics-bar">
    <div className="container">
      <div className="metrics-grid four">
        <div className="metric"><div className="mi"><MbIcMoney /></div><div className="mv">+47%</div><div className="ml">Aumento médio em vendas</div></div>
        <div className="metric"><div className="mi"><MbIcUsers /></div><div className="mv">+1.000</div><div className="ml">Empresas ativas em todo o Brasil</div></div>
        <div className="metric"><div className="mi"><MbIcCheck /></div><div className="mv">24/7</div><div className="ml">Operação contínua, sem horário comercial</div></div>
        <div className="metric"><div className="mi"><MbIcMsg /></div><div className="mv">−40%</div><div className="ml">Custo operacional médio (HBR)</div></div>
      </div>
      <div className="metrics-logos">
        <span className="mlbl">Integração simples com as ferramentas que você já usa</span>
        <div className="brand-marquee">
          <div className="brand-track">
            {[...INTEGRATIONS, ...INTEGRATIONS].map((file, i) => (
              <div className="brand" key={`${file}-${i}`} aria-hidden={i >= INTEGRATIONS.length}>
                <img src={`${INTEGRATIONS_BASE}/${file}`} alt="" />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* ══════════ PAIN / ANTES-DEPOIS ══════════ */
const PainSection = () => (
  <section className="pain">
    <div className="container">
      <div className="pain-head">
        <span className="pill"><Sparkle /> A dor real</span>
        <h2>O problema não é falta de lead.<br/><em>É o que acontece depois que ele chama.</em></h2>
      </div>

      <div className="pain-counter">
        <div className="pc-item">
          <div className="pc-val">73%</div>
          <div className="pc-lbl">dos leads desistem se a resposta demora mais de 5 min</div>
        </div>
        <div className="pc-item">
          <div className="pc-val neg"><span>R$12k</span></div>
          <div className="pc-lbl">em receita média perdida por mês com follow-up falho</div>
        </div>
        <div className="pc-item">
          <div className="pc-val">48h</div>
          <div className="pc-lbl">tempo médio de resposta fora do horário comercial</div>
        </div>
        <div className="pc-item">
          <div className="pc-val">1 em 5</div>
          <div className="pc-lbl">leads qualificados chegam a ser atendidos</div>
        </div>
      </div>

      <div className="pain-grid">
        <div className="pain-card before">
          <div className="pain-tag">Sem TechFala</div>
          <ul>
            <li><span className="x">✕</span> Leads esperando resposta por horas</li>
            <li><span className="x">✕</span> Follow-up esquecido pela equipe</li>
            <li><span className="x">✕</span> Atendentes repetindo as mesmas dúvidas</li>
            <li><span className="x">✕</span> Agendamentos manuais que atrasam</li>
            <li><span className="x">✕</span> Cliente esfriando no WhatsApp</li>
          </ul>
          <div className="pain-card-foot">
            <strong>R$ 8-12k/mês</strong>
            <span>Receita perdida<br/>em oportunidades</span>
          </div>
        </div>
        <div className="pain-vs">→</div>
        <div className="pain-card after">
          <div className="pain-tag accent">Com TechFala</div>
          <ul>
            <li><span className="ok">✓</span> IA responde na hora, com o seu tom</li>
            <li><span className="ok">✓</span> Qualifica automaticamente</li>
            <li><span className="ok">✓</span> Agenda e confirma por conta</li>
            <li><span className="ok">✓</span> Move o lead no funil sem esforço</li>
            <li><span className="ok">✓</span> Transfere pra humano na hora certa</li>
          </ul>
          <div className="pain-card-foot">
            <strong>+218%</strong>
            <span>Conversões em<br/>agendamento</span>
          </div>
        </div>
      </div>
      <p className="pain-close">Enquanto sua equipe foca nos melhores negócios, a TechFala cuida da rotina que trava sua operação.</p>
    </div>
  </section>
);

/* ══════════ BENTO FEATURES ══════════ */
const IcFunnel = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 5h18l-7 9v6l-4-2v-4z"/></svg>);
const IcBrain = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5a3 3 0 0 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 0 0 12 18a4 4 0 0 0 7.967-.517 4 4 0 0 0 .557-6.588 4 4 0 0 0-2.526-5.77A3 3 0 0 0 12 5"/><path d="M12 5v14"/></svg>);
const IcWpp = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M17.47 14.38c-.3-.15-1.76-.87-2.03-.97-.27-.1-.47-.15-.67.15s-.77.97-.94 1.16c-.17.2-.35.22-.64.08-.3-.15-1.26-.47-2.4-1.48-.88-.78-1.48-1.76-1.65-2.06s-.02-.46.13-.6c.13-.14.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52L8.5 5.95c-.24-.58-.49-.5-.67-.5h-.57c-.2 0-.52.07-.79.37S5.43 7.35 5.43 8.8s1.07 2.88 1.22 3.08c.15.2 2.1 3.2 5.08 4.48.71.3 1.26.49 1.7.62.71.23 1.36.2 1.87.12.57-.08 1.76-.72 2-1.41.25-.69.25-1.28.18-1.41-.08-.12-.28-.2-.57-.35z"/></svg>);
const IcCal = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/></svg>);
const IcHand = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M7 11V5a2 2 0 1 1 4 0v5M11 10V4a2 2 0 1 1 4 0v7M15 10V6a2 2 0 1 1 4 0v9a6 6 0 0 1-6 6H8a6 6 0 0 1-5.4-3.4L1 14"/></svg>);
const IcLock = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 1 1 8 0v4"/></svg>);
const IcChart = () => (<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="M7 14l4-4 4 3 5-7"/></svg>);

const BentoFeatures = () => (
  <section className="features" id="features">
    <div className="container">
      <div className="features-head">
        <span className="pill"><Sparkle /> Recursos</span>
        <h2 style={{ marginTop: 20 }}>Tudo que você precisa<br/><em>pra não perder nenhum lead</em></h2>
      </div>

      <div className="bento-grid">
        {/* Row 1. Funnel (big) + Jarvis (enhanced) */}
        <div className="bento c8">
          <div className="icon-pill"><IcFunnel /></div>
          <h3>Funil que se organiza sozinho</h3>
          <p>A IA entende a intenção do cliente e move cada conversa pra etapa certa: novo lead, qualificado ou agendado.</p>
          <div className="bento-visual"><FunnelAnim /></div>
        </div>

        <div className="bento c4 jarvis-card">
          <div className="icon-pill"><IcBrain /></div>
          <h3>Jarvis treinado no seu negócio</h3>
          <p>Conecte documentos, planilhas, FAQs, preços e regras comerciais. A IA responde com o seu tom de voz.</p>
          <div className="jarvis-visual">
            <div className="jv-orb">
              <div className="jv-ring" />
              <div className="jv-ring jv-ring-2" />
              <div className="jv-core">J</div>
            </div>
            <div className="jv-feeds">
              <span className="jv-feed">📄 manual.pdf</span>
              <span className="jv-feed">📊 precos.xlsx</span>
              <span className="jv-feed">💬 tom-de-voz.md</span>
              <span className="jv-feed">⚙️ regras.json</span>
            </div>
          </div>
        </div>

        {/* Row 2. Agenda + Operação (50/50) */}
        <div className="bento c6">
          <div className="icon-pill"><IcCal /></div>
          <h3>Agenda automática</h3>
          <p>Marca, confirma, remarca e envia lembretes sem depender de atendimento manual.</p>
          <div className="bento-visual"><ChatAnim /></div>
        </div>

        <div className="bento c6">
          <div className="icon-pill"><IcChart /></div>
          <h3>Operação visível, previsível e no seu controle</h3>
          <p>Acompanhe conversas, agendamentos, conversões e gargalos da operação em tempo real, sem planilha e sem adivinhação.</p>
          <div className="bento-visual"><DashAnim /></div>
        </div>
      </div>

      <div className="features-cta">
        <p className="features-cta-kicker">Tudo isso na mesma plataforma, com implantação guiada pelo nosso time.</p>
        <a href={(typeof window !== 'undefined' && window.WPP_LINK) || "https://wa.me/5512992126931?text=Ol%C3%A1%2C%20quero%20conhecer%20a%20TechFala%20IA!"} target="_blank" rel="noopener" className="btn-primary">
          Fale com o Jarvis
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="M13 5l7 7-7 7"/></svg>
        </a>
      </div>
    </div>
  </section>
);

/* ══════════ HOW IT WORKS ══════════ */
const HowItWorks = () => (
  <section className="steps" id="how">
    <div className="container">
      <div className="steps-head">
        <span className="pill"><Sparkle /> Como funciona</span>
        <h2 style={{ marginTop: 20 }}>Do primeiro "oi" à venda fechada<br/>em 4 passos</h2>
        <p>Implementação guiada. Sem dor técnica. Em operação em até 7 dias.</p>
      </div>
      <div className="steps-list">
        {[
          { n: '01', t: 'Treinamos sua IA', d: 'Mapeamos perguntas, serviços, preços, documentos, tom de voz e regras comerciais.' },
          { n: '02', t: 'Conectamos seus canais', d: 'Integramos WhatsApp, calendário, planilhas, CRM e fluxos necessários.' },
          { n: '03', t: 'A IA atende e qualifica', d: 'Jarvis conversa, entende intenção, tira dúvidas, agenda e classifica o lead.' },
          { n: '04', t: 'Sua equipe fecha mais', d: 'O time humano entra no momento certo, com contexto e prioridade.' },
        ].map(s => (
          <div className="step" key={s.n}>
            <div className="num">{s.n}</div>
            <h4>{s.t}</h4>
            <p>{s.d}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ══════════ TESTIMONIALS CAROUSEL ══════════ */
const TESTIMONIALS = [
  {
    pill: 'Clínica médica',
    text: '"O Jarvis triplicou nossa taxa de agendamento em 3 meses. Responde em segundos, qualifica, marca, lembra e remarca. A recepção foca só em paciente novo."',
    who: 'Dra. Carolina Ribeiro',
    role: 'Diretora clínica · ClinAge Saúde',
    avatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=200&h=200&fit=crop&crop=faces',
    statBig: '3×',
    statLbl: 'Agendamentos',
    statSub: 'em 3 meses com o mesmo time.',
  },
  {
    pill: 'Loja de carros',
    text: '"Recupero lead parado e fecho mais test-drive. A IA puxa quem ia esfriar e devolve a venda. Em 2 meses recuperamos R$ 180 mil em propostas que estavam perdidas."',
    who: 'Rodrigo Nunes',
    role: 'Gerente comercial · NK Veículos',
    avatar: 'https://images.unsplash.com/photo-1560250097-0b93528c311a?w=200&h=200&fit=crop&crop=faces',
    statBig: 'R$180k',
    statLbl: 'Receita recuperada',
    statSub: 'em 60 dias só com follow-up.',
  },
  {
    pill: 'Escola de idiomas',
    text: '"Captação, matrícula, dúvida de aluno. O Jarvis responde 24/7 com o nosso tom e devolve o lead qualificado pro comercial. Triplicou matrícula no semestre."',
    who: 'Marina Tavares',
    role: 'Coordenadora · Lingua Now',
    avatar: 'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=200&h=200&fit=crop&crop=faces',
    statBig: '24/7',
    statLbl: 'Atendimento',
    statSub: 'sem fila e sem horário comercial.',
  },
  {
    pill: 'Imobiliária',
    text: '"O time só toca lead quente. O Jarvis qualifica, agenda visita, manda localização e confirma. Dobramos visita marcada por corretor sem aumentar a equipe."',
    who: 'Felipe Andrade',
    role: 'Diretor · Andrade Imóveis',
    avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&h=200&fit=crop&crop=faces',
    statBig: '2×',
    statLbl: 'Visitas marcadas',
    statSub: 'por corretor sem contratar mais ninguém.',
  },
];

const renderQuoteText = (str) => {
  const parts = str.split(/<hl>(.*?)<\/hl>/g);
  return parts.map((p, i) => i % 2 === 1
    ? <span className="hl" key={i}>{p}</span>
    : <React.Fragment key={i}>{p}</React.Fragment>);
};

const Quote = () => {
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const n = TESTIMONIALS.length;

  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setIdx(i => (i + 1) % n), 6500);
    return () => clearInterval(id);
  }, [paused, n]);

  const go = (i) => setIdx(((i % n) + n) % n);

  return (
    <section className="quote-section" id="cases"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <div className="container">
        <div className="quote-head">
          <span className="pill"><Sparkle /> Cases</span>
          <h2 style={{ marginTop: 20 }}>Quem botou o Jarvis<br/><em>parou de perder venda</em></h2>
          <p>Clínica médica, automotivo, educação e imobiliária. Os setores que mais escalam com a TechFala.</p>
        </div>
        <div className="carousel-wrap">
          <button className="carousel-nav prev" onClick={() => go(idx - 1)} aria-label="Depoimento anterior">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
          </button>
          <button className="carousel-nav next" onClick={() => go(idx + 1)} aria-label="Próximo depoimento">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
          </button>

          <div className="carousel-track">
            <div className="carousel-rail" style={{ transform: `translateX(-${idx * 100}%)` }}>
              {TESTIMONIALS.map((t, i) => (
                <div className="carousel-slide" key={i}>
                  <div className="testimonial-card">
                    <span className="tc-quote-mark">“</span>
                    <div className="tc-main">
                      <span className="tc-pill"><Sparkle /> {t.pill}</span>
                      <p className="tc-text">{renderQuoteText(t.text)}</p>
                      <div className="tc-author">
                        <div className="tc-av">
                          <img src={t.avatar} alt={t.who} loading="lazy" />
                        </div>
                        <div className="tc-who">
                          <strong>{t.who}</strong>
                          <span>{t.role}</span>
                        </div>
                      </div>
                    </div>
                    <div className="tc-divider" />
                    <div className="tc-stat">
                      <div className="tc-stat-lbl">{t.statLbl}</div>
                      <div className="tc-stat-big">{t.statBig}</div>
                      <div className="tc-stat-sub">{t.statSub}</div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="carousel-dots">
            {TESTIMONIALS.map((_, i) => (
              <button
                key={i}
                className={`carousel-dot ${i === idx ? 'active' : ''}`}
                onClick={() => go(i)}
                aria-label={`Ir para depoimento ${i + 1}`}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

window.MetricsBar = MetricsBar;
window.PainSection = PainSection;
window.BentoFeatures = BentoFeatures;
window.HowItWorks = HowItWorks;
window.Quote = Quote;
