/* PC Liquors — Admin portal modules.
   POS & Sales · Inventory · Ads & Offers · Employees · Expenses ·
   Utilities · Documents · Settings.  All live against Supabase via /api. */
const DSx = window.PCLiquorsDesignSystem_ae5d4f;
const { Button, Badge, Tag, Tabs, Table, StatCard, Card, Input, Select, Textarea, Switch,
        Avatar, Alert, Tooltip, Dialog, FormField, EmptyState, Spinner } = DSx;
const { Icons:Ic, api, useCollection, FIELDS, CATEGORIES,
        money, money0, shortDate, dateInput, dtInput, bytes, SalesChart } = window.PCAdmin;

/* ================= shared building blocks ================= */

function Loading({ label }) {
  return <div className="mod-loading"><Spinner /><span>{label || "Loading…"}</span></div>;
}

/* Surfaces a module-level failure (expired session, schema not exposed, …)
   in the same voice as the rest of the portal. */
function ModuleError({ error, onRetry }) {
  if (!error) return null;
  return (
    <Alert tone="danger" title="Couldn't load this module">
      <span>{error}</span>
      {onRetry && <button className="mod-retry" onClick={onRetry}>Try again</button>}
    </Alert>
  );
}

/* One form control, driven by a FIELDS[…] spec. */
function SpecField({ spec, value, onChange }) {
  const common = { id: spec.k, placeholder: spec.placeholder };

  if (spec.type === "switch") {
    return (
      <div className="fld-switch">
        <Switch checked={Boolean(value)} onChange={(e)=>onChange(e.target.checked)} label={spec.label} />
        {spec.hint && <span className="fld-hint">{spec.hint}</span>}
      </div>
    );
  }

  let control;
  if (spec.type === "select") {
    const opts = spec.options.map((o)=> typeof o === "string" ? { v:o, t:o } : o);
    control = (
      <Select {...common} value={value === null || value === undefined ? "" : value}
              onChange={(e)=>onChange(e.target.value)}>
        {opts.map((o)=> <option key={o.v} value={o.v}>{o.t}</option>)}
      </Select>
    );
  } else if (spec.type === "textarea") {
    control = <Textarea {...common} rows={3} value={value || ""} onChange={(e)=>onChange(e.target.value)} />;
  } else if (spec.type === "date") {
    control = <Input {...common} type="date" value={dateInput(value)} onChange={(e)=>onChange(e.target.value)} />;
  } else if (spec.type === "datetime") {
    control = <Input {...common} type="datetime-local" value={dtInput(value)}
                     onChange={(e)=>onChange(e.target.value ? new Date(e.target.value).toISOString() : "")} />;
  } else {
    control = <Input {...common} type={spec.type || "text"} step={spec.step} mono={spec.mono}
                     value={value === null || value === undefined ? "" : value}
                     onChange={(e)=>onChange(e.target.value)} />;
  }
  return <FormField label={spec.label} required={spec.required} hint={spec.hint} htmlFor={spec.k}>{control}</FormField>;
}

/* Add/edit dialog generated from a module's field spec. */
function RecordDialog({ open, title, specs, record, busy, error, onSave, onClose }) {
  const [values, setValues] = React.useState({});

  React.useEffect(() => {
    if (!open) return;
    const seed = {};
    specs.forEach((s) => {
      const v = record ? record[s.k] : undefined;
      if (v !== undefined && v !== null) seed[s.k] = v;
      else if (record) seed[s.k] = s.type === "switch" ? false : "";
      else if (s.def !== undefined) seed[s.k] = s.def;
      else if (s.type === "switch") seed[s.k] = true;
      else if (s.type === "select") seed[s.k] = (typeof s.options[0] === "string" ? s.options[0] : s.options[0].v);
      else seed[s.k] = "";
    });
    setValues(seed);
  }, [open, record, specs]);

  if (!open) return null;
  const missing = specs.filter((s) => {
    if (!s.required) return false;
    const val = values[s.k];
    return val === undefined || val === null || String(val).trim() === "";
  });
  const set = (k, v) => setValues((old) => Object.assign({}, old, { [k]: v }));

  return (
    <Dialog open title={title} onClose={onClose} width={560}
      footer={
        <React.Fragment>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button variant="primary" disabled={busy || missing.length > 0} onClick={()=>onSave(values)}>
            {busy ? "Saving…" : "Save"}
          </Button>
        </React.Fragment>}>
      <div className="dlg-form">
        {error && <Alert tone="danger"><span>{error}</span></Alert>}
        <div className="dlg-grid">
          {specs.map((s)=>(
            <div key={s.k} className={s.half ? "dlg-cell dlg-cell--half" : "dlg-cell"}>
              <SpecField spec={s} value={values[s.k]} onChange={(v)=>set(s.k, v)} />
            </div>
          ))}
        </div>
      </div>
    </Dialog>
  );
}

/* Two-step delete so a mis-click can't wipe a record. */
function ConfirmDelete({ target, label, busy, onConfirm, onClose }) {
  if (!target) return null;
  return (
    <Dialog open title="Delete this record?" onClose={onClose} width={420}
      footer={
        <React.Fragment>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Keep it</Button>
          <Button variant="danger" onClick={onConfirm} disabled={busy}>{busy ? "Deleting…" : "Delete"}</Button>
        </React.Fragment>}>
      <p className="dlg-confirm">Deleting <b>{label}</b> can't be undone.</p>
    </Dialog>
  );
}

/* Add / edit / delete wiring every module reuses. */
function useEditor(collection) {
  const [editing, setEditing] = React.useState(null);   // record | "new" | null
  const [deleting, setDeleting] = React.useState(null);

  const save = async (values) => {
    const id = editing && editing !== "new" ? editing.id : null;
    if (await collection.save(values, id)) setEditing(null);
  };
  const confirmDelete = async () => {
    if (await collection.remove(deleting.id)) setDeleting(null);
  };
  return { editing, setEditing, deleting, setDeleting, save, confirmDelete };
}

const rowActions = (onEdit, onDelete) => ({
  key:"_a", label:"", align:"right",
  render:(_, r)=>(
    <div className="row-actions">
      <Tooltip label="Edit"><button className="icon-act" onClick={()=>onEdit(r)}><Ic.edit s={15} /></button></Tooltip>
      <Tooltip label="Delete"><button className="icon-act icon-act--danger" onClick={()=>onDelete(r)}><Ic.trash s={15} /></button></Tooltip>
    </div>
  ),
});

