/* SkyOps — Commercial · Owner view (asset owner buying O&M and inspection services). */

const { useState: uSCO2, useMemo: uMCO2 } = React;
const CO_LIMIT = 5000; /* POs above this need approval */

function CmOwner({ go, setActiveSite, period }) {
  const v = useCM();
  const [tab, setTab] = uSCO2("overview");
  const [modal, setModal] = uSCO2(null);
  const R = cmRange(period), year = cmRange("year");
  const sites = window.SITES || [];
  const act = uMCO2(() => cmActuals(v, R), [v, period]);
  const actY = uMCO2(() => cmActuals(v, year), [v]);
  const tot = (o) => Object.values(o).reduce((a, c) => a + Object.values(c).reduce((b, x) => b + x, 0), 0);
  const spend = tot(act);
  const budgetY = sites.reduce((a, s) => a + Object.values(v.budget[s.id] || {}).reduce((b, x) => b + x, 0), 0);
  const elapsed = (() => { const [y, m, d] = cmT().split("-").map(Number); return ((m - 1) + d / 30) / 12; })();
  const spendY = tot(actY);
  // cost per MWp inspected: supplier inspection invoices + in-house flights (cost model) / MWp of sites flown in period
  const flown = (window.INSPECTIONS || []).filter(i => (i.progress?.flying || 0) >= 1 && cmIn(i.startedAt, R));
  const inhouse = flown.filter(i => !v.pos.some(p => p.mic === i.id)).reduce((a, i) => { const area = i.area_ha || 100, fl = i.flights || 12; return a + Math.ceil(fl / 8) * v.pb.pilotDay + fl * 0.6 * v.pb.droneHour + area * v.pb.computeHa + Math.ceil((i.detections || 200) / 60) * v.pb.reviewHour; }, 0);
  const inspSpend = Object.values(act).reduce((a, c) => a + (c.inspection || 0), 0) + inhouse;
  const mwp = flown.reduce((a, i) => a + (cmSite(i.siteId).capacity_mw || 0), 0);
  const pendPO = v.pos.filter(p => p.status === "pending"), pendInv = v.sInv.filter(x => x.status === "pending"), disputed = v.sInv.filter(x => x.status === "disputed");
  const penSaved = v.sInv.filter(x => ["approved", "paid"].includes(x.status) && cmIn(x.date, R)).reduce((a, x) => { const n = cmSInvNet(v, x); return a + (x.amount - n.net); }, 0);
  const committed = v.pos.filter(p => ["approved", "received"].includes(p.status)).reduce((a, p) => a + p.amount, 0);
  const poRows = v.pos.filter(p => cmIn(p.date, R)), invRows = v.sInv.filter(x => cmIn(x.date, R));
  const pgPo = usePaged(poRows, "cm_po"), pgSi = usePaged(invRows, "cm_si");
  const setPO = (id, patch, msg) => { cmStore.set(x => ({ ...x, pos: x.pos.map(p => p.id === id ? { ...p, ...patch } : p) })); msg && window.skyToast(msg); };
  const setInv = (id, patch, msg) => { cmStore.set(x => ({ ...x, sInv: x.sInv.map(p => p.id === id ? { ...p, ...patch } : p) })); msg && window.skyToast(msg); };
  const poPdf = (p) => cmPdf("po", { id: p.id, to: p.supplier, site: cmSite(p.siteId).name, date: p.date, lines: [[p.desc, p.amount], [`Under contract ${p.contract}`, null], ...(p.wo ? [[`Work order ${p.wo}`, null]] : [])], total: p.amount, note: "Invoice must quote this PO number. Payment 30 days from approved invoice." });
  const scUsed = (c) => v.sInv.filter(x => ["approved", "paid"].includes(x.status) && (v.pos.find(p => p.id === x.po)?.contract === c.id)).reduce((a, x) => a + cmSInvNet(v, x).net, 0);

  return (<>
    <div className="wo-kpis cm-kpis">
      <div className="wo-kpi"><span className="caps">Spend · actual</span><b className="mono">{cmEur(spend)}</b><em>{cmPeriodLabel(period)}</em></div>
      <div className={`wo-kpi ${spendY > budgetY * elapsed * 1.1 ? "is-crit" : "is-ok"}`}><span className="caps">Budget · year to date</span><b className="mono">{budgetY ? Math.round(spendY / budgetY * 100) : 0}%</b><em>{cmEur(spendY)} of {cmEur(budgetY)} · {Math.round(elapsed * 100)}% of year elapsed</em></div>
      <div className="wo-kpi"><span className="caps">Cost / MWp inspected</span><b className="mono">{mwp ? cmEur(inspSpend / mwp) : "—"}</b><em>{flown.length} inspections · {Math.round(mwp)} MWp · incl. in-house</em></div>
      <div className={`wo-kpi ${pendPO.length + pendInv.length ? "is-crit" : ""}`}><span className="caps">To approve</span><b className="mono">{pendPO.length + pendInv.length}</b><em>{pendPO.length} POs · {pendInv.length} invoices · {disputed.length} disputed</em></div>
      <div className="wo-kpi is-ok"><span className="caps">SLA penalties recovered</span><b className="mono">{cmEur(penSaved)}</b><em>committed open POs {cmEur(committed)}</em></div>
    </div>
    <div className="cm-tabrow"><div className="tabs">
      {[["overview", "Overview"], ["pos", `Purchase orders · ${v.pos.length}`], ["sinv", `Supplier invoices · ${v.sInv.length}`], ["contracts", `Contracts · ${v.sContracts.length}`], ["budget", "Budget by site"], ["sla", "SLA & penalties"]].map(([k, l]) => <button key={k} className={tab === k ? "on" : ""} onClick={() => setTab(k)}>{l}</button>)}
    </div>
    <div className="cm-tabs-act"><button className="btn btn-primary btn-xs" data-perm="commercial.edit" onClick={() => setModal({ t: "po" })}><Icon name="plus" size={11}/>New purchase order</button></div></div>

    {tab === "overview" && <div className="cm-2">
      <div className="card"><div className="card-hd">Budget vs actual · {cmT().slice(0, 4)}<span className="sub">approved & paid supplier invoices + completed in-house work orders</span></div>
        <div className="cm-bars">{sites.filter(s => v.budget[s.id] || actY[s.id]).map(s => { const b = Object.values(v.budget[s.id] || {}).reduce((a, x) => a + x, 0), a = Object.values(actY[s.id] || {}).reduce((x, y) => x + y, 0), pct = b ? a / b * 100 : 0; return (
          <div key={s.id} className="cm-bar"><span className="cm-bar-n">{s.name}<em>budget {b ? cmEur(b) : "not set"}</em></span>
            <span className="cm-bar-t cm-bud"><i className="m" style={{ width: Math.min(100, pct) + "%", background: pct > elapsed * 110 ? "var(--sev-critical)" : pct > elapsed * 100 ? "var(--sev-medium)" : undefined }}/><em style={{ left: elapsed * 100 + "%" }}/></span>
            <b className="mono">{cmEur(a)}</b><b className={`mono ${pct > elapsed * 110 ? "warn" : "ok"}`}>{b ? pct.toFixed(0) + "%" : "—"}</b></div>); })}</div>
        <div className="cm-lg"><span><i className="m"/>Spent</span><span><i className="cm-lg-line"/>Year elapsed</span></div>
      </div>
      <div className="card"><div className="card-hd">Needs action</div>
        <div className="cm-act">
          {pendPO.map(p => <div key={p.id} className="cm-act-it warn"><Icon name="file" size={12}/><span><b>{p.id}</b> {p.supplier} · {cmEur(p.amount)} · above {cmEur(CO_LIMIT)} approval limit</span><button className="btn btn-primary btn-xs" data-perm="commercial.edit" onClick={() => setPO(p.id, { status: "approved", approvedBy: window.__personaName || "You" }, `${p.id} approved`)}>Approve</button></div>)}
          {pendInv.map(x => { const n = cmSInvNet(v, x); const over = n.po && x.amount > n.po.amount; return <div key={x.id} className={`cm-act-it ${over ? "crit" : "warn"}`}><Icon name="alert" size={12}/><span><b>{x.id}</b> {x.supplier} · {cmEur(x.amount)}{n.pen ? ` · SLA penalty ${n.pen}% → pay ${cmEur(n.net)}` : ""}{over ? ` · exceeds PO by ${cmEur(x.amount - n.po.amount)}` : ""}</span><button className="btn btn-secondary btn-xs" onClick={() => setTab("sinv")}>Review</button></div>; })}
          {disputed.map(x => <div key={x.id} className="cm-act-it crit"><Icon name="alert" size={12}/><span><b>{x.id}</b> disputed · {x.note}</span></div>)}
          {v.sContracts.filter(c => scUsed(c) > c.cap * 0.8).map(c => <div key={c.id} className="cm-act-it warn"><Icon name="tag" size={12}/><span><b>{c.id}</b> {c.supplier} at {Math.round(scUsed(c) / c.cap * 100)}% of annual cap</span></div>)}
          {!pendPO.length && !pendInv.length && !disputed.length && <div className="sec" style={{ fontSize: 12 }}>Nothing to approve.</div>}
        </div>
      </div>
    </div>}

    {tab === "pos" && <div className="card"><table className="tbl">
      <thead><tr><th>PO</th><th>Supplier</th><th>Site · category</th><th>Description</th><th className="r">Amount</th><th className="r">Invoiced</th><th>Date</th><th>Status</th><th className="r"></th></tr></thead>
      <tbody>{(() => { const rows = pgPo.rows; return <>{poRows.length === 0 && <tr><td colSpan={9} className="tbl-empty">No purchase orders in this period.</td></tr>}{rows.map(p => { const inv = v.sInv.filter(x => x.po === p.id && x.status !== "disputed").reduce((a, x) => a + x.amount, 0); return (
        <tr key={p.id}><td className="mono"><b>{p.id}</b>{p.wo && <div className="sec cr-sub">{p.wo}</div>}</td><td>{p.supplier}<div className="sec cr-sub mono">{p.contract}</div></td><td>{cmSite(p.siteId).name}<div className="sec cr-sub">{CM_CATS[p.cat]}</div></td><td className="sec" style={{ maxWidth: 260 }}>{p.desc}</td>
          <td className="r mono"><b>{cmEur(p.amount)}</b></td><td className={`r mono ${inv > p.amount ? "warn" : "sec"}`}>{inv ? cmEur(inv) : "—"}</td><td className="mono sec">{window.skyFmt.date(p.date)}</td>
          <td><span className={`cm-st cm-st-${{ pending: "issued", approved: "sent", received: "accepted", closed: "declined" }[p.status]}`}>{p.status === "pending" ? "awaiting approval" : p.status}</span></td>
          <td className="r"><div className="cr-acts">
            <button className="btn btn-ghost btn-xs" title="PDF" onClick={() => poPdf(p)}><Icon name="download" size={11}/></button>
            {p.status === "pending" && <button className="btn btn-primary btn-xs" data-perm="commercial.edit" onClick={() => setPO(p.id, { status: "approved" }, `${p.id} approved`)}>Approve</button>}
            {p.status === "approved" && <button className="btn btn-secondary btn-xs" data-perm="commercial.edit" onClick={() => setPO(p.id, { status: "received", receivedAt: cmT() }, `${p.id} · goods / service received`)}>Mark received</button>}
            {["approved", "received"].includes(p.status) && <button className="btn btn-ghost btn-xs" data-perm="commercial.edit" onClick={() => setModal({ t: "inv", p })}>Register invoice</button>}
            {p.status === "received" && <button className="btn btn-ghost btn-xs" data-perm="commercial.edit" onClick={() => setPO(p.id, { status: "closed" }, `${p.id} closed`)}>Close</button>}
          </div></td></tr>); })}</>; })()}</tbody></table><Pager pg={pgPo} label="purchase orders"/></div>}

    {tab === "sinv" && <div className="card"><table className="tbl">
      <thead><tr><th>Invoice</th><th>Supplier · PO</th><th className="r">Invoiced</th><th>3-way match</th><th className="r">SLA penalty</th><th className="r">To pay</th><th>Date · due</th><th>Status</th><th className="r"></th></tr></thead>
      <tbody>{(() => { const rows = pgSi.rows; return <>{invRows.length === 0 && <tr><td colSpan={9} className="tbl-empty">No supplier invoices in this period.</td></tr>}{rows.map(x => { const n = cmSInvNet(v, x); const match = !n.po ? "no PO" : x.amount > n.po.amount ? `+${cmEur(x.amount - n.po.amount)} vs PO` : n.po.status === "received" || n.po.status === "closed" ? "PO · receipt · invoice" : "not received yet"; const ok = n.po && x.amount <= n.po.amount && ["received", "closed"].includes(n.po.status); return (
        <tr key={x.id}><td className="mono"><b>{x.id}</b></td><td>{x.supplier}<div className="sec cr-sub mono">{x.po}</div></td><td className="r mono">{cmEur(x.amount)}</td>
          <td><span className={ok ? "cm-ok-t" : "cm-warn-t"} style={{ fontSize: 11 }}>{ok ? "✓ " : "⚠ "}{match}</span></td>
          <td className="r mono">{n.pen ? <span className="cm-warn-t">{x.wd} wd · −{n.pen}%</span> : <span className="sec">—</span>}</td><td className="r mono"><b>{cmEur(n.net)}</b></td>
          <td className="mono sec" style={{ fontSize: 11 }}>{window.skyFmt.date(x.date)}<br/>{window.skyFmt.date(x.due)}</td>
          <td><span className={`cm-st cm-st-${{ pending: "issued", approved: "sent", paid: "accepted", disputed: "overdue" }[x.status]}`}>{x.status}</span>{x.note && <div className="sec cr-sub" style={{ maxWidth: 200 }}>{x.note}</div>}</td>
          <td className="r"><div className="cr-acts">
            {x.status === "pending" && <><button className="btn btn-primary btn-xs" data-perm="commercial.edit" onClick={() => { if (!ok && !confirm(`3-way match failed (${match}). Approve anyway?`)) return; setInv(x.id, { status: "approved", approvedAt: cmT() }, `${x.id} approved · pay ${cmEur(n.net)}${n.pen ? ` (−${n.pen}% SLA)` : ""}`); }}>Approve</button>
              <button className="btn btn-ghost btn-xs" data-perm="commercial.edit" onClick={() => { const r = prompt("Reason for dispute", x.amount > (n.po?.amount || 0) ? "Exceeds PO amount" : "Service not delivered as specified"); if (r) setInv(x.id, { status: "disputed", note: r }, `${x.id} disputed · supplier notified`); }}>Dispute</button></>}
            {x.status === "disputed" && <button className="btn btn-ghost btn-xs" data-perm="commercial.edit" onClick={() => setInv(x.id, { status: "pending", note: "" }, `${x.id} back to review`)}>Reopen</button>}
            {x.status === "approved" && <button className="btn btn-secondary btn-xs" data-perm="commercial.edit" onClick={() => setInv(x.id, { status: "paid", paidAt: cmT() }, `${x.id} paid · ${cmEur(n.net)}`)}>Mark paid</button>}
          </div></td></tr>); })}</>; })()}</tbody></table><Pager pg={pgSi} label="supplier invoices"/></div>}

    {tab === "contracts" && <div className="card"><table className="tbl">
      <thead><tr><th>Contract</th><th>Supplier · scope</th><th>Rate</th><th>Term</th><th>SLA</th><th>Annual cap used</th></tr></thead>
      <tbody>{v.sContracts.map(c => { const u = scUsed(c), pct = u / c.cap * 100; return <tr key={c.id}><td className="mono"><b>{c.id}</b><div className="sec cr-sub">{CM_CATS[c.cat]}</div></td><td><b>{c.supplier}</b><div className="sec cr-sub">{c.scope}</div></td><td className="sec">{c.rate}</td><td className="mono sec">{window.skyFmt.date(c.start)} → {window.skyFmt.date(c.end)}</td><td className="sec" style={{ fontSize: 11 }}>≤ {c.sla.days} wd · −{c.sla.pct}%/wd · cap {c.sla.cap}%</td>
        <td><div className="cr-bar" style={{ minWidth: 160 }}><span><i style={{ width: Math.min(100, pct) + "%", background: pct > 80 ? "var(--sev-medium)" : "var(--accent-primary)" }}/></span><b className="mono">{cmEur(u)} / {cmEur(c.cap)}</b></div></td></tr>; })}</tbody></table></div>}

    {tab === "budget" && <div className="card"><table className="tbl cm-budget">
      <thead><tr><th>Site</th>{Object.entries(CM_CATS).map(([k, l]) => <th key={k} className="r">{l}</th>)}<th className="r">Total</th></tr></thead>
      <tbody>{sites.map(s => { const b = v.budget[s.id] || {}, a = actY[s.id] || {}; const bt = Object.values(b).reduce((x, y) => x + y, 0), at = Object.values(a).reduce((x, y) => x + y, 0); return (
        <tr key={s.id}><td><b>{s.name}</b><div className="sec cr-sub">{s.capacity_mw} MWp</div></td>
          {Object.keys(CM_CATS).map(k => { const pct = b[k] ? (a[k] || 0) / b[k] * 100 : 0; return <td key={k} className="r"><input className="inp mono cm-bin" type="number" value={b[k] || ""} placeholder="—" disabled={!window.skyCan("commercial.edit")} onChange={e => cmStore.set(x => ({ ...x, budget: { ...x.budget, [s.id]: { ...(x.budget[s.id] || {}), [k]: +e.target.value || 0 } } }))}/><div className={`cr-sub mono ${pct > elapsed * 110 ? "cm-warn-t" : "sec"}`} style={{ justifyContent: "flex-end" }}>{cmEur(a[k] || 0)}{b[k] ? ` · ${pct.toFixed(0)}%` : ""}</div></td>; })}
          <td className="r mono"><b>{cmEur(bt)}</b><div className={`cr-sub ${bt && at / bt > elapsed * 1.1 ? "cm-warn-t" : "sec"}`} style={{ justifyContent: "flex-end" }}>{cmEur(at)}{bt ? ` · ${Math.round(at / bt * 100)}%` : ""}</div></td></tr>); })}</tbody></table>
      <div className="cm-foot sec">Budget for {cmT().slice(0, 4)}. Actuals = approved + paid supplier invoices (net of SLA penalties) + completed in-house work orders. Flag when spend runs 10% ahead of the year elapsed ({Math.round(elapsed * 100)}%).</div>
    </div>}

    {tab === "sla" && <div className="card"><div className="card-hd">Supplier SLA & penalties<span className="sub">penalty deducted automatically at invoice approval</span></div>
      <table className="tbl"><thead><tr><th>Invoice</th><th>Supplier</th><th>Contract SLA</th><th className="r">Delivered in</th><th>Result</th><th className="r">Penalty</th><th className="r">Recovered</th></tr></thead>
        <tbody>{v.sInv.filter(x => x.wd != null).map(x => { const n = cmSInvNet(v, x); return <tr key={x.id}><td className="mono"><b>{x.id}</b><div className="sec cr-sub">{n.po?.desc}</div></td><td>{x.supplier}</td><td className="sec" style={{ fontSize: 11 }}>{n.sc ? `≤ ${n.sc.sla.days} wd · −${n.sc.sla.pct}%/wd` : "—"}</td><td className="r mono">{x.wd} wd</td>
          <td>{n.pen ? <span className="cm-st cm-st-overdue">breach</span> : <span className="cm-st cm-st-accepted">met</span>}</td><td className="r mono">{n.pen ? `${n.pen}%` : "—"}</td><td className="r mono">{n.pen ? cmEur(x.amount - n.net) : "—"}</td></tr>; })}</tbody></table></div>}

    {modal?.t === "po" && <CoPoModal onClose={() => setModal(null)}/>}
    {modal?.t === "inv" && <CoInvModal p={modal.p} onClose={() => setModal(null)}/>}
  </>);
}

