/* Truong So CRM — Reports / Analytics */
const { useState: useRS, useMemo: useRM } = React;

const PERIODS = [
  { id: "7d", key: "p_7d" },
  { id: "30d", key: "p_30d" },
  { id: "q", key: "p_q" },
  { id: "y", key: "p_y" },
];
function periodLabel(id) { return window.t("p_" + id); }

function Reports({ deals }) {
  const [period, setPeriod] = useRS("q");
  const [pipeId, setPipeId] = useRS("all");
  const [owner, setOwner] = useRS("all");

  const owners = window.CRM_OWNERS;
  const stages = window.CRM_STAGES;

  const open = useRM(() => deals.filter(d =>
    (pipeId === "all" || d.pipeline === pipeId) &&
    (owner === "all" || d.owner === owner)
  ), [deals, pipeId, owner]);

  const totalOpen = open.reduce((s, d) => s + d.value, 0);
  const count = open.length;
  const avg = count ? Math.round(totalOpen / count) : 0;

  // performance (seeded), filtered by owner
  const perfOwners = owner === "all" ? owners.map(o => o.id) : [owner];
  const perf = perfOwners.reduce((a, id) => {
    const p = window.CRM_PERF[id];
    a.won += p.won; a.lost += p.lost; a.wonValue += p.wonValue; return a;
  }, { won: 0, lost: 0, wonValue: 0 });
  const winRate = perf.won + perf.lost ? Math.round((perf.won / (perf.won + perf.lost)) * 100) : 0;
  // period scaling for "won this period"
  const periodScale = { "7d": 0.18, "30d": 0.6, "q": 1, "y": 3.4 }[period];
  const wonPeriod = Math.round(perf.wonValue * periodScale);

  // trend scaled by owner share + period
  const ownerShare = owner === "all" ? 1 : (window.CRM_PERF[owner].wonValue / Object.values(window.CRM_PERF).reduce((s, p) => s + p.wonValue, 0));
  const trend = window.CRM_TREND.map(t => ({ ...t, won: Math.round(t.won * ownerShare), lost: Math.round(t.lost * ownerShare) }));
  const trendMax = Math.max(...trend.map(t => t.won)) || 1;

  // funnel from live open deals across selected pipeline(s)
  const funnelStages = pipeId === "all" ? stages.sales : stages[pipeId];
  const funnel = funnelStages.map(s => {
    const ds = open.filter(d => d.stage === s.id);
    return { ...s, count: ds.length, value: ds.reduce((a, d) => a + d.value, 0) };
  });
  const funnelMax = Math.max(...funnel.map(f => f.value), 1);

  // leaderboard
  const board = owners.map(o => {
    const od = open.filter(d => d.owner === o.id);
    const p = window.CRM_PERF[o.id];
    return { owner: o, count: od.length, value: od.reduce((a, d) => a + d.value, 0), wr: Math.round((p.won / (p.won + p.lost)) * 100) };
  }).sort((a, b) => b.value - a.value);

  // source donut from contacts (filtered by owner)
  const contacts = (window.CRM_CONTACTS || []).filter(c => owner === "all" || c.owner === owner);
  const srcMap = {};
  contacts.forEach(c => { srcMap[c.source] = (srcMap[c.source] || 0) + 1; });
  const srcEntries = Object.entries(srcMap).sort((a, b) => b[1] - a[1]);
  const srcTotal = contacts.length || 1;
  const srcHues = [262, 215, 150, 25, 320, 60, 190];
  let acc = 0;
  const segs = srcEntries.map(([name, n], i) => {
    const from = acc / srcTotal * 360; acc += n; const to = acc / srcTotal * 360;
    return { name, n, hue: srcHues[i % srcHues.length], from, to };
  });
  const conic = segs.length
    ? "conic-gradient(" + segs.map(s => `oklch(0.62 0.15 ${s.hue}) ${s.from}deg ${s.to}deg`).join(",") + ")"
    : "var(--line)";

  const empty = count === 0;

  return (
    <div className="reports">
      <header className="topbar">
        <div className="pipeSwitch">
          <h1 className="viewTitle">{t("rep_title")}</h1>
          <div className="viewSub">{t("rep_sub")}</div>
        </div>
        <div className="repFilters">
          <div className="segCtrl">
            {PERIODS.map(p => (
              <button key={p.id} className={"segBtn" + (period === p.id ? " on" : "")} onClick={() => setPeriod(p.id)}>{t(p.key)}</button>
            ))}
          </div>
          <select className="repSelect" value={pipeId} onChange={e => setPipeId(e.target.value)}>
            <option value="all">{t("rep_all_pipe")}</option>
            {window.CRM_PIPELINES.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <select className="repSelect" value={owner} onChange={e => setOwner(e.target.value)}>
            <option value="all">{t("rep_all_staff")}</option>
            {owners.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
          </select>
        </div>
      </header>

      <div className="repBody">
        <div className="kpiRow">
          <div className="kpi"><div className="kpiLbl">{t("kpi_open")}</div><div className="kpiNum">{fmtVND(totalOpen)} ₫</div><div className="kpiSub">{count} {t("stat_deals")}</div></div>
          <div className="kpi"><div className="kpiLbl">{t("kpi_won")} ({periodLabel(period)})</div><div className="kpiNum" style={{color:"oklch(0.55 0.14 150)"}}>{wonPeriod.toLocaleString("vi-VN")} tr ₫</div><div className="kpiSub">{Math.round(perf.won*periodScale)} {t("dd_win").toLowerCase()}</div></div>
          <div className="kpi"><div className="kpiLbl">{t("kpi_winrate")}</div><div className="kpiNum">{winRate}%</div><div className="kpiBar"><span style={{width:winRate+"%"}}></span></div></div>
          <div className="kpi"><div className="kpiLbl">{t("kpi_avg")}</div><div className="kpiNum">{fmtVND(avg)} ₫</div><div className="kpiSub">{perf.won} · {perf.lost}</div></div>
        </div>

        <div className="repGrid">
          <section className="repCard wide">
            <div className="repCardHead"><h3>{t("rep_monthly")}</h3><span className="repHint">{window.__lang==="en"?"million ₫":"triệu ₫"}</span></div>
            {empty ? <Empty /> : (
              <div className="barChart">
                {trend.map(t => (
                  <div key={t.m} className="barCol">
                    <div className="barTrack">
                      <div className="barFill" style={{ height: (t.won / trendMax * 100) + "%" }} title={t.won + " tr"}>
                        <span className="barVal">{t.won}</span>
                      </div>
                    </div>
                    <span className="barLbl">{t.m}</span>
                  </div>
                ))}
              </div>
            )}
          </section>

          <section className="repCard">
            <div className="repCardHead"><h3>{t("rep_source")}</h3></div>
            {contacts.length === 0 ? <Empty /> : (
              <div className="donutWrap">
                <div className="donut" style={{ background: conic }}><div className="donutHole"><b>{srcTotal}</b><span>liên hệ</span></div></div>
                <div className="donutLegend">
                  {segs.map(s => (
                    <div key={s.name} className="legRow"><span className="legDot" style={{ background: `oklch(0.62 0.15 ${s.hue})` }}></span><span className="legName">{s.name}</span><b>{s.n}</b></div>
                  ))}
                </div>
              </div>
            )}
          </section>

          <section className="repCard">
            <div className="repCardHead"><h3>{t("rep_funnel")}</h3><span className="repHint">{pipeId === "all" ? window.CRM_PIPELINES[0].name : window.CRM_PIPELINES.find(p=>p.id===pipeId).name}</span></div>
            {empty ? <Empty /> : (
              <div className="funnel">
                {funnel.map(f => (
                  <div key={f.id} className="funRow">
                    <div className="funTop"><span className="funName">{window.tStage ? window.tStage(f) : f.name}</span><span className="funCount">{f.count} {t("stat_deals")}</span></div>
                    <div className="funTrack"><div className="funFill" style={{ width: Math.max(f.value / funnelMax * 100, f.count ? 8 : 0) + "%", background: `oklch(0.62 0.14 ${f.hue})` }}></div></div>
                    <div className="funVal">{fmtVND(f.value)} ₫</div>
                  </div>
                ))}
              </div>
            )}
          </section>

          <section className="repCard wide">
            <div className="repCardHead"><h3>{t("rep_perf")}</h3></div>
            <table className="lbTable">
              <thead><tr><th>{t("col_owner")}</th><th className="r">{t("lb_open")}</th><th className="r">{t("lb_openval")}</th><th className="r">{t("lb_wr")}</th><th>{t("lb_perf")}</th></tr></thead>
              <tbody>
                {board.map(b => (
                  <tr key={b.owner.id} className={owner === b.owner.id ? "hl" : ""}>
                    <td><div className="lbName"><Avatar owner={b.owner} size={28} />{b.owner.name}</div></td>
                    <td className="r">{b.count}</td>
                    <td className="r"><b>{fmtVND(b.value)} ₫</b></td>
                    <td className="r">{b.wr}%</td>
                    <td><div className="lbBar"><span style={{ width: b.wr + "%", background: `oklch(0.62 0.13 ${b.owner.color})` }}></span></div></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        </div>
      </div>
    </div>
  );
}

function Empty() {
  return <div className="repEmpty"><svg viewBox="0 0 24 24" width="30" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 3v18h18M7 14l4-4 3 3 5-6"/></svg><span>{window.t("no_records")}</span></div>;
}

Object.assign(window, { Reports });