/* ===================== POS & SALES ===================== */
function PosView({ go }) {
  const [sum, setSum] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [range, setRange] = React.useState("week");

  const load = React.useCallback(() => {
    setError(null);
    api.summary().then(setSum).catch((e)=>setError(e.message));
  }, []);
  React.useEffect(()=>{ load(); }, [load]);

  const products = useCollection("products");
  const top = (products.rows || []).slice()
    .sort((a,b)=> Number(b.price||0)*Number(b.stock||0) - Number(a.price||0)*Number(a.stock||0))
    .slice(0,5);

  return (
    <div className="view">
      <ModuleError error={error} onRetry={load} />

      <div className="view__row view__row--between">
        <Alert tone="warning" title="Clover POS not connected yet">
          <span>Today's sales chart below is a forecast shape. Connect the Clover feed to replace it with live transactions.</span>
        </Alert>
        <Button variant="outline" size="sm" leftIcon={<Ic.sync s={15} />} onClick={load}>Refresh</Button>
      </div>

      {!sum ? <Loading label="Loading store summary…" /> : (
        <React.Fragment>
          <div className="kpis">
            <StatCard label="Inventory value" value={money0(sum.products.retailValue)} icon={<Ic.box s={18} />}
              delta={sum.products.marginPct + "% margin"} deltaDirection="up" caption={sum.products.count + " SKUs"} />
            <StatCard label="Low / out of stock" value={String(sum.products.lowStock)} icon={<Ic.alert s={18} />}
              delta="needs reorder" deltaDirection={sum.products.lowStock ? "down" : "up"} caption="across the catalogue" />
            <StatCard label="Live offers" value={String(sum.ads.live)} icon={<Ic.megaphone s={18} />}
              delta={sum.ads.count + " total"} deltaDirection="up" caption="showing on the storefront" />
            <StatCard label="Monthly utilities" value={money0(sum.utilities.monthly)} icon={<Ic.bolt s={18} />}
              delta={sum.utilities.overdue ? sum.utilities.overdue + " overdue" : "all current"}
              deltaDirection={sum.utilities.overdue ? "down" : "up"} caption={sum.utilities.count + " services"} />
          </div>

          <div className="kpis kpis--3">
            <StatCard label="Money in" value={money0(sum.expenses.incoming)} icon={<Ic.up s={18} />} caption="recorded this period" />
            <StatCard label="Money out" value={money0(sum.expenses.outgoing)} icon={<Ic.down s={18} />} caption="recorded this period" />
            <StatCard label="Payroll" value={money0(sum.employees.payroll)} icon={<Ic.users s={18} />}
              caption={sum.employees.count + " active staff"} />
          </div>

          {sum.documents.expiringSoon > 0 && (
            <Alert tone="warning" title="Documents expiring within 30 days">
              <span>{sum.documents.expiringSoon} licence or permit needs renewing — open Documents to check.</span>
            </Alert>
          )}
        </React.Fragment>
      )}

      <Card padded className="panel">
        <div className="panel__head">
          <div>
            <div className="panel__title">Sales — past &amp; forecast</div>
            <div className="panel__sub">Solid bars are actuals; dashed bars are the model's prediction.</div>
          </div>
          <div className="panel__tools">
            <Tabs value={range} onChange={setRange} items={[{id:"day",label:"Day"},{id:"week",label:"Week"},{id:"month",label:"Month"}]} />
          </div>
        </div>
        <SalesChart />
        <div className="chart-legend">
          <span><i className="dot dot--solid"></i> Actual sales</span>
          <span><i className="dot dot--dash"></i> Predicted</span>
        </div>
      </Card>

      <Card padded className="panel">
        <div className="panel__head">
          <div><div className="panel__title">Highest-value stock</div>
            <div className="panel__sub">Retail value on hand — from your live catalogue.</div></div>
          <Button variant="ghost" size="sm" onClick={()=>go("inventory")}>Open inventory</Button>
        </div>
        {products.rows === null ? <Loading /> : top.length === 0
          ? <EmptyState icon={<Ic.box s={26} />} title="No products yet"
              message="Add your catalogue in Inventory and it will show up here." />
          : <Table
              columns={[
                { key:"name", label:"Product" },
                { key:"sku", label:"SKU", render:(v)=> <span className="mono-muted">{v}</span> },
                { key:"stock", label:"On hand", align:"right" },
                { key:"price", label:"Price", align:"right", render:(v)=> money(v) },
                { key:"_v", label:"Stock value", align:"right",
                  render:(_,r)=> money(Number(r.price||0)*Number(r.stock||0)) },
              ]}
              rows={top} getRowKey={(r)=>r.id} />}
      </Card>
    </div>
  );
}

/* ===================== INVENTORY ===================== */
const statusTone = (s) => s === "In stock" ? "success" : s === "Low" ? "warning" : "danger";

