/* global React, SEQ_UI, SEQ_LAYOUT */
const { brl, Avatar, Icon, StatusChip } = window.SEQ_UI;
const { Pill } = window.SEQ_LAYOUT;

// ─── Helpers ────────────────────────────────────────────
function getClientId() {
  const h = window.location.hash || "";
  const q = h.split("?")[1];
  return q ? new URLSearchParams(q).get("id") : null;
}

function fmtDate(iso) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("pt-BR", { day: "2-digit", month: "short", year: "numeric" });
}
function fmtRel(iso) {
  if (!iso) return "—";
  const days = Math.floor((Date.now() - new Date(iso).getTime()) / 86400000);
  if (days <= 0) return "hoje";
  if (days === 1) return "ontem";
  if (days < 30) return `há ${days}d`;
  if (days < 365) return `há ${Math.round(days / 30)}m`;
  return `há ${(days / 365).toFixed(1)} anos`;
}
function monthsLabel(n) { return n === 1 ? "1 mês" : `${n} meses`; }
function initials(name) { return (name || "").split(" ").map(s => s[0]).slice(0, 2).join(""); }

const COLOR_POOL = ["var(--kp-pink)", "var(--kp-green)", "var(--kp-cold)", "var(--kp-yellow)"];

// ─── Investimentos: combinar fontes em uma timeline única ───
function combineLedger(invoices, investments, subscriptions) {
  const rows = [];
  for (const i of invoices.filter(x => x.status === "paid")) {
    rows.push({
      id: `inv-${i.id}`,
      kind: "invoice",
      label: i.title || "Cobrança paga",
      amount: i.amount || 0,
      date: i.createdAt,
      meta: "Asaas · invoice",
    });
  }
  for (const x of investments) {
    rows.push({
      id: `inv-m-${x.id}`,
      investmentId: x.id,
      kind: "manual",
      label: x.description || "Investimento manual",
      amount: x.amount || 0,
      date: x.occurredAt,
      meta: x.source === "manual" ? "Registro manual" : x.source,
      removable: true,
    });
  }
  for (const s of subscriptions) {
    if ((s.totalPaid ?? 0) > 0) {
      rows.push({
        id: `sub-${s.id}`,
        kind: "subscription",
        label: `Assinatura ${s.billingCycle || ""}`.trim(),
        amount: s.totalPaid,
        date: s.createdAt,
        meta: `${s.chargeCount ?? 0} cobranças · ${s.status}`,
      });
    }
  }
  rows.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  return rows;
}

// ─── Monthly bars (últimos 6 meses) ───
function buildMonthly(ledger) {
  const out = [];
  const now = new Date();
  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const label = d.toLocaleDateString("pt-BR", { month: "short" }).replace(".", "");
    out.push({ key: `${d.getFullYear()}-${d.getMonth()}`, label, total: 0 });
  }
  for (const r of ledger) {
    const dt = new Date(r.date);
    const k = `${dt.getFullYear()}-${dt.getMonth()}`;
    const slot = out.find(o => o.key === k);
    if (slot) slot.total += r.amount;
  }
  const max = Math.max(1, ...out.map(o => o.total));
  return { rows: out, max };
}

