// ═══════════════════════════════════════════════════════════════
//  dashboard.jsx — Финансово табло (Фаза 4)
//  Приходи / разходи / печалба + данъци (печалба 10% год.,
//  дивидент 5% трим.) + тегления. Всичко в EUR.
//  State lives in app.jsx — this is purely presentational.
// ═══════════════════════════════════════════════════════════════

const PROFIT_TAX_RATE = 0.10;   // данък печалба — 10% годишно
const DIVIDEND_TAX_RATE = 0.05; // данък дивидент — 5% тримесечно

const QUARTER_MONTHS = ["01–03", "04–06", "07–09", "10–12"];
const MONTH_ABBR = ["Я", "Ф", "М", "А", "М", "Ю", "Ю", "А", "С", "О", "Н", "Д"];

function FinanceView({
  T, lang,
  history, expenses, withdrawals, taxPayments,
  onSaveWithdrawal, onUpdateWithdrawal, onDeleteWithdrawal,
  onSaveTaxPayment, onDeleteTaxPayment,
}) {
  const { useState, useMemo } = React;
  const L = (bg, en) => (lang === "en" ? en : bg);

  // Всичко в EUR — стара BGN сума се конвертира; останалото се брои по номинал.
  const toEUR = (amt, cur) => {
    const a = Number(amt) || 0;
    if (cur === "BGN") return a / BGN_PER_EUR;
    return a;
  };

  // ─── Налични години ───
  const years = useMemo(() => {
    const s = new Set();
    (history || []).forEach(i => { const y = (i.issueDate || "").slice(0, 4); if (y) s.add(y); });
    (expenses || []).forEach(e => { const y = (e.date || "").slice(0, 4); if (y) s.add(y); });
    (withdrawals || []).forEach(w => { const y = (w.date || "").slice(0, 4); if (y) s.add(y); });
    s.add(String(new Date().getFullYear()));
    return [...s].sort().reverse();
  }, [history, expenses, withdrawals]);

  const [year, setYear] = useState(String(new Date().getFullYear()));

  // ─── Приходи / разходи / печалба за годината ───
  const fin = useMemo(() => {
    const invs = (history || []).filter(i => i.docType === "invoice" && (i.issueDate || "").startsWith(year));
    const income = invs.reduce((s, i) => s + toEUR(i.base, i.currency), 0);        // данъчна основа (без ДДС)
    const incomeTotal = invs.reduce((s, i) => s + toEUR(i.total, i.currency), 0);  // с ДДС
    const exps = (expenses || []).filter(e => (e.date || "").startsWith(year));
    const expense = exps.reduce((s, e) => s + toEUR(e.amount, e.currency), 0);
    const profit = income - expense;
    const profitTax = profit > 0 ? profit * PROFIT_TAX_RATE : 0;

    const months = Array.from({ length: 12 }, () => ({ inc: 0, exp: 0 }));
    invs.forEach(i => { const m = parseInt((i.issueDate || "").slice(5, 7), 10) - 1; if (m >= 0 && m < 12) months[m].inc += toEUR(i.base, i.currency); });
    exps.forEach(e => { const m = parseInt((e.date || "").slice(5, 7), 10) - 1; if (m >= 0 && m < 12) months[m].exp += toEUR(e.amount, e.currency); });

    return { income, incomeTotal, expense, profit, profitTax, months, count: invs.length };
  }, [history, expenses, year]);

  // ─── Тегления + дивидентен данък по тримесечия ───
  const wYear = useMemo(() => (withdrawals || []).filter(w => (w.date || "").startsWith(year)), [withdrawals, year]);
  const quarters = useMemo(() => {
    const q = [0, 0, 0, 0];
    wYear.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); });
    return q;
  }, [wYear]);
  const withdrawnTotal = quarters.reduce((a, b) => a + b, 0);
  const dividendTaxTotal = withdrawnTotal * DIVIDEND_TAX_RATE;

  // ─── Lookup за платени данъци ───
  const taxPaid = (type, period) => (taxPayments || []).find(t => t.type === type && t.period === period);

  const markProfitTax = () => onSaveTaxPayment({ type: "profit", period: year, amount: fin.profitTax, paid_date: today() });
  const markDividendTax = (qIdx, amount) => onSaveTaxPayment({ type: "dividend", period: `${year}-Q${qIdx + 1}`, amount, paid_date: today() });

  // ─── Тегления форма ───
  const FRESH_W = { date: today(), amount: "", note: "" };
  const [wForm, setWForm] = useState(FRESH_W);
  const [wEditId, setWEditId] = useState(null);
  const [showWForm, setShowWForm] = useState(false);
  const updW = (patch) => setWForm(p => ({ ...p, ...patch }));

  const startAddW = () => { setWForm({ ...FRESH_W, date: today() }); setWEditId(null); setShowWForm(true); };
  const startEditW = (w) => { setWForm({ date: w.date || "", amount: w.amount || "", note: w.note || "" }); setWEditId(w.id); setShowWForm(true); };
  const saveW = () => {
    if (!wForm.amount) return;
    const payload = { date: wForm.date, amount: Number(wForm.amount) || 0, currency: "EUR", note: wForm.note || "" };
    if (wEditId) onUpdateWithdrawal({ ...payload, id: wEditId });
    else onSaveWithdrawal(payload);
    setShowWForm(false); setWEditId(null); setWForm({ ...FRESH_W, date: today() });
  };
  const cancelW = () => { setShowWForm(false); setWEditId(null); setWForm({ ...FRESH_W, date: today() }); };

  const eur = (n) => `€ ${fmtNum(n)}`;

  // ─── Stat card ───
  const stat = (label, value, sub, color) => (
    <div style={{ flex: 1, minWidth: 150, 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 PaidBadge = () => (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 9, background: `${T.sage}22`, color: T.sage }}>
      <Icon name="check" size={11} />{L("Платен", "Paid")}
    </span>
  );

  const maxMonth = Math.max(...fin.months.map(m => Math.max(m.inc, m.exp)), 1);

  return (
    <div style={{ maxWidth: 920, margin: "0 auto", padding: "28px 28px 60px" }}>
      {/* ─── Header + year selector ─── */}
      <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 }}>{L("Финанси", "Finance")}</h2>
        <div style={{ minWidth: 120 }}>
          <Select label={L("Година", "Year")} value={year} onChange={setYear} options={years.map(y => ({ v: y, l: y }))} T={T} minWidth={110} />
        </div>
      </div>

      {/* ─── Top cards ─── */}
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        {stat(L("Приходи (без ДДС)", "Income (net)"), eur(fin.income), `${fin.count} ${L("фактури", "invoices")} · ${L("с ДДС", "incl. VAT")} ${eur(fin.incomeTotal)}`)}
        {stat(L("Разходи", "Expenses"), eur(fin.expense), null, T.danger)}
        {stat(L("Печалба", "Profit"), eur(fin.profit), L("приходи − разходи", "income − expenses"), fin.profit >= 0 ? T.sage : T.danger)}
      </div>

      {/* ─── Данъци ─── */}
      <Card T={T} title={L("Данъци", "Taxes")} icon="chart">
        {/* Данък печалба */}
        <div style={{ padding: "14px 16px", background: T.field, border: `1px solid ${T.line}`, borderRadius: 9, marginBottom: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: T.ink }}>{L("Данък печалба", "Corporate tax")} · 10%</div>
              <div style={{ fontSize: 11, color: T.sub, marginTop: 3 }}>
                {L("Облагаема печалба", "Taxable profit")} {eur(Math.max(fin.profit, 0))} · {L("дължимо за", "due for")} {year}
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 700, color: T.ink, textAlign: "right" }}>{eur(fin.profitTax)}</div>
              {(() => {
                const paid = taxPaid("profit", year);
                return paid ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <PaidBadge />
                    <button title={L("Отмени", "Undo")} onClick={() => onDeleteTaxPayment(paid.id)} style={{ background: "none", border: "none", color: T.faint, cursor: "pointer", padding: 4 }}><Icon name="x" size={14} /></button>
                  </div>
                ) : (
                  <Button T={T} kind="ghost" size="sm" icon="check" onClick={markProfitTax}>{L("Маркирай платен", "Mark paid")}</Button>
                );
              })()}
            </div>
          </div>
        </div>

        {/* Данък дивидент по тримесечия */}
        <div style={{ fontSize: 12.5, fontWeight: 700, color: T.ink, marginBottom: 4 }}>{L("Данък дивидент", "Dividend tax")} · 5%</div>
        <div style={{ fontSize: 11, color: T.sub, marginBottom: 12 }}>{L("5% върху изтеглените суми, дължим тримесечно", "5% of withdrawn amounts, due quarterly")}</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {QUARTER_MONTHS.map((label, qIdx) => {
            const withdrawn = quarters[qIdx];
            const tax = withdrawn * DIVIDEND_TAX_RATE;
            const period = `${year}-Q${qIdx + 1}`;
            const paid = taxPaid("dividend", period);
            return (
              <div key={qIdx} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 14px", background: T.field, border: `1px solid ${T.line}`, borderRadius: 9 }}>
                <div style={{ fontWeight: 700, fontSize: 12, minWidth: 30, color: withdrawn > 0 ? T.ink : T.faint }}>Q{qIdx + 1}</div>
                <div style={{ fontSize: 10, color: T.faint, minWidth: 48 }}>{label}</div>
                <div style={{ flex: 1, fontSize: 11, color: T.sub }}>{L("тегления", "withdrawn")} <span style={{ fontFamily: MONO, color: T.ink }}>{eur(withdrawn)}</span></div>
                <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: tax > 0 ? T.ink : T.faint, textAlign: "right", minWidth: 80 }}>{eur(tax)}</div>
                <div style={{ minWidth: 130, display: "flex", justifyContent: "flex-end" }}>
                  {tax <= 0 ? <span style={{ fontSize: 10, color: T.faint }}>—</span>
                    : paid ? (
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <PaidBadge />
                        <button title={L("Отмени", "Undo")} onClick={() => onDeleteTaxPayment(paid.id)} style={{ background: "none", border: "none", color: T.faint, cursor: "pointer", padding: 4 }}><Icon name="x" size={14} /></button>
                      </div>
                    ) : (
                      <Button T={T} kind="plain" size="sm" icon="check" onClick={() => markDividendTax(qIdx, tax)}>{L("Платен", "Paid")}</Button>
                    )}
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, paddingTop: 12, borderTop: `1px solid ${T.line}`, fontSize: 12 }}>
          <span style={{ color: T.sub }}>{L("Общо дивидентен данък", "Total dividend tax")} {year}</span>
          <span style={{ fontFamily: MONO, fontWeight: 700, color: T.ink }}>{eur(dividendTaxTotal)}</span>
        </div>
      </Card>

      {/* ─── Тегления ─── */}
      <Card T={T} title={L("Тегления от сметка", "Account withdrawals")} icon="download" right={<Button T={T} kind="primary" size="sm" icon="plus" onClick={startAddW}>{L("Ново", "New")}</Button>}>
        {showWForm && (
          <div style={{ padding: "14px 16px", background: T.field, border: `1px solid ${T.line}`, borderRadius: 9, marginBottom: 12 }}>
            <Row>
              <Field label={L("Дата", "Date")} type="date" value={wForm.date} onChange={v => updW({ date: v })} T={T} minWidth={140} />
              <Field label={L("Сума (EUR)", "Amount (EUR)")} type="number" value={wForm.amount} onChange={v => updW({ amount: v })} T={T} mono minWidth={120} />
              <Field label={L("Бележка", "Note")} value={wForm.note} onChange={v => updW({ note: v })} T={T} minWidth={180} />
            </Row>
            <Row style={{ marginBottom: 0 }}>
              <div style={{ flex: 1 }} />
              <Button T={T} kind="ghost" size="sm" onClick={cancelW}>{L("Откажи", "Cancel")}</Button>
              <Button T={T} kind="primary" size="sm" icon="save" onClick={saveW}>{wEditId ? L("Актуализирай", "Update") : L("Запази", "Save")}</Button>
            </Row>
          </div>
        )}
        {wYear.length === 0 ? (
          <Empty T={T} icon="download" text={L("Няма тегления за " + year, "No withdrawals for " + year)} />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {wYear.map(w => (
              <div key={w.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 14px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
                <div style={{ fontSize: 11, color: T.faint, fontFamily: MONO, minWidth: 75 }}>{fmtDate(w.date)}</div>
                <div style={{ flex: 1, fontSize: 12, color: T.sub, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{w.note || "—"}</div>
                <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: T.ink, textAlign: "right", minWidth: 90 }}>{eur(toEUR(w.amount, w.currency))}</div>
                <button title={L("Редактирай", "Edit")} onClick={() => startEditW(w)} style={{ background: "none", border: "none", color: T.sub, cursor: "pointer", padding: 4 }}><Icon name="edit" size={15} /></button>
                <button title={L("Изтрий", "Delete")} onClick={() => onDeleteWithdrawal(w.id)} style={{ background: "none", border: "none", color: T.danger, cursor: "pointer", padding: 4 }}><Icon name="trash" size={15} /></button>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* ─── Месечен график ─── */}
      <Card T={T} title={L("Приходи срещу разходи по месеци", "Income vs expenses by month")} icon="chart">
        <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 150 }}>
          {fin.months.map((m, idx) => (
            <div key={idx} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4, height: "100%", justifyContent: "flex-end" }}>
              <div style={{ display: "flex", alignItems: "flex-end", gap: 2, height: 110, width: "100%", justifyContent: "center" }}>
                <div title={`${L("приход", "income")}: ${eur(m.inc)}`} style={{ width: 8, height: `${(m.inc / maxMonth) * 100}%`, minHeight: m.inc > 0 ? 2 : 0, background: T.blue, borderRadius: "2px 2px 0 0" }} />
                <div title={`${L("разход", "expense")}: ${eur(m.exp)}`} style={{ width: 8, height: `${(m.exp / maxMonth) * 100}%`, minHeight: m.exp > 0 ? 2 : 0, background: T.danger, borderRadius: "2px 2px 0 0" }} />
              </div>
              <div style={{ fontSize: 9, color: T.faint, fontFamily: MONO }}>{MONTH_ABBR[idx]}</div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 16, marginTop: 12, fontSize: 11, color: T.sub }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 10, height: 10, background: T.blue, borderRadius: 2, display: "inline-block" }} />{L("Приходи", "Income")}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 10, height: 10, background: T.danger, borderRadius: 2, display: "inline-block" }} />{L("Разходи", "Expenses")}</span>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { FinanceView });