function InventoryView() {
  const c = useCollection("products");
  const ed = useEditor(c);
  const [cat, setCat] = React.useState("all");
  const [q, setQ] = React.useState("");

  const all = c.rows || [];
  const lowCount = all.filter((r)=> r.status !== "In stock").length;
  const tabs = [{ id:"all", label:"All", count:all.length }]
    .concat(CATEGORIES.filter((k)=> all.some((r)=> r.category === k)).map((k)=>({ id:k, label:k })))
    .concat([{ id:"low", label:"Low stock", count:lowCount }]);

  const rows = all.filter((r)=>{
    const inCat = cat === "all" ? true : cat === "low" ? r.status !== "In stock" : r.category === cat;
    if (!inCat) return false;
    if (!q.trim()) return true;
    const hay = [r.name, r.sku, r.category, r.supplier].join(" ").toLowerCase();
    return hay.includes(q.trim().toLowerCase());
  });

  return (
    <div className="view">
      <ModuleError error={c.error} onRetry={c.reload} />
      <div className="view__row view__row--between">
        <Tabs value={cat} onChange={setCat} items={tabs} />
        <div className="view__row">
          <label className="inline-search"><Ic.search s={16} />
            <input placeholder="Search SKU, brand, supplier…" value={q} onChange={(e)=>setQ(e.target.value)} /></label>
          <Button variant="primary" size="sm" leftIcon={<Ic.plus s={15} />} onClick={()=>ed.setEditing("new")}>Add product</Button>
        </div>
      </div>

      <Card padded={false} className="panel">
        {c.rows === null ? <Loading label="Loading catalogue…" /> : rows.length === 0
          ? <EmptyState icon={<Ic.box s={26} />} title={all.length ? "Nothing matches that filter" : "No products yet"}
              message={all.length ? "Try a different category or search term." : "Add your first SKU to start tracking stock, price and margin."}
              action={all.length ? null : <Button variant="primary" size="sm" onClick={()=>ed.setEditing("new")}>Add product</Button>} />
          : <React.Fragment>
              <Table
                columns={[
                  { key:"name", label:"Product", render:(v,r)=>(
                      <div className="cell-prod"><span className="cell-prod__name">{v}{r.featured && <Badge tone="gold" style={{marginLeft:8}}>Featured</Badge>}</span>
                        <span className="cell-prod__cat">{r.category}{r.kind ? " · " + r.kind : ""}</span></div>) },
                  { key:"sku", label:"SKU", render:(v)=> <span className="mono-muted">{v}</span> },
                  { key:"price", label:"Price", align:"right", render:(v)=> money(v) },
                  { key:"cost", label:"Margin", align:"right", render:(v,r)=>{
                      const p = Number(r.price||0), cst = Number(v||0);
                      return p && cst ? Math.round(((p-cst)/p)*100) + "%" : "—"; } },
                  { key:"stock", label:"On hand", align:"right" },
                  { key:"status", label:"Status", render:(v)=> <Badge tone={statusTone(v)} dot>{v}</Badge> },
                  rowActions(ed.setEditing, ed.setDeleting),
                ]}
                rows={rows} getRowKey={(r)=>r.id} />
              <div className="panel__foot"><span className="panel__count">Showing {rows.length} of {all.length} SKUs</span></div>
            </React.Fragment>}
      </Card>

      <RecordDialog open={Boolean(ed.editing)} title={ed.editing === "new" ? "Add product" : "Edit product"}
        specs={FIELDS.products} record={ed.editing === "new" ? null : ed.editing}
        busy={c.busy} error={c.error} onSave={ed.save} onClose={()=>{ ed.setEditing(null); c.setError(null); }} />
      <ConfirmDelete target={ed.deleting} label={ed.deleting && ed.deleting.name} busy={c.busy}
        onConfirm={ed.confirmDelete} onClose={()=>ed.setDeleting(null)} />
    </div>
  );
}

/* ===================== ADS & OFFERS ===================== */
/* Live preview of exactly what the storefront will render for an offer. */
function AdPreview({ ad }) {
  return (
    <div className="adprev">
      <div className="adprev__label">Storefront preview</div>
      <div className={"adprev__strip adprev__strip--" + (ad.tone || "gold")}>
        <span className="adprev__badge">{ad.label || "LABEL"}</span>
        <span className="adprev__msg">{ad.message || ad.title || "Your offer message shows here."}</span>
        {ad.cta_label && <span className="adprev__cta">{ad.cta_label} →</span>}
      </div>
      <div className="adprev__cardrow">
        <div className="adprev__card">
          <span className="adprev__cardtag"><Badge tone={ad.tone || "gold"}>{ad.label || "LABEL"}</Badge></span>
          <div className="adprev__bottle" />
          <div className="adprev__cardname">{ad.target_product || (ad.target_category ? "Any " + ad.target_category : "Every product")}</div>
        </div>
        <p className="adprev__note">
          {ad.placement === "banner" ? "Shows in the top banner only."
            : ad.placement === "product" ? "Shows as a label on matching product cards."
            : "Shows in the top banner and as a label on matching product cards."}
        </p>
      </div>
    </div>
  );
}

function adWindow(ad) {
  if (ad.starts_at && ad.ends_at) return shortDate(ad.starts_at) + " → " + shortDate(ad.ends_at);
  if (ad.starts_at) return "From " + shortDate(ad.starts_at);
  if (ad.ends_at) return "Until " + shortDate(ad.ends_at);
  return "Always on";
}
function adState(ad) {
  if (!ad.is_active) return { tone:"neutral", text:"Off" };
  if (ad.live) return { tone:"success", text:"Live" };
  if (ad.starts_at && new Date(ad.starts_at) > new Date()) return { tone:"gold", text:"Scheduled" };
  return { tone:"danger", text:"Expired" };
}

