// hydor-page-costs.jsx — Company costs page.
function CostsPage() {
  const s = useHydor();
  const d = useDerive();
  const push = useToast();
  const [q, setQ] = React.useState("");
  const [typeF, setTypeF] = React.useState("all");
  const [catF, setCatF] = React.useState("all");
  const [sort, setSort] = React.useState({ key: "date", dir: "desc" });
  const [form, setForm] = React.useState(null);
  const [del, setDel] = React.useState(null);

  const active = s.costs.filter((c) => !c.deleted);
  let rows = active
    .filter((c) => typeF === "all" || c.costType === typeF)
    .filter((c) => catF === "all" || c.category === catF)
    .filter((c) => !q || (c.item + " " + c.notes).toLowerCase().includes(q.toLowerCase()));
  const acc = { date: (c) => c.date, item: (c) => c.item, costType: (c) => c.costType, amount: (c) => c.amount, category: (c) => c.category };
  const sorted = sortRows(rows, sort, acc);

  const fixed = active.filter((c) => c.costType === "fixed").reduce((a, c) => a + c.amount, 0);
  const op = active.filter((c) => c.costType === "operational").reduce((a, c) => a + c.amount, 0);
  const unpaid = active.filter((c) => !c.paid).reduce((a, c) => a + c.amount, 0);

  const exportCsv = () => {
    const out = [["Date", "Description", "Type", "Amount", "Taxable", "Paid", "Notes"]];
    sorted.forEach((c) => out.push([c.date, c.item, c.costType, c.amount.toFixed(3), c.taxable ? "yes" : "no", c.paid ? "yes" : "no", c.notes]));
    Hydor.exportCSV("hydor-costs.csv", out); push("Costs exported.");
  };
  const partyName = (id) => { const p = s.parties.find((x) => x.id === id); return p ? p.name : ""; };

  return (
    <div className="content-narrow">
      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(4,1fr)" }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--accent-3)" }}><div className="ms-label">Total costs</div><div className="ms-value">{Hydor.fmtMoney0(fixed + op)}</div><div className="ms-sub">JOD all time</div></div>
        <div className="mini-stat"><div className="ms-label">Fixed</div><div className="ms-value">{Hydor.fmtMoney0(fixed)}</div><div className="ms-sub">recurring overhead</div></div>
        <div className="mini-stat"><div className="ms-label">Operational</div><div className="ms-value">{Hydor.fmtMoney0(op)}</div><div className="ms-sub">variable spend</div></div>
        <div className="mini-stat" style={{ borderLeft: unpaid > 0 ? "3px solid var(--warn)" : null }}><div className="ms-label">Unpaid</div><div className="ms-value">{Hydor.fmtMoney0(unpaid)}</div><div className="ms-sub">payable</div></div>
      </div>

      <div className="toolbar">
        <div className="search"><Icon name="search" /><input placeholder="Search costs…" value={q} onChange={(e) => setQ(e.target.value)} /></div>
        <div className="chip-row">
          {["all", "fixed", "operational"].map((t) => <button key={t} className={"chip" + (typeF === t ? " on" : "")} onClick={() => setTypeF(t)}>{t === "all" ? "All" : Hydor.cap(t)}</button>)}
        </div>
        <select className="sel" style={{ width: 170 }} value={catF} onChange={(e) => setCatF(e.target.value)}>
          <option value="all">All categories</option>
          {(s.meta.costCategories || []).map((c) => <option key={c} value={c}>{c}</option>)}
        </select>
        <div className="grow" />
        <Btn icon="download" onClick={exportCsv} disabled={!active.length}>CSV</Btn>
        <Btn variant="primary" icon="plus" onClick={() => setForm({})}>Record cost</Btn>
      </div>

      <div className="hx-panel" style={{ overflow: "hidden" }}>
        {active.length === 0 ? (
          <Empty icon="cost" title="No costs recorded" action={<Btn variant="primary" icon="plus" onClick={() => setForm({})}>Record a cost</Btn>}>
            Track rent, wages, fuel, marketing and other overhead. These flow into your quarterly net profit and tax calculations.
          </Empty>
        ) : (
          <table className="hx-table">
            <thead><tr>
              <SortHeader col="date" label="Date" sort={sort} setSort={setSort} />
              <SortHeader col="item" label="Description" sort={sort} setSort={setSort} />
              <SortHeader col="costType" label="Type" sort={sort} setSort={setSort} />
              <SortHeader col="category" label="Category" sort={sort} setSort={setSort} />
              <th>Payee</th>
              <th>Tax</th>
              <th>Status</th>
              <SortHeader col="amount" label="Amount" sort={sort} setSort={setSort} r />
              <th></th>
            </tr></thead>
            <tbody>
              {sorted.map((c) => (
                <tr key={c.id}>
                  <td className="num" style={{ color: "var(--text-2)", whiteSpace: "nowrap" }}>{Hydor.fmtDate(c.date)}</td>
                  <td style={{ fontWeight: 500 }}>{c.item}{c.notes && <span style={{ color: "var(--text-3)", fontSize: 12, marginLeft: 8 }}>{c.notes}</span>}</td>
                  <td><Badge color={c.costType === "fixed" ? "purple" : "blue"}>{c.costType}</Badge>{c.recurringRef && <Badge color="gray">auto</Badge>}</td>
                  <td style={{ color: "var(--text-2)", fontSize: 12.5 }}>{c.category || "—"}</td>
                  <td style={{ color: "var(--text-2)", fontSize: 12.5 }}>{partyName(c.partyId) || "—"}</td>
                  <td>{c.taxable ? <Badge color="gray">deductible</Badge> : <span style={{ color: "var(--text-3)" }}>—</span>}</td>
                  <td>{c.paid ? <Badge color="green" dot>paid</Badge> : <span className="linkish" onClick={() => { Hydor.setPaid("cost", c.id, true); push("Marked paid."); }}>Mark paid</span>}</td>
                  <td className="r num" style={{ fontWeight: 600 }}>{Hydor.fmtMoney0(c.amount)}</td>
                  <td className="r no-print">
                    <div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                      <Btn variant="ghost" sm icon="edit" onClick={() => setForm({ editing: c })} />
                      <Btn variant="ghost" sm icon="trash" onClick={() => setDel(c)} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {form && <CostForm editing={form.editing} onClose={() => setForm(null)} />}
      {del && <Confirm title="Delete cost?" danger confirmLabel="Delete" body={`Delete "${del.item}" (${Hydor.fmtMoney0(del.amount)} JOD)?`}
        onConfirm={() => { Hydor.deleteCost(del.id); push("Cost deleted."); }} onClose={() => setDel(null)} />}
    </div>
  );
}

// hydor-page-contacts.jsx — Customers & Suppliers.
function ContactsPage({ onDrill }) {
  const s = useHydor();
  const d = useDerive();
  const push = useToast();
  const role = useRole();
  const me = Hydor.currentUser();
  const canMoney = Hydor.can(role, "seeCostProfit");
  const canSuppliers = Hydor.can(role, "seeSuppliers");
  const seeAll = Hydor.can(role, "seeAllContacts");
  const [tab, setTabRaw] = React.useState("customer");
  const tabv = canSuppliers ? tab : "customer";   // non-owner/co-founder only ever see customers
  const setTab = (t) => setTabRaw(t);
  const [q, setQ] = React.useState("");
  const [form, setForm] = React.useState(null);
  const [del, setDel] = React.useState(null);
  const [fu, setFu] = React.useState(null);   // schedule follow-up for a party
  // open follow-ups per party
  const openFU = {}; s.followups.forEach((f) => { if (f.status !== "done" && f.partyId) openFU[f.partyId] = (openFU[f.partyId] || 0) + 1; });

  const parties = s.parties
    .filter((p) => p.type === tabv)
    .filter((p) => seeAll || (me && p.createdBy === me.id))   // each employee sees only the clients they added
    .filter((p) => !q || p.name.toLowerCase().includes(q.toLowerCase()));
  // per-party rollups
  const stats = (id) => {
    if (tabv === "customer") {
      const txs = s.transactions.filter((t) => !t.deleted && t.type === "sale" && t.partyId === id);
      const sales = txs.reduce((a, t) => a + ((d.txc[t.id] || {}).subtotal || 0), 0);
      const owed = txs.filter((t) => !t.paid).reduce((a, t) => a + ((d.txc[t.id] || {}).total || 0), 0);
      return { count: txs.length, value: sales, owed };
    } else {
      const txs = s.transactions.filter((t) => !t.deleted && t.type === "purchase" && t.partyId === id);
      const costs = s.costs.filter((c) => !c.deleted && c.partyId === id);
      const spend = txs.reduce((a, t) => a + (t.qty * t.unitCost), 0) + costs.reduce((a, c) => a + c.amount, 0);
      const owed = txs.filter((t) => !t.paid).reduce((a, t) => a + t.qty * t.unitCost, 0) + costs.filter((c) => !c.paid).reduce((a, c) => a + c.amount, 0);
      return { count: txs.length + costs.length, value: spend, owed };
    }
  };

  return (
    <div className="content-narrow">
      {canSuppliers ? (
        <div className="tabs">
          <button className={"tab" + (tabv === "customer" ? " on" : "")} onClick={() => setTab("customer")}>Customers</button>
          <button className={"tab" + (tabv === "supplier" ? " on" : "")} onClick={() => setTab("supplier")}>Suppliers</button>
        </div>
      ) : (
        <div className="tabs"><button className="tab on">My Customers</button></div>
      )}
      <div className="toolbar">
        <div className="search"><Icon name="search" /><input placeholder={"Search " + tabv + "s…"} value={q} onChange={(e) => setQ(e.target.value)} /></div>
        <div className="grow" />
        <Btn variant="primary" icon="plus" onClick={() => setForm({})}>New {tabv}</Btn>
      </div>

      <div className="hx-panel" style={{ overflow: "hidden" }}>
        {parties.length === 0 ? (
          <Empty icon="people" title={`No ${tabv}s yet`} action={<Btn variant="primary" icon="plus" onClick={() => setForm({})}>Add {tabv}</Btn>}>
            {tabv === "customer" ? (seeAll ? "Add customers to track who buys from you, top accounts and outstanding receivables." : "Add your own customers here. Only you and the founders can see the clients you add.") : "Add suppliers to compare costs and track what you owe."}
          </Empty>
        ) : (
          <table className="hx-table">
            <thead><tr>
              <th>Name</th><th>Phone</th><th>Follow-ups</th>
              <th className="r">{tabv === "customer" ? "Orders" : "Bills"}</th>
              {canMoney && <th className="r">{tabv === "customer" ? "Total sales" : "Total spend"}</th>}
              {canMoney && <th className="r">Outstanding</th>}<th></th>
            </tr></thead>
            <tbody>
              {parties.map((p) => { const st = stats(p.id); return (
                <tr key={p.id} className="clickrow" onClick={() => onDrill({ type: "party", id: p.id })}>
                  <td><span className="hx-emp" style={{ gap: 10 }}><span className="hx-emp-badge">{p.name.slice(0, 1).toUpperCase()}</span><span style={{ fontWeight: 500 }}>{p.name}</span></span></td>
                  <td style={{ color: "var(--text-2)" }}>{p.phone || "—"}</td>
                  <td>{openFU[p.id] ? <Badge color="amber" dot>{openFU[p.id]} open</Badge> : <span style={{ color: "var(--text-3)", fontSize: 12 }}>—</span>}</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{st.count}</td>
                  {canMoney && <td className="r num">{Hydor.fmtMoney0(st.value)}</td>}
                  {canMoney && <td className="r num">{st.owed > 0 ? <span className="hx-num" style={{ color: "var(--warn)" }}>{Hydor.fmtMoney0(st.owed)}</span> : <span style={{ color: "var(--text-3)" }}>—</span>}</td>}
                  <td className="r no-print" onClick={(e) => e.stopPropagation()}>
                    <div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                      <Btn variant="ghost" sm icon="phone" title="Schedule follow-up" onClick={() => setFu(p)} />
                      <Btn variant="ghost" sm icon="edit" onClick={() => setForm({ editing: p })} />
                      <Btn variant="ghost" sm icon="trash" onClick={() => setDel(p)} />
                    </div>
                  </td>
                </tr>
              ); })}
            </tbody>
          </table>
        )}
      </div>

      {form && <PartyForm editing={form.editing} presetType={tabv} onClose={() => setForm(null)} />}
      {fu && <QuickFollowupForm party={fu} onClose={() => setFu(null)} push={push} />}
      {del && <Confirm title="Delete contact?" danger confirmLabel="Delete" body={`Delete ${del.name}? Their past transactions stay in the ledger.`}
        onConfirm={() => { Hydor.deleteParty(del.id); push("Contact deleted."); }} onClose={() => setDel(null)} />}
    </div>
  );
}

function QuickFollowupForm({ party, onClose, push }) {
  const s = Hydor.getState();
  const isCust = party.type === "customer";
  const kinds = isCust ? [["service", "Service / cartridge check"], ["call", "Call back"], ["quote", "Quote follow-up"], ["warranty", "Warranty check"]] : [["reorder", "Reorder before minimum stock"], ["call", "Check in / pricing"]];
  const inDays = (n) => { const x = new Date(); x.setDate(x.getDate() + n); return x.toISOString().slice(0, 10); };
  const [f, setF] = React.useState({ kind: kinds[0][0], note: "", dueDate: inDays(isCust ? 180 : 14), assignedTo: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const reps = s.users.filter((u) => u.active);
  const save = () => { Hydor.addFollowup({ ...f, partyId: party.id }); push("Follow-up scheduled for " + party.name + "."); onClose(); };
  return (
    <Modal title={"Follow-up · " + party.name} onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Schedule</Btn></>}>
      <div className="form-grid">
        <Field label="Type"><select className="sel" value={f.kind} onChange={(e) => set("kind", e.target.value)}>{kinds.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></Field>
        <Field label="Due date" hint={isCust ? "Defaulted ~6 months out" : "Defaulted 2 weeks out"}><input className="inp" type="date" value={f.dueDate} onChange={(e) => set("dueDate", e.target.value)} /></Field>
        <Field label="Assign to" span2><select className="sel" value={f.assignedTo} onChange={(e) => set("assignedTo", e.target.value)}><option value="">— unassigned —</option>{reps.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</select></Field>
        <Field label="Note" span2><input className="inp" value={f.note} onChange={(e) => set("note", e.target.value)} placeholder={isCust ? "e.g. Check if RO cartridge needs replacing" : "e.g. Confirm stock & pricing before reorder"} /></Field>
      </div>
    </Modal>
  );
}
Object.assign(window, { CostsPage, ContactsPage });
