/* =============================================================
   CoreIQ Office — Analytics (LIVE · legacy archive)

   Business intelligence over the 17-year retention archive: sales reporting,
   inventory intelligence, and debtor/supplier analytics. Every figure is a real
   aggregate from Aurora (/analytics/*) — nothing fabricated.
   ============================================================= */
const { useState: anUseState, useEffect: anUseEffect } = React;

const anM = (c) => "$" + (Number(c || 0) / 100).toLocaleString("en-AU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const anMk = (c) => { const d = Number(c || 0) / 100; return d >= 1000 ? "$" + (d / 1000).toFixed(d >= 100000 ? 0 : 1) + "k" : "$" + d.toFixed(0); };
const anN = (n) => Number(n || 0).toLocaleString("en-AU");
const anErr = (e) => <div className="off-card" style={{borderColor:"var(--void-border)", background:"var(--void-bg)", color:"var(--void-text)", padding:"12px 16px", flexDirection:"row", alignItems:"center", gap:10}}><window.OIcon name="alert"/> <span>{e}</span></div>;
const anLoad = (t) => <div className="off-screen"><header className="off-screen-header"><div className="off-screen-header-meta"><span className="off-screen-eyebrow">loading…</span><h2 className="off-screen-title">{t}</h2></div></header></div>;

// Vertical bar chart (months / hours / day-of-week)
function VBars({ items, valueKey, labelKey, height = 120, color = "var(--brand)" }) {
  const mx = Math.max(1, ...items.map((d) => Number(d[valueKey]) || 0));
  return (
    <div style={{display:"flex", alignItems:"flex-end", gap:items.length > 24 ? 2 : 4, height}}>
      {items.map((d, i) => (
        <div key={i} title={`${d[labelKey]}: ${anM(d[valueKey])}`} style={{flex:1, display:"flex", flexDirection:"column", alignItems:"center", gap:4, minWidth:0}}>
          <div style={{width:"100%", height: Math.max(2, (Number(d[valueKey]) / mx) * (height - 18)) + "px", background:color, borderRadius:"3px 3px 0 0", opacity:0.85}}/>
          <span style={{fontSize:9, color:"var(--text-subtle)", fontFamily:"var(--font-mono)", whiteSpace:"nowrap"}}>{d[labelKey]}</span>
        </div>
      ))}
    </div>
  );
}
// Horizontal bars (tender mix / shrinkage)
function HBars({ items, valueKey, labelKey, fmt }) {
  const mx = Math.max(1, ...items.map((d) => Math.abs(Number(d[valueKey]) || 0)));
  return (
    <div style={{display:"flex", flexDirection:"column", gap:8}}>
      {items.map((d, i) => (
        <div key={i} style={{display:"flex", alignItems:"center", gap:10}}>
          <div style={{flex:"0 0 130px", fontSize:"var(--fs-12)", textTransform:"capitalize", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{d[labelKey]}</div>
          <div style={{flex:1, background:"var(--bg-subtle)", borderRadius:5, height:18, position:"relative"}}>
            <div style={{position:"absolute", left:0, top:0, bottom:0, width: Math.max(2, (Math.abs(Number(d[valueKey])) / mx) * 100) + "%", background:"var(--brand)", borderRadius:5, opacity:0.85}}/>
          </div>
          <div style={{flex:"0 0 110px", textAlign:"right", fontSize:"var(--fs-12)", fontWeight:600, fontVariantNumeric:"tabular-nums"}}>{fmt(d[valueKey])}</div>
        </div>
      ))}
    </div>
  );
}

// Interactive revenue mix — a stacked bar of Retail + Script co-pay + Govt PBS
// subsidy; tick any series on/off and the bar recomputes so you can play with it.
function RevenueMix({ split }) {
  const SERIES = [
    { key: "retail",  label: "Retail (front of shop)", value: split.privateCents,     color: "var(--brand)" },
    { key: "copay",   label: "Script patient co-pay",  value: split.pbsCents,         color: "var(--hold)" },
    { key: "subsidy", label: "Government PBS subsidy",  value: split.govtSubsidyCents, color: "var(--navy-600)" },
  ];
  const [on, setOn] = anUseState({ retail: true, copay: true, subsidy: true });
  const active = SERIES.filter((s) => on[s.key]);
  const total = active.reduce((a, s) => a + s.value, 0);
  const denom = Math.max(1, total);
  return (
    <div className="off-card">
      <div className="off-card-header">
        <h3 className="off-card-title">Revenue mix</h3>
        <div className="off-card-meta">{anM(total)} · tick to add/remove</div>
      </div>
      <div style={{display:"flex", height:24, borderRadius:6, overflow:"hidden", margin:"4px 0 14px", background:"var(--bg-subtle)"}}>
        {active.map((s) => (
          <div key={s.key} title={s.label + " · " + anM(s.value)}
            style={{width:(s.value / denom * 100) + "%", background:s.color, transition:"width .25s ease"}}/>
        ))}
      </div>
      {SERIES.map((s) => (
        <label key={s.key} className="checkbox" style={{display:"flex", alignItems:"center", gap:10, padding:"9px 0", width:"100%", cursor:"pointer", opacity: on[s.key] ? 1 : 0.5, borderTop:"1px solid var(--line)"}}
          onClick={(e) => { e.preventDefault(); setOn((o) => ({ ...o, [s.key]: !o[s.key] })); }}>
          <input type="checkbox" checked={on[s.key]} readOnly/>
          <span className="checkbox-box"><window.OIcon name="check" width={12} height={12}/></span>
          <span style={{width:11, height:11, borderRadius:3, background:s.color, flexShrink:0}}/>
          <span style={{flex:1, fontSize:"var(--fs-13)"}}>{s.label}</span>
          <span style={{fontWeight:600, fontVariantNumeric:"tabular-nums", fontSize:"var(--fs-13)"}}>{anM(s.value)}</span>
        </label>
      ))}
      <div style={{display:"flex", justifyContent:"space-between", padding:"10px 0 2px", borderTop:"2px solid var(--line)", marginTop:4, fontSize:"var(--fs-13)"}}>
        <span style={{fontWeight:600, color:"var(--text-subtle)"}}>{active.length === 3 ? "Total income" : active.length === 0 ? "Nothing selected" : "Selected total"}</span>
        <span style={{fontWeight:700, fontVariantNumeric:"tabular-nums"}}>{anM(total)}</span>
      </div>
    </div>
  );
}

// -----------------------------------------------------------------
// 1) SALES ANALYTICS
// -----------------------------------------------------------------
function SalesAnalytics() {
  const [years, setYears] = anUseState([]);
  const [year, setYear] = anUseState(null);
  const [data, setData] = anUseState(null);
  const [loading, setLoading] = anUseState(true);
  const [err, setErr] = anUseState(null);

  anUseEffect(() => {
    window.OfficeAPI.analyticsMeta().then((m) => { setYears(m.years || []); setYear(m.latest); }).catch((e) => setErr(String(e.message || e)));
  }, []);
  anUseEffect(() => {
    if (!year) return;
    let alive = true; setLoading(true); setErr(null);
    window.OfficeAPI.analyticsSales(year)
      .then((s) => { if (alive) { setData(s); setLoading(false); } })
      .catch((e) => { if (alive) { setErr(String(e.message || e)); setLoading(false); } });
    return () => { alive = false; };
  }, [year]);

  const DOW = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const dowFull = data ? DOW.map((d, i) => data.byDayOfWeek.find((x) => x.dow === i) || { day: d, dow: i, revenueCents: 0 }) : [];
  const hoursFull = data ? Array.from({ length: 24 }, (_, h) => data.byHour.find((x) => x.hour === h) || { hour: h, revenueCents: 0 }).filter((x) => x.hour >= 6 && x.hour <= 21) : [];
  const split = data?.revenueSplit;
  const splitTotal = split ? Math.max(1, split.privateCents + split.pbsCents) : 1;

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">live from Aurora</span>
          <h2 className="off-screen-title">Sales analytics</h2>
        </div>
        <div className="off-screen-actions">
          <select className="input" value={year || ""} onChange={(e) => setYear(e.target.value)} style={{height:34, width:120}}>
            {years.map((y) => <option key={y} value={y}>{y}</option>)}
          </select>
        </div>
      </header>
      <div className="off-screen-body">
        {err && anErr("Couldn't load analytics: " + err)}
        {loading && !data && <div className="off-card" style={{padding:20, color:"var(--text-subtle)"}}>Crunching {year}…</div>}
        {data && (
          <>
            <div className="off-kpi-grid">
              <KpiCard label="Customer-paid revenue" value={anM(data.totals.revenueCents)} delta={{ text: anN(data.totals.sales) + " sales" }}/>
              <KpiCard label="Govt PBS subsidy" value={anM(data.revenueSplit.govtSubsidyCents)} delta={{ text: "reimbursed on scripts (extra)" }}/>
              <KpiCard label="Avg basket" value={anM(data.totals.avgBasketCents)} delta={{ text: "per sale" }}/>
              <KpiCard label="GST collected" value={anM(data.totals.gstCents)} delta={{ text: data.totals.voids + " voids" }}/>
            </div>

            <div className="off-card" style={{marginTop:16}}>
              <div className="off-card-header"><h3 className="off-card-title">Revenue by month · {year}</h3></div>
              {data.byMonth.length === 0 ? <div style={{padding:12, color:"var(--text-subtle)"}}>No sales.</div> :
                <VBars items={data.byMonth.map((m) => ({ label: m.month.slice(5), revenueCents: m.revenueCents }))} valueKey="revenueCents" labelKey="label" height={150}/>}
            </div>

            <div className="dash-grid" style={{marginTop:16}}>
              <div className="off-card">
                <div className="off-card-header"><h3 className="off-card-title">By day of week</h3></div>
                <VBars items={dowFull.map((d) => ({ label: d.day, revenueCents: d.revenueCents }))} valueKey="revenueCents" labelKey="label" height={120} color="var(--teal-600,var(--brand))"/>
              </div>
              <div className="off-card">
                <div className="off-card-header"><h3 className="off-card-title">By hour of day</h3></div>
                <VBars items={hoursFull.map((d) => ({ label: d.hour, revenueCents: d.revenueCents }))} valueKey="revenueCents" labelKey="label" height={120} color="var(--navy-600,var(--brand))"/>
              </div>
            </div>

            <div className="dash-grid" style={{marginTop:16}}>
              <RevenueMix split={data.revenueSplit}/>
              <div className="off-card">
                <div className="off-card-header"><h3 className="off-card-title">Tender mix</h3></div>
                <HBars items={data.tenderMix} valueKey="amountCents" labelKey="type" fmt={anM}/>
              </div>
            </div>

            <div className="off-card" style={{marginTop:16}}>
              <div className="off-card-header"><h3 className="off-card-title">Top sellers · {year}</h3><div className="off-card-meta">by revenue</div></div>
              <div className="off-grid" style={{gridTemplateColumns:"40px minmax(180px,1.6fr) 120px 90px 120px"}}>
                <div className="off-grid-headcell">#</div>
                <div className="off-grid-headcell">Product</div>
                <div className="off-grid-headcell">SKU</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Units</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Revenue</div>
                {data.topProducts.map((p, i) => (
                  <div key={p.productId} className="off-grid-row">
                    <div className="off-grid-cell off-muted">{i + 1}</div>
                    <div className="off-grid-cell off-cell-strong" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{p.name}</div>
                    <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:"var(--fs-12)"}}>{p.sku || "—"}</div>
                    <div className="off-grid-cell off-cell-num">{anN(p.units)}</div>
                    <div className="off-grid-cell off-cell-num off-cell-strong">{anM(p.revenueCents)}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="off-card" style={{marginTop:16}}>
              <div className="off-card-header"><h3 className="off-card-title">By operator</h3></div>
              <div className="off-grid" style={{gridTemplateColumns:"minmax(160px,1.4fr) 120px 140px"}}>
                <div className="off-grid-headcell">Staff</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Sales</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Revenue</div>
                {data.byOperator.map((o) => (
                  <div key={o.staffId} className="off-grid-row">
                    <div className="off-grid-cell off-cell-strong">{o.name}</div>
                    <div className="off-grid-cell off-cell-num off-muted">{anN(o.sales)}</div>
                    <div className="off-grid-cell off-cell-num off-cell-strong">{anM(o.revenueCents)}</div>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// -----------------------------------------------------------------
// 2) INVENTORY INTELLIGENCE
// -----------------------------------------------------------------
function InventoryAnalytics() {
  const { setScreenState, setScreen } = window.useOffice();
  const [data, setData] = anUseState(null);
  const [err, setErr] = anUseState(null);
  anUseEffect(() => {
    window.OfficeAPI.analyticsInventory().then(setData).catch((e) => setErr(String(e.message || e)));
  }, []);
  const open = (pid) => { if (pid) { setScreenState({ activeProductId: pid, productFrom: "inventoryAnalytics" }); setScreen("productDetail"); } };
  if (err) return <div className="off-screen"><div className="off-screen-body">{anErr("Couldn't load: " + err)}</div></div>;
  if (!data) return anLoad("Inventory intelligence");
  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">stale cutoff {data.cutoff}</span>
          <h2 className="off-screen-title">Inventory intelligence</h2>
        </div>
      </header>
      <div className="off-screen-body">
        <div className="off-kpi-grid">
          <KpiCard label="Dead / slow lines" value={anN(data.summary.deadStockLines)} delta={{ dir: "down", text: "no sale in 12 months" }}/>
          <KpiCard label="Capital in dead stock" value={anM(data.summary.deadStockValueCents)} delta={{ text: "at cost · top 50" }}/>
          <KpiCard label="Shrinkage" value={anN(data.summary.shrinkageUnits) + " u"} delta={{ dir: "down", text: anN(data.summary.adjustmentLines) + " adjustments" }}/>
          <KpiCard label="Adjustment events" value={anN(data.summary.adjustmentLines)} delta={{ text: "all reasons" }}/>
        </div>

        <div className="off-card" style={{marginTop:16}}>
          <div className="off-card-header"><h3 className="off-card-title">Dead &amp; slow stock</h3><div className="off-card-meta">on-hand &gt; 0, no outward movement since {data.cutoff} · highest value first</div></div>
          {data.deadStock.length === 0 ? <div style={{padding:12, color:"var(--text-subtle)"}}>No dead stock — everything's moving.</div> :
            <div className="off-grid" style={{gridTemplateColumns:"minmax(180px,1.6fr) 130px 80px 110px 110px"}}>
              <div className="off-grid-headcell">Product</div>
              <div className="off-grid-headcell">SKU</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>On hand</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Value</div>
              <div className="off-grid-headcell">Last out</div>
              {data.deadStock.map((d) => (
                <div key={d.productId} className="off-grid-row" style={{cursor:"pointer"}} onClick={() => open(d.productId)}>
                  <div className="off-grid-cell off-cell-strong" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{d.name}</div>
                  <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:"var(--fs-12)"}}>{d.sku || "—"}</div>
                  <div className="off-grid-cell off-cell-num">{anN(d.onHand)}</div>
                  <div className="off-grid-cell off-cell-num off-cell-strong">{anM(d.valueCents)}</div>
                  <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:"var(--fs-12)"}}>{d.lastOut || "never"}</div>
                </div>
              ))}
            </div>}
        </div>

        <div className="dash-grid" style={{marginTop:16}}>
          <div className="off-card">
            <div className="off-card-header"><h3 className="off-card-title">Shrinkage by reason</h3></div>
            <HBars items={data.shrinkageByReason} valueKey="units" labelKey="reason" fmt={(v) => anN(v) + " u"}/>
          </div>
          <div className="off-card">
            <div className="off-card-header"><h3 className="off-card-title">Fastest movers</h3><div className="off-card-meta">units out, last 12 months</div></div>
            <div className="off-grid" style={{gridTemplateColumns:"minmax(160px,1.6fr) 100px"}}>
              <div className="off-grid-headcell">Product</div>
              <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Units out</div>
              {data.topMovers.slice(0, 12).map((m) => (
                <div key={m.productId} className="off-grid-row" style={{cursor:"pointer"}} onClick={() => open(m.productId)}>
                  <div className="off-grid-cell off-cell-strong" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{m.name}</div>
                  <div className="off-grid-cell off-cell-num off-cell-strong">{anN(m.unitsOut)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// -----------------------------------------------------------------
// 3) FINANCIAL ANALYTICS — aged debtors + supplier spend
// -----------------------------------------------------------------
function FinancialAnalytics() {
  const [tab, setTab] = anUseState("debtors");
  const [deb, setDeb] = anUseState(null);
  const [sup, setSup] = anUseState(null);
  const [err, setErr] = anUseState(null);
  anUseEffect(() => { window.OfficeAPI.analyticsDebtors().then(setDeb).catch((e) => setErr(String(e.message || e))); }, []);
  anUseEffect(() => { window.OfficeAPI.analyticsSuppliers().then(setSup).catch((e) => setErr(String(e.message || e))); }, []);
  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">live from Aurora</span>
          <h2 className="off-screen-title">Financial analytics</h2>
        </div>
      </header>
      <div className="off-screen-body">
        <div className="tabset" style={{marginBottom:14}}>
          <button className="tabset-item" aria-selected={tab === "debtors"} onClick={() => setTab("debtors")}>Aged debtors</button>
          <button className="tabset-item" aria-selected={tab === "suppliers"} onClick={() => setTab("suppliers")}>Supplier spend</button>
        </div>
        {err && anErr(err)}

        {tab === "debtors" && deb && (
          <>
            <div className="off-kpi-grid">
              <KpiCard label="Total owing" value={anM(deb.summary.totalOwingCents)} delta={{ dir: "down", text: anN(deb.summary.accountsOwing) + " accounts" }}/>
              <KpiCard label="Accounts owing" value={anN(deb.summary.accountsOwing)} delta={{ text: "with a balance" }}/>
              <KpiCard label="In credit" value={anM(Math.abs(deb.summary.totalCreditCents))} delta={{ text: anN(deb.summary.accountsInCredit) + " accounts" }}/>
            </div>
            <div className="off-card" style={{marginTop:16}}>
              <div className="off-card-header"><h3 className="off-card-title">Top debtors</h3><div className="off-card-meta">{deb.note}</div></div>
              <div className="off-grid" style={{gridTemplateColumns:"90px minmax(160px,1.4fr) 110px 110px 110px"}}>
                <div className="off-grid-headcell">Account</div>
                <div className="off-grid-headcell">Customer</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Balance</div>
                <div className="off-grid-headcell">Last activity</div>
                <div className="off-grid-headcell">Last payment</div>
                {deb.topDebtors.map((d) => (
                  <div key={d.id} className="off-grid-row">
                    <div className="off-grid-cell off-cell-mono off-cell-strong">{d.accountNumber || "—"}</div>
                    <div className="off-grid-cell" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{d.name}</div>
                    <div className="off-grid-cell off-cell-num off-cell-strong" style={{color:"var(--void-text)"}}>{anM(d.balanceCents)}</div>
                    <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:"var(--fs-12)"}}>{d.lastActivity || "—"}</div>
                    <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:"var(--fs-12)"}}>{d.lastPayment || "—"}</div>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}

        {tab === "suppliers" && sup && (
          <>
            <div className="off-kpi-grid">
              <KpiCard label="Total spend" value={anM(sup.summary.totalSpendCents)} delta={{ text: anN(sup.summary.invoices) + " invoices" }}/>
              <KpiCard label="GST input credits" value={anM(sup.summary.gstCreditsCents)} delta={{ text: "claimable" }}/>
              <KpiCard label="Suppliers" value={anN(sup.bySupplier.length)} delta={{ text: "top by spend" }}/>
            </div>
            <div className="off-card" style={{marginTop:16}}>
              <div className="off-card-header"><h3 className="off-card-title">Spend by supplier</h3><div className="off-card-meta">all-time, GST-inclusive</div></div>
              <div className="off-grid" style={{gridTemplateColumns:"minmax(160px,1.4fr) 90px 120px 100px 160px"}}>
                <div className="off-grid-headcell">Supplier</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Invoices</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>Spend</div>
                <div className="off-grid-headcell" style={{justifyContent:"flex-end"}}>GST</div>
                <div className="off-grid-headcell">Active</div>
                {sup.bySupplier.map((s, i) => (
                  <div key={i} className="off-grid-row">
                    <div className="off-grid-cell off-cell-strong" style={{overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{s.supplier}</div>
                    <div className="off-grid-cell off-cell-num off-muted">{anN(s.invoices)}</div>
                    <div className="off-grid-cell off-cell-num off-cell-strong">{anM(s.spendCents)}</div>
                    <div className="off-grid-cell off-cell-num off-muted">{anM(s.gstCents)}</div>
                    <div className="off-grid-cell off-cell-mono off-muted" style={{fontSize:"var(--fs-11)"}}>{s.firstInvoice} → {s.lastInvoice}</div>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  salesAnalytics: SalesAnalytics,
  inventoryAnalytics: InventoryAnalytics,
  financialAnalytics: FinancialAnalytics,
});
