// ═══════════════════════════════════════════════════════════════
//  home.jsx — Начален екран с аларми (overview)
//  Събира сигнали от всички модули: данъци, неплатени фактури,
//  изтичащи договори, часове, финансов snapshot. Кликаеми карти.
//  State lives in app.jsx — this is purely presentational.
// ═══════════════════════════════════════════════════════════════

const WARN = "#C9912B"; // amber

function HomeView({ T, lang, history, expenses, withdrawals, taxPayments, documents, timeEntries, onNavigate }) {
  const { useMemo } = React;
  const L = (bg, en) => (lang === "en" ? en : bg);
  const eur = (n) => `€ ${fmtNum(n)}`;
  const toEUR = (amt, cur) => { const a = Number(amt) || 0; return cur === "BGN" ? a / BGN_PER_EUR : a; };

  const now = today();
  const ym = now.slice(0, 7);
  const year = now.slice(0, 4);

  const data = useMemo(() => {
    const invs = (history || []).filter(i => i.docType === "invoice");

    // ─── Данъци (текуща година) ───
    const incomeYTD = invs.filter(i => (i.issueDate || "").startsWith(year)).reduce((s, i) => s + toEUR(i.base, i.currency), 0);
    const expenseYTD = (expenses || []).filter(e => (e.date || "").startsWith(year)).reduce((s, e) => s + toEUR(e.amount, e.currency), 0);
    const profitYTD = incomeYTD - expenseYTD;
    const profitTax = profitYTD > 0 ? profitYTD * 0.10 : 0;
    const profitPaid = (taxPayments || []).some(t => t.type === "profit" && t.period === year);

    const q = [0, 0, 0, 0];
    (withdrawals || []).filter(w => (w.date || "").startsWith(year)).forEach(w => {
      const m = parseInt((w.date || "").slice(5, 7), 10); const idx = Math.floor((m - 1) / 3);
      if (idx >= 0 && idx < 4) q[idx] += toEUR(w.amount, w.currency);
    });
    let divDue = 0;
    q.forEach((amt, idx) => {
      const tax = amt * 0.05;
      const paid = (taxPayments || []).some(t => t.type === "dividend" && t.period === `${year}-Q${idx + 1}`);
      if (tax > 0 && !paid) divDue += tax;
    });
    const taxesDue = (profitPaid ? 0 : profitTax) + divDue;

    // ─── Неплатени / просрочени фактури ───
    const unpaid = invs.filter(i => !i.paidDate);
    const unpaidTotal = unpaid.reduce((s, i) => s + toEUR(i.total, i.currency), 0);
    const overdue = unpaid.filter(i => i.dueDate && i.dueDate < now);

    // ─── Изтичащи договори ───
    const expDocs = (documents || []).filter(d => {
      if (!d.expiry_date) return false;
      const t0 = new Date(now + "T00:00:00"); const ex = new Date(d.expiry_date + "T00:00:00");
      if (isNaN(ex.getTime())) return false;
      const days = Math.round((ex - t0) / 86400000);
      return days <= 30;
    });

    // ─── Часове този месец ───
    const hoursMonth = (timeEntries || []).filter(t => (t.date || "").startsWith(ym)).reduce((s, t) => s + (Number(t.hours) || 0), 0);

    // ─── Финансов snapshot (този месец) ───
    const incomeM = invs.filter(i => (i.issueDate || "").startsWith(ym)).reduce((s, i) => s + toEUR(i.base, i.currency), 0);
    const expenseM = (expenses || []).filter(e => (e.date || "").startsWith(ym)).reduce((s, e) => s + toEUR(e.amount, e.currency), 0);

    return {
      taxesDue, profitTax, profitPaid, divDue,
      unpaidCount: unpaid.length, unpaidTotal, overdueCount: overdue.length,
      expDocsCount: expDocs.length,
      hoursMonth,
      incomeM, expenseM, profitM: incomeM - expenseM,
    };
  }, [history, expenses, withdrawals, taxPayments, documents, timeEntries, year, ym, now]);

  // ─── Alert card ───
  const card = ({ icon, label, value, sub, accent, onClick }) => (
    <button onClick={onClick} style={{
      textAlign: "left", cursor: "pointer", padding: "18px 20px", background: T.surface,
      border: `1px solid ${accent || T.line}`, borderLeft: `3px solid ${accent || T.line}`,
      borderRadius: 10, display: "flex", flexDirection: "column", gap: 8, fontFamily: MONO,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, color: accent || T.faint }}>
        <Icon name={icon} size={15} />
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.07em", textTransform: "uppercase", color: T.faint }}>{label}</span>
      </div>
      <div style={{ fontFamily: MONO, fontSize: 22, fontWeight: 700, color: accent || T.ink }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: T.sub }}>{sub}</div>}
    </button>
  );

  const miniStat = (label, value, color) => (
    <div style={{ flex: 1, minWidth: 110, padding: "14px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.07em", textTransform: "uppercase", color: T.faint }}>{label}</div>
      <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 700, color: color || T.ink, marginTop: 4 }}>{value}</div>
    </div>
  );

  const dParts = now.split("-");

  return (
    <div style={{ maxWidth: 920, margin: "0 auto", padding: "28px 28px 60px" }}>
      <div style={{ marginBottom: 22 }}>
        <h2 style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.02em", margin: 0 }}>{L("Начало", "Home")}</h2>
        <div style={{ fontSize: 11.5, color: T.faint, marginTop: 4 }}>{`${dParts[2]}.${dParts[1]}.${dParts[0]}`}</div>
      </div>

      {/* ─── Аларми ─── */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))", gap: 12, marginBottom: 22 }}>
        {card({
          icon: "chart",
          label: L("Дължими данъци", "Taxes due"),
          value: eur(data.taxesDue),
          sub: data.taxesDue > 0
            ? `${data.profitPaid ? L("печалба платена", "profit paid") : L("печалба", "profit") + " " + eur(data.profitTax)} · ${L("дивидент", "dividend")} ${eur(data.divDue)}`
            : L("всичко платено", "all paid"),
          accent: data.taxesDue > 0 ? WARN : T.sage,
          onClick: () => onNavigate("finance"),
        })}
        {card({
          icon: "doc",
          label: L("Неплатени фактури", "Unpaid invoices"),
          value: `${data.unpaidCount}`,
          sub: data.unpaidCount > 0
            ? `${eur(data.unpaidTotal)}${data.overdueCount > 0 ? ` · ${data.overdueCount} ${L("просрочени", "overdue")}` : ""}`
            : L("няма", "none"),
          accent: data.overdueCount > 0 ? T.danger : (data.unpaidCount > 0 ? WARN : T.sage),
          onClick: () => onNavigate("history"),
        })}
        {card({
          icon: "folder",
          label: L("Изтичащи договори", "Expiring documents"),
          value: `${data.expDocsCount}`,
          sub: data.expDocsCount > 0 ? L("под 30 дни / изтекли", "≤30 days / expired") : L("няма", "none"),
          accent: data.expDocsCount > 0 ? WARN : T.sage,
          onClick: () => onNavigate("documents"),
        })}
        {card({
          icon: "clock",
          label: L("Часове този месец", "Hours this month"),
          value: `${fmtNum(data.hoursMonth)} h`,
          sub: L("в трекера", "tracked"),
          accent: T.blue,
          onClick: () => onNavigate("timetrack"),
        })}
      </div>

      {/* ─── Финансов snapshot (този месец) ─── */}
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: T.faint, marginBottom: 10 }}>{L("Този месец", "This month")}</div>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
        {miniStat(L("Приходи", "Income"), eur(data.incomeM), T.sage)}
        {miniStat(L("Разходи", "Expenses"), eur(data.expenseM), T.danger)}
        {miniStat(L("Печалба", "Profit"), eur(data.profitM), data.profitM >= 0 ? T.ink : T.danger)}
      </div>
    </div>
  );
}

Object.assign(window, { HomeView });
