// finance-pages.jsx — Фінанси: Клієнти · Договори · Рахунки і дебіторка

// ============ КЛІЄНТИ ============
function ClientsPage({ role }) {
  window.useCounterparties && window.useCounterparties();
  const clients = window.DATA.CLIENTS;
  const contracts = window.DATA.CONTRACTS;
  const objects = window.DATA.OBJECTS;
  const invoices = window.DATA.INVOICES;
  const [openId, setOpenId] = React.useState(null);
  const [wiz, setWiz] = React.useState(false);
  const canEdit = role === "director" || role === "accountant";

  // Підрахунок метрик по клієнту
  const stats = (clientId) => {
    const myContracts = contracts.filter(c => c.client === clientId);
    const totalContracts = myContracts.reduce((s, c) => s + c.total, 0);
    const myInvoices = invoices.filter(i => i.client === clientId);
    const paid = myInvoices.filter(i => i.status === "paid").reduce((s, i) => s + i.amount, 0);
    const owed = myInvoices.filter(i => i.status === "overdue" || i.status === "issued").reduce((s, i) => s + i.amount, 0);
    const overdue = myInvoices.filter(i => i.status === "overdue").reduce((s, i) => s + i.amount, 0);
    const objs = myContracts.map(c => c.obj).filter(Boolean);
    return { totalContracts, paid, owed, overdue, objCount: objs.length, contractCount: myContracts.length };
  };

  const totals = clients.reduce((acc, c) => {
    const s = stats(c.id);
    return {
      contracts: acc.contracts + s.contractCount,
      total: acc.total + s.totalContracts,
      paid: acc.paid + s.paid,
      owed: acc.owed + s.owed,
      overdue: acc.overdue + s.overdue,
    };
  }, { contracts: 0, total: 0, paid: 0, owed: 0, overdue: 0 });

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Замовники</h1>
        <div className="page-sub">
          <span>{clients.length} {window.plural(clients.length, "замовник", "замовники", "замовників")}</span>
          <span className="dot"></span>
          <span>{totals.contracts} {window.plural(totals.contracts, "активний договір", "активні договори", "активних договорів")}</span>
          {totals.overdue > 0 && <>
            <span className="dot"></span>
            <span style={{color: "var(--late)"}}>дебіторка {window.formatMoney(totals.overdue)} ₴</span>
          </>}
        </div>
      </div>

      <div className="kpi-row" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
        <div className="kpi">
          <div className="kpi-label">Сума договорів</div>
          <div className="kpi-value">{window.formatMoney(totals.total)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">за всіма замовниками</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Отримано</div>
          <div className="kpi-value" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(totals.paid)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{Math.round(totals.paid / totals.total * 100)}% від договорів</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Очікується</div>
          <div className="kpi-value">{window.formatMoney(totals.owed - totals.overdue)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">у графіку</div>
        </div>
        <div className={`kpi ${totals.overdue > 0 ? "is-warn" : ""}`}>
          <div className="kpi-label">Прострочено</div>
          <div className="kpi-value">{window.formatMoney(totals.overdue)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{totals.overdue > 0 ? "потребує дій" : "усе вчасно"}</div>
        </div>
      </div>

      {canEdit && (
        <div className="toolbar" style={{marginBottom: 4}}>
          <button className="btn btn-primary" style={{marginLeft: "auto"}} onClick={() => setWiz(true)}>
            <window.Ico name="plus" /> Новий замовник
          </button>
        </div>
      )}

      <table className="data-table">
        <thead>
          <tr>
            <th>Замовник</th>
            <th>ЄДРПОУ</th>
            <th>Об'єктів</th>
            <th className="num-col">Договорів</th>
            <th className="num-col">Сплачено</th>
            <th className="num-col">Заборгованість</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {clients.map(c => {
            const s = stats(c.id);
            return (
              <tr key={c.id} className="is-clickable" onClick={() => setOpenId(c.id)}>
                <td>
                  <div style={{display: "flex", alignItems: "center", gap: 10}}>
                    <div className="client-avatar">
                      <window.Ico name={c.type === "state" ? "landmark" : c.type === "legal" ? "building" : "user"} />
                    </div>
                    <div>
                      <div className="cell-name">{c.short}</div>
                      <div className="cell-sub">{c.contact.name} · {c.contact.role}</div>
                    </div>
                  </div>
                </td>
                <td className="td-mono" style={{fontSize: 11.5}}>{c.edrpou}</td>
                <td>
                  <span style={{fontVariantNumeric: "tabular-nums", fontWeight: 500}}>{s.objCount}</span>
                </td>
                <td className="num-col">{s.contractCount} <span style={{color: "var(--ink-3)", fontSize: 11.5}}>· {window.formatMoney(s.totalContracts)} ₴</span></td>
                <td className="num-col" style={{color: "var(--c-green-deep)"}}>
                  {window.formatMoney(s.paid)} ₴
                </td>
                <td className="num-col">
                  {s.overdue > 0
                    ? <span className="num-bold" style={{color: "var(--late)"}}>{window.formatMoney(s.overdue)} ₴</span>
                    : s.owed > 0
                      ? <span style={{color: "var(--ink-2)"}}>{window.formatMoney(s.owed)} ₴</span>
                      : <span style={{color: "var(--ink-4)"}}>—</span>
                  }
                </td>
                <td>
                  <button className="btn btn-ghost" style={{padding: "4px 8px", fontSize: 12}}>Відкрити →</button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>

      {openId && <ClientDrawer client={clients.find(c => c.id === openId)} onClose={() => setOpenId(null)} />}
      {wiz && <window.ClientWizard onClose={() => setWiz(false)} />}
    </div>
  );
}

function ClientDrawer({ client, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const contracts = window.DATA.CONTRACTS.filter(c => c.client === client.id);
  const objects = window.DATA.OBJECTS.filter(o => contracts.some(c => c.obj === o.id));
  const invoices = window.DATA.INVOICES.filter(i => i.client === client.id);
  const overdue = invoices.filter(i => i.status === "overdue");
  const paid = invoices.filter(i => i.status === "paid").reduce((s, i) => s + i.amount, 0);
  const [printDraft, setPrintDraft] = React.useState(null);
  const [pickInvoice, setPickInvoice] = React.useState(false);

  return (
    <>
      <div className="drawer-overlay" onClick={onClose}></div>
      <aside className="drawer" style={{width: "min(720px, 96vw)"}}>
        <div className="drawer-head">
          <button className="drawer-close" onClick={onClose}><window.Icon.X /></button>
          <span style={{fontSize: 12, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.06em"}}>
            {client.type === "state" ? "Державний замовник" : client.type === "legal" ? "Юридична особа" : "Фізична особа"}
          </span>
          <div style={{marginLeft: "auto", display: "flex", gap: 2}}>
            {[1,2,3,4,5].map(n =>
              <span key={n} className={`rating-star ${n <= client.rating ? "is-on" : ""}`}>★</span>
            )}
          </div>
        </div>

        <div className="drawer-body">
          <h1 className="drawer-h1">{client.name}</h1>
          <div className="drawer-meta">
            <span>з {window.formatDate(client.since)}</span>
            <span className="task-meta-dot"></span>
            <span>{contracts.length} {window.plural(contracts.length, "договір", "договори", "договорів")}</span>
            <span className="task-meta-dot"></span>
            <span>{objects.length} {window.plural(objects.length, "об'єкт", "об'єкти", "об'єктів")}</span>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Реквізити</div>
            <dl className="info-grid">
              <div><dt>ЄДРПОУ</dt><dd className="td-mono">{client.edrpou}</dd></div>
              <div><dt>Адреса</dt><dd>{client.address}</dd></div>
            </dl>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Контактна особа</div>
            <div className="contact-block">
              <div className="contact-avatar">{client.contact.name.split(" ").map(s => s[0]).slice(0,2).join("")}</div>
              <div style={{flex: 1}}>
                <div className="cell-name">{client.contact.name}</div>
                <div className="cell-sub">{client.contact.role}</div>
              </div>
              <div style={{textAlign: "right", fontSize: 12.5}}>
                <div className="td-mono">{client.contact.phone}</div>
                <a className="td-link" href={`mailto:${client.contact.email}`}>{client.contact.email}</a>
              </div>
            </div>
          </div>

          {client.note && (
            <div className="drawer-section">
              <div className="drawer-section-h">Нотатка</div>
              <div style={{fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5, padding: "10px 14px", background: "var(--bg-sunken)", borderRadius: 8}}>
                {client.note}
              </div>
            </div>
          )}

          <div className="drawer-section">
            <div className="drawer-section-h">Об'єкти</div>
            <div className="mini-list">
              {objects.map(o => (
                <div key={o.id} className="mini-list-item">
                  <span>
                    <span className="td-mono" style={{fontSize: 11.5, color: "var(--ink-3)", marginRight: 8}}>{o.code}</span>
                    {o.name}
                  </span>
                  <span className={`status-tag tone-${o.activeStage === "supervision" ? "neutral" : "live"}`}>
                    {window.getStage(o.activeStage)?.short || o.activeStage}
                  </span>
                </div>
              ))}
            </div>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Договори і рахунки</div>
            <div className="kpi-row" style={{gridTemplateColumns: "repeat(3, 1fr)", marginBottom: 12}}>
              <div className="kpi" style={{padding: "12px 14px"}}>
                <div className="kpi-label">Сплачено</div>
                <div className="kpi-value" style={{fontSize: 20, color: "var(--c-green-deep)"}}>{window.formatMoney(paid)} ₴</div>
              </div>
              <div className={`kpi ${overdue.length > 0 ? "is-warn" : ""}`} style={{padding: "12px 14px"}}>
                <div className="kpi-label">Прострочено</div>
                <div className="kpi-value" style={{fontSize: 20}}>{overdue.length}</div>
              </div>
              <div className="kpi" style={{padding: "12px 14px"}}>
                <div className="kpi-label">Договорів</div>
                <div className="kpi-value" style={{fontSize: 20}}>{contracts.length}</div>
              </div>
            </div>
          </div>
        </div>

        <div className="drawer-foot">
          <button className="btn btn-primary">Новий договір</button>
          <button className="btn" onClick={() => setPickInvoice(true)} disabled={contracts.length === 0} style={contracts.length === 0 ? {opacity: 0.5, pointerEvents: "none"} : {}}>Виставити рахунок</button>
        </div>
      </aside>
      {pickInvoice && <window.InvoiceContractPicker
        contracts={contracts}
        onClose={() => setPickInvoice(false)}
        onPick={(draft) => { setPickInvoice(false); setPrintDraft(draft); }}
      />}
      {printDraft && <window.InvoicePrintDoc invoice={printDraft} onClose={() => setPrintDraft(null)} />}
    </>
  );
}

// ============ ДОГОВОРИ ============
function ContractsPage({ role, tasks, onCreateTasks, onGoToTasks }) {
  window.useCounterparties && window.useCounterparties();
  const contracts = window.DATA.CONTRACTS;
  const [openId, setOpenId] = React.useState(null);
  const [filter, setFilter] = React.useState("active");
  const [wiz, setWiz] = React.useState(false);
  const [printId, setPrintId] = React.useState(null);
  const canEdit = role === "director" || role === "accountant";

  const filtered = filter === "all" ? contracts
                 : filter === "active" ? contracts.filter(c => c.status === "active")
                 : filter === "projects" ? []
                 : contracts.filter(c => c.status === filter);

  const goProjects = window.DATA.PROJECTS || [];
  const showProjects = filter === "all" || filter === "projects";

  const totalsAll = contracts.reduce((s, c) => s + c.total, 0);
  const paidAll = window.DATA.INVOICES.filter(i => i.status === "paid").reduce((s, i) => s + i.amount, 0);

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Договори</h1>
        <div className="page-sub">
          <span>{contracts.length} {window.plural(contracts.length, "договір", "договори", "договорів")}</span>
          {goProjects.length > 0 && <>
            <span className="dot"></span>
            <span>+ {goProjects.length} {window.plural(goProjects.length, "проєкт ГО", "проєкти ГО", "проєктів ГО")}</span>
          </>}
          <span className="dot"></span>
          <span>загальна сума <b style={{color: "var(--ink)"}}>{window.formatMoney(totalsAll)} ₴</b></span>
          <span className="dot"></span>
          <span>сплачено {Math.round(paidAll / totalsAll * 100)}%</span>
        </div>
      </div>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${filter === "active" ? "is-active" : ""}`} onClick={() => setFilter("active")}>Активні</button>
          <button className={`filter-pill-item ${filter === "supervision" ? "is-active" : ""}`} onClick={() => setFilter("supervision")}>Авт. нагляд</button>
          <button className={`filter-pill-item ${filter === "projects" ? "is-active" : ""}`} onClick={() => setFilter("projects")}>Проєкти ГО{goProjects.length > 0 && <span className="filter-pill-count">{goProjects.length}</span>}</button>
          <button className={`filter-pill-item ${filter === "all" ? "is-active" : ""}`} onClick={() => setFilter("all")}>Усі</button>
        </div>
        <button className="btn btn-primary" style={{marginLeft: "auto"}} onClick={() => setWiz(true)}>
          <window.Icon.Plus /> Новий договір
        </button>
      </div>

      <div className="contract-stack">
        {filtered.map(c => (
          <ContractCard
            key={c.id}
            contract={c}
            isOpen={openId === c.id}
            onToggle={() => setOpenId(openId === c.id ? null : c.id)}
            tasks={tasks}
            onCreateTasks={onCreateTasks}
            onGoToTasks={onGoToTasks}
          />
        ))}
        {showProjects && goProjects.length > 0 && (
          <React.Fragment>
            {filter === "all" && <div style={{ marginTop: filtered.length ? 10 : 0, fontSize: 11.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--ink-3)" }}>Проєктна діяльність · ГО / грантові</div>}
            {goProjects.map(p => (
              <window.ProjectContractCard
                key={p.id}
                project={p}
                isOpen={openId === p.id}
                onToggle={() => setOpenId(openId === p.id ? null : p.id)}
              />
            ))}
          </React.Fragment>
        )}
      </div>

      {wiz && <window.ContractWizard onClose={(rec, openBlank) => { setWiz(false); if (rec) { if (openBlank) setPrintId(rec.id); else setOpenId(rec.id); } }} />}
      {printId && <window.ContractPrintDoc contract={window.getContract(printId)} onClose={() => setPrintId(null)} />}
    </div>
  );
}

function ContractCard({ contract, isOpen, onToggle, tasks, onCreateTasks, onGoToTasks }) {
  const client = window.getClient(contract.client);
  const obj = window.getObject(contract.obj);
  const status = window.CONTRACT_STATUS[contract.status];
  const [printDraft, setPrintDraft] = React.useState(null);
  const [printAct, setPrintAct] = React.useState(null);
  const [printContract, setPrintContract] = React.useState(false);

  const paid = contract.schedule.filter(s => s.paidDate).reduce((sum, s) => sum + s.amount, 0);
  const total = contract.total;
  const progressPct = Math.round(paid / total * 100);

  // підрахунок прострочених
  const today = "2026-05-26";
  const overdueItems = contract.schedule.filter(s => !s.paidDate && s.dueDate < today);

  return (
    <div className={`contract-card ${isOpen ? "is-open" : ""}`}>
      {printContract && <window.ContractPrintDoc contract={contract} onClose={() => setPrintContract(false)} />}
      <div className="contract-card-head" onClick={onToggle}>
        <div className="contract-num">
          <div className="contract-num-val">№ {contract.number}</div>
          <div className="contract-num-date">{window.formatDate(contract.date)}</div>
        </div>
        <div className="contract-main">
          <div className="contract-name">
            {obj?.name} <span style={{fontWeight: 400, color: "var(--ink-3)"}}>· {obj?.code}</span>
          </div>
          <div className="contract-meta">
            <span>{client?.short}</span>
            <span className="dot"></span>
            <span>{contract.schedule.length} {window.plural(contract.schedule.length, "етап", "етапи", "етапів")}</span>
            {overdueItems.length > 0 && <>
              <span className="dot"></span>
              <span style={{color: "var(--late)"}}>{overdueItems.length} прострочено</span>
            </>}
          </div>
        </div>
        <div className="contract-amount">
          <div className="contract-amount-val">{window.formatMoney(total)} <span style={{color: "var(--ink-3)", fontWeight: 500, fontSize: 13}}>₴</span></div>
          <div className="contract-amount-paid">сплачено {window.formatMoney(paid)} ₴</div>
        </div>
        <span className={`status-tag tone-${status.tone}`}>{status.label}</span>
        <button className="btn btn-sm" title="Друкований договір" onClick={(e) => { e.stopPropagation(); setPrintContract(true); }}>
          <window.Ico name="file" /> Договір
        </button>
        <button className="obj-card-toggle">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{transform: isOpen ? "rotate(180deg)" : "none", transition: "transform 0.2s"}}>
            <path d="M3 5L7 9L11 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      <div className="obj-overall">
        <div className="obj-overall-bar">
          <div className="obj-overall-fill" style={{width: progressPct + "%"}}></div>
        </div>
        <div className="obj-overall-meta">
          <span>{paid > 0 ? `сплачено ${progressPct}%` : "очікує першого платежу"}</span>
          <span>{window.formatMoney(paid)} / {window.formatMoney(total)} ₴</span>
        </div>
      </div>

      {isOpen && (
        <div className="contract-schedule">
          {contract.status === "supervision" && window.SupervisionBlock && (
            <window.SupervisionBlock
              contract={contract}
              tasks={tasks}
              onCreateTasks={onCreateTasks}
              onGoToTasks={onGoToTasks}
              onPrintAct={(a) => setPrintAct(a)}
            />
          )}
          <window.ContractSchedule
            contract={contract}
            role={window.__role}
            onPrintInvoice={(d) => setPrintDraft(d)}
            onPrintAct={(a) => setPrintAct(a)}
          />
          <div className="contract-actions">
            <button className="btn btn-ghost"><window.Ico name="externalLink" size={14} /> Відкрити в Drive</button>
          </div>
        </div>
      )}
      {printDraft && <window.InvoicePrintDoc invoice={printDraft} onClose={() => setPrintDraft(null)} />}
      {printAct && <window.ActPrintDoc act={printAct} onClose={() => setPrintAct(null)} />}
    </div>
  );
}

// ============ ДЕБІТОРКА / РАХУНКИ ============
function ReceivablesPage({ role }) {
  const invoices = window.DATA.INVOICES;
  const today = "2026-05-26";
  const [printInv, setPrintInv] = React.useState(null);

  const [filter, setFilter] = React.useState("active");
  const active   = invoices.filter(i => i.status !== "paid");
  const overdue  = invoices.filter(i => i.status === "overdue");
  const upcoming = invoices.filter(i => i.status === "issued" && window.daysBetween(today, i.dueDate) <= 30);
  const paid     = invoices.filter(i => i.status === "paid");

  const overdueSum  = overdue.reduce((s, i) => s + i.amount, 0);
  const upcomingSum = active.filter(i => i.status === "issued").reduce((s, i) => s + i.amount, 0);
  const paidSum     = paid.reduce((s, i) => s + i.amount, 0);

  const shown = filter === "overdue" ? overdue
              : filter === "upcoming" ? upcoming
              : filter === "paid" ? paid
              : active;

  // Cash flow plan по тижнях найближчого місяця
  const cashflow = buildCashflow(active, today);

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Рахунки і дебіторка</h1>
        <div className="page-sub">
          <span>{active.length} {window.plural(active.length, "відкритий", "відкриті", "відкритих")}</span>
          {overdue.length > 0 && <>
            <span className="dot"></span>
            <span style={{color: "var(--late)"}}>{overdue.length} прострочено</span>
          </>}
        </div>
      </div>

      <div className="kpi-row" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
        <div className={`kpi ${overdueSum > 0 ? "is-warn" : ""}`}>
          <div className="kpi-label">Дебіторка</div>
          <div className="kpi-value">{window.formatMoney(overdueSum)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{overdue.length} прострочених рахунків</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Очікується</div>
          <div className="kpi-value">{window.formatMoney(upcomingSum)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{active.length - overdue.length} рахунків у графіку</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Сплачено</div>
          <div className="kpi-value" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(paidSum)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{paid.length} закритих рахунків</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Сер. час оплати</div>
          <div className="kpi-value">{avgPaymentDays(paid)} <span style={{fontSize: 16, color: "var(--ink-3)"}}>дн.</span></div>
          <div className="kpi-sub">від виставлення до оплати</div>
        </div>
      </div>

      {/* Cash flow прогноз */}
      <section className="section">
        <div className="section-head">
          <h2 className="section-h2">Прогноз надходжень</h2>
          <span className="section-sub">найближчі 12 тижнів</span>
        </div>
        <div className="cashflow-chart">
          {cashflow.map((w, idx) => (
            <div key={idx} className={`cashflow-col ${w.overdue ? "is-overdue" : ""}`}>
              <div className="cashflow-val">{w.sum > 0 ? Math.round(w.sum / 1000) + "k" : ""}</div>
              <div className="cashflow-track">
                <div className="cashflow-fill" style={{height: w.sum > 0 ? Math.max(8, w.sum / cashflow.reduce((m, x) => Math.max(m, x.sum), 1) * 100) + "%" : "0%"}}></div>
              </div>
              <div className="cashflow-label">{w.label}</div>
            </div>
          ))}
        </div>
      </section>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${filter === "active" ? "is-active" : ""}`} onClick={() => setFilter("active")}>
            Активні <span className="filter-pill-count">{active.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "overdue" ? "is-active" : ""}`} onClick={() => setFilter("overdue")}>
            Прострочено <span className="filter-pill-count">{overdue.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "upcoming" ? "is-active" : ""}`} onClick={() => setFilter("upcoming")}>
            Найближчі <span className="filter-pill-count">{upcoming.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "paid" ? "is-active" : ""}`} onClick={() => setFilter("paid")}>
            Сплачено <span className="filter-pill-count">{paid.length}</span>
          </button>
        </div>
        <button className="btn btn-primary" style={{marginLeft: "auto"}}>
          <window.Icon.Plus /> Новий рахунок
        </button>
      </div>

      <table className="data-table">
        <thead>
          <tr>
            <th>№ рахунку</th>
            <th>Замовник / об'єкт</th>
            <th>Етап</th>
            <th>Виставлено</th>
            <th>Термін</th>
            <th className="num-col">Сума</th>
            <th>Статус</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {shown.map(inv => {
            const client = window.getClient(inv.client);
            const obj = window.getObject(inv.obj);
            const daysUntil = window.daysBetween(today, inv.dueDate);
            return (
              <tr key={inv.id} className={`is-clickable ${inv.status === "overdue" ? "row-overdue" : ""}`}>
                <td className="td-mono">№ {inv.number}</td>
                <td>
                  <div className="cell-name">{client?.short}</div>
                  <div className="cell-sub">{obj?.code} · {obj?.name}</div>
                </td>
                <td style={{fontSize: 12.5, color: "var(--ink-2)"}}>{inv.title}</td>
                <td className="td-mono" style={{fontSize: 12}}>{window.formatDate(inv.issueDate)}</td>
                <td>
                  <div className="td-mono" style={{fontSize: 12}}>{window.formatDate(inv.dueDate)}</div>
                  {inv.status === "issued" && daysUntil >= 0 && daysUntil <= 7 &&
                    <div style={{fontSize: 11, color: "var(--ink-3)"}}>через {daysUntil} {window.plural(daysUntil, "день", "дні", "днів")}</div>
                  }
                  {inv.status === "overdue" &&
                    <div style={{fontSize: 11, color: "var(--late)", fontWeight: 600}}>+{inv.lateDays} {window.plural(inv.lateDays, "день", "дні", "днів")}</div>
                  }
                  {inv.status === "paid" && inv.paidDate &&
                    <div style={{fontSize: 11, color: "var(--c-green-deep)"}}>сплачено {window.formatDate(inv.paidDate)}</div>
                  }
                </td>
                <td className="num-col num-bold">{window.formatMoney(inv.amount)} ₴</td>
                <td>
                  {inv.status === "paid"    && <span className="status-tag tone-live">сплачено</span>}
                  {inv.status === "overdue" && <span className="status-tag tone-warn">прострочено</span>}
                  {inv.status === "issued"  && <span className="status-tag tone-neutral">виставлено</span>}
                </td>
                <td>
                  <div style={{display: "flex", alignItems: "center", gap: 6, justifyContent: "flex-end"}}>
                    <button
                      className="btn btn-ghost"
                      style={{padding: "4px 8px", fontSize: 12, display: "inline-flex", alignItems: "center", gap: 5, whiteSpace: "nowrap"}}
                      title="Друк рахунку на оплату"
                      onClick={(e) => { e.stopPropagation(); setPrintInv(inv); }}
                    >
                      <window.InvPrintIcon /> Друк рахунку
                    </button>
                    <button className="btn btn-ghost" style={{padding: "4px 8px", fontSize: 12, whiteSpace: "nowrap"}}>
                      {inv.status === "overdue" ? "Нагадати →" : "Деталі →"}
                    </button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
        {shown.length === 0 && (
          <tbody><tr><td colSpan={8} className="empty">Немає рахунків у цій категорії.</td></tr></tbody>
        )}
      </table>

      {printInv && <window.InvoicePrintDoc invoice={printInv} onClose={() => setPrintInv(null)} />}
    </div>
  );
}

// helpers
function avgPaymentDays(paid) {
  const days = paid.map(i => window.daysBetween(i.issueDate, i.paidDate));
  if (days.length === 0) return 0;
  return Math.round(days.reduce((s,d) => s + d, 0) / days.length);
}
function buildCashflow(active, today) {
  // 12 тижнів з сьогодні
  const weeks = [];
  const todayD = new Date(today);
  for (let i = -2; i < 10; i++) {
    const start = new Date(todayD);
    start.setDate(start.getDate() + i * 7);
    weeks.push({
      start: start.toISOString().slice(0, 10),
      end: new Date(start.getTime() + 6 * 86400000).toISOString().slice(0, 10),
      label: i === 0 ? "цей" : i === 1 ? "наст." : `${start.getDate()}.${String(start.getMonth()+1).padStart(2,'0')}`,
      sum: 0, overdue: false
    });
  }
  active.forEach(inv => {
    weeks.forEach(w => {
      if (inv.dueDate >= w.start && inv.dueDate <= w.end) {
        w.sum += inv.amount;
        if (inv.status === "overdue") w.overdue = true;
      }
    });
  });
  return weeks;
}

window.ClientsPage = ClientsPage;
window.ContractsPage = ContractsPage;
window.ReceivablesPage = ReceivablesPage;