function AdsView() {
  const c = useCollection("ads");
  const ed = useEditor(c);
  const [filter, setFilter] = React.useState("all");

  const all = c.rows || [];
  const live = all.filter((a)=>a.live);
  const rows = filter === "all" ? all
    : filter === "live" ? live
    : filter === "scheduled" ? all.filter((a)=> a.is_active && !a.live && a.starts_at && new Date(a.starts_at) > new Date())
    : all.filter((a)=> !a.is_active || (a.ends_at && new Date(a.ends_at) < new Date()));

  /* The switch in the table writes straight through — no dialog for on/off. */
  const toggle = (ad) => c.save({ is_active: !ad.is_active }, ad.id);

  return (
    <div className="view">
      <ModuleError error={c.error} onRetry={c.reload} />

      <div className="view__row view__row--between">
        <Tabs value={filter} onChange={setFilter} items={[
          { id:"all", label:"All offers", count: all.length },
          { id:"live", label:"Live now", count: live.length },
          { id:"scheduled", label:"Scheduled" },
          { id:"off", label:"Off / expired" },
        ]} />
        <Button variant="primary" size="sm" leftIcon={<Ic.plus s={15} />} onClick={()=>ed.setEditing("new")}>New offer</Button>
      </div>

      <Alert tone={live.length ? "success" : "info"} title={live.length ? live.length + " offer" + (live.length===1?"":"s") + " showing on pcliquors.com right now" : "No offers are live"}>
        <span>Anything switched on and inside its date window appears as a label on the storefront within a minute.</span>
      </Alert>

      <Card padded={false} className="panel">
        {c.rows === null ? <Loading label="Loading offers…" /> : rows.length === 0
          ? <EmptyState icon={<Ic.megaphone s={26} />} title={all.length ? "Nothing in this tab" : "No offers yet"}
              message={all.length ? "Switch tabs to see your other offers." : "Create an offer and its label appears on the storefront straight away."}
              action={all.length ? null : <Button variant="primary" size="sm" onClick={()=>ed.setEditing("new")}>New offer</Button>} />
          : <Table
              columns={[
                { key:"label", label:"Label", render:(v,r)=> <Badge tone={r.tone || "gold"}>{v}</Badge> },
                { key:"title", label:"Offer", render:(v,r)=>(
                    <div className="cell-prod"><span className="cell-prod__name">{v}</span>
                      <span className="cell-prod__cat">{r.message || "—"}</span></div>) },
                { key:"target_category", label:"Applies to",
                  render:(v,r)=> r.target_product ? r.target_product : (v || "All products") },
                { key:"placement", label:"Placement", render:(v)=> <Badge tone="neutral">{v}</Badge> },
                { key:"_w", label:"Runs", render:(_,r)=> <span className="mono-muted">{adWindow(r)}</span> },
                { key:"_s", label:"Status", render:(_,r)=>{ const s = adState(r);
                    return <Badge tone={s.tone} dot>{s.text}</Badge>; } },
                { key:"_t", label:"On", align:"center",
                  render:(_,r)=> <Switch checked={Boolean(r.is_active)} disabled={c.busy} onChange={()=>toggle(r)} /> },
                rowActions(ed.setEditing, ed.setDeleting),
              ]}
              rows={rows} getRowKey={(r)=>r.id} />}
      </Card>

      {live.length > 0 && (
        <Card padded className="panel">
          <div className="panel__head"><div>
            <div className="panel__title">What customers see</div>
            <div className="panel__sub">The highest-priority live offer takes the banner.</div></div></div>
          <AdPreview ad={live.slice().sort((a,b)=> (b.priority||0)-(a.priority||0))[0]} />
        </Card>
      )}

      <RecordDialog open={Boolean(ed.editing)} title={ed.editing === "new" ? "New offer" : "Edit offer"}
        specs={FIELDS.ads} record={ed.editing === "new" ? null : ed.editing}
        busy={c.busy} error={c.error} onSave={ed.save} onClose={()=>{ ed.setEditing(null); c.setError(null); }} />
      <ConfirmDelete target={ed.deleting} label={ed.deleting && ed.deleting.title} busy={c.busy}
        onConfirm={ed.confirmDelete} onClose={()=>ed.setDeleting(null)} />
    </div>
  );
}

/* ===================== EMPLOYEES ===================== */
function EmployeesView() {
  const c = useCollection("employees");
  const ed = useEditor(c);
  const all = c.rows || [];
  const active = all.filter((e)=>e.active);
  const pay = active.reduce((s,e)=> s + Number(e.hours_ytd||0) * Number(e.hourly_rate||0), 0);
  const hours = active.reduce((s,e)=> s + Number(e.hours_ytd||0), 0);

  return (
    <div className="view">
      <ModuleError error={c.error} onRetry={c.reload} />
      <div className="view__row view__row--between">
        <div className="view__row">
          <StatCard label="Team" value={String(active.length)} icon={<Ic.users s={18} />} caption="active staff" />
          <StatCard label="Hours" value={String(Math.round(hours))} icon={<Ic.clock s={18} />} caption="this period" />
          <StatCard label="Payroll" value={money(pay)} icon={<Ic.dollar s={18} />} caption="gross" />
        </div>
        <Button variant="primary" size="sm" leftIcon={<Ic.plus s={15} />} onClick={()=>ed.setEditing("new")}>Add employee</Button>
      </div>

      <Card padded={false} className="panel">
        {c.rows === null ? <Loading label="Loading team…" /> : all.length === 0
          ? <EmptyState icon={<Ic.users s={26} />} title="No employees yet"
              message="Add your team to track hours, rates and gross payroll."
              action={<Button variant="primary" size="sm" onClick={()=>ed.setEditing("new")}>Add employee</Button>} />
          : <Table
              columns={[
                { key:"name", label:"Employee", render:(v,r)=>(
                    <div className="cell-emp"><Avatar name={v} size="sm" />
                      <div><span className="cell-emp__name">{v}</span>
                        <span className="cell-emp__mail">{r.email || r.phone || "—"}</span></div></div>) },
                { key:"role", label:"Role", render:(v)=> <Badge tone="neutral">{v || "—"}</Badge> },
                { key:"hired_on", label:"Hired", render:(v)=> <span className="mono-muted">{shortDate(v)}</span> },
                { key:"hours_ytd", label:"Hours", align:"right", render:(v)=> Number(v||0) },
                { key:"hourly_rate", label:"Rate / hr", align:"right", render:(v)=> money(v) },
                { key:"_p", label:"Gross pay", align:"right",
                  render:(_,r)=> money(Number(r.hours_ytd||0) * Number(r.hourly_rate||0)) },
                { key:"active", label:"Status", render:(v)=> <Badge tone={v?"success":"neutral"} dot>{v?"Active":"Inactive"}</Badge> },
                rowActions(ed.setEditing, ed.setDeleting),
              ]}
              rows={all} getRowKey={(r)=>r.id} />}
      </Card>

      <RecordDialog open={Boolean(ed.editing)} title={ed.editing === "new" ? "Add employee" : "Edit employee"}
        specs={FIELDS.employees} record={ed.editing === "new" ? null : ed.editing}
        busy={c.busy} error={c.error} onSave={ed.save} onClose={()=>{ ed.setEditing(null); c.setError(null); }} />
      <ConfirmDelete target={ed.deleting} label={ed.deleting && ed.deleting.name} busy={c.busy}
        onConfirm={ed.confirmDelete} onClose={()=>ed.setDeleting(null)} />
    </div>
  );
}

/* ===================== EXPENSES ===================== */
const srcIcon = { pos:"receipt", bank:"bank", card:"card", mail:"mail" };

