// phase3-pages.jsx — P&L · Виплати підрядникам · Авансові звіти

// ============ P&L ============
function PnlPage({ role }) {
  const contracts = window.DATA.CONTRACTS;
  const invoices = window.DATA.INVOICES;
  const expenses = window.DATA.EXPENSES;
  const team = window.DATA.TEAM;
  const subPayments = window.DATA.SUB_PAYMENTS;

  const [period, setPeriod] = React.useState("month");

  // Спрощений розрахунок P&L
  const grossIncome = invoices.filter(i => i.status === "paid").reduce((s, i) => s + i.amount, 0);
  const subIncome = grossIncome * 0.84; // без ПДВ
  const pdvOut = grossIncome - subIncome;

  const monthlyExpenses = expenses.reduce((s, e) => s + (e.monthlyAmount || 0), 0);
  const salary = team.reduce((s, p) => {
    const pay = window.computePayroll(p.id, p.partRate ? 88 : 176, 176);
    return s + (pay?.gross || 0);
  }, 0);
  const subCosts = subPayments.filter(p => p.status === "paid").reduce((s, p) => s + p.amount, 0);
  const period_mult = period === "month" ? 1 : period === "quarter" ? 3 : 12;

  const revenue = subIncome;
  const directCosts = salary + subCosts * 0.2; // примірний розподіл
  const grossProfit = revenue - directCosts;
  const opex = monthlyExpenses * period_mult;
  const ebitda = grossProfit - opex;
  const taxes = ebitda > 0 ? ebitda * 0.05 : 0;
  const netProfit = ebitda - taxes;

  const margin = revenue > 0 ? (netProfit / revenue) * 100 : 0;

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">P&L · Звіт про прибутки і збитки</h1>
        <div className="page-sub">
          <span>фінансовий результат компанії</span>
          <span className="dot"></span>
          <span>{period === "month" ? "травень 2026" : period === "quarter" ? "Q2 2026" : "2026 рік"}</span>
        </div>
      </div>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${period === "month" ? "is-active" : ""}`} onClick={() => setPeriod("month")}>Місяць</button>
          <button className={`filter-pill-item ${period === "quarter" ? "is-active" : ""}`} onClick={() => setPeriod("quarter")}>Квартал</button>
          <button className={`filter-pill-item ${period === "year" ? "is-active" : ""}`} onClick={() => setPeriod("year")}>Рік</button>
        </div>
        <div style={{marginLeft: "auto", display: "flex", gap: 8}}>
          <button className="btn">Експорт Excel</button>
          <button className="btn btn-primary">PDF звіт</button>
        </div>
      </div>

      <div className="kpi-row" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
        <div className="kpi">
          <div className="kpi-label">Виторг</div>
          <div className="kpi-value" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(Math.round(revenue))} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">без ПДВ</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Витрати разом</div>
          <div className="kpi-value">{window.formatMoney(Math.round(directCosts + opex))} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">прямі + опер.</div>
        </div>
        <div className={`kpi ${netProfit < 0 ? "is-warn" : ""}`}>
          <div className="kpi-label">Чистий прибуток</div>
          <div className="kpi-value" style={{color: netProfit >= 0 ? "var(--c-green-deep)" : "var(--late)"}}>
            {netProfit >= 0 ? "+" : ""}{window.formatMoney(Math.round(netProfit))} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span>
          </div>
          <div className="kpi-sub">після податків</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Маржа</div>
          <div className="kpi-value">{margin.toFixed(1)}%</div>
          <div className="kpi-sub">net / revenue</div>
        </div>
      </div>

      <section className="section">
        <div className="section-head">
          <h2 className="section-h2">Деталізація</h2>
          <span className="section-sub">за {period === "month" ? "травень 2026" : period === "quarter" ? "Q2 2026" : "2026 рік"}</span>
        </div>
        <div className="payroll-breakdown" style={{background: "var(--bg-elev)", border: "1px solid var(--line)"}}>
          <div className="pb-row pb-base">
            <span className="pb-label">Виторг (gross, з ПДВ)</span>
            <span className="pb-val num-bold">{window.formatMoney(grossIncome)} ₴</span>
          </div>
          <div className="pb-row pb-deduct">
            <span className="pb-label">− ПДВ 20%</span>
            <span className="pb-val">−{window.formatMoney(Math.round(pdvOut))} ₴</span>
          </div>
          <div className="pb-row pb-sum">
            <span className="pb-label">Виторг (net, без ПДВ)</span>
            <span className="pb-val num-bold">{window.formatMoney(Math.round(revenue))} ₴</span>
          </div>
          <div className="pb-row pb-deduct">
            <span className="pb-label">Оплата праці (gross)</span>
            <span className="pb-val">−{window.formatMoney(Math.round(salary))} ₴</span>
          </div>
          <div className="pb-row pb-deduct">
            <span className="pb-label">Виплати підрядникам</span>
            <span className="pb-val">−{window.formatMoney(Math.round(subCosts * 0.2))} ₴</span>
          </div>
          <div className="pb-row pb-sub">
            <span className="pb-label">Валовий прибуток</span>
            <span className="pb-val num-bold" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(Math.round(grossProfit))} ₴</span>
          </div>
          <div className="pb-row pb-deduct">
            <span className="pb-label">Операційні витрати (АДМ/ЗВВ)</span>
            <span className="pb-val">−{window.formatMoney(Math.round(opex))} ₴</span>
          </div>
          <div className="pb-row pb-sub">
            <span className="pb-label">EBITDA</span>
            <span className="pb-val num-bold">{window.formatMoney(Math.round(ebitda))} ₴</span>
          </div>
          <div className="pb-row pb-deduct">
            <span className="pb-label">Єдиний податок 5%</span>
            <span className="pb-val">−{window.formatMoney(Math.round(taxes))} ₴</span>
          </div>
          <div className="pb-row pb-final">
            <span className="pb-label">Чистий прибуток</span>
            <span className="pb-val">{window.formatMoney(Math.round(netProfit))} ₴</span>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="section-head">
          <h2 className="section-h2">Прибутковість по об'єктах</h2>
          <span className="section-sub">маржа по кожному договору</span>
        </div>
        <table className="data-table compact-table">
          <thead>
            <tr>
              <th>Об'єкт</th>
              <th className="num-col">Договір</th>
              <th className="num-col">Сплачено</th>
              <th className="num-col">Витрати</th>
              <th className="num-col">Прибуток</th>
              <th>Маржа</th>
            </tr>
          </thead>
          <tbody>
            {contracts.map(c => {
              const obj = window.getObject(c.obj);
              const paid = c.schedule.filter(s => s.paidDate).reduce((sum, s) => sum + s.amount, 0);
              const costs = Math.round(c.total * 0.4);
              const profit = paid - costs;
              const pct = c.total > 0 ? (profit / c.total) * 100 : 0;
              return (
                <tr key={c.id}>
                  <td>
                    <div className="cell-name">{obj?.name}</div>
                    <div className="cell-sub td-mono" style={{fontSize: 11}}>{obj?.code}</div>
                  </td>
                  <td className="num-col">{window.formatMoney(c.total)} ₴</td>
                  <td className="num-col" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(paid)} ₴</td>
                  <td className="num-col" style={{color: "var(--ink-3)"}}>{window.formatMoney(costs)} ₴</td>
                  <td className="num-col num-bold" style={{color: profit >= 0 ? "var(--c-green-deep)" : "var(--late)"}}>
                    {profit >= 0 ? "+" : ""}{window.formatMoney(profit)} ₴
                  </td>
                  <td>
                    <div className="load-bar">
                      <span className="load-bar-val">{pct.toFixed(0)}%</span>
                      <div className="load-bar-track">
                        <div className="load-bar-fill" style={{width: Math.min(pct, 100) + "%", background: pct >= 30 ? "var(--c-green-deep)" : pct >= 0 ? "var(--c-orange, var(--c-green))" : "var(--late)"}}></div>
                      </div>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </section>
    </div>
  );
}

// ============ ВИПЛАТИ ПІДРЯДНИКАМ ============
function SubPaymentsPage({ role }) {
  const payments = window.DATA.SUB_PAYMENTS;
  const [filter, setFilter] = React.useState("active");

  const paid    = payments.filter(p => p.status === "paid");
  const issued  = payments.filter(p => p.status === "issued");
  const overdue = payments.filter(p => p.status === "overdue");

  const totalPaid    = paid.reduce((s, p) => s + p.amount, 0);
  const totalIssued  = issued.reduce((s, p) => s + p.amount, 0);
  const totalOverdue = overdue.reduce((s, p) => s + p.amount, 0);

  let shown = payments;
  if (filter === "active") shown = [...overdue, ...issued];
  else if (filter === "paid") shown = paid;
  else if (filter === "overdue") shown = overdue;

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Виплати підрядникам</h1>
        <div className="page-sub">
          <span>{payments.length} {window.plural(payments.length, "рахунок", "рахунки", "рахунків")}</span>
          {overdue.length > 0 && <>
            <span className="dot"></span>
            <span style={{color: "var(--late)"}}>{overdue.length} прострочено</span>
          </>}
          <span className="dot"></span>
          <span>виплачено за рік <b style={{color: "var(--ink)"}}>{window.formatMoney(totalPaid)} ₴</b></span>
        </div>
      </div>

      <div className="kpi-row" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
        <div className={`kpi ${overdue.length > 0 ? "is-warn" : ""}`}>
          <div className="kpi-label">Прострочено</div>
          <div className="kpi-value" style={{color: "var(--late)"}}>{window.formatMoney(totalOverdue)} <span style={{fontSize: 14, 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(totalIssued)} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{issued.length} в графіку</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Сплачено</div>
          <div className="kpi-value" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(totalPaid)} <span style={{fontSize: 14, 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">{issued.length + overdue.length}</div>
          <div className="kpi-sub">потребують оплати</div>
        </div>
      </div>

      <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">{issued.length + overdue.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 === "paid" ? "is-active" : ""}`} onClick={() => setFilter("paid")}>
            Сплачено <span className="filter-pill-count">{paid.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "all" ? "is-active" : ""}`} onClick={() => setFilter("all")}>
            Усі <span className="filter-pill-count">{payments.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(p => {
            const sup = window.DATA.SUPPLIERS.find(s => s.id === p.supplier);
            const obj = window.getObject(p.obj);
            const cType = window.CONTRACT_TYPE_LABELS[p.contractType];
            return (
              <tr key={p.id} className={`is-clickable ${p.status === "overdue" ? "row-overdue" : ""}`}>
                <td className="td-mono">{p.invoiceNumber}</td>
                <td>
                  <div className="cell-name">{sup?.name}</div>
                  <div className="cell-sub">{p.description.substring(0, 50)}{p.description.length > 50 ? "..." : ""}</div>
                </td>
                <td className="td-mono" style={{fontSize: 11.5, color: "var(--ink-3)"}}>{obj?.code}</td>
                <td>
                  <span className="empl-chip empl-staff" style={{fontSize: 9.5}}>{cType.short}</span>
                  {p.pdvIncluded > 0 && <div style={{fontSize: 10, color: "var(--ink-3)", marginTop: 4}}>ПДВ {window.formatMoney(p.pdvIncluded)} ₴</div>}
                </td>
                <td>
                  <div className="td-mono" style={{fontSize: 12}}>{window.formatDate(p.dueDate)}</div>
                  {p.status === "overdue" && <div style={{fontSize: 11, color: "var(--late)", fontWeight: 600}}>+{p.lateDays} дн.</div>}
                  {p.status === "paid" && p.paidDate && <div style={{fontSize: 11, color: "var(--c-green-deep)"}}>сплачено {window.formatDate(p.paidDate)}</div>}
                </td>
                <td className="num-col num-bold">{window.formatMoney(p.amount)} ₴</td>
                <td>
                  {p.status === "paid"    && <span className="status-tag tone-live">сплачено</span>}
                  {p.status === "overdue" && <span className="status-tag tone-warn">прострочено</span>}
                  {p.status === "issued"  && <span className="status-tag tone-neutral">очікує</span>}
                </td>
                <td>
                  <button className="btn btn-ghost" style={{padding: "4px 8px", fontSize: 12}}>
                    {p.status === "overdue" || p.status === "issued" ? "Оплатити →" : "Деталі →"}
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ============ АВАНСОВІ ЗВІТИ ============
function AdvancesPage({ role }) {
  const reports = window.DATA.ADVANCE_REPORTS;
  const [openId, setOpenId] = React.useState(null);
  const [filter, setFilter] = React.useState("pending");

  const pending  = reports.filter(r => r.status === "pending");
  const approved = reports.filter(r => r.status === "approved");
  const rejected = reports.filter(r => r.status === "rejected");

  let shown = reports;
  if (filter === "pending")  shown = pending;
  else if (filter === "approved") shown = approved;
  else if (filter === "rejected") shown = rejected;

  const totalApproved = approved.reduce((s, r) => s + r.amount, 0);
  const totalPending  = pending.reduce((s, r) => s + r.amount, 0);

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Авансові звіти</h1>
        <div className="page-sub">
          <span>відрядження, дрібні витрати з власних коштів</span>
          {pending.length > 0 && <>
            <span className="dot"></span>
            <span style={{color: "var(--c-green-deep)"}}>{pending.length} {window.plural(pending.length, "очікує", "очікують", "очікують")} затвердження</span>
          </>}
        </div>
      </div>

      <div className="kpi-row" style={{gridTemplateColumns: "repeat(3, 1fr)"}}>
        <div className={`kpi ${pending.length > 0 ? "is-warn" : ""}`}>
          <div className="kpi-label">На розгляді</div>
          <div className="kpi-value">{window.formatMoney(totalPending)} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{pending.length} {window.plural(pending.length, "звіт", "звіти", "звітів")}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Затверджено (рік)</div>
          <div className="kpi-value" style={{color: "var(--c-green-deep)"}}>{window.formatMoney(totalApproved)} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">{approved.length} {window.plural(approved.length, "звіт", "звіти", "звітів")}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Відхилено</div>
          <div className="kpi-value" style={{color: "var(--ink)"}}>{rejected.length}</div>
          <div className="kpi-sub">не відповідає політиці</div>
        </div>
      </div>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${filter === "pending" ? "is-active" : ""}`} onClick={() => setFilter("pending")}>
            На розгляді <span className="filter-pill-count">{pending.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "approved" ? "is-active" : ""}`} onClick={() => setFilter("approved")}>
            Затверджено <span className="filter-pill-count">{approved.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "rejected" ? "is-active" : ""}`} onClick={() => setFilter("rejected")}>
            Відхилено <span className="filter-pill-count">{rejected.length}</span>
          </button>
          <button className={`filter-pill-item ${filter === "all" ? "is-active" : ""}`} onClick={() => setFilter("all")}>
            Усі <span className="filter-pill-count">{reports.length}</span>
          </button>
        </div>
        <button className="btn btn-primary" style={{marginLeft: "auto"}}>
          <window.Icon.Plus /> Подати звіт
        </button>
      </div>

      <div className="lead-stack">
        {shown.map(r => <AdvanceCard key={r.id} report={r} onOpen={() => setOpenId(r.id)} />)}
      </div>

      {openId && <AdvanceDrawer report={reports.find(r => r.id === openId)} onClose={() => setOpenId(null)} />}
    </div>
  );
}

