/* =============================================================
   CoreIQ Office — Dashboard (LIVE · this pharmacy)

   Every figure here is a real aggregate pulled from Aurora via the Office API
   (/overview), scoped to the signed-in organisation (and the selected store).
   Nothing is fabricated: where a vertical has no data yet — e.g. no sales
   history, dispensing not migrated — the figure is honestly zero and labelled,
   rather than filled with a placeholder.
   ============================================================= */
const { useState: dashUseState, useEffect: dashUseEffect } = React;

const dashMoney = (cents) =>
  "$" + (Number(cents || 0) / 100).toLocaleString("en-AU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const dashNum = (n) => Number(n || 0).toLocaleString("en-AU");

// date math on YYYY-MM-DD (UTC)
const dMinusMonths = (d, n) => { const t = new Date(d + "T00:00:00Z"); t.setUTCMonth(t.getUTCMonth() - n); return t.toISOString().slice(0, 10); };

function Dashboard() {
  const { scope, stores, setScreen, setScope } = window.useOffice();

  const [ov, setOv] = dashUseState(null);
  const [loading, setLoading] = dashUseState(true);
  const [err, setErr] = dashUseState(null);
  const [range, setRange] = dashUseState(null);     // fetched takings for the window
  const [from, setFrom] = dashUseState("");
  const [to, setTo] = dashUseState("");

  const siteId = scope === "all" ? undefined : scope;

  dashUseEffect(() => {
    let alive = true;
    setLoading(true); setErr(null);
    window.OfficeAPI.getOverview(siteId)
      .then((o) => { if (alive) { setOv(o); setLoading(false); } })
      .catch((e) => { if (alive) { setErr(String((e && e.message) || e)); setLoading(false); } });
    return () => { alive = false; };
  }, [scope]);

  // Sales for the chosen window — history + new sales as ONE timeline. First load
  // uses the API default (trailing 12 months of data) and seeds the date inputs.
  const loadRange = (f, t) => {
    const q = { ...(f ? { from: f } : {}), ...(t ? { to: t } : {}), ...(siteId ? { siteId } : {}) };
    window.OfficeAPI.getSalesRange(Object.keys(q).length ? q : undefined)
      .then((r) => { setRange(r); setFrom(r.range.from || ""); setTo(r.range.to || ""); })
      .catch(() => setRange(null));
  };
  dashUseEffect(() => { loadRange(); }, [scope]);

  const cur = stores.find((s) => s.id === scope);
  const scopeName = scope === "all" ? `All stores · ${stores.length}` : (cur?.name || "—");
  const v = (fn) => (loading || !ov ? "…" : fn(ov));
  const bounds = range?.bounds;
  const preset = (months) => { if (!bounds) return; const f = months == null ? bounds.from : dMinusMonths(bounds.to, months); setFrom(f); setTo(bounds.to); loadRange(f, bounds.to); };
  const rv = (fn) => (range ? fn(range) : "…");

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">{scopeName} · live from Aurora</span>
          <h2 className="off-screen-title">Dashboard</h2>
        </div>
        <div className="off-screen-actions">
          <button className="btn btn--secondary btn--sm" onClick={() => setScreen("catalogue")}>
            <OIcon name="pill"/> Browse catalogue
          </button>
        </div>
      </header>

      <div className="off-screen-body">
        {err && (
          <div className="off-card" style={{borderColor:'var(--void-border)', background:'var(--void-bg)', color:'var(--void-text)', marginBottom:16, padding:'12px 16px', flexDirection:'row', alignItems:'center', gap:10}}>
            <OIcon name="alert"/> <span>Couldn't load live data from the API: {err}</span>
          </div>
        )}

        {/* Takings — pick a period; history + new sales are one continuous timeline */}
        <div className="off-card">
          <div className="off-card-header" style={{flexWrap:'wrap', gap:10}}>
            <div>
              <h3 className="off-card-title">Takings</h3>
              <div className="off-card-meta">{from} → {to} · {rv((r) => dashNum(r.sales))} sales</div>
            </div>
            <div style={{display:'flex', alignItems:'center', gap:6, flexWrap:'wrap'}}>
              <button className="btn btn--ghost btn--sm" onClick={() => preset(12)}>12 months</button>
              <button className="btn btn--ghost btn--sm" onClick={() => preset(24)}>2 years</button>
              <button className="btn btn--ghost btn--sm" onClick={() => preset(null)}>All time</button>
              <span style={{width:1, height:20, background:'var(--line)', margin:'0 2px'}}/>
              <input className="input" type="date" value={from} min={bounds?.from} max={to} onChange={(e) => setFrom(e.target.value)} style={{height:32, width:140}}/>
              <span style={{color:'var(--text-subtle)'}}>→</span>
              <input className="input" type="date" value={to} min={from} max={bounds?.to} onChange={(e) => setTo(e.target.value)} style={{height:32, width:140}}/>
              <button className="btn btn--primary btn--sm" onClick={() => loadRange(from, to)}>Apply</button>
              <button className="btn btn--secondary btn--sm" onClick={() => setScreen("salesHistory")}><OIcon name="doc"/> Receipts</button>
            </div>
          </div>
          <div className="off-kpi-grid" style={{marginTop:4}}>
            <KpiCard label="Takings" value={rv((r) => dashMoney(r.takingsCents))} delta={{ dir: "up", text: rv((r) => dashNum(r.sales) + " sales") }}/>
            <KpiCard label="Avg basket" value={rv((r) => dashMoney(r.avgBasketCents))} delta={{ text: "per sale" }}/>
            <KpiCard label="Stock value" value={v((o) => dashMoney(o.stockValueCents))} delta={{ text: v((o) => dashNum(o.stockedSkus) + " SKUs in stock") }}/>
            <KpiCard label="Customers" value={v((o) => dashNum(o.customers))} delta={{ text: "account + patient records" }}/>
          </div>
          {range && range.byMonth.length > 0 && (
            <div style={{marginTop:16}}>
              <div style={{display:'flex', alignItems:'flex-end', gap: range.byMonth.length > 36 ? 1 : 3, height:96}}>
                {(() => { const mx = Math.max(...range.byMonth.map((m) => m.takingsCents), 1); const showLbl = range.byMonth.length <= 14;
                  return range.byMonth.map((m) => (
                    <div key={m.month} title={m.month + ": " + dashMoney(m.takingsCents) + " · " + dashNum(m.sales) + " sales"} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:4, minWidth:0}}>
                      <div style={{width:'100%', height: Math.max(2, (m.takingsCents / mx) * 78) + 'px', background:'var(--brand)', borderRadius:'3px 3px 0 0', opacity:0.85}}/>
                      {showLbl && <span style={{fontSize:9, color:'var(--text-subtle)', fontFamily:'var(--font-mono)', whiteSpace:'nowrap'}}>{m.month.slice(2)}</span>}
                    </div>
                  )); })()}
              </div>
              {range.byMonth.length > 14 && <div style={{fontSize:'var(--fs-11)', color:'var(--text-subtle)', textAlign:'center', marginTop:6}}>{range.byMonth[0].month} → {range.byMonth[range.byMonth.length - 1].month}</div>}
            </div>
          )}
        </div>

        {/* Catalogue / customer counts */}
        <div className="off-kpi-grid" style={{marginTop:12}}>
          <KpiCard label="Products in catalogue" value={v((o) => dashNum(o.products))} delta={{ text: v((o) => dashNum(o.activeProducts) + " active / sellable") }} spark={null}/>
          <KpiCard label="Customers"             value={v((o) => dashNum(o.customers))} delta={{ text: "patient + account records" }} spark={null}/>
          <KpiCard label="Stocked SKUs"          value={v((o) => dashNum(o.stockedSkus))} delta={{ text: "lines with on-hand > 0" }} spark={null}/>
          <KpiCard label="Stores"                value={v((o) => dashNum(o.stores))} delta={{ text: stores.length === 1 ? "single site" : "in this organisation" }} spark={null}/>
        </div>

        <div className="dash-grid" style={{marginTop:18}}>
          {/* Stores — real, from /sites */}
          <div className="off-card">
            <div className="off-card-header">
              <div>
                <h3 className="off-card-title">Stores</h3>
                <div className="off-card-meta">Live from Aurora · click to scope the dashboard</div>
              </div>
            </div>
            <div style={{display:'flex', flexDirection:'column', gap:0}}>
              {stores.length === 0 && <div style={{padding:'14px 4px', fontSize:'var(--fs-13)', color:'var(--text-subtle)'}}>No stores for this organisation.</div>}
              {stores.map((s) => (
                <div key={s.id} className="alert-row" style={{cursor:'pointer'}} onClick={() => setScope(s.id)}>
                  <div className="off-topbar-store-av" style={{width:34, height:34, borderRadius:8, background:'var(--teal-700)', color:'#fff'}}>{s.code || "··"}</div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontWeight:500, color:'var(--text)', fontSize:'var(--fs-13)'}}>{s.name}</div>
                    <div style={{fontSize:'var(--fs-11)', color:'var(--text-subtle)', fontFamily:'var(--font-mono)'}}>{s.id}</div>
                  </div>
                  {scope === s.id && <OIcon name="check" style={{color:'var(--brand)'}}/>}
                </div>
              ))}
            </div>
          </div>

          {/* Data sources — what's loaded, at the data level */}
          <div className="off-card">
            <div className="off-card-header">
              <h3 className="off-card-title">What's loaded</h3>
            </div>
            <div style={{display:'flex', flexDirection:'column', gap:0}}>
              {[
                { ok: true,  label: "Product catalogue", meta: v((o) => dashNum(o.products) + " products, live in Aurora") },
                { ok: true,  label: "Customers & accounts", meta: v((o) => dashNum(o.customers) + " patient / account records") },
                { ok: true,  label: "Stock on hand",     meta: v((o) => dashNum(o.stockedSkus) + " stocked SKUs · " + dashMoney(o.stockValueCents) + " at cost") },
                { ok: true,  label: "Sales history",      meta: bounds ? "continuous trading history from " + bounds.from : "trading history on file" },
                { ok: true,  label: "Purchasing & accounts", meta: "supplier invoices + account statements on file" },
                { ok: false, label: "New POS sales",      meta: "appear here as the POS rings them" },
                { ok: false, label: "Scripts / dispensing", meta: "handled by the dispensing system" },
              ].map((r, i) => (
                <div key={i} className="alert-row">
                  <div className={"alert-row-icon alert-row-icon--" + (r.ok ? "stock" : "void")}>
                    <OIcon name={r.ok ? "check-circle" : "close-circle"}/>
                  </div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontWeight:500, color:'var(--text)', fontSize:'var(--fs-13)'}}>{r.label}</div>
                    <div style={{fontSize:'var(--fs-11)', color:'var(--text-subtle)'}}>{r.meta}</div>
                  </div>
                  <span style={{fontSize:10, fontWeight:700, letterSpacing:'0.04em', color: r.ok ? 'var(--paid)' : 'var(--hold)'}}>{r.ok ? "LIVE" : "NONE"}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function KpiCard({ label, value, delta, spark }) {
  return (
    <div className="off-kpi">
      <div className="off-kpi-label">{label}</div>
      <div className="off-kpi-value">{value}</div>
      {delta && <div className={"off-kpi-delta" + (delta.dir === "up" ? " off-kpi-delta--up" : delta.dir === "down" ? " off-kpi-delta--down" : "")}>{delta.text}</div>}
      {spark && (
        <div className="off-kpi-spark">
          {spark.map((v, i) => (
            <span key={i} className={i === spark.length - 1 ? "peak" : ""} style={{height: Math.max(8, v * 100) + "%"}}/>
          ))}
        </div>
      )}
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, { dashboard: Dashboard });
window.KpiCard = KpiCard;