function CoPoModal({ onClose }) {
  const v = cmStore.v, sites = window.SITES || [];
  const [f, setF] = uSCO2({ contract: v.sContracts[0]?.id, siteId: sites[0]?.id, desc: "", amount: "", wo: "" });
  const sc = v.sContracts.find(c => c.id === f.contract);
  const wos = (window.woStore?.list || []).filter(w => w.siteId === f.siteId && !["verified"].includes(w.status));
  const ok = f.desc.trim() && +f.amount > 0;
  const save = () => { let id; const needs = +f.amount > CO_LIMIT; cmStore.set(x => { id = cmNextId("PO-26-0", x.pos); return { ...x, pos: [{ id, supplier: sc.supplier, contract: sc.id, siteId: f.siteId, cat: sc.cat, desc: f.desc.trim(), amount: +f.amount, date: cmT(), status: needs ? "pending" : "approved", wo: f.wo || undefined }, ...x.pos] }; }); window.skyToast(needs ? `${id} created · awaiting approval (above ${cmEur(CO_LIMIT)})` : `${id} approved and sent to ${sc.supplier}`); onClose(); };
  return <div className="ni-scrim" onClick={onClose}><div className="ni-modal" onClick={e => e.stopPropagation()} role="dialog">
    <div className="ni-hd"><div><div className="kicker">Procurement</div><h3>New purchase order</h3></div><button className="ask-hd-btn" onClick={onClose}><Icon name="x" size={13}/></button></div>
    <div className="ni-body"><div className="ni-grid">
      <label className="field ni-span"><span>Supplier contract</span><select className="sel" value={f.contract} onChange={e => setF(x => ({ ...x, contract: e.target.value }))}>{v.sContracts.map(c => <option key={c.id} value={c.id}>{c.supplier} · {CM_CATS[c.cat]} · {c.rate}</option>)}</select></label>
      <label className="field"><span>Site</span><select className="sel" value={f.siteId} onChange={e => setF(x => ({ ...x, siteId: e.target.value, wo: "" }))}>{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select></label>
      <label className="field"><span>Linked work order</span><select className="sel" value={f.wo} onChange={e => { const w = wos.find(y => y.id === e.target.value); setF(x => ({ ...x, wo: e.target.value, desc: w ? `${w.id} · ${w.title}` : x.desc, amount: w && w.cost ? w.cost : x.amount })); }}><option value="">— none —</option>{wos.map(w => <option key={w.id} value={w.id}>{w.id} · {w.title}</option>)}</select></label>
      <label className="field ni-span"><span>Description *</span><input className="inp" value={f.desc} onChange={e => setF(x => ({ ...x, desc: e.target.value }))} placeholder="Scope, quantities, location"/></label>
      <label className="field"><span>Amount *</span><input className="inp mono" type="number" min="0" value={f.amount} onChange={e => setF(x => ({ ...x, amount: e.target.value }))}/></label>
      <div className="field"><span>Approval</span><div className="inp dm-ro">{+f.amount > CO_LIMIT ? "Needs approval" : "Auto-approved"}<em>limit {cmEur(CO_LIMIT)}</em></div></div>
    </div></div>
    <div className="ni-ft"><span className="grow"/><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" disabled={!ok} onClick={save}><Icon name="send" size={12}/>Create PO</button></div>
  </div></div>;
}

function CoInvModal({ p, onClose }) {
  const [f, setF] = uSCO2({ id: "", amount: p.amount, date: cmT(), wd: p.cat === "inspection" ? 5 : "" });
  const over = +f.amount > p.amount;
  const save = () => { cmStore.set(x => ({ ...x, sInv: [{ id: f.id.trim(), supplier: p.supplier, po: p.id, amount: +f.amount, date: f.date, due: window.skyAdd(30, f.date), status: "pending", ...(f.wd !== "" ? { wd: +f.wd } : {}) }, ...x.sInv] })); window.skyToast(`${f.id} registered against ${p.id}`); onClose(); };
  return <div className="ni-scrim" onClick={onClose}><div className="ni-modal" onClick={e => e.stopPropagation()} role="dialog" style={{ width: "min(520px,100%)" }}>
    <div className="ni-hd"><div><div className="kicker">{p.id} · {p.supplier} · PO {cmEur(p.amount)}</div><h3>Register supplier invoice</h3></div><button className="ask-hd-btn" onClick={onClose}><Icon name="x" size={13}/></button></div>
    <div className="ni-body"><div className="ni-grid">
      <label className="field"><span>Supplier invoice no. *</span><input className="inp mono" autoFocus value={f.id} onChange={e => setF(x => ({ ...x, id: e.target.value }))}/></label>
      <label className="field"><span>Amount *</span><input className="inp mono" type="number" value={f.amount} onChange={e => setF(x => ({ ...x, amount: e.target.value }))}/>{over && <em className="dm-err-t">Exceeds PO by {cmEur(+f.amount - p.amount)} — will need override</em>}</label>
      <label className="field"><span>Invoice date</span><input className="inp" type="date" value={f.date} onChange={e => setF(x => ({ ...x, date: e.target.value }))}/></label>
      {p.cat === "inspection" && <label className="field"><span>Report delivered in (wd)</span><input className="inp mono" type="number" min="0" value={f.wd} onChange={e => setF(x => ({ ...x, wd: e.target.value }))}/></label>}
    </div></div>
    <div className="ni-ft"><span className="grow"/><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" disabled={!f.id.trim() || !(+f.amount > 0)} onClick={save}>Register</button></div>
  </div></div>;
}

Object.assign(window, { CmOwner });
