// dashboard-page.jsx — Головний дашборд директора

function DashboardPage({ role, tasks, onNewTask, user }) {
  const today = window.SYS_DATE || "2026-05-26";  // жива дата з бекенду
  // Рядок дати/часу — з живої дати + поточного часу браузера (Київ для команди в Україні).
  const _WD = ["неділя", "понеділок", "вівторок", "середа", "четвер", "п'ятниця", "субота"];
  const _MO = ["січня", "лютого", "березня", "квітня", "травня", "червня", "липня", "серпня", "вересня", "жовтня", "листопада", "грудня"];
  const _dt = new Date(today + "T00:00:00");
  const _now = new Date();
  const nowHHMM = String(_now.getHours()).padStart(2, "0") + ":" + String(_now.getMinutes()).padStart(2, "0");
  const dateLine = `${_WD[_dt.getDay()]} · ${_dt.getDate()} ${_MO[_dt.getMonth()]} ${_dt.getFullYear()} · ${nowHHMM}`;
  const team = window.DATA.TEAM;
  const objects = window.DATA.OBJECTS;
  const contracts = window.DATA.CONTRACTS;
  const invoices = window.DATA.INVOICES;
  const expenses = window.DATA.EXPENSES;
  const leads = window.DATA.LEADS;
  const accounts = window.DATA.CASH_ACCOUNTS;
  const [printDraft, setPrintDraft] = React.useState(null);
  const [pickInvoice, setPickInvoice] = React.useState(false);
  const [pickAct, setPickAct] = React.useState(false);
  const [printAct, setPrintAct] = React.useState(null);

  // Аналітика
  const totalBalance = accounts.reduce((s, a) => s + (a.currency === "UAH" ? a.balance : a.balance * 41.5), 0);
  const overdueInv = invoices.filter(i => i.status === "overdue");
  const overdueSum = overdueInv.reduce((s, i) => s + i.amount, 0);
  const paidSum = invoices.filter(i => i.status === "paid").reduce((s, i) => s + i.amount, 0);
  const monthlyExpenses = expenses.reduce((s, e) => s + (e.monthlyAmount || 0), 0);
  const totalSalary = team.reduce((s, p) => {
    const pay = window.computePayroll(p.id, p.partRate ? 88 : 176, 176);
    return s + (pay?.net || 0);
  }, 0);
  const todayTasks = tasks.filter(t => t.day === window.TODAY.day && t.status !== "done");
  const lateTasks = tasks.filter(t => t.status === "late");
  const liveTasks = tasks.filter(t => t.status === "live");

  const activeLeads = leads.filter(l => { const s = window.leadStage(l); return !s.terminal && !s.won; });
  const directActive = activeLeads.filter(l => l.track === "direct");
  const tenderActive = activeLeads.filter(l => l.track === "tender");
  const pipelineValue = activeLeads.reduce((s, l) => s + l.estimatedValue * (l.probability / 100), 0);

  const monthlyProfit = paidSum - monthlyExpenses - totalSalary;

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">{window.dashGreeting(user)}</h1>
        <div className="page-sub">
          <span>{dateLine}</span>
          <span className="dot"></span>
          <span>усе під контролем</span>
          {lateTasks.length > 0 && <>
            <span className="dot"></span>
            <span style={{color: "var(--late)"}}>{lateTasks.length} {window.plural(lateTasks.length, "задача потребує", "задачі потребують", "задач потребують")} уваги</span>
          </>}
        </div>
      </div>

      {/* Хедер-блок з ключовими цифрами */}
      <div className="dash-hero">
        <div className="dash-hero-main">
          <div className="dash-hero-label">Баланс компанії</div>
          <div className="dash-hero-val">{window.formatMoney(Math.round(totalBalance))} <span>₴</span></div>
          <div className="dash-hero-sub">
            на {accounts.length} рахунках · оновлено о {nowHHMM}
          </div>
        </div>
        <div className="dash-hero-divider"></div>
        <div className="dash-hero-stats">
          <div className="dash-hs-row">
            <span className="dash-hs-label">Виторг за травень</span>
            <span className="dash-hs-val good">+{window.formatMoney(paidSum)} ₴</span>
          </div>
          <div className="dash-hs-row">
            <span className="dash-hs-label">Витрати + ЗП</span>
            <span className="dash-hs-val bad">−{window.formatMoney(monthlyExpenses + Math.round(totalSalary))} ₴</span>
          </div>
          <div className="dash-hs-row dash-hs-total">
            <span className="dash-hs-label">Прибуток</span>
            <span className="dash-hs-val good big">+{window.formatMoney(Math.round(monthlyProfit))} ₴</span>
          </div>
        </div>
      </div>

      {/* 4 ключові області */}
      <div className="dash-grid">
        {role === "director" && window.BirthdayCard && <window.BirthdayCard />}
        {/* Сьогодні + команда */}
        <section className="dash-card dash-card-wide">
          <div className="dash-card-head">
            <h2 className="dash-card-title"><window.Ico name="zap" /> Сьогодні</h2>
            <a className="dash-card-link" href="#">Усі задачі →</a>
          </div>
          <div className="dash-stats-row">
            <div className="dash-stat">
              <div className="dash-stat-val">{todayTasks.length}</div>
              <div className="dash-stat-label">задач на сьогодні</div>
            </div>
            <div className="dash-stat">
              <div className="dash-stat-val" style={{color: liveTasks.length > 0 ? "var(--c-green-deep)" : "var(--ink)"}}>{liveTasks.length}</div>
              <div className="dash-stat-label">у роботі зараз</div>
            </div>
            <div className="dash-stat">
              <div className="dash-stat-val" style={{color: lateTasks.length > 0 ? "var(--late)" : "var(--ink)"}}>{lateTasks.length}</div>
              <div className="dash-stat-label">прострочено</div>
            </div>
          </div>
          {lateTasks.length > 0 && (
            <div className="dash-alert is-warn">
              <span><window.Ico name="alert" style={{verticalAlign: "-0.15em"}} /> Прострочено: <b>{lateTasks[0].title}</b></span>
              <button className="btn btn-ghost" style={{padding: "2px 8px", fontSize: 12, color: "var(--late)"}}>Перейти →</button>
            </div>
          )}
          <div className="dash-team-row">
            {team.map(p => (
              <div key={p.id} className="dash-team-cell" title={`${p.name} · ${p.load}%`}>
                <div className="team-avatar" style={{width: 32, height: 32, fontSize: 12}}>{p.initials}</div>
                <div className={`dash-team-load ${p.load >= 90 ? "is-high" : ""}`} style={{width: p.load + "%"}}></div>
              </div>
            ))}
          </div>
        </section>

        {/* Дебіторка */}
        <section className="dash-card">
          <div className="dash-card-head">
            <h2 className="dash-card-title"><window.Ico name="coins" /> Дебіторка</h2>
            <a className="dash-card-link" href="#">Деталі →</a>
          </div>
          <div className="dash-big-num" style={{color: overdueSum > 0 ? "var(--late)" : "var(--ink)"}}>
            {window.formatMoney(overdueSum)} <span>₴</span>
          </div>
          <div className="dash-card-sub">{overdueInv.length} прострочених рахунків</div>
          <div style={{marginTop: 16}}>
            {overdueInv.slice(0, 2).map(inv => {
              const cli = window.getClient(inv.client);
              return (
                <div key={inv.id} className="dash-row">
                  <div>
                    <div className="cell-name" style={{fontSize: 13}}>{cli?.short}</div>
                    <div className="cell-sub" style={{fontSize: 11}}>{inv.title}</div>
                  </div>
                  <div className="num-bold" style={{color: "var(--late)", fontSize: 13, fontVariantNumeric: "tabular-nums"}}>
                    +{inv.lateDays} дн.
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        {/* Cash flow прогноз */}
        <section className="dash-card">
          <div className="dash-card-head">
            <h2 className="dash-card-title"><window.Ico name="trending" /> Прогноз 4 тижні</h2>
            <a className="dash-card-link" href="#">Cash flow →</a>
          </div>
          <div className="dash-mini-chart">
            {[
              { w: "Цей", val: 60, in: 425000, out: 220000 },
              { w: "Наст", val: 75, in: 600000, out: 180000 },
              { w: "+2", val: 50, in: 0, out: 250000 },
              { w: "+3", val: 90, in: 2940000, out: 220000 },
            ].map((m, i) => (
              <div key={i} className="dash-mini-col">
                <div className="dash-mini-bar" style={{height: m.val + "%"}}></div>
                <div className="dash-mini-label">{m.w}</div>
              </div>
            ))}
          </div>
          <div className="dash-card-sub" style={{marginTop: 8}}>+2.96 млн надходжень очікується</div>
        </section>

        {/* Об'єкти */}
        <section className="dash-card dash-card-wide">
          <div className="dash-card-head">
            <h2 className="dash-card-title"><window.Ico name="construction" /> Активні об'єкти</h2>
            <a className="dash-card-link" href="#">Усі об'єкти →</a>
          </div>
          {objects.slice(0, 3).map(o => {
            const objTasks = tasks.filter(t => t.obj === o.id);
            const done = objTasks.filter(t => t.status === "done").length;
            const total = Object.values(o.plan || {}).reduce((s, n) => s + n, 0);
            const pct = total > 0 ? Math.round(done / total * 100) : 0;
            const contract = contracts.find(c => c.obj === o.id);
            return (
              <div key={o.id} className="dash-row">
                <div style={{minWidth: 0, flex: 1}}>
                  <div style={{display: "flex", alignItems: "center", gap: 8}}>
                    <span className="td-mono" style={{fontSize: 10.5, color: "var(--ink-3)"}}>{o.code}</span>
                    <span className="cell-name" style={{fontSize: 13}}>{o.name}</span>
                  </div>
                  <div style={{display: "flex", alignItems: "center", gap: 10, marginTop: 6}}>
                    <div className="load-bar-track" style={{flex: 1, height: 4}}>
                      <div className="load-bar-fill" style={{width: pct + "%", background: "var(--accent)"}}></div>
                    </div>
                    <span style={{fontSize: 11, color: "var(--ink-3)", fontVariantNumeric: "tabular-nums", minWidth: 50, textAlign: "right"}}>
                      {done}/{total}
                    </span>
                  </div>
                </div>
                <span style={{fontSize: 11.5, color: "var(--ink-3)", fontVariantNumeric: "tabular-nums", marginLeft: 12}}>до {o.deadline}</span>
              </div>
            );
          })}
        </section>

        {/* Воронка лідів */}
        <section className="dash-card">
          <div className="dash-card-head">
            <h2 className="dash-card-title"><window.Ico name="target" /> Воронка</h2>
            <a className="dash-card-link" href="#">Усі ліди →</a>
          </div>
          <div className="dash-big-num">
            {window.formatMoney(Math.round(pipelineValue / 1000000 * 10) / 10)}<span>М ₴</span>
          </div>
          <div className="dash-card-sub">прогнозований виторг з {activeLeads.length} лідів у роботі</div>
          <div className="dash-funnel">
            <div className="dash-funnel-step">
              <span className="status-tag tone-blue">прямі</span>
              <b style={{fontSize: 14, fontVariantNumeric: "tabular-nums"}}>{directActive.length}</b>
            </div>
            <div className="dash-funnel-step">
              <span className="status-tag tone-neutral">тендери</span>
              <b style={{fontSize: 14, fontVariantNumeric: "tabular-nums"}}>{tenderActive.length}</b>
            </div>
          </div>
        </section>

        {/* Команда */}
        <section className="dash-card">
          <div className="dash-card-head">
            <h2 className="dash-card-title"><window.Ico name="users" /> Команда</h2>
            <a className="dash-card-link" href="#">Профілі →</a>
          </div>
          <div className="dash-big-num">{team.length}</div>
          <div className="dash-card-sub">людей у штаті</div>
          <div className="dash-team-stats">
            <div><b>{Math.round(team.reduce((s,p) => s + p.load, 0) / team.length)}%</b><span>сер. завантаження</span></div>
            <div><b>{team.filter(p => p.load >= 90).length}</b><span>перевантажено</span></div>
            <div><b>{window.DATA.VACATIONS.filter(v => v.status === "pending").length}</b><span>заявок на відпустку</span></div>
          </div>
        </section>
      </div>

      {/* Швидкі дії */}
      <section className="section" style={{marginTop: 32}}>
        <div className="section-head">
          <h2 className="section-h2">Швидкі дії</h2>
        </div>
        <div className="quick-actions">
          <button className="quick-action" onClick={onNewTask}>
            <window.Ico name="pencil" size={22} className="qa-ic" />
            <span>Створити задачу</span>
          </button>
          <button className="quick-action" onClick={() => setPickAct(true)}>
            <window.Ico name="receipt" size={22} className="qa-ic" />
            <span>Скласти акт</span>
          </button>
          <button className="quick-action">
            <window.Ico name="user" size={22} className="qa-ic" />
            <span>Додати лід</span>
          </button>
          <button className="quick-action">
            <window.Ico name="chart" size={22} className="qa-ic" />
            <span>Звіт замовнику</span>
          </button>
          <button className="quick-action">
            <window.Ico name="coins" size={22} className="qa-ic" />
            <span>Розрахунок ЗП</span>
          </button>
          <button className="quick-action">
            <window.Ico name="calendar" size={22} className="qa-ic" />
            <span>Записати виїзд</span>
          </button>
        </div>
      </section>
      {pickInvoice && <window.InvoiceContractPicker
        onClose={() => setPickInvoice(false)}
        onPick={(draft) => { setPickInvoice(false); setPrintDraft(draft); }}
      />}
      {printDraft && <window.InvoicePrintDoc invoice={printDraft} onClose={() => setPrintDraft(null)} />}
      {pickAct && window.ActContractPicker && <window.ActContractPicker
        onClose={() => setPickAct(false)}
        onPick={(draft) => { setPickAct(false); setPrintAct(draft); }}
      />}
      {printAct && window.ActPrintDoc && <window.ActPrintDoc act={printAct} onClose={() => setPrintAct(null)} />}
    </div>
  );
}

window.DashboardPage = DashboardPage;
