/* =====================================================
   Betting Tracker — Dashboard
   Headline KPIs, equity curve, profit-by-period bars,
   win-rate donut, recent bets.
   ===================================================== */

function periodBuckets(bets, mode) {
  // returns ordered [{key, profit, staked, n}]
  const fmtKey = (iso) => {
    const d = new Date(iso + "T00:00:00");
    if (mode === "day") return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
    if (mode === "month") return d.toLocaleDateString(undefined, { month: "short" });
    // week -> "Wk of Mon d"
    const day = (d.getDay() + 6) % 7;
    const monday = new Date(d); monday.setDate(d.getDate() - day);
    return monday.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  };
  const map = {};
  const order = [];
  bets.filter(TRK.isSettled).slice().sort(TRK.byDate).forEach((b) => {
    const k = fmtKey(b.date);
    if (!map[k]) { map[k] = { key: k, profit: 0, staked: 0, n: 0 }; order.push(k); }
    map[k].profit += TRK.betProfit(b); map[k].staked += b.stake; map[k].n++;
  });
  let rows = order.map((k) => { const r = map[k]; r.profit = TRK.round(r.profit); return r; });
  // keep the chart readable
  const cap = mode === "day" ? 10 : mode === "week" ? 8 : 12;
  if (rows.length > cap) rows = rows.slice(rows.length - cap);
  return rows;
}

