/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

/* ─── Icons (inline, stroke-based) ─────────────────── */
const Ic = {
  eye: (p) => (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z" /><circle cx="8" cy="8" r="2" />
    </svg>
  ),
  eyeOff: (p) => (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M2 2l12 12M6.9 6.9A2 2 0 0010 10M4.2 4.2C2.6 5.3 1 8 1 8s2.5 5 7 5c1.4 0 2.7-.4 3.8-1.2M9 3.1A6.9 6.9 0 0115 8s-.6 1.2-1.5 2.3" />
    </svg>
  ),
  arrow: (p) => (
    <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 8h10M9 4l4 4-4 4" /></svg>
  ),
  check: (p) => (
    <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 8.5l3 3 7-7" /></svg>
  ),
  store: (p) => (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" {...p}><path d="M2 6l1-3h10l1 3M2 6h12v8H2zM2 6v0a2 2 0 004 0 2 2 0 004 0 2 2 0 004 0M6 14v-4h4v4" /></svg>
  ),
  truck: (p) => (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" {...p}><path d="M1 4h8v7H1zM9 7h4l2 2v2h-6zM4 13a1.5 1.5 0 100-3 1.5 1.5 0 000 3zM12 13a1.5 1.5 0 100-3 1.5 1.5 0 000 3z" /></svg>
  ),
  building: (p) => (
    <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" {...p}><path d="M2 14V3l6-2v13M8 14V6l6 2v6M5 6h1M5 9h1M5 12h1M11 9h1M11 12h1" /></svg>
  ),
};

/* ─── Logo ───────────────────────────────────────────── */
function Logo({ dark = false }) {
  return (
    <img
      src={dark ? "../assets/logo-alimo-branco-lateral.svg" : "../assets/logo-alimo-original-lateral.svg"}
      alt="Alimo"
      style={{ height: "52px", width: "auto", display: "block" }}
    />
  );
}

/* ─── Field ──────────────────────────────────────────── */
function Field({ label, hint, error, children }) {
  const id = 'field-' + label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/, '');
  return (
    <div className="space-y-1.5">
      <div className="flex items-center justify-between">
        <label htmlFor={id} className="text-[15px] font-medium text-ink-700">{label}</label>
        {hint && <span className="text-[14px] text-ink-400">{hint}</span>}
      </div>
      {React.Children.map(children, child =>
        React.isValidElement(child) ? React.cloneElement(child, { id }) : child
      )}
      {error && <p className="text-[13px] text-err">{error}</p>}
    </div>
  );
}

function Input({ type = "text", placeholder, value, onChange, className = "", ...props }) {
  return (
    <input
      type={type}
      placeholder={placeholder}
      value={value}
      onChange={onChange}
      className={`w-full h-[56px] px-4 rounded-xl2 border border-line bg-white text-[16px] text-ink-900
        placeholder:text-ink-300 focus:border-brand-600 focus:ring-2 focus:ring-brand-600/10
        transition-colors ${className}`}
      {...props}
    />
  );
}

function PasswordInput({ value, onChange, placeholder = "••••••••", className = "", ...props }) {
  const [show, setShow] = useState(false);
  return (
    <div className="relative">
      <Input
        type={show ? "text" : "password"}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        className={`pr-10 ${className}`}
        {...props}
      />
      <button
        type="button"
        className="eye-btn absolute right-4 top-1/2 -translate-y-1/2 text-ink-400 hover:text-ink-700 transition-colors"
        onClick={() => setShow((s) => !s)}
        tabIndex={-1}
        aria-label={show ? "Ocultar senha" : "Mostrar senha"}
      >
        {show ? <Ic.eyeOff /> : <Ic.eye />}
      </button>
    </div>
  );
}

