/* Pricing. real Techfala plans from ui/pricing-section.tsx */

const PLANS = [
  {
    name: 'Essencial',
    desc: 'Pra autônomos e pequenos negócios começando com IA no WhatsApp.',
    price: 497, biannual: 2685, yearly: 4970,
    cta: 'Começar agora',
    featured: false,
    items: [
      { head: true, text: 'Inclui:' },
      'Jarvis (IA treinada no seu negócio)',
      'Atendimento 24/7 no WhatsApp',
      'Agendamento automático',
      'Suporte por chat',
      'Dashboard de métricas',
      'Confirmações e lembretes',
      'Respostas humanizadas',
    ],
  },
  {
    name: 'Crescimento',
    desc: 'Pra quem já valida IA e quer escalar qualificação e agendamento.',
    price: 797, biannual: 4305, yearly: 7970,
    cta: 'Começar agora',
    featured: true,
    tag: 'Mais popular',
    items: [
      { head: true, text: 'Tudo do Essencial, mais:' },
      'Qualificação básica de leads',
      'Integração Google Calendar',
      'Campanhas em massa (até 5/mês)',
      'Suporte prioritário',
      'Múltiplos fluxos de atendimento',
      'Relatórios semanais por e-mail',
    ],
  },
  {
    name: 'Profissional',
    desc: 'Pra negócios em crescimento com qualificação e funil automatizado.',
    price: 1199, biannual: 6475, yearly: 11990,
    cta: 'Começar agora',
    featured: false,
    items: [
      { head: true, text: 'Tudo do Crescimento, mais:' },
      'NeuralSales (funil ToFu/MoFu/BoFu)',
      'Qualificação automática de leads',
      'Integrações CRM completas',
      'Relatórios avançados em tempo real',
      'Campanhas em massa ilimitadas',
      'Catálogo dinâmico (Sheets)',
    ],
  },
];

const ENTERPRISE = {
  name: 'Operador Dedicado',
  price: 'R$ 4.200',
  period: '/mês',
  desc: 'Licença Jarvis + um vendedor de IA humano alocado na sua operação. Ele alimenta, ajusta, prospecta e fecha junto com seu time. Pra quem quer resultado em receita, não brincar de configurar IA.',
  items: [
    'Jarvis treinado no seu negócio (proprietário)',
    'Vendedor de IA dedicado ao seu time',
    'Operação executada por nós, não por você',
    'Integrações com CRM, ERP, agenda, planilhas',
    'Multi-atendente com roteamento humano',
    'SLA de resposta e metas de receita em contrato',
    'Gerente de conta + treinamento da equipe',
  ],
  cta: 'Quero o operador dedicado',
};

const Check = () => (
  <svg className="check" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 10.5l4 4 8-9"/>
  </svg>
);

// animated number (lightweight NumberFlow replacement)
function useAnimatedNumber(target, duration = 450) {
  const [v, setV] = React.useState(target);
  const raf = React.useRef(null);
  const from = React.useRef(target);
  const start = React.useRef(0);
  React.useEffect(() => {
    cancelAnimationFrame(raf.current);
    from.current = v;
    start.current = performance.now();
    const step = now => {
      const p = Math.min(1, (now - start.current) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(from.current + (target - from.current) * eased));
      if (p < 1) raf.current = requestAnimationFrame(step);
    };
    raf.current = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf.current);
  }, [target]);
  return v;
}

const PriceNum = ({ value }) => {
  const v = useAnimatedNumber(value);
  return <>{v.toLocaleString('pt-BR')}</>;
};

const PricingCard = ({ plan, billing }) => {
  const price =
    billing === 'yearly'   ? Math.round(plan.yearly / 12)
    : billing === 'biannual' ? Math.round(plan.biannual / 6)
    : plan.price;
  const note =
    billing === 'yearly'   ? `Cobrado R$ ${plan.yearly.toLocaleString('pt-BR')}/ano`
    : billing === 'biannual' ? `Cobrado R$ ${plan.biannual.toLocaleString('pt-BR')}/semestre`
    : 'Cobrança mensal, cancele a qualquer momento';
  const wpp = (typeof window !== 'undefined' && window.WPP_LINK) || "https://wa.me/5512992126931?text=Ol%C3%A1%2C%20quero%20conhecer%20a%20TechFala%20IA!";
  return (
    <div className={'plan' + (plan.featured ? ' featured' : '')}>
      {plan.tag && <span className="tag">{plan.tag}</span>}
      <h3>{plan.name}</h3>
      <p className="desc">{plan.desc}</p>
      <div className="price-wrap">
        <span className="price-prefix">R$</span>
        <span className="price"><PriceNum value={price} /></span>
        <span className="price-period">/mês</span>
      </div>
      <div className="price-note">{note}</div>
      <a href={(typeof window !== 'undefined' && window.REGISTER_URL) || "https://www.techfala.com/login/register/863/MONTHLY"} target="_blank" rel="noopener" className="cta">{plan.cta}</a>
      <ul>
        {plan.items.map((it, i) => {
          if (typeof it === 'object' && it.head) return <li key={i} className="head">{it.text}</li>;
          return (
            <li key={i}>
              <Check /> <span>{it}</span>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

const Pricing = () => {
  const [billing, setBilling] = React.useState('monthly');
  return (
    <section className="pricing" id="pricing">
      <div className="container">
        <div className="pricing-head">
          <span className="pill"><Sparkle /> Planos</span>
          <h2 style={{ marginTop: 20 }}>Planos que acompanham<br/><em>o tamanho da sua operação</em></h2>
          <p>Escolha e receba seu agente pronto pra operar em até 7 dias.</p>
          <div className="pricing-toggle">
            <button className={billing === 'monthly' ? 'active' : ''} onClick={() => setBilling('monthly')}>Mensal</button>
            <button className={billing === 'biannual' ? 'active' : ''} onClick={() => setBilling('biannual')}>
              Semestral <span className="save-badge">-10%</span>
            </button>
            <button className={billing === 'yearly' ? 'active' : ''} onClick={() => setBilling('yearly')}>
              Anual <span className="save-badge">-17%</span>
            </button>
          </div>
        </div>

        <div className="pricing-grid">
          {PLANS.map(p => <PricingCard key={p.name} plan={p} billing={billing} />)}
        </div>

        <div className="enterprise-card operator-card">
          <div className="ec-left">
            <span className="ec-badge">Premium · Recomendado</span>
            <h3>{ENTERPRISE.name}</h3>
            <div className="ec-price">
              <span className="ec-price-prefix">a partir de</span>
              <span className="ec-price-num">{ENTERPRISE.price}</span>
              <span className="ec-price-period">{ENTERPRISE.period}</span>
            </div>
            <p className="ec-desc">{ENTERPRISE.desc}</p>
          </div>
          <ul className="ec-list">
            {ENTERPRISE.items.map((it, i) => (
              <li key={i}><Check /> <span>{it}</span></li>
            ))}
          </ul>
          <div className="ec-cta-wrap">
            <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">
              {ENTERPRISE.cta}
              <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>
            <span className="ec-micro">Conversamos no WhatsApp pra montar sua operação.</span>
          </div>
        </div>

        <div className="pricing-foot">
          <p className="pf-imp">Implementação cobrada à parte conforme complexidade: <strong>R$ 3.000 a R$ 15.000</strong>.</p>
        </div>
      </div>
    </section>
  );
};

window.Pricing = Pricing;
