/* ─── Header ─── */
const Header = ({ onTweaksToggle, tweaksEnabled }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { href:'#modulos', label:'Módulos' },
    { href:'#funcionalidades', label:'Funcionalidades' },
    { href:'#roi', label:'ROI' },
    { href:'#precos', label:'Preços' },
    { href:'#faq', label:'FAQ' },
  ];

  return (
    <header className={`fixed top-0 inset-x-0 z-50 transition-all duration-500 ${scrolled ? 'bg-white/85 backdrop-blur-xl border-b border-ink-100' : 'bg-transparent'}`}>
      <nav className="max-w-7xl mx-auto px-6 lg:px-8 h-[72px] flex items-center justify-between">
        <a href="#" className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-brand-500 flex items-center justify-center">
            <I.building size={16} className="text-white"/>
          </div>
          <span className={`text-[17px] font-bold tracking-tight transition-colors ${scrolled ? 'text-ink-900' : 'text-white'}`}>
            Restaurante<span className="text-brand-400">Pro</span>
          </span>
        </a>

        <div className="hidden md:flex items-center gap-0.5">
          {links.map(l => (
            <a key={l.href} href={l.href}
               className={`px-3.5 py-2 text-[13px] font-medium transition-colors ${scrolled ? 'text-ink-500 hover:text-ink-900' : 'text-white/75 hover:text-white'}`}>
              {l.label}
            </a>
          ))}
        </div>

        <div className="hidden md:flex items-center gap-2">
          <a href="https://painel.restaurantepro.com.br/login" className={`px-3.5 py-2 text-[13px] font-medium transition-colors ${scrolled ? 'text-ink-700 hover:text-ink-900' : 'text-white/80 hover:text-white'}`}>
            Entrar
          </a>
          <a href="#precos" className="px-4 py-2 text-[13px] font-semibold text-white bg-ink-900 hover:bg-ink-800 rounded-lg transition-colors shadow-sm">
            Começar grátis
          </a>
        </div>

        <button onClick={() => setMobileOpen(!mobileOpen)}
                className={`md:hidden p-2 rounded-lg ${scrolled ? 'text-ink-700' : 'text-white'}`}>
          {mobileOpen ? <I.x size={20}/> : <I.menu size={20}/>}
        </button>
      </nav>
      {mobileOpen && (
        <div className="md:hidden bg-white border-t border-ink-100 px-6 py-4 space-y-1">
          {links.map(l => <a key={l.href} href={l.href} onClick={()=>setMobileOpen(false)} className="block py-2.5 text-[14px] text-ink-700">{l.label}</a>)}
          <a href="#precos" className="block mt-2 text-center px-5 py-3 text-[13px] font-semibold text-white bg-ink-900 rounded-lg">Começar grátis</a>
        </div>
      )}
    </header>
  );
};

/* ─── Hero (kept — only very small polish) ─── */
const textLoopWords = ['Reservas','Cardápio','Delivery','Fila de espera','Avaliações','IA integrada','CRM completo','Fichas técnicas','Checklists'];

