// ═══════════════════════════════════════════════════════════════
//  income.jsx — Приходи (income ledger + AR aging).
//  Uses the live globals Card / Row / Empty / Field / Select / Button
//  / Icon (no re-declaration) and income-logic.js helpers.
// ═══════════════════════════════════════════════════════════════
const { useState: useStateI, useMemo: useMemoI } = React;

// `eur` is provided globally by income-logic.js

// tone → theme colour
const toneColor = (tone, T) => ({ blue: T.blue, sage: T.sage, gold: "#B7791F", sub: T.sub, faint: T.faint }[tone] || T.sub);

// ─── Source badge ───
function SourceBadge({ source, T }) {
  const s = sourceDef(source);
  const c = toneColor(s.tone, T);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 9.5, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase", color: c, background: `${c}1A`, padding: "3px 8px", borderRadius: 5 }}>
      <Icon name={s.icon} size={11} />{s.l}
    </span>
  );
}

// ─── Invoice status pill ───
const STATUS_DEF = {
  paid:    { l: "Платена",    tone: "sage",   icon: "check" },
  partial: { l: "Частично",   tone: "gold",   icon: "clock" },
  sent:    { l: "Изпратена",  tone: "blue",   icon: "doc" },
  overdue: { l: "Просрочена", tone: "danger", icon: "clock" },
};
function StatusPill({ status, T, suffix }) {
  const d = STATUS_DEF[status] || STATUS_DEF.sent;
  const c = d.tone === "danger" ? T.danger : toneColor(d.tone, T);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 9.5, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: c, background: `${c}1A`, padding: "3px 9px", borderRadius: 5, whiteSpace: "nowrap" }}>
      <Icon name={d.icon} size={11} />{d.l}{suffix ? ` · ${suffix}` : ""}
    </span>
  );
}

const FRESH_INCOME = () => ({ mode: "standalone", invoiceNum: "", source: "platform", date: TODAY, payer: "", project: "", amount: "", currency: "EUR", vat: "", account: "wise", note: "" });