/* ─── Role card (Cadastro) ───────────────────────────── */
const TEXT_FORBIDDEN_RE = /[<>{}\[\]\\|`~]/g;
const EMAIL_ALLOWED_RE = /[^a-zA-Z0-9@._%+\-]/g;
const PASSWORD_FORBIDDEN_RE = /[\s<>]/g;

function cleanText(value) {
  return value.replace(TEXT_FORBIDDEN_RE, "");
}

function cleanEmail(value) {
  return value.replace(EMAIL_ALLOWED_RE, "").toLowerCase();
}

function cleanPassword(value) {
  return value.replace(PASSWORD_FORBIDDEN_RE, "");
}

function emailError(value) {
  if (!value) return "";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Digite um e-mail válido.";
  return "";
}

function passwordStrength(value) {
  if (!value) return null;
  const checks = [
    { label: "8 caracteres", ok: value.length >= 8 },
    { label: "maiúscula", ok: /[A-Z]/.test(value) },
    { label: "minúscula", ok: /[a-z]/.test(value) },
    { label: "número", ok: /\d/.test(value) },
    { label: "símbolo", ok: /[^A-Za-z0-9\s<>]/.test(value) },
  ];
  const passed = checks.filter((item) => item.ok).length;
  if (passed <= 2) return { level: 1, label: "Fraca", color: "bg-err", text: "text-err", checks };
  if (passed < checks.length) return { level: 2, label: "Média", color: "bg-[#F59E0B]", text: "text-[#B45309]", checks };
  return { level: 3, label: "Forte", color: "bg-ok", text: "text-ok", checks };
}

function PasswordStrength({ value }) {
  const strength = passwordStrength(value);
  if (!value || !strength) return null;

  return (
    <div className="mt-2.5 space-y-2">
      <div className="flex gap-1">
        {[1, 2, 3].map((n) => (
          <div
            key={n}
            className={`h-1.5 flex-1 rounded-full transition-colors duration-300 ${
              n <= strength.level ? strength.color : "bg-ink-100"
            }`}
          />
        ))}
      </div>
      <div className="flex items-center justify-between gap-3">
        <p className={`text-[13px] font-medium ${strength.text}`}>Senha {strength.label}</p>
        <p className="text-[12.5px] text-ink-400">Sem espaços, &lt; ou &gt;</p>
      </div>
      <div className="flex flex-wrap gap-1.5">
        {strength.checks.map((item) => (
          <span
            key={item.label}
            className={`rounded-full border px-2.5 py-1 text-[12px] ${
              item.ok
                ? "border-brand-600/20 bg-brand-50 text-brand-600"
                : "border-line bg-white text-ink-300"
            }`}
          >
            {item.label}
          </span>
        ))}
      </div>
    </div>
  );
}

function RoleCard({ icon: Icon, title, desc, selected, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`w-full text-left p-5 rounded-xl2 border-2 transition-all duration-150
        ${selected
          ? "border-brand-600 bg-brand-50"
          : "border-line bg-white hover:border-ink-300"
        }`}
    >
      <div className="flex items-start gap-3.5">
        <div className={`w-11 h-11 rounded-lg flex items-center justify-center shrink-0 mt-0.5
          ${selected ? "bg-brand-600 text-white" : "bg-ink-100 text-ink-500"}`}>
          <Icon />
        </div>
        <div>
          <div className={`text-[16px] font-semibold ${selected ? "text-ink-900" : "text-ink-700"}`}>{title}</div>
          <div className="text-[14px] text-ink-400 mt-1 leading-relaxed">{desc}</div>
        </div>
        <div className={`ml-auto w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 mt-0.5
          ${selected ? "border-brand-600 bg-brand-600" : "border-line"}`}>
          {selected && <Ic.check className="text-white" style={{ width: 10, height: 10 }} />}
        </div>
      </div>
    </button>
  );
}

/* ─── Live bid ticker (left panel decoration) ─────── */
const BID_ROWS = [
  { supplier: "CD Norte", item: "Arroz parboilizado", price: "R$ 8,21", down: true },
  { supplier: "Verdes Mares", item: "Óleo de soja", price: "R$ 4,18", down: true },
  { supplier: "Safra Real", item: "Açúcar cristal", price: "R$ 3,94", down: false },
  { supplier: "Sertão Agrícola", item: "Farinha de trigo", price: "R$ 2,87", down: true },
  { supplier: "Agroeste", item: "Óleo de soja", price: "R$ 4,22", down: false },
];

function LiveTicker() {
  const [rows, setRows] = useState(BID_ROWS.slice(0, 3));
  const nextIdx = useRef(3);

  useEffect(() => {
    const id = setInterval(() => {
      const next = BID_ROWS[nextIdx.current % BID_ROWS.length];
      nextIdx.current += 1;
      setRows((prev) => [next, ...prev].slice(0, 3));
    }, 2400);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="rounded-xl2 bg-white/8 border border-white/12 backdrop-blur-sm overflow-hidden">
      <div className="px-4 py-3 border-b border-white/10 flex items-center justify-between">
        <span className="text-[11px] font-mono uppercase tracking-wider text-white/50">Lances ao vivo</span>
        <span className="flex items-center gap-1.5 text-[11px] text-ok">
          <span className="w-1.5 h-1.5 rounded-full bg-ok live-dot" /> Ao vivo
        </span>
      </div>
      <div className="divide-y divide-white/8">
        {rows.map((r, i) => (
          <div key={`${r.supplier}-${i}`} className={`flex items-center justify-between px-4 py-2.5 gap-3 ${i === 0 ? "tick-in" : ""}`}>
            <div className="min-w-0">
              <div className="text-[12.5px] font-medium text-white truncate">{r.supplier}</div>
              <div className="text-[11px] text-white/40 truncate">{r.item}</div>
            </div>
            <div className={`font-mono text-[13px] font-semibold shrink-0 ${r.down ? "text-ok" : "text-white/60"}`}>
              {r.price}<span className="text-[10px] ml-0.5">/kg</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── Feature item (left panel) ─────────────────────── */
function Feature({ children }) {
  return (
    <div className="flex items-start gap-2.5">
      <div className="mt-0.5 w-5 h-5 rounded-full bg-brand-600/20 text-brand-400 flex items-center justify-center shrink-0">
        <Ic.check />
      </div>
      <div className="text-[14px] leading-snug text-white/80">{children}</div>
    </div>
  );
}

/* ─── Left branding panel ────────────────────────────── */
function LeftPanel() {
  return (
    <div className="hidden lg:flex flex-col justify-between relative bg-ink-900 min-h-screen w-full px-12 py-12">
      {/* Drifting orbs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
        <div className="orb1 absolute -top-32 -right-32 w-[500px] h-[500px] rounded-full bg-brand-600/20 blur-3xl" />
        <div className="orb2 absolute -bottom-40 -left-24 w-[400px] h-[400px] rounded-full bg-brand-500/10 blur-3xl" />
      </div>

      {/* Logo */}
      <a href="/landing" className="relative block shrink-0">
        <Logo dark />
      </a>

      {/* Headline */}
      <div className="relative shrink-0">
        <p className="text-[12px] font-mono uppercase tracking-[0.14em] text-brand-400 mb-3">
          Conectando empresas do setor alimentício
        </p>
        <h2 className="text-[38px] leading-[1.08] font-semibold tracking-[-0.025em] text-white max-w-[380px]">
          Negocie melhor. Com mais transparência e controle.
        </h2>
        <p className="mt-4 text-[15px] text-white/50 max-w-[340px] leading-relaxed">
          Centralize suas operações, compare propostas e tome decisões com mais segurança.
        </p>
      </div>

      {/* Features */}
      <div className="relative shrink-0 grid grid-cols-1 gap-4 pt-6 border-t border-white/10">
        <Feature>Negociações em tempo real</Feature>
        <Feature>Comparação entre fornecedores</Feature>
        <Feature>Controle completo dos pedidos</Feature>
      </div>

      {/* Live ticker */}
      <div className="relative shrink-0">
        <LiveTicker />
      </div>

      {/* Footer */}
      <p className="relative text-[11px] text-white/25 font-mono shrink-0">
        © 2026 Alimo Tecnologia Ltda. · São Paulo, SP
      </p>
    </div>
  );
}

/* ─── Divider ────────────────────────────────────────── */
function Divider({ label }) {
  return (
    <div className="relative flex items-center gap-3 my-5">
      <div className="flex-1 h-px bg-line" />
      <span className="text-[14px] text-ink-300 shrink-0">{label}</span>
      <div className="flex-1 h-px bg-line" />
    </div>
  );
}

/* ─── Login form ─────────────────────────────────────── */
function LoginForm({ onSwitch }) {
  const [email, setEmail] = useState("");
  const [pass, setPass] = useState("");
  const [loading, setLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [authErr, setAuthErr] = useState("");

  // Etapa de verificação em duas etapas (TOTP) — só aparece se a conta tiver
  // um fator MFA verificado. A sessão após signInWithPassword() fica em aal1;
  // sem esse passo o dashboard já era acessível com só a senha, mesmo com o
  // 2FA "ativado" em Configurações.
  const [awaitingMfa, setAwaitingMfa] = useState(false);
  const [mfaFactorId, setMfaFactorId] = useState(null);
  const [mfaCode, setMfaCode] = useState("");
  const [mfaErr, setMfaErr] = useState("");
  const [mfaBusy, setMfaBusy] = useState(false);

  const loginEmailError = submitted ? emailError(email) : "";
  const loginPassError = submitted && !pass ? "Digite sua senha." : "";

  async function finishLogin(userId) {
    const { data: profile } = await window.sb.from("profiles").select("role").eq("id", userId).single();
    // Auditoria (best-effort) — alimenta o filtro "Acesso" em Configurações >
    // Auditoria, que antes ficava sempre vazio por falta desse hook. Cobre os
    // dois caminhos de login (com e sem 2FA), já que os dois chamam finishLogin.
    window.sb.from('audit_log').insert({
      profile_id: userId, actor_id: userId, tipo: 'Acesso', acao: 'Login realizado',
    }).then(() => {});
    // Rascunho de cotação é por conta, não por navegador: descarta o que houver no
    // localStorage local (pode ser de outra conta) e recarrega o desta conta, se existir.
    ['cotacao_rascunho', 'cotacao_produtos', 'cotacao_quantidades', 'cotacao_entrega'].forEach((k) => localStorage.removeItem(k));
    try {
      const { data: draftRow } = await window.sb.from('rfq_drafts').select('data').eq('profile_id', userId).maybeSingle();
      if (draftRow?.data) localStorage.setItem('cotacao_rascunho', JSON.stringify(draftRow.data));
    } catch (_) {}
    window.location.href = window.ROLE_DASHBOARDS[profile?.role ?? "comprador"];
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setSubmitted(true);
    if (emailError(email) || !pass) return;
    setLoading(true);
    setAuthErr("");
    const { data, error } = await window.sb.auth.signInWithPassword({ email, password: pass });
    if (error) {
      setAuthErr("E-mail ou senha incorretos.");
      setLoading(false);
      return;
    }

    const { data: aal } = await window.sb.auth.mfa.getAuthenticatorAssuranceLevel();
    if (aal && aal.nextLevel === 'aal2' && aal.nextLevel !== aal.currentLevel) {
      const { data: factors } = await window.sb.auth.mfa.listFactors();
      const factor = (factors?.totp || []).find((f) => f.status === 'verified');
      if (factor) {
        setMfaFactorId(factor.id);
        setLoading(false);
        setAwaitingMfa(true);
        return;
      }
    }
    await finishLogin(data.user.id);
  }

  async function handleVerifyMfa(e) {
    e.preventDefault();
    if (mfaCode.replace(/\D/g, "").length !== 6) { setMfaErr("Informe os 6 dígitos do código."); return; }
    setMfaErr("");
    setMfaBusy(true);
    const { data: ch, error: chErr } = await window.sb.auth.mfa.challenge({ factorId: mfaFactorId });
    if (chErr) { setMfaBusy(false); setMfaErr("Não foi possível validar o código: " + chErr.message); return; }
    const { data: verifyData, error: vErr } = await window.sb.auth.mfa.verify({
      factorId: mfaFactorId, challengeId: ch.id, code: mfaCode.replace(/\D/g, ""),
    });
    if (vErr) { setMfaBusy(false); setMfaErr("Código incorreto ou expirado. Tente novamente."); setMfaCode(""); return; }
    await finishLogin(verifyData.user.id);
  }

  async function handleCancelMfa() {
    // Desfaz o login em aal1 — sem isso, uma sessão válida (mesmo sem o 2FA
    // confirmado) ficaria no localStorage se o usuário só fechasse a aba.
    await window.sb.auth.signOut();
    setAwaitingMfa(false);
    setMfaFactorId(null);
    setMfaCode("");
    setMfaErr("");
    setPass("");
  }

  if (awaitingMfa) {
    return (
      <div>
        <h1 className="text-[36px] font-semibold tracking-[-0.015em] text-ink-900">
          Verificação em duas etapas
        </h1>
        <p className="mt-2.5 text-[17px] text-ink-400">
          Digite o código de 6 dígitos do seu aplicativo autenticador.
        </p>

        <form className="mt-9 space-y-5" onSubmit={handleVerifyMfa}>
          <Field label="Código" error={mfaErr}>
            <Input
              type="text"
              autoFocus
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder="000000"
              value={mfaCode}
              onChange={(e) => { setMfaCode(e.target.value.replace(/\D/g, "").slice(0, 6)); setMfaErr(""); }}
              className={`text-center text-[22px] font-mono tracking-[0.4em] ${mfaErr ? "border-err focus:border-err focus:ring-err/10" : ""}`}
            />
          </Field>

          <button
            type="submit"
            disabled={mfaBusy}
            className="w-full h-[56px] rounded-full bg-brand-600 text-white text-[16px] font-semibold
              hover:bg-[#186430] active:translate-y-px transition-all duration-150
              flex items-center justify-center gap-2 disabled:opacity-60"
          >
            {mfaBusy ? (
              <span className="font-mono text-[14px] tracking-wide">Confirmando…</span>
            ) : (
              <>Confirmar <Ic.arrow /></>
            )}
          </button>
        </form>

        <p className="mt-7 text-center text-[15px] text-ink-400">
          <button type="button" className="text-brand-600 font-medium hover:underline" onClick={handleCancelMfa}>
            Voltar para o login
          </button>
        </p>
      </div>
    );
  }

  const confirmed = new URLSearchParams(window.location.search).get('confirmed') === '1';

  return (
    <div>
      {confirmed && (
        <div className="mb-6 flex items-center gap-3 rounded-xl border border-brand-600/20 bg-brand-50 px-4 py-3">
          <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="#1F7A3A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="shrink-0"><path d="M3 8.5l3 3 7-7"/></svg>
          <p className="text-[14px] text-brand-600 font-medium">E-mail confirmado! Agora entre na sua conta.</p>
        </div>
      )}
      <h1 className="text-[36px] font-semibold tracking-[-0.015em] text-ink-900">
        Bom ter você de volta
      </h1>
      <p className="mt-2.5 text-[17px] text-ink-400">
        Entre na sua conta para continuar.
      </p>

      <form className="mt-9 space-y-5" onSubmit={handleSubmit}>
        <Field label="E-mail" error={loginEmailError}>
          <Input
            type="email"
            autoFocus
            placeholder="seu@email.com.br"
            value={email}
            onChange={(e) => setEmail(cleanEmail(e.target.value))}
            className={loginEmailError ? "border-err focus:border-err focus:ring-err/10" : ""}
            autoComplete="email"
            required
          />
        </Field>

        <Field
          label="Senha"
          hint={<a href="/auth/forgot-password" className="text-brand-600 hover:underline">Esqueci a senha</a>}
          error={loginPassError}
        >
          <PasswordInput
            value={pass}
            onChange={(e) => setPass(cleanPassword(e.target.value))}
            className={loginPassError ? "border-err focus:border-err focus:ring-err/10" : ""}
            autoComplete="current-password"
          />
        </Field>

        <button
          type="submit"
          disabled={loading}
          className="w-full h-[56px] rounded-full bg-brand-600 text-white text-[16px] font-semibold
            hover:bg-[#186430] active:translate-y-px transition-all duration-150
            flex items-center justify-center gap-2 disabled:opacity-60"
        >
          {loading ? (
            <span className="font-mono text-[14px] tracking-wide">Entrando…</span>
          ) : (
            <>Entrar <Ic.arrow /></>
          )}
        </button>
        {authErr && (
          <p className="text-[14px] text-err text-center mt-2" role="alert">{authErr}</p>
        )}
      </form>

      <Divider label="ou" />

      {/* Google SSO placeholder */}
      <button
        type="button"
        disabled
        title="Em breve"
        className="w-full h-[56px] rounded-full border border-line bg-white text-[15.5px] text-ink-700 font-medium
          flex items-center justify-center gap-2.5 opacity-50 cursor-not-allowed"
      >
        <svg viewBox="0 0 18 18" width="18" height="18"><path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"/><path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z"/><path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"/><path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"/></svg>
        Continuar com Google
      </button>

      <p className="mt-7 text-center text-[15px] text-ink-400">
        Ainda não tem conta?{" "}
        <a href="/auth/signup" className="text-brand-600 font-medium hover:underline">
          Criar conta gratuita
        </a>
      </p>
    </div>
  );
}

/* ─── Signup form ────────────────────────────────────── */
function SignupForm({ onSwitch }) {
  const [role, setRole] = useState(null);

  const ROLE_URLS = {
    buyer: "/auth/register-buyer",
    supplier: "/auth/register-supplier",
    transporter: "/auth/register-carrier",
  };

  return (
    <div>
      <h1 className="text-[36px] font-semibold tracking-[-0.015em] text-ink-900">
        Criar conta gratuita
      </h1>
      <p className="mt-2.5 text-[17px] text-ink-400">
        Como você vai usar a Alimo?
      </p>

      <div className="mt-9 space-y-4">
        <RoleCard
          icon={Ic.store}
          title="Sou comprador"
          desc="Quero cotar insumos e receber lances de fornecedores qualificados."
          selected={role === "buyer"}
          onClick={() => setRole("buyer")}
        />
        <RoleCard
          icon={Ic.truck}
          title="Sou fornecedor"
          desc="Quero participar de leilões e fechar pedidos com indústrias de alimentos."
          selected={role === "supplier"}
          onClick={() => setRole("supplier")}
        />
        <RoleCard
          icon={Ic.building}
          title="Sou transportadora"
          desc="Quero oferecer serviços de frete e logística para entregas na plataforma."
          selected={role === "transporter"}
          onClick={() => setRole("transporter")}
        />
      </div>

      <button
        type="button"
        disabled={!role}
        onClick={() => { window.location.href = ROLE_URLS[role]; }}
        className="mt-7 w-full h-[56px] rounded-full bg-brand-600 text-white text-[16px] font-semibold
          hover:bg-[#186430] active:translate-y-px transition-all duration-150
          flex items-center justify-center gap-2 disabled:opacity-40 disabled:cursor-not-allowed"
      >
        Continuar <Ic.arrow />
      </button>

      <p className="mt-7 text-center text-[15px] text-ink-400">
        Já tem conta?{" "}
        <a href="/auth/login" className="text-brand-600 font-medium hover:underline">
          Entrar
        </a>
      </p>
    </div>
  );
}

/* ─── Right panel — form switcher ───────────────────── */
function RightPanel() {
  const [mode, setMode] = useState(() =>
    window.AUTH_PAGE_MODE === "signup" ||
    new URLSearchParams(window.location.search).get("mode") === "signup"
      ? "signup"
      : "login"
  ); // "login" | "signup"

  return (
    <div className="flex flex-col min-h-screen bg-white">
      {/* Mobile logo */}
      <div className="lg:hidden px-6 pt-6 pb-2">
        <a href="#"><Logo /></a>
      </div>

      <div className="flex-1 flex items-center justify-center px-7 py-12">
        <div className="w-full max-w-[520px]">
          {mode === "login"
            ? <LoginForm onSwitch={() => setMode("signup")} />
            : <SignupForm onSwitch={() => setMode("login")} />
          }
        </div>
      </div>

      <div className="px-7 pb-6 text-center text-[13px] text-ink-300 font-mono">
        © 2026 Alimo · <a href="#" className="hover:text-ink-500">Privacidade</a> · <a href="#" className="hover:text-ink-500">Termos</a>
      </div>
    </div>
  );
}

/* ─── Root ───────────────────────────────────────────── */
function AuthPage() {
  return (
    <div className="grid lg:grid-cols-[540px_1fr] min-h-screen">
      <LeftPanel />
      <RightPanel />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<AuthPage />);