const Hero = ({ heroCopy }) => {
  const [idx, setIdx] = React.useState(0);
  const [demoOpen, setDemoOpen] = React.useState(false);
  React.useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % textLoopWords.length), 2600);
    return () => clearInterval(t);
  }, []);
  React.useEffect(() => {
    if (!demoOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setDemoOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
  }, [demoOpen]);

  return (
    <section className="relative min-h-screen h-screen flex items-center pt-20 pb-36 overflow-hidden bg-ink-950">
      {/* Video background */}
      <div className="absolute inset-0">
        <video autoPlay muted loop playsInline
               className="absolute inset-0 w-full h-full object-cover"
               poster="https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?q=80&w=1920&auto=format&fit=crop">
          <source src="assets/hero.mp4" type="video/mp4"/>
        </video>
        <div className="absolute inset-0 bg-black/60"></div>
        <div className="absolute inset-0 noise-dark"></div>
      </div>

      <div className="relative z-10 max-w-7xl mx-auto px-6 lg:px-8 py-10 w-full">
        <div className="max-w-3xl">
          <span className="inline-flex items-center gap-2 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.1em] text-white bg-white/10 border border-white/15 rounded-full backdrop-blur-sm mb-6">
            <span className="w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse-soft"></span>
            Sistema #1 para restaurantes brasileiros
          </span>

          <h1 className="text-[44px] sm:text-[56px] lg:text-[68px] font-bold text-white leading-[1.02] tracking-[-0.03em] mb-7">
            <span>Gestão completa</span><br/>
            <span>para seu restaurante.</span><br/>
            <span className="serif italic text-brand-400 font-normal inline-block min-h-[1.1em]">
              <span key={idx} className="inline-block" style={{animation:'fadeInUp .6s'}}>{textLoopWords[idx]}</span>
            </span>
          </h1>

          <p className="text-[17px] text-white/65 leading-relaxed mb-9 max-w-[560px]">
            {heroCopy || 'Reservas, delivery, cardápio digital, controle de estoque, WhatsApp integrado e fichas técnicas. Tudo em um só lugar, sem taxa por pedido.'}
          </p>

          <div className="flex flex-col sm:flex-row gap-3 mb-10">
            <a href="https://wa.me/5516991999000?text=Ol%C3%A1!%20Quero%20saber%20mais%20sobre%20o%20RestaurantePro."
               target="_blank" rel="noopener"
               className="inline-flex items-center justify-center gap-2 px-7 py-3.5 text-[14px] font-semibold text-white bg-brand-500 hover:bg-brand-400 rounded-xl shadow-[0_8px_32px_-8px_rgba(14,165,233,.6)] transition-all hover:-translate-y-0.5 group">
              <I.whatsapp size={16}/> Falar no WhatsApp
              <I.arrow size={16} className="group-hover:translate-x-0.5 transition-transform"/>
            </a>
            <button type="button" onClick={() => setDemoOpen(true)}
               className="inline-flex items-center justify-center gap-2 px-7 py-3.5 text-[14px] font-semibold text-white bg-white/10 border border-white/15 hover:bg-white/15 rounded-xl backdrop-blur-sm transition-colors">
              <I.play size={14} className="text-brand-400"/> Agendar Demonstração
            </button>
          </div>

          <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-[12px] text-white/50">
            <div className="flex items-center gap-1.5"><I.check size={14} className="text-brand-400"/> Sem cartão de crédito</div>
            <div className="flex items-center gap-1.5"><I.check size={14} className="text-brand-400"/> Sem taxa por pedido</div>
            <div className="flex items-center gap-1.5"><I.check size={14} className="text-brand-400"/> Cancele quando quiser</div>
          </div>
        </div>
      </div>

      {/* Partner logos strip */}
      <div className="absolute bottom-0 inset-x-0">
        <div className="border-t border-white/10 bg-black/30 backdrop-blur-sm py-5">
          <p className="text-center text-[10px] font-semibold uppercase tracking-[0.18em] text-white/45 mb-3">
            Empresas que confiam no RestaurantePro
          </p>
          <div className="relative overflow-hidden">
            <div className="absolute inset-y-0 left-0 w-16 bg-gradient-to-r from-black/60 to-transparent z-10 pointer-events-none"></div>
            <div className="absolute inset-y-0 right-0 w-16 bg-gradient-to-l from-black/60 to-transparent z-10 pointer-events-none"></div>
            <div className="flex animate-scroll">
              {[...Array(2)].flatMap((_,k) => Array.from({length:13},(_,i) => (
                <div key={`${k}-${i}`} className="flex-shrink-0 mx-5 flex items-center justify-center">
                  <img src={`assets/parceiros/${i+1}.jpg`} alt="" className="h-14 w-auto object-contain rounded-md opacity-75 hover:opacity-100 transition-opacity"/>
                </div>
              )))}
            </div>
          </div>
        </div>
      </div>

      <style>{`@keyframes fadeInUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}`}</style>

      {demoOpen && (
        <div
          className="fixed inset-0 z-[100] flex items-center justify-center p-3 sm:p-6 bg-black/80 backdrop-blur-sm"
          onClick={() => setDemoOpen(false)}
          role="dialog" aria-modal="true" aria-label="Agendar demonstração"
        >
          <div
            className="relative w-full max-w-[880px] h-[85vh] sm:h-[620px] bg-ink-950 border border-white/10 rounded-2xl shadow-2xl overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setDemoOpen(false)}
              aria-label="Fechar"
              className="absolute top-3 right-3 z-10 w-9 h-9 rounded-full bg-white/10 hover:bg-white/20 border border-white/15 text-white flex items-center justify-center transition-transform hover:scale-105 backdrop-blur-sm"
            >
              <I.x size={18}/>
            </button>
            <div className="absolute inset-0 overflow-hidden">
              <iframe
                src="https://cal.com/restaurante-pro?embed=true&layout=month_view&theme=dark"
                title="Agendar Demonstração"
                className="absolute left-0 top-0 w-full border-0"
                style={{ height: 'calc(100% + 140px)' }}
                loading="lazy"
                allow="camera; microphone; fullscreen; payment"
              />
            </div>
          </div>
        </div>
      )}
    </section>
  );
};

