// Team screen — Module → Sub-Team → Individual hierarchy with raw activity drill-down.
// Includes Custom column. Uses multi-select via ScopeFilters.

function TeamScreen({ scope, setScope, period, setPeriod, year, setYear }) {
  const F = window.VAULT_FIRM;
  const { fmtNum } = window.VaultUtils;
  const { PeriodSelector, periodWeeks, applyScope, aggregate } = window.VaultPeriod;

  const weeks = periodWeeks(period);
  const empty = weeks.length === 0;
  const people = applyScope(F.PEOPLE, scope);

  // Per-person totals
  const rows = useMemo(() => {
    if (empty) return [];
    const wset = new Set(weeks);
    return people.map(p => {
      const r = F.ACTIVITY.filter(a => a.personId === p.id && wset.has(a.week));
      const sum = (k) => r.reduce((acc, x) => acc + x[k], 0);
      return {
        person: p,
        lists: sum("lists"), mailings: sum("mailings"), calls: sum("calls"),
        leads: sum("leads"), confCalls: sum("confCalls"), visits: sum("visits"),
        offers: sum("offers"), signedLOIs: sum("signedLOIs"), closedDeals: sum("closedDeals"),
        custom: sum("custom"),
      };
    }).sort((a, b) => b.calls - a.calls);
  }, [people, weeks, empty]);

  // Sub-team rollup
  const subteamRollup = useMemo(() => {
    if (empty) return [];
    const map = {};
    rows.forEach(r => {
      const sid = r.person.subteam;
      if (!map[sid]) map[sid] = { subteam: F.SUBTEAMS.find(s => s.id === sid), people: 0, lists:0, mailings:0, calls:0, leads:0, confCalls:0, visits:0, offers:0, signedLOIs:0, closedDeals:0, custom:0 };
      map[sid].people += 1;
      ["lists","mailings","calls","leads","confCalls","visits","offers","signedLOIs","closedDeals","custom"].forEach(k => map[sid][k] += r[k]);
    });
    return Object.values(map).sort((a, b) => b.calls - a.calls);
  }, [rows, empty]);

  return (
    <div style={{ padding: "20px 28px 60px" }}>
      <div className="row" style={{ justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 12 }}>
        <window.ScopeFilters scope={scope} setScope={setScope}/>
        <window.VaultPeriod.PeriodSelector value={period} onChange={setPeriod} year={year} onYearChange={setYear}/>
      </div>
      <div className="muted small" style={{ marginBottom: 14 }}>
        Multi-select individuals: <kbd className="mono" style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 3, padding: "0 4px" }}>⌘</kbd>/<kbd className="mono" style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 3, padding: "0 4px" }}>Ctrl</kbd>-click in the dropdown.
      </div>

      {empty
        ? <div className="card card-pad" style={{ textAlign: "center", padding: "60px 20px" }}>
            <div className="display" style={{ fontSize: 24, color: "var(--muted)" }}>No data yet for this period</div>
          </div>
        : <>
          {/* Sub-team rollup */}
          <h3 className="display" style={{ fontSize: 18, fontWeight: 400, margin: "0 0 8px" }}>Module rollup</h3>
          <div className="card" style={{ overflow: "hidden", marginBottom: 24 }}>
            <table className="dt">
              <thead><tr>
                <th>Module</th>
                <th className="r">People</th>
                <th className="r">Lists</th>
                <th className="r">Mailings</th>
                <th className="r">Calls</th>
                <th className="r">Leads</th>
                <th className="r">Conf Calls</th>
                <th className="r">Visits</th>
                <th className="r">Offers</th>
                <th className="r">LOIs</th>
                <th className="r">Closed</th>
                <th className="r">Custom</th>
              </tr></thead>
              <tbody>
                {subteamRollup.map(r => (
                  <tr key={r.subteam.id} onClick={() => setScope({ ...scope, subteam: r.subteam.id, individuals: [] })}>
                    <td>
                      <span className="row" style={{ gap: 8 }}>
                        <span style={{ fontWeight: 600 }}>{r.subteam.label}</span>
                        {r.subteam.synth && <window.SynthTag/>}
                      </span>
                    </td>
                    <td className="r mono">{r.people}</td>
                    <td className="r mono">{fmtNum(r.lists)}</td>
                    <td className="r mono">{fmtNum(r.mailings)}</td>
                    <td className="r mono"><strong>{fmtNum(r.calls)}</strong></td>
                    <td className="r mono">{fmtNum(r.leads)}</td>
                    <td className="r mono">{fmtNum(r.confCalls)}</td>
                    <td className="r mono">{fmtNum(r.visits)}</td>
                    <td className="r mono">{fmtNum(r.offers)}</td>
                    <td className="r mono">{fmtNum(r.signedLOIs)}</td>
                    <td className="r mono" style={{ color: "var(--accent)", fontWeight: 600 }}>{fmtNum(r.closedDeals)}</td>
                    <td className="r mono">{fmtNum(r.custom)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Individual breakdown */}
          <h3 className="display" style={{ fontSize: 18, fontWeight: 400, margin: "0 0 8px" }}>Individuals</h3>
          <div className="card" style={{ overflow: "hidden" }}>
            <table className="dt">
              <thead><tr>
                <th>Person</th>
                <th>Module</th>
                <th className="r">Lists</th>
                <th className="r">Mailings</th>
                <th className="r">Calls</th>
                <th className="r">Leads</th>
                <th className="r">Conf Calls</th>
                <th className="r">Visits</th>
                <th className="r">Offers</th>
                <th className="r">LOIs</th>
                <th className="r">Closed</th>
                <th className="r">Custom</th>
              </tr></thead>
              <tbody>
                {rows.map(r => (
                  <tr key={r.person.id}>
                    <td>
                      <span className="row" style={{ gap: 8 }}>
                        <window.Avatar id={r.person.id}/>
                        <div>
                          <div style={{ fontWeight: 600 }}>{r.person.name}{r.person.synth && <window.SynthTag/>}</div>
                          <div className="muted small">{r.person.role}</div>
                        </div>
                      </span>
                    </td>
                    <td className="muted small">{F.SUBTEAMS.find(s => s.id === r.person.subteam)?.label.replace(/^.*— /, "")}</td>
                    <td className="r mono">{fmtNum(r.lists)}</td>
                    <td className="r mono">{fmtNum(r.mailings)}</td>
                    <td className="r mono"><strong>{fmtNum(r.calls)}</strong></td>
                    <td className="r mono">{fmtNum(r.leads)}</td>
                    <td className="r mono">{fmtNum(r.confCalls)}</td>
                    <td className="r mono">{fmtNum(r.visits)}</td>
                    <td className="r mono">{fmtNum(r.offers)}</td>
                    <td className="r mono">{fmtNum(r.signedLOIs)}</td>
                    <td className="r mono" style={{ color: "var(--accent)", fontWeight: 600 }}>{fmtNum(r.closedDeals)}</td>
                    <td className="r mono">{fmtNum(r.custom)}</td>
                  </tr>
                ))}
                {rows.length === 0 && <tr><td colSpan={12} className="muted" style={{ textAlign: "center", padding: 24 }}>No individuals match this scope.</td></tr>}
              </tbody>
            </table>
          </div>
        </>
      }
    </div>
  );
}
window.TeamScreen = TeamScreen;

// ----------------- Leaderboards -----------------

function LeaderboardsScreen({ scope, setScope, period, setPeriod, year, setYear }) {
  const F = window.VAULT_FIRM;
  const { fmtNum } = window.VaultUtils;
  const { periodWeeks, applyScope } = window.VaultPeriod;

  const [tab, setTab] = useState("standings"); // standings | badges

  const weeks = periodWeeks(period);
  const people = applyScope(F.PEOPLE, scope);

  const rows = useMemo(() => {
    if (!weeks.length) return [];
    const wset = new Set(weeks);
    return people.map(p => {
      const r = F.ACTIVITY.filter(a => a.personId === p.id && wset.has(a.week));
      const sum = (k) => r.reduce((acc, x) => acc + x[k], 0);
      // Hot streak: count of weeks in the period where calls > 30
      const hot = r.filter(x => x.calls > 30).length;
      return {
        person: p,
        calls: sum("calls"), leads: sum("leads"),
        hotStreak: hot,
        contribution: sum("closedDeals") * 25 + sum("signedLOIs") * 10 + sum("offers") * 4 + sum("visits") * 2,
      };
    });
  }, [people, weeks]);

  const top10 = (key) => [...rows].sort((a, b) => b[key] - a[key]).slice(0, 10);

  // Tab nav (chrome stays visible across tabs; filters only apply to Standings)
  const TabBtn = ({ id, label }) => (
    <button
      onClick={() => setTab(id)}
      style={{
        background: "transparent",
        border: "none",
        padding: "10px 2px",
        marginRight: 22,
        fontFamily: "var(--f-display)",
        fontSize: 16,
        fontWeight: 400,
        letterSpacing: "-0.01em",
        cursor: "pointer",
        color: tab === id ? "var(--ink)" : "var(--muted)",
        borderBottom: tab === id ? "2px solid var(--accent)" : "2px solid transparent",
        transition: "color 120ms, border-color 120ms",
      }}
    >{label}</button>
  );

  return (
    <div style={{ padding: "20px 28px 60px" }}>
      {/* Tab bar */}
      <div className="row" style={{ borderBottom: "1px solid var(--line-2)", marginBottom: 18 }}>
        <TabBtn id="standings" label="Standings"/>
        <TabBtn id="badges" label="Badges"/>
        <span className="stretch"/>
        {tab === "standings" && (
          <span className="muted small mono" style={{ letterSpacing: "0.04em" }}>{weeks.length} weeks in scope</span>
        )}
      </div>

      {tab === "standings" && (
        <>
          <div className="row" style={{ justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 18 }}>
            <window.ScopeFilters scope={scope} setScope={setScope}/>
            <window.VaultPeriod.PeriodSelector value={period} onChange={setPeriod} year={year} onYearChange={setYear}/>
          </div>

          {weeks.length === 0
            ? <div className="card card-pad" style={{ textAlign: "center", padding: 60 }}>
                <div className="display" style={{ fontSize: 24, color: "var(--muted)" }}>No data yet</div>
              </div>
            : <>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
                <LeaderTable title="Top 10 — Calls"               metric="calls"        rows={top10("calls")}        formatter={fmtNum}/>
                <LeaderTable title="Top 10 — Leads"               metric="leads"        rows={top10("leads")}        formatter={fmtNum}/>
                <LeaderTable title="Top 10 — Hot Streaks"         metric="hotStreak"    rows={top10("hotStreak")}    formatter={(v) => `${v} wk${v===1?"":"s"}`}/>
                <LeaderTable title="Top 10 — Closed Deal Contrib" metric="contribution" rows={top10("contribution")} formatter={(v) => `${fmtNum(v)} pts`}/>
              </div>

              <h3 className="display" style={{ fontSize: 18, fontWeight: 400, margin: "26px 0 8px" }}>Achievements this period</h3>
              <div className="card card-pad">
                <BadgeGrid people={people} weeks={weeks}/>
              </div>
            </>
          }
        </>
      )}

      {tab === "badges" && <window.BadgesView userId={window.__VAULT_CURRENT_USER_ID || "scott_b"}/>}
    </div>
  );
}

function LeaderTable({ title, metric, rows, formatter }) {
  const F = window.VAULT_FIRM;
  return (
    <div className="card" style={{ overflow: "hidden" }}>
      <div className="row" style={{ padding: "14px 16px", borderBottom: "1px solid var(--line-2)" }}>
        <h3 className="display" style={{ margin: 0, fontSize: 16, fontWeight: 400 }}>{title}</h3>
      </div>
      <table className="dt" style={{ fontSize: 12.5 }}>
        <tbody>
          {rows.map((r, i) => (
            <tr key={r.person.id}>
              <td style={{ width: 36, color: "var(--muted)", fontFamily: "var(--f-mono)" }}>{String(i+1).padStart(2, "0")}</td>
              <td>
                <span className="row" style={{ gap: 8 }}>
                  <window.Avatar id={r.person.id}/>
                  <span>
                    <span style={{ fontWeight: 600 }}>{r.person.name}</span>
                    {r.person.synth && <window.SynthTag/>}
                  </span>
                </span>
              </td>
              <td className="muted small">{F.SUBTEAMS.find(s => s.id === r.person.subteam)?.label.replace(/^.*— /, "")}</td>
              <td className="r mono" style={{ fontWeight: 600, color: i === 0 ? "var(--accent)" : "var(--ink)" }}>
                {formatter(r[metric])}
              </td>
            </tr>
          ))}
          {rows.length === 0 && <tr><td colSpan={4} className="muted" style={{ textAlign: "center", padding: 18 }}>No one matches this scope.</td></tr>}
        </tbody>
      </table>
    </div>
  );
}

function BadgeGrid({ people, weeks }) {
  const F = window.VAULT_FIRM;
  const wset = new Set(weeks);
  // Award logic: every person earns 0–6 badges based on activity in scope.
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 12 }}>
      {people.slice(0, 18).map(p => {
        const r = F.ACTIVITY.filter(a => a.personId === p.id && wset.has(a.week));
        const calls = r.reduce((s,x) => s+x.calls, 0);
        const leads = r.reduce((s,x) => s+x.leads, 0);
        const visits = r.reduce((s,x) => s+x.visits, 0);
        const lois = r.reduce((s,x) => s+x.signedLOIs, 0);
        const closed = r.reduce((s,x) => s+x.closedDeals, 0);
        const hot = r.filter(x => x.calls > 30).length;
        const earned = [];
        if (lois > 0) earned.push("first_loi");
        if (visits >= 5) earned.push("five_visits");
        if (hot >= 4) earned.push("hot_streak");
        if (Math.max(...r.map(x => x.calls), 0) >= 100) earned.push("century");
        if (leads >= 10) earned.push("lead_machine");
        if (closed >= 1) earned.push("closed_deal");
        return (
          <div key={p.id} style={{
            border: "1px solid var(--line)", borderRadius: 10,
            padding: 12, background: "var(--canvas)",
          }}>
            <div className="row" style={{ gap: 8 }}>
              <window.Avatar id={p.id}/>
              <div className="stretch" style={{ minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                <div className="muted small">{p.role}</div>
              </div>
            </div>
            <div className="row" style={{ marginTop: 10, gap: 6, flexWrap: "wrap" }}>
              {earned.map(id => {
                const a = F.ACHIEVEMENTS.find(x => x.id === id);
                if (!a) return null;
                const I = window.Icon[a.icon] || (() => null);
                return (
                  <span key={id} title={a.label} style={{
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    width: 26, height: 26, borderRadius: 6,
                    background: "var(--accent-soft)", color: "var(--accent)",
                    border: "1px solid color-mix(in oklab, var(--accent) 25%, transparent)",
                  }}><I/></span>
                );
              })}
              {earned.length === 0 && <span className="muted small">No badges this period</span>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

window.LeaderboardsScreen = LeaderboardsScreen;
