// -------------------------------------------------------------------------
// SELETOR DE CHECKOUTS
//
// Destino: /lp/components/middle.jsx
// Protótipo: lab/protos/seletor-de-checkouts.html · Ficha: refs/seletor-de-checkouts/ficha.md
// GERADO por tools/portar.py — edite o protótipo e rode de novo.
//
// Ícones: use `II` (window.Icon), já aliasado no topo de middle.jsx.
// Tudo vive numa IIFE porque os arquivos de /lp/components/ dividem o
// mesmo escopo global — nomes soltos colidem entre si.
// -------------------------------------------------------------------------

(function () {
  // ---------------------------------------------------------------------------
  // Lojas reais rodando cartROI. Cores extraídas do site de cada uma
  // (refs/clientes/clientes.json), produtos de /products.json.
  // A tipografia usa pilhas do sistema: mostra a diferença sem baixar fonte nova.
  // ---------------------------------------------------------------------------
  const LOJAS = [
    { slug:'b2grifes', nome:'B2 Grifes', dominio:'pagamento.b2grifes.com',
      primaria:'#111111', acento:'#111111', claro:'#f4f4f4', fonte:"'Helvetica Neue', Arial, sans-serif",
      aviso:'Frete grátis acima de R$ 299 · 12x sem juros',
      produto:{ nome:'Camisa Xadrez Polo Ralph Lauren Manga Longa', de:649.90, por:169.90,
                img:'/lp/assets/lojas/produto-b2grifes.png' } },
    { slug:'flashdental', nome:'Flash Dental', logoClaro:true, dominio:'pagamento.flashdental.com.br',
      primaria:'#1B6AD6', acento:'#1DB912', claro:'#eef5ff', fonte:"'Helvetica Neue', Arial, sans-serif",
      aviso:'Chegou! Clareamento com 45% OFF por tempo limitado',
      produto:{ nome:'Caneta Para Clareamento Dental Removedor de Manchas', de:159.90, por:87.90,
                img:'/lp/assets/lojas/produto-flashdental.jpg' } },
    { slug:'essencialwear', nome:'Essencial Wear', dominio:'pagamento.essencialwear.com',
      primaria:'#111111', acento:'#8a6a4f', claro:'#f7f5f2', fonte:"'Helvetica Neue', Arial, sans-serif",
      aviso:'Compre 3 camisetas e pague 2',
      produto:{ nome:'Camiseta Básica Essencial® — Bordô', de:0, por:99.00,
                img:'/lp/assets/lojas/produto-essencialwear.png' } },
    { slug:'uperclean', nome:'UperClean', dominio:'pagamento.uperclean.com',
      primaria:'#5148FF', acento:'#18E889', claro:'#f2f1ff', fonte:"'Helvetica Neue', Arial, sans-serif",
      aviso:'Pague com PIX e ganhe 5% de desconto! Frete grátis acima de R$200',
      produto:{ nome:'Flotador Multiuso Power Clean 500 ml', de:28.90, por:19.90,
                img:'/lp/assets/lojas/produto-uperclean.jpg' } },
    { slug:'molduralle', nome:'Molduralle', logoClaro:true, dominio:'pagamento.molduralle.com.br',
      primaria:'#806047', acento:'#a3805f', claro:'#f7f4f0', fonte:"Georgia, 'Times New Roman', serif",
      aviso:'Quadros com moldura inclusa · Envio em 24h',
      produto:{ nome:'Quadro Decorativo Mãos de Jesus Abençoando o Pão', de:0, por:399.00,
                img:'/lp/assets/lojas/produto-molduralle.png' } },
  ];

  const DUR_LOJA = 4600;
  const brl = (v) => v.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  function useReduced() {
    const [r, setR] = React.useState(false);
    React.useEffect(() => {
      if (!window.matchMedia) return;
      const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
      setR(mq.matches);
      const on = (e) => setR(e.matches);
      mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
      return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
    }, []);
    return r;
  }

  // Miolo do checkout, tematizado pelas custom properties do container.
  function Checkout({ loja, compacto }) {
    const p = loja.produto;
    return (
      <div className="flex h-full flex-col bg-[var(--claro)]" style={{ fontFamily: 'var(--fonte)' }}>
        <div className="flex items-center justify-between bg-white px-3 py-2">
          <span className="inline-grid place-items-center rounded"
                style={{ background: loja.logoClaro ? 'var(--primaria)' : 'transparent',
                         padding: loja.logoClaro ? '3px 7px' : 0 }}>
            <img src={`/lp/assets/lojas/${loja.slug}.png`} alt={loja.nome}
                 className="max-w-[92px] object-contain" style={{ height: compacto ? 12 : 16 }} />
          </span>
          {!compacto && <span className="whitespace-nowrap text-[8px] text-black/45">Pagamento seguro</span>}
        </div>
        <div className="px-2 py-1.5 text-center font-medium text-white" style={{ background:'var(--primaria)', fontSize: compacto ? 7 : 8.5 }}>
          {loja.aviso}
        </div>

        <div className="flex items-center gap-1 px-3 py-2" style={{ fontSize: compacto ? 6.5 : 8 }}>
          {['Identificação','Endereço','Pagamento'].map((s,i)=>(
            <React.Fragment key={s}>
              <span className="flex items-center gap-1" style={{ color: i===0 ? 'var(--primaria)' : 'rgba(0,0,0,.4)' }}>
                <span className="grid place-items-center rounded-full font-bold text-white"
                      style={{ width: compacto?9:11, height: compacto?9:11, fontSize: compacto?5:6,
                               background: i===0 ? 'var(--primaria)' : '#c9c9d0' }}>{i+1}</span>
                {s}
              </span>
              {i<2 && <span className="h-px flex-1 bg-black/10"></span>}
            </React.Fragment>
          ))}
        </div>

        <div className={`flex items-start gap-2 px-3 pb-3 ${compacto ? 'flex-col' : ''}`}>
          {/* Formulário */}
          <div className="flex-1 rounded-lg bg-white p-2.5">
            <div className="font-semibold text-black/85" style={{ fontSize: compacto?8.5:10.5 }}>Identificação</div>
            {['CPF ou CNPJ','Nome completo','E-mail'].map((l,i)=>(
              <div key={l} className={i?'mt-1.5':'mt-2'}>
                <div className="text-black/45" style={{ fontSize: compacto?5.5:6.5 }}>{l}</div>
                <div className="mt-0.5 rounded border border-black/10 bg-white"
                     style={{ height: compacto?12:16 }}></div>
              </div>
            ))}
            <div className="mt-2 grid place-items-center rounded font-semibold uppercase text-white"
                 style={{ background:'var(--primaria)', height: compacto?15:20, fontSize: compacto?6.5:8 }}>
              Continuar
            </div>
          </div>

          {/* Resumo */}
          <div className={`rounded-lg bg-white p-2.5 ${compacto ? '' : 'w-[38%]'}`}>
            <div className="font-semibold text-black/85" style={{ fontSize: compacto?8:9.5 }}>Resumo do pedido</div>
            <div className="mt-1.5 flex items-center gap-1.5">
              <img src={p.img} alt="" className="shrink-0 rounded object-cover"
                   style={{ width: compacto?18:24, height: compacto?18:24 }} />
              <span className="min-w-0 flex-1 leading-tight text-black/70" style={{ fontSize: compacto?5.5:6.5 }}>
                {p.nome}
              </span>
            </div>
            <div className="mt-1.5 flex items-baseline justify-between border-t border-black/8 pt-1.5">
              <span className="text-black/50" style={{ fontSize: compacto?5.5:6.5 }}>Total</span>
              <span className="flex items-baseline gap-1">
                {p.de > 0 && (
                  <span className="text-black/30 line-through" style={{ fontSize: compacto?5.5:6.5 }}>R$ {brl(p.de)}</span>
                )}
                <span className="font-bold tabular-nums" style={{ color:'var(--acento)', fontSize: compacto?9:11 }}>
                  R$ {brl(p.por)}
                </span>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  function SeletorDeCheckouts() {
    const reduzido = useReduced();
    const [i, setI] = React.useState(0);
    const [pausado, setPausado] = React.useState(false);
    const [visivel, setVisivel] = React.useState(false);
    const secaoRef = React.useRef(null);

    React.useEffect(() => {
      const el = secaoRef.current; if (!el) return;
      const io = new IntersectionObserver(([e]) => setVisivel(e.isIntersecting), { threshold: 0.3 });
      io.observe(el); return () => io.disconnect();
    }, []);

    React.useEffect(() => {
      if (reduzido || pausado || !visivel) return;
      const t = setTimeout(() => setI((v) => (v + 1) % LOJAS.length), DUR_LOJA);
      return () => clearTimeout(t);
    }, [i, pausado, visivel, reduzido]);

    const loja = LOJAS[i];
    const tema = { '--primaria': loja.primaria, '--acento': loja.acento, '--claro': loja.claro, '--fonte': loja.fonte };
    const rodando = !reduzido && !pausado && visivel;

    return (
      <section ref={secaoRef} className="relative overflow-hidden bg-ink py-20 lg:py-28">
        <div className="absolute inset-0 -z-10">
          <div className="mesh-blob bg-violet-700/45 w-[560px] h-[560px] -top-32 -left-20 animate-drift1"></div>
          <div className="mesh-blob bg-cyan-400/20 w-[420px] h-[420px] bottom-0 -right-24 animate-drift3"></div>
          <div className="absolute inset-0 dot-grid opacity-[0.18]"></div>
        </div>

        <div className="mx-auto max-w-7xl px-6 lg:px-10">
          <div className="reveal max-w-3xl">
            <div className="inline-flex items-center gap-2 rounded-full border border-violet-300/20 bg-violet-500/10 px-3 py-1.5 text-[12px] font-medium text-violet-200">
              <span className="h-1.5 w-1.5 rounded-full bg-cyan-400"></span> Lojas rodando cartROI
            </div>
            <h2 className="mt-5 text-4xl font-semibold leading-[1.05] tracking-[-0.03em] sm:text-5xl">
              Cinco lojas. <span className="grad-cyan">Cinco checkouts diferentes.</span>
            </h2>
            <p className="mt-6 text-lg leading-relaxed text-violet-100/70">
              Mesma engine, mesma taxa, mesma segurança — e nenhum parece com o outro.
              Cor, tipografia, aviso, fluxo: tudo é da marca, não nosso.
            </p>
          </div>

          <div className="reveal mt-12 grid gap-6 lg:grid-cols-[196px_1fr]"
               onMouseEnter={() => setPausado(true)} onMouseLeave={() => setPausado(false)}>
            {/* Lista de lojas */}
            <div className="flex gap-2 overflow-x-auto no-scrollbar lg:flex-col lg:overflow-visible">
              <div className="hidden pb-1 text-[11px] uppercase tracking-[0.16em] text-violet-200/40 lg:block">
                Selecione um checkout
              </div>
              {LOJAS.map((l, k) => (
                <button key={l.slug} onClick={() => setI(k)}
                  className={`group relative shrink-0 overflow-hidden rounded-xl border p-1.5 text-left transition-colors ${
                    k === i ? 'border-violet-300/40 bg-white/[0.07]' : 'border-white/8 bg-white/[0.02] hover:bg-white/[0.05]'}`}>
                  {/* Chip branco: metade das marcas tem logo preto e sumiria no fundo escuro. */}
                  <span className="grid h-11 w-[168px] place-items-center rounded-lg px-3 transition-all"
                        style={{ background: l.logoClaro ? l.primaria : '#fff',
                                 filter: k === i ? 'none' : 'grayscale(1)', opacity: k === i ? 1 : 0.4 }}>
                    <img src={`/lp/assets/lojas/${l.slug}.png`} alt={l.nome}
                         className="max-h-7 max-w-full object-contain" />
                  </span>
                  {/* Barra de auto-advance */}
                  <span className="absolute inset-x-0 bottom-0 h-[2px] origin-left"
                    style={{
                      background: 'linear-gradient(90deg,#a78bfa,#22d3ee)',
                      transform: `scaleX(${k === i && rodando ? 1 : 0})`,
                      transition: k === i && rodando ? `transform ${DUR_LOJA}ms linear` : 'transform .2s ease',
                    }}></span>
                </button>
              ))}
            </div>

            {/* Preview: navegador + celular, ambos tematizados */}
            <div className="grid items-start gap-5 sm:grid-cols-[1fr_auto]" style={tema} aria-hidden="true">
              <div className="overflow-hidden rounded-2xl border border-white/10 bg-[#15102a] shadow-card">
                <div className="flex items-center gap-2 border-b border-white/5 bg-[#100a22] px-3 py-2">
                  <span className="h-2 w-2 rounded-full bg-rose-400/70"></span>
                  <span className="h-2 w-2 rounded-full bg-amber-300/70"></span>
                  <span className="h-2 w-2 rounded-full bg-emerald-400/70"></span>
                  <span className="ml-2 truncate rounded bg-white/[0.06] px-2 py-0.5 font-mono text-[10px] text-violet-200/60">
                    {loja.dominio}
                  </span>
                </div>
                <div key={loja.slug + '-d'} className="h-[268px] animate-[troca_.5s_cubic-bezier(.2,.7,.2,1)]">
                  <Checkout loja={loja} />
                </div>
              </div>

              <div className="mx-auto hidden w-[176px] rounded-[26px] border border-white/10 bg-[#0b0718] p-1.5 shadow-card sm:block">
                <div key={loja.slug + '-m'} className="h-[356px] overflow-hidden rounded-[20px] animate-[troca_.5s_cubic-bezier(.2,.7,.2,1)]">
                  <Checkout loja={loja} compacto />
                </div>
              </div>
            </div>
          </div>

          <p className="mt-6 font-mono text-[11.5px] text-violet-200/40">
            Lojas reais, com autorização de uso. Cores e produtos capturados dos sites em 10/08/2026.
          </p>
        </div>

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

  setTimeout(() => window.__attachReveal && window.__attachReveal(), 50);

  Object.assign(window, { SeletorDeCheckouts });
})();
