// ═══════════════════════════════════════════════════════════════
//  clients.jsx — Клиенти (профил-изглед, Етап redesign).
//  Списък → клик → всички фактури/плащания/неплатено + контакт.
//  Адаптивна форма по вид (bg = ЕИК+МОЛ · eu/noneu = държава+VAT ID).
//  Реални данни от app (clients/invoices/incomes), без MOCK.
//  Ползва глобалните Card/Empty/StatusPill/SourceBadge/income-logic.
// ═══════════════════════════════════════════════════════════════
const { useState: useStateC, useMemo: useMemoC } = React;
const eurC = (n) => `€ ${fmtNum(n)}`;

function RowC({ T, left, title, sub, right, rightColor, tail }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", background: T.field, border: `1px solid ${T.line}`, borderRadius: 9 }}>
      {left}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{title}</div>
        {sub && <div style={{ fontSize: 10.5, color: T.faint, marginTop: 1 }}>{sub}</div>}
      </div>
      {right != null && <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: rightColor || T.ink, textAlign: "right", whiteSpace: "nowrap" }}>{right}</div>}
      {tail}
    </div>
  );
}

const CLIENT_KINDS = [
  { v: "bg", l: "Български" },
  { v: "eu", l: "Чужд · ЕС" },
  { v: "noneu", l: "Чужд · извън ЕС" },
];
const KIND_LABEL = { bg: "Български", eu: "ЕС", noneu: "Извън ЕС" };
const FRESH_CLIENT_C = () => ({ kind: "bg", name: "", nameEn: "", eik: "", vatId: "", mol: "", country: "", address: "", note: "" });

function ClientForm({ T, initial, onSave, onCancel }) {
  const [f, setF] = useStateC(initial ? { ...FRESH_CLIENT_C(), ...initial } : FRESH_CLIENT_C());
  const upd = (patch) => setF(p => ({ ...p, ...patch }));
  const bg = f.kind === "bg";
  const editing = !!(initial && (initial.id || initial._id));
  const kindBtn = (v, l) => (
    <button key={v} onClick={() => upd({ kind: v })} style={{ flex: 1, padding: "8px 10px", borderRadius: 7, fontSize: 11, fontWeight: 600, fontFamily: MONO, cursor: "pointer",
      border: `1px solid ${f.kind === v ? T.blue : T.line}`, background: f.kind === v ? T.blueSoft : "transparent", color: f.kind === v ? T.blue : T.sub }}>{l}</button>
  );
  const save = () => { if (!f.name && !f.nameEn) return; onSave(f); };
  return (
    <Card T={T} title={editing ? "Редактирай клиент" : "Нов клиент"} icon="users">
      <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>{CLIENT_KINDS.map(k => kindBtn(k.v, k.l))}</div>
      <Row>
        <Field label="Име (БГ)" value={f.name} onChange={v => upd({ name: v })} T={T} minWidth={200} />
        <Field label="Name (EN)" value={f.nameEn} onChange={v => upd({ nameEn: v })} T={T} minWidth={200} />
      </Row>
      {bg ? (
        <Row>
          <Field label="ЕИК" value={f.eik} onChange={v => upd({ eik: v })} T={T} mono minWidth={130} />
          <Field label="ИН по ДДС" value={f.vatId} onChange={v => upd({ vatId: v })} T={T} mono minWidth={130} />
          <Field label="МОЛ" value={f.mol} onChange={v => upd({ mol: v })} T={T} minWidth={150} />
        </Row>
      ) : (
        <Row>
          <Field label="Държава" value={f.country} onChange={v => upd({ country: v })} T={T} minWidth={150} />
          <Field label="VAT ID" value={f.vatId} onChange={v => upd({ vatId: v })} T={T} mono minWidth={160} />
        </Row>
      )}
      <Row><Field label="Адрес" value={f.address} onChange={v => upd({ address: v })} T={T} minWidth={280} /></Row>
      <Row style={{ marginBottom: 0 }}>
        <Field label="Бележка" value={f.note} onChange={v => upd({ note: v })} T={T} minWidth={280} />
        <div style={{ flex: 1 }} />
        <Button T={T} kind="ghost" size="sm" onClick={onCancel}>Откажи</Button>
        <Button T={T} kind="primary" size="sm" icon="save" onClick={save}>{editing ? "Актуализирай" : "Запиши клиент"}</Button>
      </Row>
    </Card>
  );
}