/* ─── Stats strip (new — "above" features, product-forward) ─── */
const StatsStrip = () => (
  <section className="relative bg-white py-12 border-b border-ink-100">
    <div className="max-w-7xl mx-auto px-6 lg:px-8">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-8 md:gap-12">
        {[
          {n:'2.4M', l:'Mensagens respondidas', s:'por IA em 2025'},
          {n:'−18%', l:'CMV médio reduzido', s:'no primeiro trimestre'},
          {n:'R$ 4,2k', l:'Economia mensal', s:'vs sistemas avulsos'},
        ].map(s => (
          <div key={s.l} className="border-l-2 border-brand-500 pl-4">
            <div className="serif text-[42px] leading-none text-ink-900 mb-1">{s.n}</div>
            <div className="text-[13px] font-semibold text-ink-800">{s.l}</div>
            <div className="text-[12px] text-ink-400">{s.s}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ─── Features grid (kept — minor polish) ─── */
const FeaturesGrid = () => {
  const features = [
    { icon: I.calendar, title: 'Reservas online',
      d: 'Processo automatizado com confirmação inteligente 24/7.',
      long: 'Reservas pelo site, Google, WhatsApp e redes sociais. Confirmação e lembrete automáticos, reduzindo no-shows em até 60%. Pré-pagamento opcional via PIX.',
      tag: 'Automação' },
    { icon: I.users, title: 'Fila de espera',
      d: 'Notificações automáticas e acompanhamento em tempo real.',
      long: 'O cliente entra na fila pelo QR Code ou pela recepção. Receba notificações quando a mesa estiver pronta — sem voucher de papel, sem fila na porta.',
      tag: 'Atendimento' },
    { icon: I.cart, title: 'Compras & cotação',
      d: 'Controle de fornecedores, pedidos e reposição.',
      long: 'Envie a lista para todos os fornecedores ao mesmo tempo, compare item a item e escolha o melhor preço. Ao finalizar a compra, as fichas técnicas são atualizadas em tempo real — o CMV fica sempre correto, sem retrabalho.',
      tag: 'Operação' },
    { icon: I.clipboard, title: 'Checklists digitais',
      d: 'Rotinas auditáveis com evidência fotográfica.',
      long: 'Abertura, fechamento, limpeza e rotinas diárias com foto obrigatória. Tudo registrado — o gestor audita sem precisar estar presente.',
      tag: 'Operação' },
    { icon: I.star, title: 'Avaliações & NPS',
      d: 'Coleta automática de feedback pós-visita.',
      long: 'Envio automático de pesquisa por WhatsApp após a visita. Dashboard com NPS, notas por atendente e alertas de avaliações negativas.',
      tag: 'Atendimento' },
    { icon: I.utensils, title: 'Fichas técnicas',
      d: 'Receitas padronizadas com CMV em tempo real.',
      long: 'Cada ficha puxa o preço atual do estoque. Ao registrar uma compra, o CMV de todas as receitas envolvidas é recalculado automaticamente.',
      tag: 'Operação' },
    { icon: I.list, title: 'Tarefas',
      d: 'Atribuição e acompanhamento com prazos.',
      long: 'Delegue tarefas para equipe com prazo e responsável. Notificações automáticas e relatórios de conclusão por pessoa.',
      tag: 'Gestão' },
    { icon: I.bot, title: 'Atendimento via IA',
      d: 'Chatbot 24/7 integrado ao WhatsApp, site e redes.',
      long: 'Conectado ao WhatsApp e ao Instagram, responde com inteligência artificial de verdade — não um chatbot engessado. Entende o contexto, consulta o cardápio, tira dúvidas e faz reservas. Escala para humano quando precisa.',
      tag: 'IA' },
    { icon: I.qr, title: 'Cardápio digital',
      d: 'QR Code, fotos, delivery e impressão por setores.',
      long: 'Cardápio com fotos, descrição e preços sempre atualizado. Impressão segmentada por cozinha, bar e forno — sem comissão no delivery.',
      tag: 'Atendimento' },
    { icon: I.whatsapp, title: 'WhatsApp API',
      d: 'Integração oficial Cloud da Meta com coexistência total.',
      long: 'API Oficial Meta com seu número atual. Use o WhatsApp do celular normalmente — tudo espelhado no sistema para equipe e IA.',
      tag: 'Integração' },
    { icon: I.contact, title: 'CRM',
      d: 'Histórico, preferências e segmentação inteligente.',
      long: 'Ficha completa do cliente com todas as visitas, ticket médio, ocasiões especiais e preferências. Campanhas segmentadas por WhatsApp.',
      tag: 'Relacionamento' },
    { icon: I.shield, title: 'Permissões',
      d: 'Controle granular por cargo e setor.',
      long: 'Defina quem vê o quê. Permissões por módulo, por empresa e por ação. Logs de auditoria de todas as alterações sensíveis.',
      tag: 'Segurança' },
    { icon: I.factory, title: 'Produção de insumos',
      d: 'Lotes, validade, etiquetas e rendimento.',
      long: 'Produção interna controlada por lote e validade. Etiquetas impressas automaticamente. Baixa no estoque por rendimento real.',
      tag: 'Operação' },
  ];

  // first two get hero treatment — Atendimento IA + Compras
  const hero1 = features.find(f => f.title === 'Atendimento via IA');
  const hero2 = features.find(f => f.title === 'Compras & cotação');
  const rest = features.filter(f => f !== hero1 && f !== hero2);

  return (
    <section id="funcionalidades" className="relative py-14 lg:py-20 bg-ink-50 overflow-hidden">
      <div className="absolute inset-0 grid-bg opacity-40"></div>
      <div className="absolute top-0 right-0 w-[40%] h-[50%] bg-brand-100/50 blur-[100px] rounded-full pointer-events-none"></div>

      <div className="relative max-w-7xl mx-auto px-6 lg:px-8">
        {/* Header */}
        <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6 mb-14">
          <div className="max-w-2xl">
            <span className="inline-flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-brand-600 mb-4">
              <span className="w-6 h-px bg-brand-500"></span> Funcionalidades
            </span>
            <h2 className="text-[38px] sm:text-[48px] lg:text-[56px] font-bold text-ink-900 tracking-[-0.02em] leading-[1.04] mb-4">
              Tudo que seu restaurante precisa, <span className="serif italic text-brand-600 font-normal">num só lugar.</span>
            </h2>
            <p className="text-[16px] text-ink-500 max-w-lg leading-relaxed">
              13 módulos integrados. Sem planilhas paralelas, sem sistemas avulsos. Cada dado fluindo do WhatsApp à ficha técnica — automaticamente.
            </p>
          </div>
          <div className="flex items-center gap-6 text-[11px] mono text-ink-500">
            <div><span className="text-[22px] font-bold text-brand-600 serif block leading-none">13</span>módulos</div>
            <div className="w-px h-8 bg-ink-200"></div>
            <div><span className="text-[22px] font-bold text-brand-600 serif block leading-none">∞</span>usuários</div>
            <div className="w-px h-8 bg-ink-200"></div>
            <div><span className="text-[22px] font-bold text-brand-600 serif block leading-none">1</span>sistema</div>
          </div>
        </div>

        {/* Hero feature cards (larger) */}
        <div className="grid md:grid-cols-2 gap-4 mb-4">
          {[hero1, hero2].map((f, i) => (
            <a key={f.title} href="#modulos" data-reveal style={{transitionDelay: `${i*60}ms`}}
                     className="group relative overflow-hidden rounded-2xl bg-gradient-to-br from-ink-900 to-ink-950 p-7 lg:p-8 ring-1 ring-ink-800 cursor-pointer hover:ring-brand-400/50 transition-all">
              <div className="absolute top-0 right-0 w-[50%] h-[80%] bg-brand-500/15 blur-[80px] rounded-full pointer-events-none"></div>
              <div className="absolute -right-8 -bottom-10 opacity-5 text-white pointer-events-none">
                <f.icon size={220}/>
              </div>

              <div className="relative">
                <div className="flex items-center justify-between mb-6">
                  <div className="w-11 h-11 rounded-xl bg-brand-500 text-white flex items-center justify-center shadow-lg shadow-brand-500/30">
                    <f.icon size={19}/>
                  </div>
                  <span className="mono text-[10px] text-brand-300 uppercase tracking-[0.18em]">/ {f.tag}</span>
                </div>

                <h3 className="text-[24px] lg:text-[28px] font-bold text-white tracking-[-0.01em] mb-2">{f.title}</h3>
                <p className="text-[14px] text-white/55 leading-relaxed mb-5 max-w-md">{f.long}</p>

                <div className="flex items-center gap-2 text-[12px] text-brand-300 font-semibold group-hover:gap-3 transition-all">
                  Ver em ação <I.arrow size={12} className="group-hover:translate-x-1 transition-transform"/>
                </div>
              </div>
            </a>
          ))}
        </div>

        {/* Standard feature cards */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
          {rest.map((f, i) => (
            <article key={f.title} data-reveal style={{transitionDelay: `${(i+2)*30}ms`}}
                     className="group relative p-5 rounded-2xl bg-white border border-ink-100 hover:border-brand-300 hover:shadow-[0_16px_40px_-14px_rgba(14,165,233,0.25)] hover:-translate-y-0.5 transition-all duration-300 cursor-default overflow-hidden">
              {/* top accent bar */}
              <div className="absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-brand-500 to-brand-300 scale-x-0 group-hover:scale-x-100 origin-left transition-transform duration-500"></div>
              {/* big ghost icon */}
              <div className="absolute -right-3 -bottom-4 text-brand-50 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                <f.icon size={90}/>
              </div>

              <div className="relative">
                <div className="flex items-start justify-between mb-4">
                  <div className="w-10 h-10 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center group-hover:bg-brand-500 group-hover:text-white transition-all group-hover:scale-105 group-hover:rotate-[-4deg]">
                    <f.icon size={17}/>
                  </div>
                  <span className="mono text-[9px] text-ink-400 uppercase tracking-[0.14em] pt-1">/ {f.tag}</span>
                </div>

                <h3 className="text-[15px] font-bold text-ink-900 mb-1.5 leading-tight">{f.title}</h3>
                <p className="text-[12.5px] text-ink-500 leading-[1.55]">{f.long}</p>
              </div>
            </article>
          ))}
        </div>

        {/* Footer link */}
        <div className="mt-10 flex items-center justify-center">
          <a href="#modulos" className="group inline-flex items-center gap-2 text-[13px] font-semibold text-brand-600 hover:text-brand-700">
            Ver o produto em ação <I.arrow size={14} className="group-hover:translate-x-1 transition-transform"/>
          </a>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Header, Hero, StatsStrip, FeaturesGrid });
