// invoice-list.jsx — Invoices list with filters

const InvoiceList = ({ t, lang, onOpenInvoice, onNew }) => {
  const [search, setSearch] = React.useState("");
  const [filter, setFilter] = React.useState("all");

  const filtered = INVOICES.filter(inv => {
    if (filter !== "all" && inv.status !== filter) return false;
    if (!search) return true;
    const c = CLIENTS.find(c => c.id === inv.clientId);
    const q = search.toLowerCase();
    return inv.number.toLowerCase().includes(q) || c.name.toLowerCase().includes(q) || inv.project.toLowerCase().includes(q);
  });

  const counts = {
    all: INVOICES.length,
    paid: INVOICES.filter(i => i.status === "paid").length,
    pending: INVOICES.filter(i => i.status === "pending").length,
    overdue: INVOICES.filter(i => i.status === "overdue").length,
    draft: INVOICES.filter(i => i.status === "draft").length,
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <div className="search-input" style={{ flex: 1, minWidth: 240, maxWidth: 420 }}>
          <Icon name="search"/>
          <input className="input" placeholder={t("search")} value={search} onChange={e => setSearch(e.target.value)}/>
          <kbd>⌘K</kbd>
        </div>
        <div className="seg">
          {[
            { k: "all", l: t("all") },
            { k: "pending", l: t("pending") },
            { k: "overdue", l: t("overdue") },
            { k: "paid", l: t("paid") },
            { k: "draft", l: t("draft") },
          ].map(o => (
            <button key={o.k} className={filter === o.k ? "on" : ""} onClick={() => setFilter(o.k)}>
              {o.l} <span style={{ color: "var(--fg-3)", fontFamily: "var(--font-mono)", fontSize: 10.5, marginLeft: 4 }}>{counts[o.k]}</span>
            </button>
          ))}
        </div>
        <button className="btn"><Icon name="filter" size={13}/> {lang === "es" ? "Filtros" : "Filters"}</button>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <button className="btn"><Icon name="download" size={13}/> {t("exportCsv")}</button>
          <button className="btn primary" onClick={onNew}><Icon name="plus" size={13}/> {t("newInvoice")}</button>
        </div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 36 }}><input type="checkbox" style={{ accentColor: "var(--accent)" }}/></th>
              <th>{t("number")}</th>
              <th>{t("client")} / {t("project")}</th>
              <th>{t("issued")}</th>
              <th>{t("due")}</th>
              <th className="right">{t("amount")}</th>
              <th>{t("status")}</th>
              <th style={{ width: 36 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(inv => {
              const c = CLIENTS.find(c => c.id === inv.clientId);
              const tot = calcInvoiceTotal(inv).total;
              return (
                <tr key={inv.id} onClick={() => onOpenInvoice(inv.id)}>
                  <td onClick={e => e.stopPropagation()}><input type="checkbox" style={{ accentColor: "var(--accent)" }}/></td>
                  <td className="num" style={{ fontWeight: 500 }}>{inv.number}</td>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 22, height: 22, borderRadius: 5, background: c.color, flexShrink: 0, opacity: 0.85, display: "grid", placeItems: "center", color: "oklch(0.18 0 0)", fontSize: 10, fontWeight: 700 }}>
                        {c.name.split(" ").slice(0, 2).map(w => w[0]).join("")}
                      </div>
                      <div>
                        <div style={{ fontSize: 12.5, fontWeight: 500 }}>{c.name}</div>
                        <div style={{ fontSize: 11, color: "var(--fg-2)" }}>{inv.project}</div>
                      </div>
                    </div>
                  </td>
                  <td className="num" style={{ color: "var(--fg-1)" }}>{inv.issued}</td>
                  <td className="num" style={{ color: inv.status === "overdue" ? "var(--red)" : "var(--fg-1)" }}>{inv.due}</td>
                  <td className="num right" style={{ fontWeight: 600 }}>{fmtMoney(tot)}</td>
                  <td><StatusPill status={inv.status} t={t}/></td>
                  <td onClick={e => e.stopPropagation()}>
                    <button className="btn ghost icon sm"><Icon name="more" size={14}/></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="empty">
            <Icon name="invoice" size={28} style={{ opacity: 0.4 }}/>
            <div style={{ marginTop: 10 }}>{lang === "es" ? "Sin resultados" : "No results"}</div>
          </div>
        )}
      </div>
    </div>
  );
};

const StatusPill = ({ status, t }) => (
  <span className={`pill ${status}`}><span className="dot"/>{t(status)}</span>
);

window.InvoiceList = InvoiceList;
window.StatusPill = StatusPill;
