// Custom abstract visuals (no clip-art, no real photos).
const { useState, useEffect, useRef } = React;

// Hero "data flow" — abstract flowing receivables. Light & dark aware.
const FlowOrb = ({ className = "" }) => {
  const ref = useRef(null);
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf, start = performance.now();
    const tick = (now) => { setT((now - start) / 1000); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Generate three orbiting "receivable" particles
  const particles = [];
  const N = 14;
  for (let i = 0; i < N; i++) {
    const phase = (i / N) * Math.PI * 2;
    const r = 130 + Math.sin(t * 0.4 + i) * 8;
    const x = 240 + Math.cos(phase + t * 0.25) * r;
    const y = 240 + Math.sin(phase + t * 0.25) * r * 0.78;
    const s = 0.6 + (Math.sin(t + i) * 0.5 + 0.5) * 0.6;
    particles.push({ x, y, s, hue: i % 3 });
  }

  return (
    <div ref={ref} className={cn("relative aspect-square w-full max-w-[560px]", className)}>
      <svg viewBox="0 0 480 480" className="absolute inset-0 w-full h-full">
        <defs>
          <radialGradient id="orb-g1" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="rgb(var(--primary))" stopOpacity="0.55" />
            <stop offset="55%" stopColor="rgb(var(--secondary))" stopOpacity="0.30" />
            <stop offset="100%" stopColor="rgb(var(--accent))" stopOpacity="0" />
          </radialGradient>
          <radialGradient id="orb-g2" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="rgb(var(--accent))" stopOpacity="0.45" />
            <stop offset="100%" stopColor="rgb(var(--accent))" stopOpacity="0" />
          </radialGradient>
          <linearGradient id="orb-stroke" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="rgb(var(--fg))" stopOpacity="0.18" />
            <stop offset="100%" stopColor="rgb(var(--fg))" stopOpacity="0.04" />
          </linearGradient>
        </defs>

        {/* concentric flow rings */}
        {[180, 150, 120, 90, 60].map((r, i) => (
          <ellipse key={r} cx="240" cy="240" rx={r} ry={r * 0.78}
            stroke="url(#orb-stroke)" strokeWidth="1" fill="none"
            transform={`rotate(${t * (8 - i * 1.4)} 240 240)`} />
        ))}

        {/* core blob */}
        <g style={{ transform: `translate(240px, 240px) scale(${1 + Math.sin(t * 0.7) * 0.02})`, transformOrigin: '0 0' }}>
          <circle cx="0" cy="0" r="200" fill="url(#orb-g1)" />
          <circle cx={Math.cos(t * 0.5) * 30} cy={Math.sin(t * 0.5) * 20} r="120" fill="url(#orb-g2)" />
        </g>

        {/* Particles */}
        {particles.map((p, i) => {
          const fill = p.hue === 0 ? 'rgb(var(--primary))' : p.hue === 1 ? 'rgb(var(--secondary))' : 'rgb(var(--accent))';
          return <circle key={i} cx={p.x} cy={p.y} r={3.4 * p.s} fill={fill} />;
        })}

        {/* connection lines from center */}
        {[0, 1, 2].map(i => {
          const phase = i * (Math.PI * 2 / 3) + t * 0.35;
          const x = 240 + Math.cos(phase) * 170;
          const y = 240 + Math.sin(phase) * 170 * 0.78;
          return <path key={i} d={`M240 240 L ${x} ${y}`} stroke="rgb(var(--fg))" strokeOpacity="0.08" strokeWidth="1" />;
        })}
      </svg>

      {/* floating chips */}
      <FloatChip className="absolute top-[8%] right-[6%]" delay={0}>
        <div className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted">Repasse Unimed</div>
        <div className="font-display text-lg tabular">R$ 84.320,00</div>
        <div className="text-[11px] text-primary mt-1 flex items-center gap-1">
          <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
          Aprovado · score 0.91
        </div>
      </FloatChip>

      <FloatChip className="absolute bottom-[10%] left-[2%]" delay={1.2}>
        <div className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted">Decisão IA</div>
        <div className="font-display text-lg">2.1<span className="text-base text-muted">s</span></div>
        <div className="h-1 mt-2 rounded-full bg-subtle relative overflow-hidden">
          <div className="absolute inset-y-0 left-0 bg-secondary rounded-full" style={{ width: `${60 + Math.sin(t) * 20}%` }} />
        </div>
      </FloatChip>

      <FloatChip className="absolute bottom-[8%] right-[4%]" delay={2.4}>
        <div className="flex items-center gap-2">
          <div className="w-7 h-7 rounded-lg bg-accent/15 grid place-items-center">
            <Icon name="bolt" className="w-4 h-4 text-accent" />
          </div>
          <div>
            <div className="text-[11px] text-muted">Liberação</div>
            <div className="font-display text-sm">9 min</div>
          </div>
        </div>
      </FloatChip>
    </div>
  );
};

const FloatChip = ({ children, className, delay = 0 }) => (
  <div
    className={cn("bg-card border border-line rounded-xl p-3 shadow-lg backdrop-blur-sm min-w-[160px]", className)}
    style={{ animation: `float 8s ease-in-out ${delay}s infinite` }}
  >
    {children}
    <style>{`@keyframes float { 0%,100% { transform: translateY(0) } 50% { transform: translateY(-8px) } }`}</style>
  </div>
);

// Decision flow visual — used in dark "How our AI decides" section
const DecisionFlow = () => {
  const tradicional = [
    { label: "Faturamento enviado à operadora", time: "—" },
    { label: "Processamento e auditoria do plano", time: "20–40 dias" },
    { label: "Glosa e recurso", time: "10–30 dias" },
    { label: "Repasse na conta", time: "30–90 dias" },
  ];
  const flow = [
    { label: "CNPJ + repasses e cartão", time: "30 s" },
    { label: "IA lê histórico e glosa", time: "~ 2 s" },
    { label: "Recebível registrado em CERC/B3", time: "1–2 min" },
    { label: "Pix na conta da clínica", time: "≤ 10 min" },
  ];
  return (
    <div className="grid md:grid-cols-2 gap-6 md:gap-8">
      <div className="rounded-2xl border border-white/10 bg-white/[0.02] p-6 md:p-8">
        <div className="flex items-center justify-between mb-6">
          <div className="font-mono text-xs uppercase tracking-[0.18em] text-white/50">Esperar o convênio</div>
          <div className="font-mono text-xs text-white/50">30–90 dias</div>
        </div>
        <ol className="space-y-3">
          {tradicional.map((s, i) => (
            <li key={i} className="flex items-center gap-3 p-3 rounded-xl border border-white/5 bg-white/[0.02]">
              <div className="w-7 h-7 rounded-md bg-white/5 grid place-items-center font-mono text-xs text-white/60">{i+1}</div>
              <div className="flex-1 text-sm text-white/85">{s.label}</div>
              <div className="font-mono text-xs text-white/50">{s.time}</div>
            </li>
          ))}
        </ol>
      </div>
      <div className="rounded-2xl border border-[color:rgb(var(--primary))]/30 p-6 md:p-8 relative"
        style={{ background: 'radial-gradient(120% 80% at 0% 0%, rgb(var(--primary) / 0.08), transparent 50%)' }}>
        <div className="flex items-center justify-between mb-6">
          <div className="font-mono text-xs uppercase tracking-[0.18em] text-[rgb(var(--primary))]">flui.cash</div>
          <div className="font-mono text-xs text-[rgb(var(--primary))]">≤ 10 min</div>
        </div>
        <ol className="space-y-3">
          {flow.map((s, i) => (
            <li key={i} className="flex items-center gap-3 p-3 rounded-xl border border-white/10 bg-white/[0.03]">
              <div className="w-7 h-7 rounded-md bg-[rgb(var(--primary))]/15 grid place-items-center font-mono text-xs text-[rgb(var(--primary))]">{i+1}</div>
              <div className="flex-1 text-sm text-white/95">{s.label}</div>
              <div className="font-mono text-xs text-[rgb(var(--primary))]">{s.time}</div>
            </li>
          ))}
        </ol>
      </div>
    </div>
  );
};

// Editorial "time back" visual — abstract editorial composition (no human photo)
const EditorialTime = () => {
  // 60 pontos = os 60 dias médios até o repasse da operadora
  const dias = Array.from({ length: 60 }, (_, i) => i);
  return (
    <div className="relative aspect-[4/5] w-full rounded-3xl overflow-hidden border border-line bg-subtle">
      <svg viewBox="0 0 400 500" className="absolute inset-0 w-full h-full">
        <defs>
          <linearGradient id="edit-g" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="rgb(var(--accent))" stopOpacity="0.45" />
            <stop offset="70%" stopColor="rgb(var(--secondary))" stopOpacity="0.25" />
            <stop offset="100%" stopColor="rgb(var(--secondary))" stopOpacity="0" />
          </linearGradient>
          <pattern id="edit-stripes" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(35)">
            <line x1="0" y1="0" x2="0" y2="6" stroke="rgb(var(--fg))" strokeOpacity="0.05" strokeWidth="1.2" />
          </pattern>
        </defs>

        <rect width="400" height="500" fill="url(#edit-stripes)" />

        {/* brilho decorativo, sem figura */}
        <circle cx="358" cy="34" r="126" fill="url(#edit-g)" />

        {/* eyebrow */}
        <g fontFamily="JetBrains Mono, monospace" fill="rgb(var(--fg))" letterSpacing="2">
          <text x="34" y="58" fontSize="13" opacity="0.55">CICLO DE CAIXA DA CLINICA</text>
          <text x="34" y="98" fontSize="38" fontWeight="700" opacity="0.9">60 DIAS</text>
          <text x="34" y="120" fontSize="13" opacity="0.55">ATE O REPASSE DA OPERADORA</text>
        </g>

        {/* grade de 60 dias */}
        <g transform="translate(34 150)">
          {dias.map((d) => {
            const col = d % 10, row = Math.floor(d / 10);
            const x = col * 36, y = row * 30;
            if (d === 0) {
              return (
                <g key={d}>
                  <circle cx={x} cy={y} r="9" fill="rgb(var(--primary))" opacity="0.18" />
                  <circle cx={x} cy={y} r="5.5" fill="rgb(var(--primary))" />
                </g>
              );
            }
            if (d === 59) return <circle key={d} cx={x} cy={y} r="5" fill="rgb(var(--fg))" opacity="0.45" />;
            return <circle key={d} cx={x} cy={y} r="3.2" fill="rgb(var(--fg))" opacity="0.14" />;
          })}
        </g>

        {/* legenda */}
        <g fontFamily="JetBrains Mono, monospace" fontSize="12" letterSpacing="1.2">
          <circle cx="38" cy="336" r="4.5" fill="rgb(var(--primary))" />
          <text x="54" y="341" fill="rgb(var(--fg))" opacity="0.85">DIA 1 · A FLUI.CASH PAGA</text>
          <circle cx="38" cy="363" r="4" fill="rgb(var(--fg))" opacity="0.45" />
          <text x="54" y="367" fill="rgb(var(--fg))" opacity="0.55">DIA 60 · A OPERADORA PAGA</text>
        </g>
      </svg>

      {/* scrim para a citação nunca colidir com a arte */}
      <div className="absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-subtle via-subtle/90 to-transparent" />
      <div className="absolute bottom-6 left-6 right-6">
        <div className="font-mono text-[10px] uppercase tracking-[0.2em] text-fg/70">Fisioterapeuta, clínica própria · São Paulo</div>
        <div className="font-display text-2xl mt-1 leading-snug">"Faturei em março e recebi em março."</div>
      </div>
    </div>
  );
};

// Pillar icon block
const PillarCard = ({ icon, kicker, title, body, idx }) => (
  <Card className="p-7 hover:border-fg/30 transition-colors h-full flex flex-col group">
    <div className="flex items-center justify-between mb-8">
      <div className="w-11 h-11 rounded-xl bg-subtle border border-line grid place-items-center group-hover:bg-fg group-hover:text-bg transition-colors">
        <Icon name={icon} className="w-5 h-5" />
      </div>
      <div className="font-mono text-xs text-muted">0{idx}</div>
    </div>
    <div className="font-mono text-xs uppercase tracking-[0.18em] text-muted mb-2">{kicker}</div>
    <h3 className="font-display text-xl mb-2 leading-snug">{title}</h3>
    <p className="text-muted text-sm leading-relaxed mt-auto">{body}</p>
  </Card>
);

// Logo placeholder strip (partner / press logos as wordmarks)
const LogoStrip = ({ items }) => (
  <div className="flex items-center justify-between flex-wrap gap-x-10 gap-y-6">
    {items.map((it, i) => (
      <div key={i} className="font-mono text-sm uppercase tracking-[0.22em] text-muted opacity-70 hover:opacity-100 transition-opacity">
        {it}
      </div>
    ))}
  </div>
);

// Mock dashboard preview (used in Smart Management section)
const DashboardPreview = () => (
  <div className="rounded-2xl border border-line bg-card overflow-hidden shadow-2xl shadow-black/5">
    <div className="flex items-center gap-1.5 px-4 h-8 border-b border-line bg-subtle">
      <span className="w-2.5 h-2.5 rounded-full bg-line"></span>
      <span className="w-2.5 h-2.5 rounded-full bg-line"></span>
      <span className="w-2.5 h-2.5 rounded-full bg-line"></span>
      <span className="ml-3 font-mono text-[10px] text-muted">app.flui.cash / repasses</span>
    </div>
    <div className="grid grid-cols-12 gap-3 p-4">
      <div className="col-span-3 space-y-3">
        {['Visão Geral', 'Repasses', 'Glosa', 'Cartão', 'Relatórios'].map((it, i) => (
          <div key={i} className={cn("h-7 rounded-md flex items-center px-2 text-xs", i === 1 ? "bg-fg text-bg" : "text-muted hover:bg-subtle")}>
            <span className="w-1 h-1 rounded-full bg-current mr-2 opacity-60" />
            {it}
          </div>
        ))}
      </div>
      <div className="col-span-9 space-y-3">
        <div className="grid grid-cols-3 gap-3">
          {[
            { l: 'A receber de operadoras', v: 'R$ 284.330', d: '+ 8.2%', tone: 'primary' },
            { l: 'Preso em glosa', v: 'R$ 11.902', d: '4.2% do mês', tone: 'neutral' },
            { l: 'Antecipável hoje', v: 'R$ 196.500', d: 'Pix em 9 min', tone: 'secondary' },
          ].map((m, i) => (
            <div key={i} className="rounded-lg border border-line p-3">
              <div className="text-[10px] text-muted uppercase tracking-wider">{m.l}</div>
              <div className="font-display text-xl tabular mt-1">{m.v}</div>
              <div className={cn("text-[10px] mt-0.5",
                m.tone === 'primary' ? 'text-primary' : m.tone === 'secondary' ? 'text-secondary' : 'text-muted')}>{m.d}</div>
            </div>
          ))}
        </div>
        <div className="rounded-lg border border-line p-3 h-36 relative">
          <div className="text-[10px] text-muted uppercase tracking-wider mb-2">Caixa da clínica projetado · 90 d</div>
          <svg viewBox="0 0 360 100" className="w-full h-24">
            <defs>
              <linearGradient id="dash-g" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="rgb(var(--primary))" stopOpacity="0.28" />
                <stop offset="100%" stopColor="rgb(var(--primary))" stopOpacity="0" />
              </linearGradient>
            </defs>
            <path d="M0 70 C 40 50 60 80 90 60 S 160 30 200 50 260 80 300 40 360 30 360 30 L 360 100 L 0 100 Z" fill="url(#dash-g)" />
            <path d="M0 70 C 40 50 60 80 90 60 S 160 30 200 50 260 80 300 40 360 30 360 30" stroke="rgb(var(--primary))" strokeWidth="1.5" fill="none" />
            <path d="M0 80 C 50 70 80 85 130 78 S 220 70 280 65 360 60 360 60" stroke="rgb(var(--secondary))" strokeOpacity="0.7" strokeWidth="1.2" strokeDasharray="3 3" fill="none" />
          </svg>
        </div>
        <div className="rounded-lg border border-line p-3">
          <div className="text-[10px] text-muted uppercase tracking-wider mb-2">Alertas de repasse e glosa</div>
          <div className="space-y-1.5">
            <Alert tone="accent">Glosa recorrente no código 40304361 — 7 ocorrências este mês na SulAmérica</Alert>
            <Alert tone="primary">Repasse Bradesco Saúde conciliado: 248 / 251 guias</Alert>
            <Alert tone="secondary">Amil atrasou 12 dias além do contrato — quer antecipar esse lote?</Alert>
          </div>
        </div>
      </div>
    </div>
  </div>
);
const Alert = ({ tone, children }) => (
  <div className="flex items-start gap-2 px-2.5 py-2 rounded-md bg-subtle text-xs">
    <span className={cn("w-1.5 h-1.5 rounded-full mt-1.5 shrink-0",
      tone === 'accent' ? 'bg-accent' : tone === 'primary' ? 'bg-primary' : 'bg-secondary')} />
    <span className="text-fg/90">{children}</span>
  </div>
);

// Aurora background blob (for hero / cta-final)
const Aurora = ({ className = "" }) => (
  <div className={cn("absolute inset-0 -z-10 overflow-hidden pointer-events-none", className)} aria-hidden>
    <div className="absolute -top-40 -left-40 w-[700px] h-[700px] rounded-full pulse-soft"
      style={{ background: 'radial-gradient(circle, rgb(var(--primary) / 0.12) 0%, transparent 60%)' }} />
    <div className="absolute -top-20 right-0 w-[600px] h-[600px] rounded-full pulse-soft"
      style={{ background: 'radial-gradient(circle, rgb(var(--accent) / 0.10) 0%, transparent 60%)', animationDelay: '2s' }} />
    <div className="absolute bottom-0 left-1/3 w-[800px] h-[600px] rounded-full pulse-soft"
      style={{ background: 'radial-gradient(circle, rgb(var(--secondary) / 0.10) 0%, transparent 65%)', animationDelay: '4s' }} />
  </div>
);

Object.assign(window, { FlowOrb, FloatChip, DecisionFlow, EditorialTime, PillarCard, LogoStrip, DashboardPreview, Aurora });
