// ═══════════════════════════════════════════════════════════════
//  views.jsx — History · Clients · Items · Templates · Dashboard · Archive
// ═══════════════════════════════════════════════════════════════

function Empty({ T, icon, text }) {
  return (
    <div style={{ textAlign: "center", padding: "70px 20px", color: T.faint }}>
      <div style={{ display: "inline-flex", opacity: 0.5, marginBottom: 14 }}><Icon name={icon} size={40} sw={1.3} /></div>
      <div style={{ fontSize: 13, fontWeight: 500 }}>{text}</div>
    </div>
  );
}

const docBadge = (T, type) => {
  const d = DOC_TYPES.find(x => x.v === type) || DOC_TYPES[0];
  const map = { invoice: T.blue, proforma: T.sage, credit: "#B7791F", debit: T.danger };
  const c = map[type] || T.blue;
  return <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: c, background: `${c}1A`, padding: "3px 8px", borderRadius: 5 }}>{d.bg}</span>;
};

// ─── HISTORY ───
function HistoryView({ T, history, onOpen, onDuplicate, onDelete }) {
  const [q, setQ] = React.useState("");
  const filt = history.filter(inv => {
    if (!q.trim()) return true;
    const s = q.toLowerCase();
    const c = inv.client || {};
    return (inv.num || "").includes(s) || (c.name || "").toLowerCase().includes(s) || (c.nameEn || "").toLowerCase().includes(s) || (c.eik || "").includes(s);
  });
  return (
    <div>
      <div style={{ position: "relative", marginBottom: 16 }}>
        <div style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: T.faint }}><Icon name="search" size={15} /></div>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Търси по номер, клиент, ЕИК…"
          style={{ width: "100%", padding: "10px 12px 10px 36px", border: `1px solid ${T.line}`, borderRadius: 8, fontSize: 13, fontFamily: MONO, color: T.ink, background: T.field, outline: "none", boxSizing: "border-box" }} />
      </div>
      {filt.length === 0 ? <Empty T={T} icon="history" text={q ? "Няма резултати" : "Все още няма издадени документи"} /> :
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {filt.map(inv => (
            <div key={inv.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
              <div style={{ minWidth: 96 }}>{docBadge(T, inv.docType)}</div>
              <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, minWidth: 110 }}>{inv.num}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{inv.client?.name || inv.client?.nameEn || "—"}</div>
                <div style={{ fontSize: 10.5, color: T.faint }}>{fmtDate(inv.issueDate)}</div>
              </div>
              <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: T.blue, textAlign: "right", minWidth: 110 }}>{money(inv.total, inv.currency)}</div>
              <div style={{ display: "flex", gap: 2 }}>
                <button title="Отвори" onClick={() => onOpen(inv)} style={iconBtn(T)}><Icon name="eye" size={16} /></button>
                <button title="Дублирай" onClick={() => onDuplicate(inv)} style={iconBtn(T)}><Icon name="copy" size={16} /></button>
                <button title="Изтрий" onClick={() => onDelete(inv.id)} style={iconBtn(T, true)}><Icon name="trash" size={16} /></button>
              </div>
            </div>
          ))}
        </div>}
    </div>
  );
}
const iconBtn = (T, danger) => ({ background: "none", border: "none", color: danger ? T.danger : T.sub, cursor: "pointer", padding: 6, borderRadius: 6, display: "flex" });

// ─── CLIENTS ───
function ClientsView({ T, clients, onUse, onDelete }) {
  if (clients.length === 0) return <Empty T={T} icon="users" text="Няма записани клиенти. Запази клиент от формата." />;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {clients.map((c, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{c.name || c.nameEn}</div>
            <div style={{ fontSize: 10.5, color: T.faint, fontFamily: MONO }}>{c.eik ? `ЕИК ${c.eik}` : ""}{c.vatId ? ` · ${c.vatId}` : ""}</div>
          </div>
          <Button T={T} kind="ghost" size="sm" onClick={() => onUse(c)}>Използвай</Button>
          <button title="Изтрий" onClick={() => onDelete(i)} style={iconBtn(T, true)}><Icon name="trash" size={16} /></button>
        </div>
      ))}
    </div>
  );
}

// ─── SAVED ITEMS ───
function ItemsView({ T, savedItems, onDelete }) {
  if (savedItems.length === 0) return <Empty T={T} icon="box" text="Няма записани артикули. Запази артикул от формата." />;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {savedItems.map((s, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{s.desc || s.descEn}</div>
            <div style={{ fontSize: 10.5, color: T.faint, fontFamily: MONO }}>{fmtNum(s.price)} · {s.unit} · ДДС {s.vat}%</div>
          </div>
          <button title="Изтрий" onClick={() => onDelete(i)} style={iconBtn(T, true)}><Icon name="trash" size={16} /></button>
        </div>
      ))}
    </div>
  );
}

// ─── TEMPLATES ───
function TemplatesView({ T, templates, onUse, onDelete }) {
  if (templates.length === 0) return <Empty T={T} icon="repeat" text="Няма шаблони. Запази текущата фактура като шаблон." />;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {templates.map(tp => (
        <div key={tp.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{tp.name}</div>
            <div style={{ fontSize: 10.5, color: T.faint, fontFamily: MONO }}>{tp.items?.length || 0} реда · {tp.currency}</div>
          </div>
          <Button T={T} kind="ghost" size="sm" icon="repeat" onClick={() => onUse(tp)}>Зареди</Button>
          <button title="Изтрий" onClick={() => onDelete(tp.id)} style={iconBtn(T, true)}><Icon name="trash" size={16} /></button>
        </div>
      ))}
    </div>
  );
}