function ExpensesView() {
  const c = useCollection("expenses");
  const ed = useEditor(c);
  const [plaidStatus, setPlaidStatus] = React.useState(null);
  const [imported, setImported] = React.useState(null);
  const fileRef = React.useRef();

  const all = c.rows || [];
  const incoming = all.filter((e)=>e.type==="in").reduce((s,e)=> s+Number(e.amount||0), 0);
  const outgoing = all.filter((e)=>e.type==="out").reduce((s,e)=> s+Number(e.amount||0), 0);

  const connectPlaid = async () => {
    setPlaidStatus("Connecting…");
    try {
      const res = await fetch("/api/create-link-token", { method: "POST" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Plaid not configured");
      setPlaidStatus("Link token created — hand off to the Plaid Link SDK to finish the bank connection.");
    } catch (e) {
      setPlaidStatus("Plaid isn't configured yet — add PLAID_CLIENT_ID and PLAID_SECRET in Vercel env vars.");
    }
  };

  /* CSV import: date,description,amount[,in|out] — saved straight into the ledger. */
  const onCsv = (e) => {
    const file = e.target.files[0]; if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => {
      const lines = String(reader.result).split(/\r?\n/).filter((l)=>l.trim());
      const body = lines.slice(1).map((line)=>{
        const cells = line.split(",").map((x)=>x.trim().replace(/^"|"$/g, ""));
        const amount = parseFloat(String(cells[2] || "0").replace(/[$,]/g, ""));
        if (!cells[0] || !cells[1] || isNaN(amount)) return null;
        return { date: cells[0], description: cells[1], amount: Math.abs(amount),
                 type: (cells[3] || (amount < 0 ? "out" : "in")).toLowerCase() === "in" ? "in" : "out",
                 source: "bank", channel: "CSV import" };
      }).filter(Boolean);
      if (!body.length) { setImported("Couldn't read any rows — expected columns: date, description, amount, in/out."); return; }
      setImported("Importing " + body.length + " rows…");
      let ok = 0;
      for (const row of body) { if (await c.save(row)) ok++; }
      setImported("Imported " + ok + " of " + body.length + " rows from " + file.name + ".");
      e.target.value = "";
    };
    reader.readAsText(file);
  };

  return (
    <div className="view">
      <ModuleError error={c.error} onRetry={c.reload} />
      <div className="kpis kpis--3">
        <StatCard label="Incoming" value={money(incoming)} icon={<Ic.up s={18} />} delta="POS + bank" deltaDirection="up" caption="recorded" />
        <StatCard label="Outgoing" value={money(outgoing)} icon={<Ic.down s={18} />} delta="vendors + bills" deltaDirection="down" caption="recorded" />
        <StatCard label="Net" value={money(incoming-outgoing)} icon={<Ic.dollar s={18} />}
          delta={incoming-outgoing>=0?"surplus":"deficit"} deltaDirection={incoming-outgoing>=0?"up":"down"} caption="this period" />
      </div>

      <Card padded className="panel">
        <div className="panel__head">
          <div><div className="panel__title">Bring in real transactions</div>
            <div className="panel__sub">Link the bank via Plaid, or import a CSV export from your POS or bank right now.</div></div>
        </div>
        <div className="view__row" style={{gap:"1rem", flexWrap:"wrap"}}>
          <Button variant="outline" size="sm" leftIcon={<Ic.bank s={15} />} onClick={connectPlaid}>Connect bank (Plaid)</Button>
          <Button variant="outline" size="sm" leftIcon={<Ic.upload s={15} />} onClick={()=>fileRef.current.click()}>Import CSV</Button>
          <input ref={fileRef} type="file" accept=".csv" style={{display:"none"}} onChange={onCsv} />
        </div>
        {plaidStatus && <Alert tone="warning" style={{marginTop:"1rem"}}><span>{plaidStatus}</span></Alert>}
        {imported && <Alert tone="success" style={{marginTop:"1rem"}}><span>{imported}</span></Alert>}
      </Card>

      <Card padded={false} className="panel">
        <div className="panel__head" style={{padding:"1.25rem 1.5rem 0"}}>
          <div><div className="panel__title">Transactions</div>
            <div className="panel__sub">Everything recorded across POS, bank, cards and invoices.</div></div>
          <Button variant="primary" size="sm" leftIcon={<Ic.plus s={15} />} onClick={()=>ed.setEditing("new")}>Add transaction</Button>
        </div>
        {c.rows === null ? <Loading label="Loading ledger…" /> : all.length === 0
          ? <EmptyState icon={<Ic.receipt s={26} />} title="No transactions yet"
              message="Add one by hand, or import a CSV from your bank or POS." />
          : <Table
              columns={[
                { key:"date", label:"Date", render:(v)=> <span className="mono-muted">{shortDate(v)}</span> },
                { key:"description", label:"Description", render:(v,r)=>(
                    <div className="cell-exp"><span className={"cell-exp__ic cell-exp__ic--"+(r.source||"bank")}>
                      {Ic[srcIcon[r.source] || "bank"]({s:14})}</span>{v}</div>) },
                { key:"channel", label:"Channel", render:(v)=> <Badge tone="neutral">{v || "—"}</Badge> },
                { key:"amount", label:"Amount", align:"right", render:(v,r)=>(
                    <span className={"amt amt--"+(r.type==="in"?"in":"out")}>
                      {r.type==="in"?"+":"−"}{money(v)}</span>) },
                rowActions(ed.setEditing, ed.setDeleting),
              ]}
              rows={all} getRowKey={(r)=>r.id} />}
      </Card>

      <RecordDialog open={Boolean(ed.editing)} title={ed.editing === "new" ? "Add transaction" : "Edit transaction"}
        specs={FIELDS.expenses} record={ed.editing === "new" ? null : ed.editing}
        busy={c.busy} error={c.error} onSave={ed.save} onClose={()=>{ ed.setEditing(null); c.setError(null); }} />
      <ConfirmDelete target={ed.deleting} label={ed.deleting && ed.deleting.description} busy={c.busy}
        onConfirm={ed.confirmDelete} onClose={()=>ed.setDeleting(null)} />
    </div>
  );
}

/* ===================== UTILITIES ===================== */
const utilIcon = { electricity:"bolt", water:"activity", gas:"bolt", internet:"activity", phone:"bell",
                   waste:"trash", alarm:"shield", pos:"receipt", insurance:"shield", rent:"bank",
                   software:"settings", other:"tag" };
const utilTone = { active:"success", pending:"warning", overdue:"danger", cancelled:"neutral" };

/* Monthly-equivalent cost, so annual and quarterly bills compare fairly. */
const monthlyOf = (u) => {
  const a = Number(u.amount || 0);
  if (u.status === "cancelled") return 0;
  if (u.billing_cycle === "annual") return a / 12;
  if (u.billing_cycle === "quarterly") return a / 3;
  if (u.billing_cycle === "one-time") return 0;
  return a;
};

function UtilitiesView() {
  const c = useCollection("utilities");
  const ed = useEditor(c);
  const all = c.rows || [];
  const monthly = all.reduce((s,u)=> s + monthlyOf(u), 0);
  const overdue = all.filter((u)=> u.status === "overdue");
  const dueSoon = all.filter((u)=> u.next_due_on && new Date(u.next_due_on) <= new Date(Date.now()+14*864e5) && u.status !== "cancelled");

  return (
    <div className="view">
      <ModuleError error={c.error} onRetry={c.reload} />
      <div className="view__row view__row--between">
        <div className="view__row">
          <StatCard label="Monthly run-rate" value={money(monthly)} icon={<Ic.bolt s={18} />} caption="all services" />
          <StatCard label="Services" value={String(all.length)} icon={<Ic.activity s={18} />}
            caption={all.filter((u)=>u.autopay).length + " on autopay"} />
          <StatCard label="Due in 14 days" value={String(dueSoon.length)} icon={<Ic.cal s={18} />}
            delta={overdue.length ? overdue.length + " overdue" : "none overdue"}
            deltaDirection={overdue.length ? "down" : "up"} caption="upcoming bills" />
        </div>
        <Button variant="primary" size="sm" leftIcon={<Ic.plus s={15} />} onClick={()=>ed.setEditing("new")}>Add service</Button>
      </div>

      {overdue.length > 0 && (
        <Alert tone="danger" title={overdue.length + " overdue bill" + (overdue.length===1?"":"s")}>
          <span>{overdue.map((u)=>u.name).join(", ")} — settle these to avoid a service interruption.</span>
        </Alert>
      )}

      <Card padded={false} className="panel">
        {c.rows === null ? <Loading label="Loading services…" /> : all.length === 0
          ? <EmptyState icon={<Ic.bolt s={26} />} title="No services tracked yet"
              message="Add electricity, water, internet, alarm, POS and insurance to see your true monthly run-rate."
              action={<Button variant="primary" size="sm" onClick={()=>ed.setEditing("new")}>Add service</Button>} />
          : <Table
              columns={[
                { key:"name", label:"Service", render:(v,r)=>(
                    <div className="cell-exp"><span className={"cell-exp__ic cell-exp__ic--"+(r.status==="overdue"?"card":"bank")}>
                      {Ic[utilIcon[r.category] || "tag"]({s:14})}</span>
                      <div className="cell-prod"><span className="cell-prod__name">{v}</span>
                        <span className="cell-prod__cat">{r.provider}{r.location ? " · " + r.location : ""}</span></div></div>) },
                { key:"account_number", label:"Account", render:(v)=> <span className="mono-muted">{v || "—"}</span> },
                { key:"amount", label:"Amount", align:"right", render:(v,r)=>(
                    <div className="cell-amt"><span>{money(v)}</span>
                      <span className="cell-amt__sub">{r.billing_cycle}</span></div>) },
                { key:"_m", label:"Per month", align:"right", render:(_,r)=> money(monthlyOf(r)) },
                { key:"next_due_on", label:"Next due", render:(v)=> <span className="mono-muted">{shortDate(v)}</span> },
                { key:"autopay", label:"Autopay", render:(v)=> v
                    ? <Badge tone="success" dot>Auto</Badge> : <Badge tone="neutral">Manual</Badge> },
                { key:"status", label:"Status", render:(v)=> <Badge tone={utilTone[v] || "neutral"} dot>{v}</Badge> },
                rowActions(ed.setEditing, ed.setDeleting),
              ]}
              rows={all} getRowKey={(r)=>r.id} />}
      </Card>

      <RecordDialog open={Boolean(ed.editing)} title={ed.editing === "new" ? "Add service" : "Edit service"}
        specs={FIELDS.utilities} record={ed.editing === "new" ? null : ed.editing}
        busy={c.busy} error={c.error} onSave={ed.save} onClose={()=>{ ed.setEditing(null); c.setError(null); }} />
      <ConfirmDelete target={ed.deleting} label={ed.deleting && ed.deleting.name} busy={c.busy}
        onConfirm={ed.confirmDelete} onClose={()=>ed.setDeleting(null)} />
    </div>
  );
}

/* ===================== DOCUMENTS ===================== */
const DOC_FOLDERS = ["Licenses & Permits","Tax & EIN","Insurance","Lease & Property","Vendor Contracts","Payroll & HR","General"];
const FOLDER_TONE = { "Licenses & Permits":"gold", "Tax & EIN":"green", "Insurance":"wine",
                      "Lease & Property":"info", "Vendor Contracts":"gold", "Payroll & HR":"green", "General":"info" };

function UploadDialog({ open, busy, error, onUpload, onClose }) {
  const [file, setFile] = React.useState(null);
  const [folder, setFolder] = React.useState(DOC_FOLDERS[0]);
  const [expires, setExpires] = React.useState("");
  const fileRef = React.useRef();

  React.useEffect(()=>{ if (open) { setFile(null); setFolder(DOC_FOLDERS[0]); setExpires(""); } }, [open]);
  if (!open) return null;

  const submit = () => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      // FileReader gives "data:<mime>;base64,<payload>" — the API wants just the payload.
      const b64 = String(reader.result).split(",")[1];
      onUpload({ name: file.name, folder, mimeType: file.type, dataBase64: b64,
                 expiresOn: expires || null, tone: FOLDER_TONE[folder] || "gold" });
    };
    reader.readAsDataURL(file);
  };

  return (
    <Dialog open title="Upload a business document" onClose={onClose} width={480}
      footer={<React.Fragment>
        <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
        <Button variant="primary" disabled={!file || busy} onClick={submit}>{busy ? "Uploading…" : "Upload"}</Button>
      </React.Fragment>}>
      <div className="dlg-form">
        {error && <Alert tone="danger"><span>{error}</span></Alert>}
        <FormField label="File" required hint="PDF, image or scan — up to 4 MB">
          <div className="filepick">
            <Button variant="outline" size="sm" leftIcon={<Ic.upload s={15} />} onClick={()=>fileRef.current.click()}>Choose file</Button>
            <span className="filepick__name">{file ? file.name + " · " + bytes(file.size) : "No file chosen"}</span>
            <input ref={fileRef} type="file" style={{display:"none"}} onChange={(e)=>setFile(e.target.files[0] || null)} />
          </div>
        </FormField>
        <FormField label="Folder">
          <Select value={folder} onChange={(e)=>setFolder(e.target.value)}>
            {DOC_FOLDERS.map((f)=> <option key={f} value={f}>{f}</option>)}
          </Select>
        </FormField>
        <FormField label="Expires on" hint="Licences and permits renew — we'll flag it 30 days out">
          <Input type="date" value={expires} onChange={(e)=>setExpires(e.target.value)} />
        </FormField>
      </div>
    </Dialog>
  );
}