function AdvanceCard({ report, onOpen }) {
  const person = window.getTeam(report.who);
  const status = window.ADVANCE_STATUS[report.status];

  return (
    <div className="lead-card" onClick={onOpen} style={{borderLeft: report.status === "pending" ? "3px solid var(--accent)" : report.status === "rejected" ? "3px solid var(--late)" : "3px solid var(--c-green-deep)"}}>
      <div className="lead-card-head">
        <div className="lead-card-stage">
          <span className={`status-tag tone-${status.tone}`}>{status.label}</span>
        </div>
        <div className="team-avatar" style={{width: 32, height: 32, fontSize: 11}}>{person?.initials}</div>
      </div>
      <div className="lead-card-name" style={{fontSize: 14}}>{report.title}</div>
      <div className="lead-card-meta">
        <span>{person?.name}</span>
        <span className="dot"></span>
        <span>{window.formatDate(report.date)}</span>
        <span className="dot"></span>
        <span>{report.items.length} {window.plural(report.items.length, "позиція", "позиції", "позицій")}</span>
      </div>
      <div className="lead-card-foot">
        <div className="lead-value">
          <div className="lead-value-label">сума</div>
          <div className="lead-value-num">{window.formatMoney(report.amount)} <span>₴</span></div>
        </div>
        <div className="lead-action">
          {report.status === "pending"
            ? <span style={{fontSize: 12, color: "var(--accent)"}}>чекає затвердження</span>
            : report.status === "rejected"
              ? <span style={{fontSize: 12, color: "var(--late)"}}>{report.rejectReason?.substring(0, 60)}…</span>
              : <span style={{fontSize: 12, color: "var(--c-green-deep)"}}>повернено: {window.formatDate(report.approvedDate)}</span>
          }
        </div>
      </div>
    </div>
  );
}

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

  const person = window.getTeam(report.who);
  const status = window.ADVANCE_STATUS[report.status];

  return (
    <>
      <div className="drawer-overlay" onClick={onClose}></div>
      <aside className="drawer">
        <div className="drawer-head">
          <button className="drawer-close" onClick={onClose}><window.Icon.X /></button>
          <span className={`status-tag tone-${status.tone}`}>{status.label}</span>
          <span style={{marginLeft: "auto", fontSize: 11, color: "var(--ink-3)"}}>{report.id}</span>
        </div>
        <div className="drawer-body">
          <h1 className="drawer-h1">{report.title}</h1>
          <div className="drawer-meta">
            <div className="team-avatar" style={{width: 24, height: 24, fontSize: 9}}>{person?.initials}</div>
            <span>{person?.name}</span>
            <span className="task-meta-dot"></span>
            <span>{window.formatDate(report.date)}</span>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Позиції витрат</div>
            <table className="data-table compact-table">
              <thead>
                <tr><th>Що</th><th className="num-col">Сума</th></tr>
              </thead>
              <tbody>
                {report.items.map((it, i) => (
                  <tr key={i}>
                    <td>{it.what}</td>
                    <td className="num-col num-bold">{window.formatMoney(it.amount)} ₴</td>
                  </tr>
                ))}
                <tr>
                  <td><b>Усього</b></td>
                  <td className="num-col num-bold" style={{fontSize: 16, color: "var(--c-green-deep)"}}>{window.formatMoney(report.amount)} ₴</td>
                </tr>
              </tbody>
            </table>
          </div>

          {report.rejectReason && (
            <div className="drawer-section">
              <div className="drawer-section-h">Причина відхилення</div>
              <div style={{fontSize: 13, color: "var(--late)", padding: "12px 14px", background: "var(--late-bg)", borderRadius: 8}}>
                {report.rejectReason}
              </div>
            </div>
          )}

          {report.approvedDate && (
            <div className="drawer-section">
              <div className="drawer-section-h">Хронологія</div>
              <dl className="info-grid">
                <div><dt>Подано</dt><dd>{window.formatDate(report.date)}</dd></div>
                <div><dt>{report.status === "approved" ? "Затверджено" : "Відхилено"}</dt><dd>{window.formatDate(report.approvedDate)}</dd></div>
              </dl>
            </div>
          )}
        </div>
        <div className="drawer-foot">
          {report.status === "pending" ? (
            <>
              <button className="btn btn-primary">Затвердити</button>
              <button className="btn" style={{color: "var(--late)"}}>Відхилити</button>
            </>
          ) : (
            <button className="btn">Переглянути чеки</button>
          )}
        </div>
      </aside>
    </>
  );
}

window.PnlPage = PnlPage;
window.SubPaymentsPage = SubPaymentsPage;
window.AdvancesPage = AdvancesPage;
