// STEPS SECTION — "Personalize em 3 passos"
const IS = window.Icon;
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

function useInView(threshold = 0.4) {
  const ref = useRefS(null);
  const [seen, setSeen] = useStateS(false);
  useEffectS(() => {
    if (seen) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setSeen(true); io.disconnect(); }
    }, { threshold });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [seen, threshold]);
  return [ref, seen];
}

function StepCard({ idx, title, body, children, accent }) {
  const isCyan = accent === 'cyan';
  return (
    <div className="relative group">
      {/* Number badge */}
      <div className="absolute -top-4 left-7 flex items-center gap-2.5 z-10">
        <span className={`relative h-8 w-8 rounded-full grid place-items-center text-[13px] font-mono font-bold leading-none bg-ink ${isCyan ? 'border border-cyan-300/60 text-cyan-200' : 'border border-violet-300/60 text-violet-200'} shadow-glow-violet-sm`}>
          {idx}
        </span>
        <span className="text-[10px] font-mono uppercase tracking-[0.22em] text-violet-300/50">Passo {idx}</span>
      </div>

      <div className="rounded-3xl bg-gradient-to-br from-white/[0.04] to-white/[0.01] border border-white/10 p-7 pt-9 h-full flex flex-col">
        <h3 className="text-2xl font-semibold tracking-tight">{title}</h3>
        <p className="mt-2 text-[14.5px] text-violet-100/65 leading-relaxed">{body}</p>
        <div className="mt-6 flex-1 min-h-[268px]">
          {children}
        </div>
      </div>
    </div>
  );
}