function Dashboard() {
  const { state, t, go } = useTracker();
  const [period, setPeriod] = useState("week");
  const [eqMode, setEqMode] = useState("money"); // equity curve: currency vs units
  const [scope, setScope] = useState("all"); // all | year | month

  const cur = state.settings.currency;
  const now = new Date();
  const inScope = (b) => {
    if (scope === "all") return true;
    const d = new Date(b.date + "T00:00:00");
    if (scope === "year") return d.getFullYear() === now.getFullYear();
    return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth();
  };
  const scoped = state.bets.filter(inScope);

  const s = TRK.summarize(scoped);
  const startBank = TRK.netDeposits(state);
  const eq = scope === "all"
    ? TRK.equitySeries(scoped, startBank, state.transactions)
    : TRK.equitySeries(scoped, 0);
  const balance = TRK.bankrollBalance(state);
  const clv = TRK.avgCLV(scoped);
  const withClose = scoped.filter((b) => TRK.betCLV(b) != null).length;
  const avgProfitPerBet = s.settledCount ? TRK.round(s.profit / s.settledCount, 0) : 0;
  const avgImplied = s.avgOdds > 1 ? Math.round(100 / s.avgOdds) : null;
  const buckets = periodBuckets(scoped, period);

  const recent = scoped.slice().sort((a, b) => TRK.byDate(b, a)).slice(0, 6);

  const unitSize = state.settings.unitSize || 100;
  const eqFmt = eqMode === "units"
    ? (v) => (v < 0 ? "\u2212" : "") + (Math.abs(v) / unitSize).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 1 }) + "u"
    : (v) => TRK.fmtMoney(TRK.round(v, 0), cur);

  const rec = s.won + "\u2013" + s.lost + (s.push ? "\u2013" + s.push : "");
  const growth = startBank ? (balance - startBank) / startBank * 100 : 0;
  const kpis = [
    { label: t("dash.bankroll"), icon: "wallet", value: TRK.fmtMoney(balance, cur), big: true,
      chip: { text: TRK.fmtSignedPct(growth, 1), tone: growth >= 0 ? "pos" : "neg" }, sub: t("bank.growth").toLowerCase() },
    { label: t("dash.profit"), icon: "chart", value: TRK.fmtMoney(s.profit, cur), tone: s.profit >= 0 ? "pos" : "neg", big: true,
      chip: { text: TRK.fmtUnits(s.profit / state.settings.unitSize), tone: s.profit >= 0 ? "pos" : "neg" } },
    { label: t("dash.roi"), icon: "analytics", value: TRK.fmtSignedPct(s.roi, 1), tone: s.roi >= 0 ? "pos" : "neg", sub: TRK.fmtMoney(avgProfitPerBet, cur) + t("dash.perbet") },
    { label: t("dash.winrate"), icon: "check", value: s.winRate + "%", chip: { text: rec } },
    { label: t("dash.clv"), icon: "target", value: clv == null ? "\u2014" : TRK.fmtSignedPct(clv, 2),
      tone: clv != null ? (clv >= 0 ? "pos" : "neg") : null, sub: withClose + " " + t("dash.wclose") },
    { label: t("dash.turnover"), icon: "layers", value: TRK.fmtMoney(s.staked, cur), sub: s.settledCount + " " + t("dash.settled").toLowerCase() },
    { label: t("dash.open"), icon: "bets", value: String(s.pending), sub: TRK.fmtMoney(s.pendingStake, cur) + " staked" },
    { label: t("dash.avgodds"), icon: "sliders", value: TRK.fmtOdds(s.avgOdds), sub: avgImplied == null ? null : avgImplied + "% " + t("dash.implied") }
  ];

  return (
    <div className="trk-page">
      <SectionHead title={t("dash.title")} sub={t("dash.sub")}
        right={<Segmented size="sm" value={scope} onChange={setScope}
          options={[{ value: "all", label: t("dash.all") }, { value: "year", label: t("dash.thisYear") }, { value: "month", label: t("dash.thisMonth") }]} />} />

      {s.pending > 0 && (
        <button className="trk-settlenudge glass" onClick={() => go("bets")}>
          <span className="trk-settlenudge__l"><Icon name="bets" size={16} /> <b>{s.pending}</b> {t("dash.open").toLowerCase()} {t("dash.tosettle")}</span>
          <span className="trk-settlenudge__cta">{t("dash.settlenow")}</span>
        </button>
      )}


      <div className="trk-kpis">
        {kpis.map((k, i) => (
          <Panel key={i} pad={18} className="trk-kpi2" hover>
            <div className="trk-kpi2__top">
              <span className="trk-kpi2__cap">{k.label}</span>
              <span className="trk-kpi2__ic"><Icon name={k.icon} size={14} /></span>
            </div>
            <div className="trk-kpi2__valrow">
              <div className={"trk-kpi2__val" + (k.big ? " trk-kpi2__val--big" : "") + (k.tone === "pos" ? " is-pos" : k.tone === "neg" ? " is-neg" : "")}>{k.value}</div>
              {(k.chip || k.sub) && (
                <div className="trk-kpi2__foot">
                  {k.chip && <span className={"trk-kpi2__chip" + (k.chip.tone === "pos" ? " is-pos" : k.chip.tone === "neg" ? " is-neg" : "")}>{k.chip.text}</span>}
                  {k.sub && <span className="trk-kpi2__sub">{k.sub}</span>}
                </div>
              )}
            </div>
          </Panel>
        ))}
      </div>

      <div className="trk-grid2">
        <Panel pad={26} className="trk-eqpanel">
          <SectionHead title={t("dash.equity")} sub={t("dash.equitySub")}
            right={<>
              <Segmented size="sm" value={eqMode} onChange={setEqMode}
                options={[{ value: "money", label: t("dash.money") }, { value: "units", label: t("dash.units") }]} />
              <span className={"trk-eqdelta " + (eq.end >= (eq.points[0] ? eq.points[0].equity : 0) ? "is-pos" : "is-neg")}>
                {eqFmt(eq.end)}</span>
            </>} />
          {eq.points.length > 1
            ? <EquityCurve series={eq} currency={cur} fmtVal={eqFmt} />
            : <Placeholder label="equity curve · needs settled bets" height={220} />}
        </Panel>

        <Panel pad={26} className="trk-donutpanel">
          <SectionHead title={t("dash.winrate")} />
          <div className="trk-donutwrap">
            <Donut won={s.won} lost={s.lost} push={s.push} size={196} />
            <div className="trk-donutlegend">
              <div><span className="dot dot--pos"></span>{t("res.won")} <b>{s.won}</b></div>
              <div><span className="dot dot--neg"></span>{t("res.lost")} <b>{s.lost}</b></div>
              <div><span className="dot dot--mute"></span>{t("res.push")}/{t("res.void")} <b>{s.push}</b></div>
            </div>
          </div>
        </Panel>
      </div>

      <Panel pad={26}>
        <SectionHead title={t("dash.byperiod")}
          right={<Segmented size="sm" value={period} onChange={setPeriod}
            options={[{ value: "day", label: t("dash.day") }, { value: "week", label: t("dash.week") }, { value: "month", label: t("dash.month") }]} />} />
        {buckets.length ? <PeriodBars data={buckets} currency={cur} /> : <Placeholder label="no settled bets in range" height={160} />}
      </Panel>

      <Panel pad={26}>
        <SectionHead title={t("dash.recent")} right={<button className="trk-textlink trk-textlink--sm" onClick={() => go("bets")}>{t("dash.viewall")}</button>} />
        {recent.length ? (
          <div className="table-wrap trk-tablewrap">
            <table className="table trk-table">
              <thead>
                <tr>
                  <th style={{ textAlign: "left" }}>{t("col.date")}</th>
                  <th style={{ textAlign: "left" }}>{t("col.event")}</th>
                  <th>{t("col.market")}</th>
                  <th>{t("col.odds")}</th>
                  <th>{t("col.stake")}</th>
                  <th>{t("col.result")}</th>
                  <th style={{ textAlign: "right" }}>{t("col.profit")}</th>
                </tr>
              </thead>
              <tbody>
                {recent.map((b) => {
                  const p = TRK.isSettled(b) ? TRK.betProfit(b) : null;
                  return (
                    <tr key={b.id} onClick={() => go("bets", b.id)}>
                      <td style={{ textAlign: "left", color: "var(--text-dim)" }}>{TRK.fmtDate(b.date)}</td>
                      <td style={{ textAlign: "left" }}>
                        <div className="trk-cellmain">{b.teamA}{b.teamB && b.teamB !== "\u2014" ? " v " + b.teamB : ""}</div>
                        <div className="trk-cellsub">{b.league}</div>
                      </td>
                      <td><div className="trk-cellmain">{b.side}</div><div className="trk-cellsub">{b.market}</div></td>
                      <td style={{ fontWeight: 700 }}>{TRK.fmtOdds(b.odds)}</td>
                      <td>{TRK.fmtMoney(b.stake, cur)}</td>
                      <td><ResultBadge result={b.result} t={t} /></td>
                      <td style={{ textAlign: "right", fontWeight: 700 }}
                        className={p == null ? "" : p > 0 ? "trk-pos" : p < 0 ? "trk-neg" : ""}>
                        {p == null ? "\u2014" : TRK.fmtMoney(TRK.round(p), cur)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : <EmptyState icon="bets" title={t("bets.empty")} sub={t("bets.emptySub")} />}
      </Panel>
    </div>
  );
}

Object.assign(window, { Dashboard });