function aggregateClient(name, { invoices, incomes }, meta) {
  const nl = name.toLowerCase();
  const invs = (invoices || []).filter(i => i.docType === "invoice" && `${i.client?.name || ""} ${i.client?.nameEn || ""}`.toLowerCase().includes(nl));
  const nums = new Set(invs.map(i => i.num));
  const inc = (incomes || []).filter(e => (e.invoiceNum && nums.has(e.invoiceNum)) || (e.payer || "").toLowerCase() === nl);
  const billed = invs.reduce((s, i) => s + toEUR(i.total, i.currency), 0);
  const billedNet = invs.reduce((s, i) => s + toEUR(i.base, i.currency), 0);
  const received = invs.reduce((s, i) => s + invoicePaidGross(i, incomes), 0)
    + inc.filter(e => e.source !== "invoice").reduce((s, e) => s + incomeGrossEUR(e), 0);
  const outstanding = invs.reduce((s, i) => s + (toEUR(i.total, i.currency) - invoicePaidGross(i, incomes)), 0);
  const overdue = invs.filter(i => invoiceStatus(i, incomes) === "overdue");
  const overdueTotal = overdue.reduce((s, i) => s + (toEUR(i.total, i.currency) - invoicePaidGross(i, incomes)), 0);
  const projects = [...new Set(invs.map(i => i.project).filter(Boolean))];
  const avg = invs.length ? billed / invs.length : 0;
  const last = invs.map(i => i.issueDate).sort().slice(-1)[0] || "";
  return { name, invs, inc, billed, billedNet, received, outstanding, overdue, overdueTotal, projects, avg, last, meta: meta || { name } };
}

function ClientsProfile({ T, clients, invoices, incomes, onSave, onDelete }) {
  const data = { invoices: invoices || [], incomes: incomes || [] };
  const [open, setOpen] = useStateC(null);
  const [showForm, setShowForm] = useStateC(false);
  const [editClient, setEditClient] = useStateC(null);

  const metaOf = (n) => (clients || []).find(c => c.name === n || c.nameEn === n) || { name: n };

  const names = useMemoC(() => {
    const s = new Set();
    (clients || []).forEach(c => { if (c.name || c.nameEn) s.add(c.name || c.nameEn); });
    (invoices || []).forEach(i => { const n = i.client?.name || i.client?.nameEn; if (n) s.add(n); });
    return [...s];
  }, [clients, invoices]);

  const rows = useMemoC(() => names.map(n => aggregateClient(n, data, metaOf(n))).sort((a, b) => b.billed - a.billed), [names, data, clients]);

  const saveClient = (f) => { onSave(f); setShowForm(false); setEditClient(null); };
  const startEdit = (meta) => { setEditClient(meta); setShowForm(true); };

  if (open) {
    const row = rows.find(r => r.name === open) || aggregateClient(open, data, metaOf(open));
    return <ClientDetail T={T} row={row} incomes={data.incomes} onBack={() => setOpen(null)}
      onEdit={() => { startEdit(row.meta); setOpen(null); }}
      onDelete={row.meta && row.meta._id ? () => { onDelete(row.meta._id); setOpen(null); } : null} />;
  }

  const totalBilled = rows.reduce((s, r) => s + r.billed, 0);
  const totalOutstanding = rows.reduce((s, r) => s + r.outstanding, 0);

  const headStat = (label, value, color) => (
    <div style={{ flex: 1, minWidth: 150, padding: "16px 18px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint, marginBottom: 6 }}>{label}</div>
      <div style={{ fontFamily: MONO, fontSize: 21, fontWeight: 700, color: color || T.ink }}>{value}</div>
    </div>
  );
  const mini = (label, value, color) => (
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 9, letterSpacing: "0.06em", textTransform: "uppercase", color: T.faint }}>{label}</div>
      <div style={{ fontFamily: MONO, fontSize: 14, fontWeight: 700, color: color || T.ink, marginTop: 2, whiteSpace: "nowrap" }}>{value}</div>
    </div>
  );

  return (
    <div style={{ maxWidth: 980, margin: "0 auto", padding: "28px 28px 60px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, gap: 12, flexWrap: "wrap" }}>
        <h2 style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.02em", margin: 0 }}>Клиенти</h2>
        <Button T={T} kind="primary" size="sm" icon="plus" onClick={() => { setEditClient(null); setShowForm(true); }}>Нов клиент</Button>
      </div>

      {showForm && <ClientForm T={T} initial={editClient} onSave={saveClient} onCancel={() => { setShowForm(false); setEditClient(null); }} />}

      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        {headStat("Общо фактурирано", eurC(totalBilled))}
        {headStat("Неплатено", eurC(totalOutstanding), totalOutstanding > 0 ? T.danger : T.sage)}
        {headStat("Клиенти", String(rows.length))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 12 }}>
        {rows.map(row => (
          <button key={row.name} onClick={() => setOpen(row.name)} style={{ textAlign: "left", cursor: "pointer", padding: "16px 18px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 11, display: "flex", flexDirection: "column", gap: 12, fontFamily: MONO }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = T.blue; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = T.line; }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: T.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{row.name}</div>
                <div style={{ fontSize: 10, color: T.faint, marginTop: 2 }}>{row.meta.vatId || row.meta.country || "—"}</div>
              </div>
              <span style={{ fontSize: 9, fontWeight: 700, padding: "2px 8px", borderRadius: 9, background: row.meta.kind === "bg" ? `${T.sage}22` : T.blueSoft, color: row.meta.kind === "bg" ? T.sage : T.blue, whiteSpace: "nowrap" }}>{KIND_LABEL[row.meta.kind] || "—"}</span>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              {mini("Фактурирано", eurC(row.billed))}
              {mini("Получено", eurC(row.received), T.sage)}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 10, borderTop: `1px solid ${T.line}` }}>
              <span style={{ fontSize: 10, color: T.faint, textTransform: "uppercase", letterSpacing: "0.06em" }}>Неплатено</span>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: row.outstanding > 0.01 ? T.danger : T.sage }}>{eurC(row.outstanding)}{row.overdueTotal > 0.01 ? " ●" : ""}</span>
            </div>
          </button>
        ))}
        {rows.length === 0 && <Empty T={T} icon="users" text="Няма записани клиенти. Добави първия с „Нов клиент“." />}
      </div>
    </div>
  );
}

