// ============ TaskQuest — Summary section & leaderboard ============
const { ROLES: R3, PROJECTS: P3, CONSULTANTS: C3 } = window.TQ;

function StatCard({ icon, iconColor, label, children, foot }) {
  return (
    <div className="stat-card">
      <div className="stat-top">
        <span className="stat-ic" style={{ background: iconColor + "22", color: iconColor }}>
          {React.createElement(icon, { size: 15 })}
        </span>
        {label}
      </div>
      {children}
      {foot && <div className="stat-foot">{foot}</div>}
    </div>
  );
}

function MiniLeaderboard({ board, meKey, label, scopeName, metric, headerRight, headline }) {
  // metric: undefined/"both" → "X pts · Y%"; "points" → ranked by points; "perf" → ranked by performance
  const rows = metric === "perf"
    ? board.slice().sort((a, b) => (b.perf - a.perf) || (b.total - a.total)).map((s, i) => ({ ...s, _rank: i + 1 }))
    : board.map(s => ({ ...s, _rank: s.rank }));
  return (
    <div className="stat-card lb-card">
      <div className="stat-top">
        <span className="stat-ic" style={{ background: "#e0902b22", color: "#e0902b" }}><Ic.Trophy size={15} /></span>
        {label}
        {headerRight
          ? <span style={{ marginLeft: "auto", display: "inline-flex" }}>{headerRight}</span>
          : <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--faint)", fontWeight: 600, whiteSpace: "nowrap" }}>{scopeName}</span>}
      </div>
      {headline}
      <div style={{ marginTop: 4 }}>
        {rows.map(s => (
          <div key={s.key} className={`lb-row ${s.key === meKey ? "me" : ""}`}>
            <span className={`lb-rank ${s._rank === 1 ? "top" : ""}`}>
              {s._rank === 1 ? <Ic.Crown size={13} style={{ display: "inline" }} /> : s._rank}
            </span>
            <Avatar who={s.key} size="sm" />
            <span className="lb-name">{R3[s.key].name}{s.key === meKey ? " (You)" : ""}</span>
            <span className="lb-pts tabnum">
              {metric === "perf"
                ? <>{s.perf}<span> %</span></>
                : metric === "points"
                ? <>{(s.avg || 0).toFixed(1)}<span> avg</span></>
                : <>{(s.avg || 0).toFixed(1)}<span> avg · {s.perf}%</span></>}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SummarySection({ role, project, tasks, bonus }) {
  const { leaderboard, computeScores } = window.TQ;
  const r = R3[role];
  const scope = project;
  const scopeName = scope === "all" ? "All projects" : (P3[scope] ? P3[scope].name : "");
  const board = leaderboard(tasks, bonus, scope);
  const scopedTasks = scope === "all" ? tasks : tasks.filter(t => t.project === scope);

  const pendingApprovals = scopedTasks.filter(t =>
    (t.request && t.request.status === "pending") || (t.completion && t.completion.status === "pending")
  ).length;

  if (r.type === "consultant") {
    // A consultant's board shows ALL their tasks regardless of the project
    // switcher, so their stats + rank must span every project too (otherwise
    // points earned on another project's deliverable silently read as zero).
    const cBoard = leaderboard(tasks, bonus, "all");
    const me = cBoard.find(s => s.key === role) || { total: 0, avg: 0, perf: 0, rank: "—", ontime: 0, completed: 0, assigned: 0, bonus: 0 };
    return (
      <div className="summary-grid">
        <StatCard icon={Ic.Coins} iconColor="#5E6AD2" label="Avg Points / Task"
          foot={me.completed ? <><b>{me.total}</b> pts over {me.completed} completed{me.bonus > 0 ? <> · <span className="trend-up">+{me.bonus}</span> bonus</> : null}</> : <>No completed tasks yet</>}>
          <div className="stat-value tabnum">{(me.avg || 0).toFixed(1)}<span className="unit">pts</span></div>
        </StatCard>
        <StatCard icon={Ic.Target} iconColor="#4cb782" label="Performance Score"
          foot={`${me.completed} of ${me.assigned} tasks completed`}>
          <div className="stat-value tabnum">{me.perf}<span className="unit">%</span></div>
          <div className="progress-track"><div className="progress-fill" style={{ width: me.perf + "%" }} /></div>
        </StatCard>
        <StatCard icon={Ic.Medal} iconColor="#e0902b" label="Your Rank"
          foot={`Among ${cBoard.length} consultants`}>
          <div className="rank-badge tabnum"><span className="hash">#</span>{me.rank}</div>
        </StatCard>
        <MiniLeaderboard board={cBoard} meKey={role} label="Leaderboard" scopeName="All projects" />
      </div>
    );
  }

  // Manager aggregate stats
  const totalPts = board.reduce((a, s) => a + s.total, 0);
  const completedAll = board.reduce((a, s) => a + s.completed, 0);
  const assignedAll = board.reduce((a, s) => a + s.assigned, 0);
  const teamAvg = completedAll ? totalPts / completedAll : 0;
  const teamPerf = assignedAll ? Math.round((completedAll / assignedAll) * 100) : 0;
  const onTrack = scopedTasks.filter(t => t.status === "happy").length;

  return (
    <div className="summary-grid">
      <StatCard icon={Ic.Coins} iconColor="#5E6AD2" label="Avg Points / Task"
        foot={completedAll ? <><b>{totalPts}</b> pts over {completedAll} completed</> : `${onTrack} tasks on the happy path`}>
        <div className="stat-value tabnum">{(teamAvg || 0).toFixed(1)}<span className="unit">pts</span></div>
      </StatCard>
      <StatCard icon={Ic.Target} iconColor="#4cb782" label="Team Performance"
        foot={`${completedAll} of ${assignedAll} tasks completed`}>
        <div className="stat-value tabnum">{teamPerf}<span className="unit">%</span></div>
        <div className="progress-track"><div className="progress-fill" style={{ width: teamPerf + "%" }} /></div>
      </StatCard>
      <StatCard icon={Ic.Inbox} iconColor={pendingApprovals ? "#f2c94c" : "#878b94"} label="Pending Approvals"
        foot={pendingApprovals ? "Awaiting your review" : "Nothing to review"}>
        <div className="stat-value tabnum">{pendingApprovals}</div>
      </StatCard>
      <MiniLeaderboard board={board} meKey={null} label={scope === "all" ? "Global Leaderboard" : "Project Leaderboard"} scopeName={scopeName} />
    </div>
  );
}

window.SummarySection = SummarySection;
window.StatCard = StatCard;
window.MiniLeaderboard = MiniLeaderboard;