// Small framed-panel header that mimics the real editor chrome
function PanelHead({ title, sub, right }) {
  return (
    <div className="flex items-start justify-between mb-3">
      <div>
        <div className="text-[12px] font-semibold text-violet-50 tracking-tight">{title}</div>
        {sub && <div className="text-[10px] text-violet-300/50 mt-0.5">{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// --- Visual demo 1: block library — "Layout que mais converte" ---
function Step1Visual() {
  const [ref, seen] = useInView(0.3);
  const blocks = [
    'Cabeçalho da loja',
    'Resumo do pedido',
    'Identificação',
    'Endereço',
    'Opções de frete',
    'Métodos de pagamento',
    'Botão de finalizar',
    'Selos de segurança',
  ];
  return (
    <div ref={ref} className="rounded-2xl border border-white/8 bg-[#0d0820]/60 p-3.5">
      <PanelHead title="Biblioteca de blocos" sub="Arraste ou clique para adicionar" />

      {/* Search */}
      <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-white/[0.03] border border-white/8 mb-3">
        <span className="text-violet-300/45"><IS.Sparkles size={12}/></span>
        <span className="text-[11px] text-violet-300/40">Buscar bloco…</span>
      </div>

      {/* Recommended layout card */}
      <div className="rounded-xl border border-violet-300/30 bg-violet-500/[0.07] p-3">
        <div className="flex items-center gap-1.5 mb-2.5">
          <span className="text-violet-300"><IS.Sparkles size={13}/></span>
          <span className="text-[11px] font-semibold text-violet-100">Layout que mais converte</span>
        </div>
        <div className="space-y-1">
          {blocks.map((b, i) => (
            <div key={i}
                 style={{ transitionDelay: `${i * 70}ms` }}
                 className={`flex items-center gap-2 transition-all duration-500 ${seen ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-2'}`}>
              <span className="h-4 w-4 shrink-0 rounded-full grid place-items-center text-[9px] font-mono font-bold bg-violet-500/25 border border-violet-300/40 text-violet-100 leading-none">{i + 1}</span>
              <span className="text-[11.5px] text-violet-100/80 truncate">{b}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="mt-2.5 text-center text-[10px] font-mono text-cyan-300/70 tracking-wide">8 blocos adicionados ao editor</div>
    </div>
  );
}

// --- Visual demo 2: theme editor — colors / corners / payment order ---
function Step2Visual() {
  const [ref, seen] = useInView(0.3);
  const corners = ['SM', 'MD', 'LG', 'XL'];
  const [active, setActive] = useStateS(1);
  useEffectS(() => {
    if (!seen) return;
    let n = 1;
    const t = setInterval(() => { n = (n + 1) % corners.length; setActive(n); }, 1500);
    return () => clearInterval(t);
  }, [seen]);
  const radiusByIdx = ['rounded-md', 'rounded-lg', 'rounded-xl', 'rounded-2xl'];
  const swatches = [
    { n: 'Cor primária', hex: '#7c3aed', bg: '#7c3aed' },
    { n: 'Cor de texto', hex: '#111827', bg: '#111827' },
    { n: 'Fundo', hex: '#f9fafb', bg: '#f9fafb' },
  ];
  const pays = [
    { n: 'PIX', tag: 'Destaque', ic: <IS.Zap size={12}/> },
    { n: 'Cartão de crédito', ic: <IS.CreditCard size={12}/> },
    { n: 'Boleto', ic: <IS.Tag size={12}/> },
  ];
  return (
    <div ref={ref} className="rounded-2xl border border-white/8 bg-[#0d0820]/60 p-3.5">
      <PanelHead title="Tema do checkout" sub="Estilo global em todos os blocos" />

      {/* Colors */}
      <div className="text-[9.5px] font-mono uppercase tracking-[0.18em] text-violet-300/45 mb-1.5">Cores</div>
      <div className="space-y-1.5 mb-3.5">
        {swatches.map((s, i) => (
          <div key={i} className="flex items-center justify-between px-2.5 py-1.5 rounded-lg bg-white/[0.02] border border-white/8">
            <span className="text-[11.5px] text-violet-100/80">{s.n}</span>
            <span className="flex items-center gap-2">
              <span className="text-[10px] font-mono text-violet-200/60">{s.hex}</span>
              <span className="h-4 w-4 rounded-md border border-white/15" style={{ background: s.bg }}></span>
            </span>
          </div>
        ))}
      </div>

      {/* Corner style */}
      <div className="text-[9.5px] font-mono uppercase tracking-[0.18em] text-violet-300/45 mb-1.5">Estilo dos cantos</div>
      <div className="flex p-0.5 rounded-lg bg-white/5 border border-white/8 mb-3.5">
        {corners.map((c, i) => (
          <div key={c} className={`flex-1 text-center py-1 rounded-md text-[10.5px] font-medium transition-all duration-300 ${active === i ? 'bg-violet-500 text-white' : 'text-violet-200/55'}`}>{c}</div>
        ))}
      </div>

      {/* Payment order */}
      <div className="text-[9.5px] font-mono uppercase tracking-[0.18em] text-violet-300/45 mb-1.5">Ordem dos pagamentos</div>
      <div className="space-y-1.5">
        {pays.map((p, i) => (
          <div key={i} className={`flex items-center gap-2 px-2.5 py-1.5 ${radiusByIdx[active]} bg-white/[0.02] border ${i === 0 ? 'border-violet-300/40' : 'border-white/8'} transition-all duration-300`}>
            <span className="text-violet-300/40"><IS.GripVertical size={12}/></span>
            <span className="h-4 w-4 rounded-full grid place-items-center text-[8px] font-mono font-bold bg-white/5 border border-white/10 text-violet-200/70 leading-none">{i + 1}</span>
            <span className="text-violet-200/70">{p.ic}</span>
            <span className="text-[11.5px] text-violet-100/80">{p.n}</span>
            {p.tag && <span className="ml-auto text-[9px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded bg-cyan-400/15 border border-cyan-300/40 text-cyan-200">{p.tag}</span>}
          </div>
        ))}
      </div>
    </div>
  );
}

// --- Visual demo 3: publish by button ---
function Step3Visual() {
  const [ref, seen] = useInView(0.3);
  // phase: 0 idle, 1 publishing, 2 live
  const [phase, setPhase] = useStateS(0);
  useEffectS(() => {
    if (!seen) return;
    setPhase(0);
    const t1 = setTimeout(() => setPhase(1), 900);
    const t2 = setTimeout(() => setPhase(2), 2300);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [seen]);

  return (
    <div ref={ref} className="rounded-2xl border border-white/8 bg-[#0d0820]/60 p-3.5 flex flex-col">
      {/* Editor top bar */}
      <div className="flex items-center justify-between pb-3 border-b border-white/8">
        <div className="flex items-center gap-1.5 text-[10px] text-violet-300/55">
          <span className="font-mono">Etapas</span>
          {[1, 2, 3].map(n => (
            <span key={n} className="h-4 w-4 rounded grid place-items-center text-[9px] font-mono bg-white/5 border border-white/10 text-violet-200/70 leading-none">{n}</span>
          ))}
        </div>
        <div className="flex items-center gap-1.5">
          <span className="text-[10px] px-2 py-1 rounded-md border border-white/10 text-violet-200/70">Preview</span>
        </div>
      </div>

      {/* Big publish button / status */}
      <div className="flex-1 flex flex-col items-center justify-center py-5">
        {phase < 2 ? (
          <button
            className={`shine-btn relative flex items-center gap-2 px-5 py-3 rounded-xl text-[14px] font-semibold text-white transition-all duration-300 ${phase === 1 ? 'bg-violet-600/70 cursor-wait' : 'bg-violet-600'}`}
            style={{ boxShadow: '0 0 0 1px rgba(167,139,250,0.5), 0 14px 40px -12px rgba(124,58,237,0.8)' }}>
            {phase === 1
              ? <><span className="h-3.5 w-3.5 rounded-full border-2 border-white/40 border-t-white animate-spin"></span> Publicando…</>
              : <><IS.Rocket size={15}/> Publicar checkout</>}
          </button>
        ) : (
          <div className="flex flex-col items-center text-center animate-[floaty_6s_ease-in-out_infinite]">
            <span className="h-11 w-11 rounded-full grid place-items-center bg-emerald-500/15 border border-emerald-300/50 text-emerald-300 mb-2.5">
              <IS.Check size={22} sw={2.6}/>
            </span>
            <div className="text-[14px] font-semibold text-emerald-200">Checkout no ar</div>
            <div className="mt-1 text-[11px] font-mono text-violet-200/60">checkout.minhaloja.com.br</div>
          </div>
        )}
        <div className={`mt-3 text-[10.5px] text-violet-300/50 transition-opacity duration-300 ${phase === 0 ? 'opacity-100' : 'opacity-0'}`}>
          Deploy direto na sua Nuvemshop — 1 clique.
        </div>
      </div>

      {/* Footer status */}
      <div className="flex items-center justify-between pt-3 border-t border-white/8 text-[10px] font-mono">
        <span className="text-violet-300/50">Auto-save ativo</span>
        <span className={`flex items-center gap-1.5 px-2 py-0.5 rounded-md border transition-all duration-300 ${phase === 2 ? 'border-emerald-300/40 bg-emerald-500/10 text-emerald-200' : 'border-white/10 text-violet-300/50'}`}>
          <span className={`h-1.5 w-1.5 rounded-full ${phase === 2 ? 'bg-emerald-400' : 'bg-violet-300/40'}`}></span>
          {phase === 2 ? 'LIVE' : 'rascunho'}
        </span>
      </div>
    </div>
  );
}

function StepsSection() {
  return (
    <section className="relative py-28 overflow-hidden">
      <div className="absolute inset-0 -z-10">
        <div className="mesh-blob bg-violet-700 w-[520px] h-[520px] top-10 -left-20 opacity-25 animate-drift1"></div>
        <div className="mesh-blob bg-cyan-400/40 w-[420px] h-[420px] bottom-20 right-0 opacity-25 animate-drift2"></div>
      </div>

      <div className="max-w-7xl mx-auto px-6 lg:px-10">
        <div className="reveal max-w-3xl mb-16">
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[12px] font-medium border border-violet-300/20 bg-violet-500/10 text-violet-200">
            <span className="h-1.5 w-1.5 rounded-full bg-cyan-400"></span>
            Personalização em 3 passos
          </div>
          <h2 className="mt-5 font-semibold tracking-[-0.03em] text-5xl sm:text-6xl lg:text-7xl leading-[0.95]">
            Do template <span className="text-violet-300/70">para o</span> <span className="grad-cyan">seu</span> checkout <span className="text-violet-300/70">em 7 minutos.</span>
          </h2>
          <p className="mt-6 text-lg text-violet-100/70">
            Sem deploy, sem code review, sem chamado pro suporte. Você escolhe, configura e publica — tudo no editor visual.
          </p>
        </div>

        <div className="relative grid md:grid-cols-3 gap-5 reveal-stagger">
          {/* Connector line on desktop */}
          <div aria-hidden="true" className="hidden md:block absolute top-1/2 left-[12%] right-[12%] h-px bg-gradient-to-r from-violet-400/0 via-violet-400/40 to-cyan-300/40 -z-10"></div>

          <StepCard idx={1} title="Escolha os blocos" accent="violet"
            body="Biblioteca pronta de blocos: cabeçalho, identificação, frete, pagamento, selos. Comece pelo layout que mais converte e arraste o que faz sentido.">
            <Step1Visual/>
          </StepCard>

          <StepCard idx={2} title="Configure o tema" accent="violet"
            body="Cores, cantos e ordem dos pagamentos num só painel. Estilo global aplicado a todos os blocos, sem tocar em código.">
            <Step2Visual/>
          </StepCard>

          <StepCard idx={3} title="Publique por botão" accent="cyan"
            body="Um clique em publicar e o checkout vai pro ar na sua Nuvemshop, no seu domínio. Sem refresh do cliente, sem dor no fim de semana.">
            <Step3Visual/>
          </StepCard>
        </div>

        <div className="reveal mt-12 flex flex-wrap items-center justify-center gap-x-8 gap-y-3 text-[13px] text-violet-200/60">
          <span className="flex items-center gap-1.5"><IS.Check size={14} sw={2.5} className="text-cyan-300"/> Versões salvas automaticamente</span>
          <span className="text-violet-200/20">·</span>
          <span className="flex items-center gap-1.5"><IS.Check size={14} sw={2.5} className="text-cyan-300"/> A/B test nativo</span>
          <span className="text-violet-200/20">·</span>
          <span className="flex items-center gap-1.5"><IS.Check size={14} sw={2.5} className="text-cyan-300"/> Rollback em 1 clique</span>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { StepsSection });
