// DASHBOARD SECTION — espelha o painel real do cartROI, com números preenchidos
const ID = window.Icon;
const { useState: useStateD, useEffect: useEffectD, useRef: useRefD } = React;

function DashNum({ value, decimals = 0, prefix = '', suffix = '' }) {
  const ref = useRefD(null);
  const [v, setV] = useStateD(0);
  useEffectD(() => {
    let raf, start;
    const io = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      io.disconnect();
      const tick = (t) => {
        if (start === undefined) start = t;
        const p = Math.min(1, (t - start) / 1200);
        const eased = 1 - Math.pow(1 - p, 3);
        setV(value * eased);
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [value]);
  const fmt = v.toLocaleString('pt-BR', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  return <span ref={ref} className="tabular-nums">{prefix}{fmt}{suffix}</span>;
}

function MetricCard({ label, children, icon, live, delta }) {
  return (
    <div className="rounded-2xl bg-white border border-[#1a1233]/8 p-5 shadow-[0_1px_2px_rgba(16,18,39,0.04)]">
      <div className="flex items-center justify-between">
        <div className="text-[13px] text-[#4b4565]">{label}</div>
        {live
          ? <span className="flex items-center gap-1 text-[11px] font-medium text-emerald-600"><span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"></span>Live</span>
          : <span className="text-[#9890b3]">{icon}</span>}
      </div>
      <div className="mt-2.5 text-3xl font-semibold tracking-[-0.03em] text-[#111827]">{children}</div>
      {delta && (
        <div className="mt-2 text-[12px] text-[#9890b3]">
          <span className={delta.up ? 'text-emerald-600 font-medium' : 'text-rose-500 font-medium'}>{delta.up ? '↑' : '↓'} {delta.v}</span> {delta.note}
        </div>
      )}
    </div>
  );
}

function OpCard({ label, value, icon, accent }) {
  return (
    <div className="rounded-2xl bg-white border border-[#1a1233]/8 p-5 shadow-[0_1px_2px_rgba(16,18,39,0.04)]">
      <div className="flex items-center justify-between">
        <div className="text-[13px] text-[#4b4565]">{label}</div>
        <span className={`h-7 w-7 rounded-lg grid place-items-center ${accent}`}>{icon}</span>
      </div>
      <div className="mt-2.5 text-3xl font-semibold tracking-[-0.03em] text-[#111827]">{value}</div>
    </div>
  );
}

function DashboardSection() {
  return (
    <section id="painel" 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-32 right-0 opacity-25 animate-drift1"></div>
        <div className="mesh-blob bg-cyan-400/40 w-[420px] h-[420px] bottom-0 -left-20 opacity-20 animate-drift2"></div>
      </div>

      <div className="max-w-7xl mx-auto px-6 lg:px-10">
        <div className="reveal max-w-3xl mb-12">
          <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>
            Painel em tempo real
          </div>
          <h2 className="mt-5 font-semibold tracking-[-0.03em] text-5xl sm:text-6xl lg:text-7xl leading-[0.95]">
            Tudo o que importa, <br/><span className="grad-cyan">num olhar</span>.
          </h2>
          <p className="mt-6 text-lg text-violet-100/70">
            Visitantes ao vivo, checkouts, faturamento, conversão e operação — atualizando em tempo real, sem planilha, sem abrir cinco abas.
          </p>
        </div>

        {/* Dashboard window */}
        <div className="reveal relative rounded-3xl overflow-hidden border border-white/10 shadow-[0_40px_120px_-40px_rgba(124,58,237,0.5)]">
          {/* window chrome */}
          <div className="flex items-center gap-2 px-4 py-3 bg-[#0a0617] border-b border-white/8">
            <span className="h-2.5 w-2.5 rounded-full bg-rose-400/80"></span>
            <span className="h-2.5 w-2.5 rounded-full bg-amber-300/80"></span>
            <span className="h-2.5 w-2.5 rounded-full bg-emerald-400/80"></span>
            <div className="ml-3 text-[11px] font-mono text-violet-200/50">cartroi.com/dashboard</div>
          </div>

          {/* light dashboard body */}
          <div className="bg-[#f9fafb] p-6 sm:p-8">
            <div className="flex items-start justify-between flex-wrap gap-3">
              <div>
                <h3 className="text-2xl font-semibold tracking-tight text-[#111827]">Boa noite, Marcos Vinícius!</h3>
                <p className="text-[14px] text-[#6b6485] mt-0.5">Aqui está o resumo do seu cartROI hoje.</p>
              </div>
              <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white border border-[#1a1233]/10 text-[12px] text-[#4b4565]">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
                Sincronizado agora
              </div>
            </div>

            {/* top metrics */}
            <div className="mt-7 grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
              <MetricCard label="Visitantes agora" live delta={{up:true, v:'12%', note:'vs última hora'}}>
                <DashNum value={142}/>
              </MetricCard>
              <MetricCard label="Checkouts" icon={<ID.CreditCard size={16}/>} delta={{up:true, v:'8%', note:'vs ontem'}}>
                <DashNum value={1284}/>
              </MetricCard>
              <MetricCard label="Faturamento hoje" icon={<ID.DollarSign size={16}/>} delta={{up:true, v:'23%', note:'vs ontem'}}>
                R$ <DashNum value={38940} decimals={0}/>
              </MetricCard>
              <MetricCard label="Taxa de conversão" icon={<ID.TrendingUp size={16}/>} delta={{up:true, v:'0,6 p.p.', note:'vs ontem'}}>
                <DashNum value={3.8} decimals={1} suffix="%"/>
              </MetricCard>
            </div>

            {/* operação */}
            <div className="mt-7">
              <div className="text-[13px] font-semibold text-[#111827] mb-3">Operação</div>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
                <OpCard label="Carrinhos para recuperar" value={<DashNum value={47}/>} accent="bg-amber-100 text-amber-600" icon={<ID.MessageCircle size={15}/>}/>
                <OpCard label="Pagamentos pendentes" value={<DashNum value={12}/>} accent="bg-violet-100 text-violet-600" icon={<ID.Timer size={15}/>}/>
                <OpCard label="Falhas em pagamento" value={<DashNum value={3}/>} accent="bg-rose-100 text-rose-500" icon={<ID.X size={15}/>}/>
                <OpCard label="Clientes ativos" value={<DashNum value={2318}/>} accent="bg-emerald-100 text-emerald-600" icon={<ID.Users size={15}/>}/>
              </div>
            </div>
          </div>
        </div>

        <p className="reveal mt-5 text-[13px] text-violet-300/55 italic">*Dados ilustrativos de uma loja em operação. Seu painel reflete os números reais da sua loja em tempo real.</p>
      </div>
    </section>
  );
}

window.DashboardSection = DashboardSection;