// ─── DASHBOARD ───
function DashboardView({ T, history }) {
  const invs = history.filter(i => i.docType === "invoice");
  const byCur = {};
  invs.forEach(i => { byCur[i.currency] = (byCur[i.currency] || 0) + i.total; });
  const eurTotal = invs.reduce((s, i) => s + (i.currency === "EUR" ? i.total : i.currency === "BGN" ? i.total / BGN_PER_EUR : 0), 0);

  const byClient = {};
  invs.forEach(i => { const n = i.client?.name || i.client?.nameEn || "—"; byClient[n] = (byClient[n] || 0) + (i.currency === "BGN" ? i.total / BGN_PER_EUR : i.currency === "USD" ? 0 : i.total); });
  const topClients = Object.entries(byClient).sort((a, b) => b[1] - a[1]).slice(0, 6);

  const byMonth = {};
  invs.forEach(i => { const m = (i.issueDate || "").slice(0, 7); if (m) byMonth[m] = (byMonth[m] || 0) + (i.currency === "BGN" ? i.total / BGN_PER_EUR : i.currency === "USD" ? 0 : i.total); });
  const months = Object.entries(byMonth).sort((a, b) => a[0].localeCompare(b[0])).slice(-12);
  const maxMonth = Math.max(...months.map(m => m[1]), 1);

  const stat = (label, value, sub) => (
    <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: T.ink }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: T.sub, marginTop: 3 }}>{sub}</div>}
    </div>
  );

  if (invs.length === 0) return <Empty T={T} icon="chart" text="Статистиката се появява след първата издадена фактура" />;

  return (
    <div>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        {stat("Издадени фактури", invs.length)}
        {stat("Приходи (EUR екв.)", `€ ${fmtNum(eurTotal)}`, `≈ ${fmtNum(eurTotal * BGN_PER_EUR)} BGN`)}
        {stat("Среден документ", `€ ${fmtNum(eurTotal / invs.length)}`)}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div style={{ padding: "18px 20px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: T.ink, marginBottom: 16 }}>По месеци (EUR екв.)</div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 130 }}>
            {months.map(([m, v]) => (
              <div key={m} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
                <div style={{ fontSize: 8.5, color: T.faint, fontFamily: MONO }}>{Math.round(v)}</div>
                <div style={{ width: "100%", height: `${(v / maxMonth) * 90}px`, minHeight: 2, background: T.blue, borderRadius: "3px 3px 0 0" }} />
                <div style={{ fontSize: 8.5, color: T.faint, fontFamily: MONO }}>{m.slice(5)}/{m.slice(2, 4)}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: "18px 20px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: T.ink, marginBottom: 16 }}>Топ клиенти</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            {topClients.map(([n, v]) => (
              <div key={n}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, marginBottom: 4 }}>
                  <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 150 }}>{n}</span>
                  <span style={{ fontFamily: MONO, fontWeight: 600, color: T.sub }}>€ {fmtNum(v)}</span>
                </div>
                <div style={{ height: 5, background: T.line, borderRadius: 3 }}><div style={{ height: "100%", width: `${(v / topClients[0][1]) * 100}%`, background: T.sage, borderRadius: 3 }} /></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── ARCHIVE / SETTINGS ───
function ArchiveView({ T, history, onCSV, onBackup, onRestore, onReset, confirmReset }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ padding: "20px 22px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10 }}>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: T.ink, marginBottom: 6 }}>Архив на данните</div>
        <p style={{ fontSize: 12, color: T.sub, margin: "0 0 16px", lineHeight: 1.6 }}>Всичко се пази локално в браузъра. Сваляй резервно копие редовно и го пази на сигурно място.</p>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <Button T={T} kind="ghost" icon="download" onClick={onBackup}>Свали резервно копие (.json)</Button>
          <label style={{ cursor: "pointer" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 16px", borderRadius: 7, fontSize: 12.5, fontWeight: 600, fontFamily: MONO, border: `1px solid ${T.line}`, color: T.ink }}><Icon name="save" size={14} />Възстанови от копие</span>
            <input type="file" accept=".json" onChange={onRestore} style={{ display: "none" }} />
          </label>
          {history.length > 0 && <Button T={T} kind="ghost" icon="chart" onClick={onCSV}>Експорт CSV</Button>}
        </div>
      </div>
      {history.length > 0 && (
        <div style={{ padding: "20px 22px", background: T.surface, border: `1px solid ${T.danger}40`, borderRadius: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: T.danger, marginBottom: 6 }}>Опасна зона</div>
          <p style={{ fontSize: 12, color: T.sub, margin: "0 0 14px", lineHeight: 1.6 }}>Изтрива цялата история, клиенти, артикули и шаблони. Необратимо.</p>
          <Button T={T} kind="ghost" danger icon="trash" onClick={onReset}>{confirmReset ? "⚠ Натисни пак за потвърждение" : "Изтрий всички данни"}</Button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { HistoryView, ClientsView, ItemsView, TemplatesView, DashboardView, ArchiveView, Empty });
