// Period selector — quarters + year + trailing windows.
// Q3/Q4 are labeled "no data yet" (empty).

function PeriodSelector({ value, year, onChange, onYearChange }) {
  const F = window.VAULT_FIRM;
  const cur = F.PERIODS.find(p => p.id === value) || F.PERIODS[0];
  const trailing = F.PERIODS.filter(p => !p.quarter && p.id !== "ytd");
  const quarters = F.PERIODS.filter(p => p.quarter);

  return (
    <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
      <div className="seg" role="tablist" aria-label="Trailing window">
        {trailing.map(p => (
          <button key={p.id} className={value === p.id ? "on" : ""} onClick={() => onChange(p.id)}>
            {p.label.replace("Trailing ", "")}
          </button>
        ))}
        <button className={value === "ytd" ? "on" : ""} onClick={() => onChange("ytd")}>YTD</button>
      </div>

      <div className="seg" role="tablist" aria-label="Quarter">
        {quarters.map(p => (
          <button key={p.id}
            className={value === p.id ? "on" : ""}
            onClick={() => !p.empty && onChange(p.id)}
            disabled={p.empty}
            style={p.empty ? { color: "var(--muted-2)", cursor: "not-allowed" } : undefined}
            title={p.empty ? "No data yet" : ""}>
            {p.label.split(" ")[0]}
            {p.empty && <span className="micro" style={{ marginLeft: 5, fontSize: 9, color: "var(--muted-2)" }}>—</span>}
          </button>
        ))}
      </div>

      <select value={year} onChange={e => onYearChange(parseInt(e.target.value, 10))}
        style={{
          border: "1px solid var(--line)", background: "var(--surface)",
          borderRadius: 8, padding: "5px 9px", fontSize: 12.5, color: "var(--ink)",
        }}>
        {F.YEARS.map(y => <option key={y} value={y}>{y}</option>)}
      </select>
    </div>
  );
}

// Compute weeks selected by current period.
function periodWeeks(value) {
  const F = window.VAULT_FIRM;
  const p = F.PERIODS.find(x => x.id === value);
  if (!p) return F.WEEKS;
  if (p.empty) return [];
  if (p.weeksBack === 0) return [];
  return F.WEEKS.slice(-p.weeksBack);
}

// Filter scope: { module, subteam, subSubteam, individuals[] }
function applyScope(people, scope) {
  const F = window.VAULT_FIRM;
  let out = people;
  if (scope.module) {
    const subs = F.SUBTEAMS.filter(s => s.moduleId === scope.module).map(s => s.id);
    out = out.filter(p => subs.includes(p.subteam));
  }
  if (scope.subteam) {
    const workers = new Set(
      (F.ACTIVITY || [])
        .filter(a => a.moduleTeam === scope.subteam && ((a.mailings || 0) + (a.calls || 0) + (a.leads || 0) + (a.confCalls || 0) + (a.visits || 0) + (a.offers || 0) + (a.signedLOIs || 0)) > 0)
        .map(a => a.personId)
    );
    out = out.filter(p => p.subteam === scope.subteam || workers.has(p.id));
  }
  if (scope.subSubteam) {
    const sst = (F.SUBSUBTEAMS || []).find(s => s.id === scope.subSubteam);
    if (sst) {
      const set = new Set(sst.memberIds);
      out = out.filter(p => set.has(p.id));
    }
  }
  if (scope.individuals && scope.individuals.length) {
    out = out.filter(p => scope.individuals.includes(p.id));
  }
  return out;
}

// Aggregate metrics across people/weeks.
// Activity rows carry their own `moduleTeam` (subteam id derived from the row's module-lead
// tag in raw data). That overrides person-home-subteam attribution — e.g. epark's mailings
// tagged module "bscott" roll up to the Scott subteam regardless of whose home subteam she's
// listed under, and her "bkaneko" mailings roll up to the Kaneko subteam.
function aggregate(scope, weeks) {
  const F = window.VAULT_FIRM;
  const people = applyScope(F.PEOPLE, scope);
  const wset = new Set(weeks);

  // For totals we filter activity rows directly so module attribution is row-level.
  let rows = F.ACTIVITY.filter(a => wset.has(a.week));
  if (scope.module) {
    rows = rows.filter(a => a.module === scope.module);
  }
  if (scope.subteam) {
    rows = rows.filter(a => a.moduleTeam === scope.subteam);
  }
  if (scope.subSubteam) {
    const sst = (F.SUBSUBTEAMS || []).find(s => s.id === scope.subSubteam);
    if (sst) {
      const set = new Set(sst.memberIds);
      rows = rows.filter(a => set.has(a.personId));
    }
  }
  if (scope.individuals && scope.individuals.length) {
    const sel = new Set(scope.individuals);
    rows = rows.filter(a => sel.has(a.personId));
  }

  const totals = { lists: 0, mailings: 0, calls: 0, leads: 0, confCalls: 0, visits: 0, offers: 0, signedLOIs: 0, closedDeals: 0, custom: 0 };
  rows.forEach(r => { for (const k of Object.keys(totals)) totals[k] += (r[k] || 0); });
  return { rows, people, totals };
}

window.VaultPeriod = { PeriodSelector, periodWeeks, applyScope, aggregate };