function DocumentsView() {
  const c = useCollection("documents");
  const [uploading, setUploading] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [deleting, setDeleting] = React.useState(null);

  const all = c.rows || [];
  const soon = new Date(Date.now() + 30*864e5);
  const expiring = all.filter((d)=> d.expires_on && new Date(d.expires_on) <= soon);

  const folders = DOC_FOLDERS
    .map((f)=> ({ name:f, tone:FOLDER_TONE[f], items: all.filter((d)=> d.folder === f) }))
    .filter((f)=> f.items.length > 0);

  const doUpload = async (payload) => {
    setBusy(true); setErr(null);
    try { await api.upload(payload); setUploading(false); await c.reload(); }
    catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  /* Storage links are signed and short-lived, so fetch one on demand. */
  const open = async (doc) => {
    setErr(null);
    try {
      const { url } = await api.docUrl(doc.id);
      window.open(url, "_blank", "noopener");
    } catch (e) { setErr(e.message); }
  };

  const confirmDelete = async () => { if (await c.remove(deleting.id)) setDeleting(null); };

  return (
    <div className="view">
      <ModuleError error={c.error || err} onRetry={c.reload} />
      <div className="view__row view__row--between">
        <div><div className="panel__title">Company documents</div>
          <div className="panel__sub">EIN, TABC licences, insurance, leases, vendor contracts and HR files.</div></div>
        <Button variant="primary" size="sm" leftIcon={<Ic.upload s={15} />} onClick={()=>{ setErr(null); setUploading(true); }}>Upload document</Button>
      </div>

      {expiring.length > 0 && (
        <Alert tone="warning" title={expiring.length + " document" + (expiring.length===1?"":"s") + " expiring within 30 days"}>
          <span>{expiring.map((d)=> d.name + " (" + shortDate(d.expires_on) + ")").join(", ")}</span>
        </Alert>
      )}

      {c.rows === null ? <Loading label="Loading documents…" /> : all.length === 0
        ? <EmptyState icon={<Ic.folder s={26} />} title="No documents yet"
            message="Upload your TABC permit, EIN letter, insurance policy and lease so they're never lost."
            action={<Button variant="primary" size="sm" onClick={()=>setUploading(true)}>Upload document</Button>} />
        : <div className="doc-grid">
            {folders.map((f)=>(
              <Card key={f.name} padded hover className="doc-card">
                <div className="doc-card__top">
                  <span className={"doc-card__folder doc-card__folder--"+f.tone}><Ic.folder s={22} /></span>
                  <Badge tone="neutral">{f.items.length} file{f.items.length===1?"":"s"}</Badge>
                </div>
                <div className="doc-card__name">{f.name}</div>
                <ul className="doc-card__list">
                  {f.items.map((d)=>(
                    <li key={d.id}>
                      <Ic.doc s={14} />
                      <button className="doc-link" onClick={()=>open(d)} title="Open">{d.name}</button>
                      <span className="doc-meta">{bytes(d.size_bytes)}</span>
                      {d.expires_on && <Badge tone={new Date(d.expires_on) <= soon ? "warning" : "neutral"}>
                        exp {shortDate(d.expires_on)}</Badge>}
                      <button className="icon-act icon-act--danger" onClick={()=>setDeleting(d)}><Ic.trash s={13} /></button>
                    </li>
                  ))}
                </ul>
              </Card>
            ))}
          </div>}

      <UploadDialog open={uploading} busy={busy} error={err} onUpload={doUpload} onClose={()=>setUploading(false)} />
      <ConfirmDelete target={deleting} label={deleting && deleting.name} busy={c.busy}
        onConfirm={confirmDelete} onClose={()=>setDeleting(null)} />
    </div>
  );
}

/* ===================== SETTINGS ===================== */
function ChangePassword({ forced }) {
  const [cur, setCur] = React.useState("");
  const [next, setNext] = React.useState("");
  const [again, setAgain] = React.useState("");
  const [state, setState] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const mismatch = next && again && next !== again;
  const tooShort = next.length > 0 && next.length < 10;
  const ok = cur && next.length >= 10 && next === again;

  const submit = async () => {
    setBusy(true); setState(null);
    try {
      await api.changePassword(cur, next);
      setState({ tone:"success", msg:"Password updated. Use it next time you sign in." });
      setCur(""); setNext(""); setAgain("");
      if (forced) setTimeout(()=>window.location.reload(), 1200);
    } catch (e) { setState({ tone:"danger", msg:e.message }); }
    finally { setBusy(false); }
  };

  return (
    <Card padded className="panel">
      <div className="panel__head"><div>
        <div className="panel__title">Your password</div>
        <div className="panel__sub">At least 10 characters. Stored as a scrypt hash — nobody can read it back.</div>
      </div></div>
      <div className="set-form">
        <FormField label="Current password"><Input type="password" value={cur} onChange={(e)=>setCur(e.target.value)} /></FormField>
        <FormField label="New password" error={tooShort ? "Use at least 10 characters." : null}>
          <Input type="password" value={next} onChange={(e)=>setNext(e.target.value)} /></FormField>
        <FormField label="Confirm new password" error={mismatch ? "These don't match." : null}>
          <Input type="password" value={again} onChange={(e)=>setAgain(e.target.value)} /></FormField>
        {state && <Alert tone={state.tone}><span>{state.msg}</span></Alert>}
        <Button variant="primary" disabled={!ok || busy} onClick={submit}>{busy ? "Updating…" : "Update password"}</Button>
      </div>
    </Card>
  );
}

function AdminUsers() {
  const [users, setUsers] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [created, setCreated] = React.useState(null);
  const [form, setForm] = React.useState({ uid:"", name:"", email:"", role:"staff" });

  const load = React.useCallback(()=>{
    api.users().then(setUsers).catch((e)=>{ setUsers([]); setError(e.message); });
  }, []);
  React.useEffect(()=>{ load(); }, [load]);

  const create = async () => {
    setBusy(true); setError(null);
    try {
      const res = await api.createUser(form);
      // Shown once — the plain password is never stored or retrievable again.
      setCreated(res);
      setAdding(false);
      setForm({ uid:"", name:"", email:"", role:"staff" });
      load();
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  };

  const toggle = async (u) => {
    setError(null);
    try { await api.updateUser(u.uid, { is_active: !u.is_active }); load(); }
    catch (e) { setError(e.message); }
  };

  return (
    <Card padded={false} className="panel">
      <div className="panel__head" style={{padding:"1.25rem 1.5rem 0"}}>
        <div><div className="panel__title">Admin logins</div>
          <div className="panel__sub">Who can sign in to this portal, and what they're allowed to change.</div></div>
        <Button variant="primary" size="sm" leftIcon={<Ic.plus s={15} />} onClick={()=>{ setCreated(null); setAdding(true); }}>Add login</Button>
      </div>

      {error && <div style={{padding:"0 1.5rem"}}><Alert tone="danger"><span>{error}</span></Alert></div>}
      {created && (
        <div style={{padding:"0 1.5rem 1rem"}}>
          <Alert tone="success" title="Login created — copy this password now">
            <span>ID <b className="mono-muted">{created.uid}</b> · password <b className="mono-muted">{created.password}</b>.
              It won't be shown again; they'll be asked to change it at first sign-in.</span>
          </Alert>
        </div>
      )}

      {users === null ? <Loading /> : (
        <Table
          columns={[
            { key:"uid", label:"Admin ID", render:(v)=> <span className="mono-muted">{v}</span> },
            { key:"name", label:"Name", render:(v,r)=>(
                <div className="cell-emp"><Avatar name={v} size="sm" />
                  <div><span className="cell-emp__name">{v}</span>
                    <span className="cell-emp__mail">{r.email || "—"}</span></div></div>) },
            { key:"role", label:"Role", render:(v)=> <Badge tone={v==="owner"?"gold":v==="manager"?"info":"neutral"}>{v}</Badge> },
            { key:"last_login_at", label:"Last sign-in", render:(v)=> <span className="mono-muted">{v ? shortDate(v) : "never"}</span> },
            { key:"is_active", label:"Access", render:(v,r)=>(
                <Switch checked={Boolean(v)} onChange={()=>toggle(r)} />) },
          ]}
          rows={users} getRowKey={(r)=>r.uid} />
      )}

      {adding && (
        <Dialog open title="Add an admin login" onClose={()=>setAdding(false)} width={460}
          footer={<React.Fragment>
            <Button variant="ghost" onClick={()=>setAdding(false)} disabled={busy}>Cancel</Button>
            <Button variant="primary" disabled={busy || !form.uid.trim() || !form.name.trim()} onClick={create}>
              {busy ? "Creating…" : "Create login"}</Button>
          </React.Fragment>}>
          <div className="dlg-form">
            <FormField label="Admin ID" required hint="What they type to sign in — lowercase, no spaces">
              <Input mono placeholder="marcus" value={form.uid}
                onChange={(e)=>setForm(Object.assign({}, form, { uid:e.target.value.toLowerCase().replace(/\s+/g,"") }))} /></FormField>
            <FormField label="Full name" required>
              <Input placeholder="Marcus Reed" value={form.name}
                onChange={(e)=>setForm(Object.assign({}, form, { name:e.target.value }))} /></FormField>
            <FormField label="Email">
              <Input type="email" placeholder="marcus@pcliquors.com" value={form.email}
                onChange={(e)=>setForm(Object.assign({}, form, { email:e.target.value }))} /></FormField>
            <FormField label="Role" hint="Staff is read-only. Managers can edit. Only the owner manages logins.">
              <Select value={form.role} onChange={(e)=>setForm(Object.assign({}, form, { role:e.target.value }))}>
                <option value="staff">Staff — read only</option>
                <option value="manager">Manager — can edit</option>
                <option value="owner">Owner — full access</option>
              </Select></FormField>
          </div>
        </Dialog>
      )}
    </Card>
  );
}

function ActivityLog() {
  const [entries, setEntries] = React.useState(null);
  React.useEffect(()=>{ api.auditLog().then((d)=>setEntries(d.entries || [])).catch(()=>setEntries([])); }, []);
  if (entries === null) return <Card padded className="panel"><Loading /></Card>;
  if (!entries.length) return null;
  return (
    <Card padded={false} className="panel">
      <div className="panel__head" style={{padding:"1.25rem 1.5rem 0"}}>
        <div><div className="panel__title">Recent activity</div>
          <div className="panel__sub">Every sign-in and change made through this portal.</div></div>
      </div>
      <Table
        columns={[
          { key:"created_at", label:"When", render:(v)=> <span className="mono-muted">{new Date(v).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}</span> },
          { key:"admin_uid", label:"Who", render:(v)=> <span className="mono-muted">{v || "—"}</span> },
          { key:"action", label:"Action", render:(v)=> <Badge tone={v.indexOf("failed")>=0?"danger":v==="login"?"success":"neutral"}>{v.replace(/_/g," ")}</Badge> },
          { key:"entity", label:"Module", render:(v)=> v || "—" },
        ]}
        rows={entries} getRowKey={(r)=>r.id} />
    </Card>
  );
}

function SettingsView({ user }) {
  return (
    <div className="view">
      <div className="set-who">
        <Avatar name={user.name} size="lg" />
        <div>
          <div className="set-who__name">{user.name}</div>
          <div className="set-who__meta">
            <span className="mono-muted">{user.uid}</span>
            <Badge tone={user.role==="owner"?"gold":user.role==="manager"?"info":"neutral"}>{user.role}</Badge>
            {user.email && <span>{user.email}</span>}
          </div>
        </div>
      </div>
      <ChangePassword />
      {user.role === "owner" && <AdminUsers />}
      <ActivityLog />
    </div>
  );
}

window.PCAdminViews = { PosView, InventoryView, AdsView, EmployeesView, ExpensesView,
                        UtilitiesView, DocumentsView, SettingsView, ChangePassword };