function ClientDetail({ T, row, incomes, onBack, onEdit, onDelete }) {
  const stat = (label, value, sub, color) => (
    <div style={{ flex: 1, minWidth: 150, padding: "16px 18px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint, marginBottom: 6 }}>{label}</div>
      <div style={{ fontFamily: MONO, fontSize: 21, fontWeight: 700, color: color || T.ink }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: T.sub, marginTop: 3 }}>{sub}</div>}
    </div>
  );
  const section = (title, icon, count, children) => (
    <Card T={T} title={title} icon={icon} right={<span style={{ fontSize: 11, color: T.faint }}>{count}</span>}>{children}</Card>
  );

  return (
    <div style={{ maxWidth: 980, margin: "0 auto", padding: "22px 28px 60px" }}>
      <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "none", border: "none", color: T.sub, cursor: "pointer", fontFamily: MONO, fontSize: 12, padding: "4px 0", marginBottom: 12 }}>
        <span style={{ transform: "rotate(180deg)", display: "flex" }}><Icon name="chevron" size={15} /></span>Клиенти
      </button>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12, flexWrap: "wrap" }}>
        <h2 style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-0.02em", margin: "0 0 4px" }}>{row.name}</h2>
        <div style={{ display: "flex", gap: 8 }}>
          {onDelete && <Button T={T} kind="plain" size="sm" danger icon="trash" onClick={onDelete}>Изтрий</Button>}
          {onEdit && <Button T={T} kind="ghost" size="sm" icon="edit" onClick={onEdit}>Редактирай</Button>}
        </div>
      </div>
      <div style={{ fontSize: 12, color: T.sub, marginBottom: 20 }}>
        {[row.meta.eik && `ЕИК ${row.meta.eik}`, row.meta.vatId && `ИН по ДДС ${row.meta.vatId}`, row.meta.country, row.meta.address].filter(Boolean).join(" · ") || "—"}
        {row.meta.note ? ` · ${row.meta.note}` : ""}
      </div>

      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 12 }}>
        {stat("Фактурирано", eurC(row.billed), `${row.invs.length} фактури · ср. ${eurC(row.avg)}`)}
        {stat("Получено", eurC(row.received), null, T.sage)}
        {stat("Неплатено", eurC(row.outstanding), row.overdueTotal > 0.01 ? `${eurC(row.overdueTotal)} просрочени` : null, row.outstanding > 0.01 ? T.danger : T.sage)}
      </div>

      {row.projects.length > 0 && (
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
          <span style={{ fontSize: 10.5, color: T.faint, textTransform: "uppercase", letterSpacing: "0.06em" }}>Проекти</span>
          {row.projects.map(p => <span key={p} style={{ fontSize: 11, fontWeight: 600, padding: "4px 10px", borderRadius: 8, background: T.blueSoft, color: T.blue }}>{p}</span>)}
        </div>
      )}

      {section("Фактури", "doc", `${row.invs.length} бр.`, row.invs.length === 0 ? <Empty T={T} icon="doc" text="Няма фактури" /> : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {row.invs.slice().sort((a, b) => (b.issueDate || "").localeCompare(a.issueDate || "")).map(i => (
            <RowC key={i.id} T={T} left={<div style={{ minWidth: 120 }}><StatusPill status={invoiceStatus(i, incomes)} T={T} /></div>}
              title={`№ ${i.num}`} sub={`${fmtDate(i.issueDate)} · падеж ${fmtDate(effectiveDue(i))}${i.project ? ` · ${i.project}` : ""}`}
              right={eurC(toEUR(i.total, i.currency))} />
          ))}
        </div>
      ))}

      {section("Плащания", "wallet", `${row.inc.length} бр.`, row.inc.length === 0 ? <Empty T={T} icon="wallet" text="Няма постъпления" /> : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {row.inc.slice().sort((a, b) => (b.date || "").localeCompare(a.date || "")).map(e => (
            <RowC key={e.id} T={T} left={<div style={{ minWidth: 116 }}><SourceBadge source={e.source} T={T} /></div>}
              title={e.payer || "—"} sub={`${fmtDate(e.date)} · ${accountLabel(e.account)}${e.invoiceNum ? ` · № ${e.invoiceNum}` : ""}`}
              right={`+${fmtNum(e.amount)} ${e.currency}`} rightColor={T.sage} />
          ))}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { ClientsProfile, aggregateClient });