// ─── Page ───────────────────────────────────────────────
function ClienteDetalhe() {
  const [clientId, setClientId] = React.useState(getClientId());
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [investOpen, setInvestOpen] = React.useState(false);

  React.useEffect(() => {
    function onHash() { setClientId(getClientId()); }
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const reload = React.useCallback(() => {
    if (!clientId) return;
    setLoading(true);
    window.SEQ_API.getClient(clientId)
      .then(d => { setData(d); setError(null); })
      .catch(e => setError(e.message || "Falha ao carregar"))
      .finally(() => setLoading(false));
  }, [clientId]);

  React.useEffect(() => { reload(); }, [reload]);

  if (!clientId) {
    return (
      <div style={{ padding: 64, textAlign: "center" }}>
        <div className="kp-mono" style={{ fontSize: 10, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>SEM CLIENTE SELECIONADO</div>
        <a href="#/clientes" className="kp-btn kp-btn-sm" style={{ marginTop: 16, display: "inline-block" }}>← Voltar pra lista</a>
      </div>
    );
  }

  if (loading && !data) {
    return <div style={{ padding: 64, textAlign: "center", color: "var(--kp-muted)", fontFamily: "var(--kp-mono)", fontSize: 11 }}>Carregando…</div>;
  }
  if (error || !data) {
    return (
      <div style={{ padding: 64, textAlign: "center" }}>
        <div className="kp-mono" style={{ fontSize: 10, letterSpacing: "0.2em", color: "#C73E3E" }}>⚠ {error || "Cliente não encontrado"}</div>
        <a href="#/clientes" className="kp-btn kp-btn-sm" style={{ marginTop: 16, display: "inline-block" }}>← Voltar</a>
      </div>
    );
  }

  const { client, stats, invoices, proposals, subscriptions, investments } = data;
  const ledger = combineLedger(invoices || [], investments || [], subscriptions || []);
  const monthly = buildMonthly(ledger);
  const color = COLOR_POOL[(client.name?.charCodeAt(0) || 0) % COLOR_POOL.length];

  return (
    <div style={{ minHeight: "100vh", background: "var(--kp-paper)" }}>
      {/* Top bar */}
      <div style={{
        borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-paper)",
        position: "sticky", top: 0, zIndex: 30,
      }}>
        <div className="kp-container kp-container-wide" style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "12px 32px", maxWidth: 1320, gap: 16,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
            <a href="#/clientes" className="kp-btn kp-btn-sm kp-btn-ghost" style={{ padding: "6px 10px" }}>
              <Icon.back s={14} /> Clientes
            </a>
            <span style={{ color: "var(--kp-faint)" }}>|</span>
            <div className="kp-display" style={{ fontSize: 18, lineHeight: 1.1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {client.name}
            </div>
            <Pill bg={color}>{client.company || "Pessoa física"}</Pill>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="kp-btn kp-btn-sm" onClick={() => setInvestOpen(true)} style={{ background: "var(--kp-green)" }}>
              + Registrar investimento
            </button>
            <a href={`https://wa.me/${(client.phone || "").replace(/\D/g, "")}`} target="_blank" rel="noopener noreferrer" className="kp-btn kp-btn-sm" style={{ textDecoration: "none" }}>
              <Icon.whatsapp s={12} /> WhatsApp
            </a>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 1320, margin: "0 auto", padding: "24px 32px 80px" }}>
        {/* Hero card + KPIs */}
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 2fr", gap: 16, marginBottom: 16 }}>
          {/* Hero card escuro estilo Coinest */}
          <div className="kp-card" style={{
            padding: 24, background: "var(--kp-ink)", color: "var(--kp-paper)",
            boxShadow: "4px 4px 0 0 var(--kp-green)",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <Avatar initials={initials(client.name)} size={56} bg={color} />
              <div style={{ minWidth: 0 }}>
                <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.22em", color: "var(--kp-faint)" }}>CLIENTE DESDE</div>
                <div className="kp-display" style={{ fontSize: 18, lineHeight: 1.1, marginTop: 4, color: "var(--kp-paper)" }}>
                  {fmtDate(stats.sinceAt)}
                </div>
                <div style={{ fontSize: 11.5, color: "rgba(247,241,232,0.7)", marginTop: 2 }}>
                  {monthsLabel(stats.monthsActive)} · {fmtRel(stats.sinceAt)}
                </div>
              </div>
            </div>
            <div style={{ borderTop: "1px solid rgba(247,241,232,0.15)", margin: "20px 0 14px" }} />
            <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.22em", color: "var(--kp-faint)" }}>TOTAL JÁ INVESTIDO</div>
            <div className="kp-display" style={{ fontSize: 56, fontStyle: "italic", lineHeight: 1, color: "var(--kp-paper)", marginTop: 8 }}>
              {brl(stats.totalInvested / 100)}
            </div>
            <div style={{ display: "flex", gap: 18, marginTop: 14, fontSize: 12, color: "rgba(247,241,232,0.75)" }}>
              <span><em style={{ color: "var(--kp-green)", fontStyle: "normal" }}>{stats.paidInvoiceCount}</em> cobranças pagas</span>
              <span>·</span>
              <span><em style={{ color: "var(--kp-green)", fontStyle: "normal" }}>{stats.activeSubscriptions}</em> recorrência ativa</span>
            </div>
          </div>

          {/* KPI grid */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 12 }}>
            <KPICard
              label="MÉDIA MENSAL"
              value={brl(stats.monthlyAvg / 100)}
              sub={`em ${monthsLabel(stats.monthsActive)}`}
              bg="var(--kp-pink-soft)"
              icon={<Icon.flame s={12} />}
            />
            <KPICard
              label="PROPOSTAS"
              value={String(stats.proposalCount)}
              sub={proposals?.[0] ? `Última: ${fmtDate(proposals[0].createdAt)}` : "Nenhuma ainda"}
              bg="var(--kp-cold)"
              icon={<Icon.send s={12} />}
            />
            <KPICard
              label="COBRANÇAS"
              value={`${stats.paidInvoiceCount} / ${stats.invoiceCount}`}
              sub="pagas · totais"
              bg="var(--kp-yellow)"
              icon={<Icon.check s={12} />}
            />
            <KPICard
              label="PRÓXIMA COBRANÇA"
              value={stats.nextChargeDate ? fmtDate(stats.nextChargeDate) : "—"}
              sub={stats.activeSubscriptions ? "Recorrência ativa" : "Sem recorrência"}
              bg="var(--kp-green)"
              icon={<Icon.clock s={12} />}
            />
          </div>
        </div>

        {/* Bottom: ledger + sidebar info */}
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16 }}>
          {/* Ledger + chart */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <MonthlyBars data={monthly} />
            <Ledger ledger={ledger} clientId={client.id} onChange={reload} />
          </div>

          {/* Right column */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <ContactCard client={client} />
            <ProposalsList proposals={proposals || []} />
            <SubscriptionsList subscriptions={subscriptions || []} />
          </div>
        </div>
      </div>

      {investOpen && (
        <InvestmentModal
          clientId={client.id}
          onClose={() => setInvestOpen(false)}
          onSaved={() => { setInvestOpen(false); reload(); }}
        />
      )}
    </div>
  );
}

// ─── KPI card ───────────────────────────────────────────
function KPICard({ label, value, sub, bg, icon }) {
  return (
    <div className="kp-card" style={{ padding: 18 }}>
      <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)", display: "flex", alignItems: "center", gap: 6 }}>
        <span style={{
          width: 22, height: 22, background: bg,
          border: "1.5px solid var(--kp-ink)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}>{icon}</span>
        {label}
      </div>
      <div className="kp-display" style={{ fontSize: typeof value === "string" && value.length > 8 ? 26 : 36, fontStyle: "italic", lineHeight: 1.05, marginTop: 10 }}>
        {value}
      </div>
      <div style={{ fontSize: 11.5, color: "var(--kp-muted)", marginTop: 6 }}>{sub}</div>
    </div>
  );
}

// ─── Monthly bars ───────────────────────────────────────
function MonthlyBars({ data }) {
  return (
    <div className="kp-card" style={{ padding: 0 }}>
      <div style={{ padding: "16px 20px", borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>EVOLUÇÃO · ÚLTIMOS 6 MESES</div>
        <div className="kp-display" style={{ fontSize: 18, marginTop: 2 }}>Quanto entrou por mês</div>
      </div>
      <div style={{ padding: "22px 20px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 12, alignItems: "end", height: 160 }}>
          {data.rows.map((r, i) => {
            const h = data.max > 0 ? Math.max(4, (r.total / data.max) * 140) : 4;
            return (
              <div key={r.key} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.1em", color: "var(--kp-muted)" }}>
                  {r.total > 0 ? brl(r.total / 100) : ""}
                </div>
                <div style={{
                  width: "100%", height: h,
                  background: i === data.rows.length - 1 ? "var(--kp-green)" : "var(--kp-pink)",
                  border: "1.5px solid var(--kp-ink)",
                }} />
                <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--kp-ink)" }}>
                  {r.label}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─── Ledger ─────────────────────────────────────────────
function Ledger({ ledger, clientId, onChange }) {
  async function remove(investmentId) {
    if (!confirm("Apagar este registro de investimento?")) return;
    try {
      await window.SEQ_API.deleteClientInvestment(clientId, investmentId);
      onChange();
    } catch (e) { alert(e.message); }
  }
  return (
    <div className="kp-card" style={{ padding: 0 }}>
      <div style={{ padding: "16px 20px", borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>HISTÓRICO</div>
          <div className="kp-display" style={{ fontSize: 18, marginTop: 2 }}>O que esse cliente já investiu</div>
        </div>
        <span className="kp-mono" style={{ fontSize: 9, color: "var(--kp-muted)", letterSpacing: "0.16em" }}>
          {ledger.length} {ledger.length === 1 ? "registro" : "registros"}
        </span>
      </div>
      {ledger.length === 0 && (
        <div style={{ padding: "32px 20px", textAlign: "center", color: "var(--kp-muted)", fontSize: 13 }}>
          Sem investimentos registrados ainda.
        </div>
      )}
      <div>
        {ledger.map((r, i) => (
          <div key={r.id} style={{
            display: "grid", gridTemplateColumns: "auto 1fr auto auto",
            gap: 12, padding: "13px 20px", alignItems: "center",
            borderBottom: i === ledger.length - 1 ? "none" : "1px solid rgba(10,10,10,0.08)",
            background: i % 2 === 1 ? "var(--kp-soft)" : "var(--kp-white)",
          }}>
            <span style={{
              width: 28, height: 28, background:
                r.kind === "invoice" ? "var(--kp-green)" :
                r.kind === "subscription" ? "var(--kp-pink)" :
                "var(--kp-yellow)",
              border: "1.5px solid var(--kp-ink)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
              {r.kind === "manual" ? <Icon.edit s={12} /> : <Icon.check s={12} />}
            </span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {r.label}
              </div>
              <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.14em", color: "var(--kp-muted)", marginTop: 2 }}>
                {fmtDate(r.date)} · {r.meta}
              </div>
            </div>
            <span className="kp-display" style={{ fontSize: 18, fontStyle: "italic" }}>{brl(r.amount / 100)}</span>
            {r.removable ? (
              <button onClick={() => remove(r.investmentId)} className="kp-btn kp-btn-sm" style={{ padding: "4px 8px", fontSize: 9.5 }} title="Apagar">×</button>
            ) : <span style={{ width: 28 }} />}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Contact card ───────────────────────────────────────
function ContactCard({ client }) {
  return (
    <div className="kp-card" style={{ padding: 18 }}>
      <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>CONTATO</div>
      <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 10 }}>
        <Field label="EMAIL" value={client.email} />
        <Field label="TELEFONE" value={client.phone} />
        <Field label="DOCUMENTO" value={client.document} mono />
        {client.company && <Field label="EMPRESA" value={client.company} />}
      </div>
    </div>
  );
}

function Field({ label, value, mono }) {
  return (
    <div>
      <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.2em", color: "var(--kp-faint)" }}>{label}</div>
      <div style={{ fontSize: 13, marginTop: 2, fontFamily: mono ? "var(--kp-mono)" : "inherit" }}>{value || "—"}</div>
    </div>
  );
}

// ─── Proposals list ─────────────────────────────────────
function ProposalsList({ proposals }) {
  if (!proposals.length) return null;
  return (
    <div className="kp-card" style={{ padding: 0 }}>
      <div style={{ padding: "12px 18px", borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>PROPOSTAS · {proposals.length}</div>
      </div>
      {proposals.slice(0, 5).map((p, i) => (
        <a key={p.id} href={`#/proposta?id=${p.id}`} style={{
          display: "block", padding: "11px 18px", textDecoration: "none", color: "var(--kp-ink)",
          borderBottom: i === Math.min(proposals.length, 5) - 1 ? "none" : "1px solid rgba(10,10,10,0.06)",
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.title}</div>
              <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.14em", color: "var(--kp-muted)", marginTop: 2 }}>
                {fmtDate(p.createdAt)} · {p.viewCount ?? 0} views
              </div>
            </div>
            <StatusChip status={p.status} />
          </div>
        </a>
      ))}
    </div>
  );
}

// ─── Subscriptions list ─────────────────────────────────
function SubscriptionsList({ subscriptions }) {
  if (!subscriptions.length) return null;
  return (
    <div className="kp-card" style={{ padding: 0 }}>
      <div style={{ padding: "12px 18px", borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>RECORRÊNCIAS · {subscriptions.length}</div>
      </div>
      {subscriptions.map((s, i) => (
        <div key={s.id} style={{
          padding: "11px 18px",
          borderBottom: i === subscriptions.length - 1 ? "none" : "1px solid rgba(10,10,10,0.06)",
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{brl((s.amount || 0) / 100)} / {s.billingCycle}</div>
              <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.14em", color: "var(--kp-muted)", marginTop: 2 }}>
                {s.chargeCount ?? 0} cobranças · próxima {s.nextChargeDate ? fmtDate(s.nextChargeDate) : "—"}
              </div>
            </div>
            <span className="status-chip" style={{
              background: s.status === "active" ? "var(--kp-green)" :
                          s.status === "past_due" ? "var(--kp-warm)" : "var(--kp-soft)",
            }}>{s.status}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Investment modal ───────────────────────────────────
function InvestmentModal({ clientId, onClose, onSaved }) {
  const [amount, setAmount] = React.useState("");
  const [description, setDescription] = React.useState("");
  const [occurredAt, setOccurredAt] = React.useState(new Date().toISOString().split("T")[0]);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  async function submit(e) {
    e.preventDefault();
    const cleaned = String(amount).replace(/[^0-9.,]/g, "").replace(",", ".");
    const cents = cleaned ? Math.round(parseFloat(cleaned) * 100) : 0;
    if (!cents) { setError("Valor obrigatório"); return; }
    setSubmitting(true);
    setError(null);
    try {
      await window.SEQ_API.createClientInvestment(clientId, {
        amount: cents,
        description: description.trim() || undefined,
        occurredAt,
      });
      onSaved();
    } catch (err) {
      setError(err.message || "Falha ao salvar.");
      setSubmitting(false);
    }
  }

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(10,10,10,0.5)", zIndex: 300, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} className="kp-card" style={{ padding: 28, maxWidth: 480, width: "100%", background: "var(--kp-paper)" }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>NOVO INVESTIMENTO</div>
        <h2 className="kp-display" style={{ fontSize: 32, lineHeight: 1.05, marginTop: 6 }}>Quanto <em>entrou agora</em>?</h2>
        <form onSubmit={submit}>
          <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 12 }}>
            <label>
              <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>VALOR (R$) *</span>
              <input className="kp-input" required autoFocus value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="2500,00" inputMode="decimal" style={{ marginTop: 6 }} />
            </label>
            <label>
              <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>QUANDO</span>
              <input className="kp-input" type="date" value={occurredAt} onChange={(e) => setOccurredAt(e.target.value)} style={{ marginTop: 6 }} />
            </label>
            <label>
              <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>DESCRIÇÃO</span>
              <input className="kp-input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="ex: Pagamento em dinheiro · janta" style={{ marginTop: 6 }} />
            </label>
          </div>
          {error && <div style={{ marginTop: 10, padding: "8px 12px", background: "#FFB5B5", border: "1.5px solid var(--kp-ink)", fontFamily: "var(--kp-mono)", fontSize: 10, letterSpacing: "0.14em" }}>⚠ {error}</div>}
          <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
            <button type="button" onClick={onClose} className="kp-btn" style={{ flex: 1 }}>Cancelar</button>
            <button type="submit" disabled={submitting} className="kp-btn kp-btn-ink" style={{ flex: 2 }}>{submitting ? "Salvando..." : "Registrar →"}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

window.SEQ_CLIENTE = ClienteDetalhe;
