// Sales rep leaderboard
function Reps({ deals, allDeals, reps, stages, showrooms, showroomScope, targets, openDeal }) {
  const [period, setPeriod] = React.useState('all');
  const [customFrom, setCustomFrom] = React.useState('');
  const [customTo, setCustomTo] = React.useState('');
  const today = new Date('2026-05-27');

  // Compute each rep's target from the real targets set in Admin → Targets,
  // scoped to the selected period (all FY / this quarter / this month)
  const FYM = window.FY_MONTHS || [];
  const curMonthKey = '2026-05';
  const curQ = (FYM.find(m => m.key === curMonthKey) || {}).q || 4;
  const targetKeys = period === 'month'
    ? [curMonthKey]
    : period === 'quarter'
      ? FYM.filter(m => m.q === curQ).map(m => m.key)
      : period === 'custom'
        ? FYM.filter(m => (!customFrom || m.key >= customFrom.slice(0, 7)) && (!customTo || m.key <= customTo.slice(0, 7))).map(m => m.key)
        : FYM.map(m => m.key);
  function repTarget(repId) {
    if (!targets || !targets[repId]) return 0;
    return targetKeys.reduce((s, k) => s + (targets[repId][k] || 0), 0);
  }

  // Apply period filter to deals
  const periodDeals = React.useMemo(() => {
    if (period === 'all') return deals;
    if (period === 'custom') {
      return deals.filter(d => {
        const date = d.lastActivity || d.created;
        if (!date) return false;
        if (customFrom && date < customFrom) return false;
        if (customTo && date > customTo) return false;
        return true;
      });
    }
    return deals.filter(d => {
      const date = d.lastActivity || d.created;
      if (!date) return false;
      const dt = new Date(date);
      if (period === 'month') {
        return dt.getFullYear() === today.getFullYear() && dt.getMonth() === today.getMonth();
      }
      if (period === 'quarter') {
        const q = Math.floor(today.getMonth() / 3);
        return dt.getFullYear() === today.getFullYear() && Math.floor(dt.getMonth() / 3) === q;
      }
      return true;
    });
  }, [deals, period, customFrom, customTo]);

  // When showroom is filtered, only show reps that work there
  const scopedReps = showroomScope === 'all' ? reps : reps.filter(r => r.works.includes(showroomScope));
  const agg = scopedReps.map(r => {
    const repDeals = periodDeals.filter(d => d.rep === r.id);
    const won = repDeals.filter(d => d.stage === 'sold');
    const lost = repDeals.filter(d => d.stage === 'lost');
    const active = repDeals.filter(d => d.stage !== 'sold' && d.stage !== 'lost');
    const wonVal = won.reduce((s, d) => s + d.value, 0);
    const activeVal = active.reduce((s, d) => s + d.value, 0);
    const closed = won.length + lost.length;
    const winRate = closed ? won.length / closed : 0;
    const avgDeal = won.length ? wonVal / won.length : 0;
    const stuck = active.filter(d => d.lastActivityDaysAgo > 21).length;
    const homeShow = showrooms.find(s => s.id === r.home);
    const worksAt = r.works.map(id => showrooms.find(s => s.id === id));
    const target = repTarget(r.id);
    return { ...r, wonVal, activeVal, wonCount: won.length, lostCount: lost.length, activeCount: active.length, winRate, avgDeal, stuck, target, quotaPct: target > 0 ? wonVal / target : 0, homeShow, worksAt };
  }).sort((a, b) => b.wonVal - a.wonVal);

  const teamTarget = agg.reduce((s, r) => s + r.target, 0);
  const teamWon = agg.reduce((s, r) => s + r.wonVal, 0);

  return (
    <div>
      <div className="grid-kpis" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <div className="kpi">
          <div className="kpi-label">Team quota progress</div>
          <div className="kpi-value num">{teamTarget > 0 ? fmt.pct(teamWon / teamTarget, 0) : '—'}</div>
          <div className="kpi-meta">
            <span className="kpi-foot">{teamTarget > 0 ? `${fmt.money(teamWon, true)} of ${fmt.money(teamTarget, true)}` : 'No targets set · Admin → Targets'}</span>
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Avg deal size (team)</div>
          <div className="kpi-value num">{fmt.money(agg.reduce((s, r) => s + r.wonVal, 0) / Math.max(agg.reduce((s, r) => s + r.wonCount, 0), 1), true)}</div>
          <div className="kpi-meta">
            <span className="kpi-foot">{agg.reduce((s, r) => s + r.wonCount, 0)} total wins</span>
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Top performer</div>
          <div className="kpi-value" style={{ fontSize: 22 }}>{agg[0].name}</div>
          <div className="kpi-meta">
            <span className="kpi-foot">{fmt.money(agg[0].wonVal, true)} closed · {agg[0].wonCount} wins</span>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-hd">
          <div>
            <div className="card-title">Rep leaderboard</div>
            <div className="card-sub">Sorted by closed-won value · current period</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
            <div className="seg">
              <button className={period === 'all' ? 'on' : ''} onClick={() => setPeriod('all')}>All time</button>
              <button className={period === 'quarter' ? 'on' : ''} onClick={() => setPeriod('quarter')}>This Q</button>
              <button className={period === 'month' ? 'on' : ''} onClick={() => setPeriod('month')}>This month</button>
              <button className={period === 'custom' ? 'on' : ''} onClick={() => setPeriod('custom')}>Custom</button>
            </div>
            {period === 'custom' && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--ink-3)' }}>
                <input type="date" value={customFrom} onChange={(e) => setCustomFrom(e.target.value)} style={{ padding: '4px 6px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 11 }} title="From"/>
                <span>→</span>
                <input type="date" value={customTo} onChange={(e) => setCustomTo(e.target.value)} style={{ padding: '4px 6px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 11 }} title="To"/>
              </div>
            )}
          </div>
        </div>

        <div className="rep-row" style={{ background: 'var(--surface-2)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)', fontWeight: 500 }}>
          <div>#</div>
          <div>Sales rep</div>
          <div style={{ textAlign: 'right' }}>Won · Lost</div>
          <div style={{ textAlign: 'right' }}>Closed-won</div>
          <div style={{ textAlign: 'right' }}>Win rate</div>
          <div style={{ textAlign: 'right' }}>Avg deal</div>
          <div>Quota</div>
        </div>

        {agg.map((r, i) => (
          <div className="rep-row" key={r.id}>
            <div className="rep-rank num">{String(i + 1).padStart(2, '0')}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Avatar name={r.name}/>
              <div>
                <div style={{ fontWeight: 500 }}>{r.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 5, marginTop: 1 }}>
                  <span className={`ss-tab-dot ${r.home}`} style={{ width: 6, height: 6 }}></span>
                  {r.homeShow.name}
                  {r.worksAt.length > 1 && (
                    <span style={{ color: 'var(--ink-4)' }}>+ {r.worksAt.length - 1} other</span>
                  )}
                  <span style={{ color: 'var(--ink-4)' }}>·</span>
                  <span>{r.activeCount} active</span>
                </div>
              </div>
            </div>
            <div style={{ textAlign: 'right' }} className="num" title="Won / Lost">
              <span style={{ color: 'var(--won)', fontWeight: 500 }}>{r.wonCount}W</span>
              <span style={{ color: 'var(--ink-3)' }}> · {r.lostCount}L</span>
            </div>
            <div style={{ textAlign: 'right', fontWeight: 500 }} className="num">{fmt.money(r.wonVal, true)}</div>
            <div style={{ textAlign: 'right' }} className="num">{fmt.pct(r.winRate, 0)}</div>
            <div style={{ textAlign: 'right' }} className="num">{fmt.money(r.avgDeal, true)}</div>
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
                <span style={{ color: 'var(--ink-3)' }}>{r.target > 0 ? `${fmt.pct(r.quotaPct, 0)} of ${fmt.money(r.target, true)}` : 'No target set'}</span>
                {r.stuck > 0 && <span style={{ color: 'var(--lost)', fontSize: 10.5 }}>{r.stuck} stuck</span>}
              </div>
              <div className="rep-prog">
                <div className={`fill ${r.quotaPct >= 1 ? 'over' : ''}`} style={{ width: Math.min(r.quotaPct, 1.2) * 100 + '%' }}></div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.Reps = Reps;