function IncomeView({ T, invoices, incomes, onSave, onUpdate, onDelete, pendingReceive, onPendingConsumed }) {
  const [year, setYear] = useStateI(YEAR);
  const [showForm, setShowForm] = useStateI(false);
  const [editingId, setEditingId] = useStateI(null);
  const [form, setForm] = useStateI(FRESH_INCOME());
  const [filterSource, setFilterSource] = useStateI("");
  const upd = (patch) => setForm(p => ({ ...p, ...patch }));

  const years = useMemoI(() => {
    const s = new Set([YEAR]);
    (incomes || []).forEach(e => { const y = (e.date || "").slice(0, 4); if (y) s.add(y); });
    (invoices || []).forEach(i => { const y = (i.issueDate || "").slice(0, 4); if (y) s.add(y); });
    return [...s].sort().reverse();
  }, [incomes, invoices]);

  const outstanding = useMemoI(() => (invoices || [])
    .filter(i => i.docType === "invoice")
    .map(inv => ({ inv, status: invoiceStatus(inv, incomes), paid: invoicePaidGross(inv, incomes), due: effectiveDue(inv), od: daysOverdue(effectiveDue(inv)) }))
    .filter(x => x.status !== "paid")
    .sort((a, b) => b.od - a.od || a.due.localeCompare(b.due)), [invoices, incomes]);

  const expectedTotal = outstanding.reduce((s, x) => s + (toEUR(x.inv.total, x.inv.currency) - x.paid), 0);
  const overdueTotal = outstanding.filter(x => x.status === "overdue").reduce((s, x) => s + (toEUR(x.inv.total, x.inv.currency) - x.paid), 0);
  const overdueCount = outstanding.filter(x => x.status === "overdue").length;

  const yearIncomes = useMemoI(() => (incomes || [])
    .filter(e => (e.date || "").startsWith(year))
    .filter(e => !filterSource || e.source === filterSource)
    .sort((a, b) => (b.date || "").localeCompare(a.date || "") || (b.id - a.id)), [incomes, year, filterSource]);
  const receivedTotal = (incomes || []).filter(e => (e.date || "").startsWith(year)).reduce((s, e) => s + incomeGrossEUR(e), 0);
  const offInvoiceTotal = (incomes || []).filter(e => (e.date || "").startsWith(year) && e.source !== "invoice").reduce((s, e) => s + incomeGrossEUR(e), 0);

  const startAddStandalone = () => { setForm({ ...FRESH_INCOME(), mode: "standalone", source: "platform" }); setEditingId(null); setShowForm(true); };
  const startReceiveInvoice = (inv) => {
    const remaining = toEUR(inv.total, inv.currency) - invoicePaidGross(inv, incomes);
    setForm({ ...FRESH_INCOME(), mode: "invoice", invoiceNum: inv.num, source: "invoice", payer: inv.client?.name || inv.client?.nameEn || "", project: inv.project || "", amount: remaining.toFixed(2), currency: inv.currency, account: "wise" });
    setEditingId(null); setShowForm(true);
  };
  const startEdit = (e) => {
    setForm({ mode: e.source === "invoice" ? "invoice" : "standalone", invoiceNum: e.invoiceNum || "", source: e.source, date: e.date || TODAY, payer: e.payer || "", project: e.project || "", amount: String(e.amount ?? ""), currency: e.currency || "EUR", vat: String(e.vat ?? ""), account: e.account || "wise", note: e.note || "" });
    setEditingId(e.id); setShowForm(true);
  };
  const pickInvoice = (num) => {
    const inv = (invoices || []).find(i => i.num === num);
    if (!inv) { upd({ invoiceNum: "" }); return; }
    const remaining = toEUR(inv.total, inv.currency) - invoicePaidGross(inv, incomes);
    upd({ invoiceNum: num, payer: inv.client?.name || inv.client?.nameEn || "", project: inv.project || "", amount: remaining.toFixed(2), currency: inv.currency });
  };
  const cancel = () => { setShowForm(false); setEditingId(null); setForm(FRESH_INCOME()); };

  React.useEffect(() => {
    if (pendingReceive) { startReceiveInvoice(pendingReceive); onPendingConsumed && onPendingConsumed(); }
  }, [pendingReceive]);

  const save = () => {
    if (!form.amount) return;
    const payload = {
      source: form.mode === "invoice" ? "invoice" : form.source,
      invoiceNum: form.mode === "invoice" ? form.invoiceNum : "",
      date: form.date, payer: form.payer, project: form.project,
      amount: Number(form.amount) || 0, currency: form.currency, vat: Number(form.vat) || 0,
      account: form.account, note: form.note,
    };
    if (editingId) onUpdate({ ...payload, id: editingId }); else onSave(payload);
    cancel();
  };

  const invoiceOptions = [{ v: "", l: "— Избери фактура —" }, ...(invoices || [])
    .filter(i => i.docType === "invoice" && invoiceStatus(i, incomes) !== "paid")
    .map(i => ({ v: i.num, l: `№ ${i.num} · ${i.client?.name || i.client?.nameEn} · ${eur(toEUR(i.total, i.currency) - invoicePaidGross(i, incomes))}` }))];

  const stat = (label, value, sub, color) => (
    <div style={{ flex: 1, minWidth: 170, padding: "18px 20px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint, marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: MONO, fontSize: 23, fontWeight: 700, color: color || T.ink }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: T.sub, marginTop: 3 }}>{sub}</div>}
    </div>
  );

  const modeBtn = (v, l) => (
    <button key={v} onClick={() => upd({ mode: v })} style={{ flex: 1, padding: "8px 12px", borderRadius: 7, fontSize: 11.5, fontWeight: 600, fontFamily: MONO, cursor: "pointer",
      border: `1px solid ${form.mode === v ? T.blue : T.line}`, background: form.mode === v ? T.blueSoft : "transparent", color: form.mode === v ? T.blue : T.sub }}>{l}</button>
  );

  return (
    <div style={{ maxWidth: 920, 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>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 10 }}>
          <div style={{ minWidth: 110 }}><Select label="Година" value={year} onChange={setYear} options={years.map(y => ({ v: y, l: y }))} T={T} /></div>
          <Button T={T} kind="primary" size="sm" icon="plus" onClick={startAddStandalone}>Нов приход</Button>
        </div>
      </div>

      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        {stat("Получени " + year, eur(receivedTotal), `вкл. ${eur(offInvoiceTotal)} извън фактури`, T.sage)}
        {stat("Очаквани (неплатени)", eur(expectedTotal), `${outstanding.length} ${outstanding.length === 1 ? "фактура" : "фактури"}`, T.ink)}
        {stat("Просрочени", eur(overdueTotal), overdueCount ? `${overdueCount} ${overdueCount === 1 ? "фактура" : "фактури"}` : "няма", overdueTotal > 0 ? T.danger : T.faint)}
      </div>

      {showForm && (
        <div id="income-form-top">
        <Card T={T} title={editingId ? "Редактирай приход" : "Нов приход"} icon="wallet">
          {!editingId && (
            <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
              {modeBtn("invoice", "Плащане по фактура")}
              {modeBtn("standalone", "Приход извън фактура")}
            </div>
          )}
          {form.mode === "invoice" ? (
            <React.Fragment>
              <Row>
                <Select label="Фактура" value={form.invoiceNum} onChange={pickInvoice} options={invoiceOptions} T={T} minWidth={280} />
              </Row>
              <Row>
                <Field label="Дата на получаване" type="date" value={form.date} onChange={v => upd({ date: v })} T={T} minWidth={150} />
                <Field label="Получена сума" type="number" value={form.amount} onChange={v => upd({ amount: v })} T={T} mono minWidth={130} suffix={form.currency} />
                <Select label="Сметка" value={form.account} onChange={v => upd({ account: v })} options={ACCOUNTS} T={T} minWidth={140} />
              </Row>
              <Row style={{ marginBottom: 0 }}>
                <Field label="Бележка" value={form.note} onChange={v => upd({ note: v })} T={T} minWidth={240} />
              </Row>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <Row>
                <Select label="Източник" value={form.source} onChange={v => upd({ source: v })} options={INCOME_SOURCES.filter(s => s.v !== "invoice")} T={T} minWidth={160} />
                <Field label="Платец / описание" value={form.payer} onChange={v => upd({ payer: v })} T={T} minWidth={200} />
                <Select label="Проект" value={form.project} onChange={v => upd({ project: v })} options={INCOME_PROJECTS} T={T} minWidth={150} />
              </Row>
              <Row>
                <Field label="Дата" type="date" value={form.date} onChange={v => upd({ date: v })} T={T} minWidth={150} />
                <Field label="Сума" type="number" value={form.amount} onChange={v => upd({ amount: v })} T={T} mono minWidth={120} />
                <Select label="Валута" value={form.currency} onChange={v => upd({ currency: v })} options={["EUR", "BGN", "USD", "PLN"]} T={T} minWidth={100} />
                <Field label="ДДС" type="number" value={form.vat} onChange={v => upd({ vat: v })} T={T} mono minWidth={90} />
                <Select label="Сметка" value={form.account} onChange={v => upd({ account: v })} options={ACCOUNTS} T={T} minWidth={130} />
              </Row>
              <Row style={{ marginBottom: 0 }}>
                <Field label="Бележка" value={form.note} onChange={v => upd({ note: v })} T={T} minWidth={240} />
              </Row>
            </React.Fragment>
          )}
          <Row style={{ marginBottom: 0, marginTop: 14 }}>
            <div style={{ flex: 1 }} />
            <Button T={T} kind="ghost" size="sm" onClick={cancel}>Откажи</Button>
            <Button T={T} kind="primary" size="sm" icon="save" onClick={save}>{editingId ? "Актуализирай" : "Запиши приход"}</Button>
          </Row>
        </Card>
        </div>
      )}

      <Card T={T} title="Очаквани плащания" icon="clock" right={<span style={{ fontSize: 11, color: T.faint }}>{outstanding.length ? "кой ти дължи" : ""}</span>}>
        {outstanding.length === 0 ? <Empty T={T} icon="check" text="Всичко е платено 🎉" /> : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {outstanding.map(({ inv, status, paid, od }) => (
              <div key={inv.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", background: T.field, border: `1px solid ${status === "overdue" ? T.danger + "55" : T.line}`, borderRadius: 9, flexWrap: "wrap" }}>
                <StatusPill status={status} T={T} suffix={od > 0 ? `${od} дни` : ""} />
                <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, minWidth: 100 }}>{inv.num}</div>
                <div style={{ flex: 1, minWidth: 120 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{inv.client?.name || inv.client?.nameEn}</div>
                  <div style={{ fontSize: 10.5, color: T.faint }}>издадена {fmtDate(inv.issueDate)} · падеж {fmtDate(effectiveDue(inv))}{paid > 0 ? ` · платено ${eur(paid)}` : ""}</div>
                </div>
                <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: T.ink, textAlign: "right", minWidth: 96 }}>{eur(toEUR(inv.total, inv.currency) - paid)}</div>
                <Button T={T} kind="ghost" size="sm" icon="check" onClick={() => startReceiveInvoice(inv)}>Получено</Button>
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card T={T} title="Постъпления" icon="wallet"
        right={<div style={{ minWidth: 150 }}><Select value={filterSource} onChange={setFilterSource} options={[{ v: "", l: "Всички източници" }, ...INCOME_SOURCES]} T={T} /></div>}>
        {yearIncomes.length === 0 ? <Empty T={T} icon="wallet" text="Няма постъпления за този период" /> : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {yearIncomes.map(e => (
              <div key={e.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
                <div style={{ fontSize: 11, color: T.faint, fontFamily: MONO, minWidth: 72 }}>{fmtDate(e.date)}</div>
                <div style={{ minWidth: 116 }}><SourceBadge source={e.source} T={T} /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    {e.payer || "—"}{e.invoiceNum ? ` · № ${e.invoiceNum}` : ""}
                  </div>
                  <div style={{ fontSize: 10.5, color: T.faint }}>{accountLabel(e.account)}{e.project ? ` · ${e.project}` : ""}{e.note ? ` · ${e.note}` : ""}</div>
                </div>
                <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: T.sage, textAlign: "right", minWidth: 100 }}>+{fmtNum(e.amount)} {e.currency}</div>
                <button title="Редактирай" onClick={() => startEdit(e)} style={{ background: "none", border: "none", color: T.sub, cursor: "pointer", padding: 4 }}><Icon name="edit" size={15} /></button>
                <button title="Изтрий" onClick={() => onDelete(e.id)} style={{ background: "none", border: "none", color: T.danger, cursor: "pointer", padding: 4 }}><Icon name="trash" size={15} /></button>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { IncomeView, SourceBadge, StatusPill, STATUS_DEF, toneColor });
