// Staff: everyone with an in-game role, how much they play and what they do in game. Kicks are
// logged by the game (a kick is a Photon RPC), staff reports and item grants by the server.

const LAR_STAFF_ACTIONS = { staff_kick: "Kicked", staff_report: "Reported", staff_grant: "Granted" };
const LAR_RANK_ORDER = { admin: 3, developer: 2, moderator: 1 };

function larStaffDetail(a) {
  if (a.action === "staff_grant") return a.detail?.itemId || "";
  return a.detail?.room ? `room ${a.detail.room}` : "";
}

function LarStaffPage() {
  const { data, error, loading, reload } = useLarLoad(() => larApi("staff"), []);
  const [busy, setBusy] = React.useState(false);
  const [notice, setNotice] = React.useState(null);

  React.useEffect(() => {
    const t = setInterval(() => reload(), 60000);
    return () => clearInterval(t);
  }, [reload]);

  const syncPerks = async () => {
    if (!confirm("Give every current staff member the perks they are missing (name tag, free menu, one-time gold)?")) return;
    setBusy(true);
    try {
      const res = await larApi("staff/sync-perks", { method: "POST" });
      setNotice(res.changed.length ? `Updated ${res.changed.length} of ${res.staff} staff.` : `All ${res.staff} staff already had their perks.`);
      reload();
    } catch (e) { setNotice(e.message); }
    setBusy(false);
  };

  const staff = [...(data?.staff || [])].sort((a, b) =>
    (LAR_RANK_ORDER[b.rank] || 0) - (LAR_RANK_ORDER[a.rank] || 0) || b.playtime30d - a.playtime30d);
  const online = staff.filter(s => s.onlineSince).length;
  const sum = (key) => staff.reduce((n, s) => n + s[key], 0);
  const now = Date.now() / 1000;
  const perks = data?.perks;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Staff</h1>
          <p className="page-subtitle">
            Everyone with an in-game role and what they do in game. Numbers cover the last 30 days.
            {perks && <> Staff get their role's name tag, the {perks.menu === "ULTRAMENU" ? "Ultra menu" : perks.menu} and {fmt.num(perks.gold)} gold once.</>}
          </p>
        </div>
        <div className="page-head-actions">
          <button className="btn btn-sm" disabled={busy || !data} onClick={syncPerks}>Give missing perks</button>
        </div>
      </div>

      {notice && (
        <div className="lar-note lar-note-ok lar-notice">
          <Icon name="check" size={14}/><span style={{flex:1}}>{notice}</span>
          <button className="icon-btn" onClick={() => setNotice(null)}><Icon name="close" size={12}/></button>
        </div>
      )}

      {error && <div className="card"><div className="empty"><h3>Failed to load</h3><p>{error}</p></div></div>}
      {!error && !data && loading && <div className="card"><div className="empty"><h3>Loading…</h3></div></div>}

      {data && (
        <>
          <div className="card">
            <div className="lar-figures">
              <LarFigure label="Staff" value={fmt.num(staff.length)}/>
              <LarFigure label="Online now" value={fmt.num(online)}/>
              <LarFigure label="Kicks" value={fmt.num(sum("kicks30d"))}/>
              <LarFigure label="Staff reports" value={fmt.num(sum("reports30d"))}/>
              <LarFigure label="Items granted" value={fmt.num(sum("grants30d"))}/>
            </div>
          </div>

          <div className="card card-flush section-gap">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Staff member</th><th>Rank</th><th>Status</th><th>Playtime</th><th>Sessions</th><th>Avg session</th>
                  <th style={{textAlign:"right"}}>Kicks</th><th style={{textAlign:"right"}}>Reports</th><th style={{textAlign:"right"}}>Grants</th>
                </tr>
              </thead>
              <tbody>
                {staff.map(s => (
                  <tr key={s.id} onClick={() => window.larOpenPlayer(s.id)}>
                    <td><div className="p-name">{s.name}</div><div className="tiny muted mono">{s.id}</div></td>
                    <td style={{textTransform:"capitalize", fontWeight:600}}>{s.rank}</td>
                    <td>
                      {s.onlineSince
                        ? <span className="lar-presence" data-online="true"><span className="lar-presence-dot"/>Online · {larDuration(now - s.onlineSince)}</span>
                        : <span className="muted">{s.lastLoginAt ? `Last login ${timeSince(larIso(s.lastLoginAt))}` : "Never logged in"}</span>}
                    </td>
                    <td className="mono">{larDuration(s.playtime30d)}<div className="tiny muted">{larDuration(s.playtimeTotal)} all time</div></td>
                    <td className="mono">{fmt.num(s.sessions30d)}</td>
                    <td className="mono">{larDuration(s.avgSession)}</td>
                    <td className="mono" style={{textAlign:"right"}}>{fmt.num(s.kicks30d)}</td>
                    <td className="mono" style={{textAlign:"right"}}>{fmt.num(s.reports30d)}</td>
                    <td className="mono" style={{textAlign:"right"}}>{fmt.num(s.grants30d)}</td>
                  </tr>
                ))}
                {staff.length === 0 && <tr><td colSpan={9}><div className="empty"><h3>No staff yet</h3><p>Give a player a role on their page (Staff Roles tab).</p></div></td></tr>}
              </tbody>
            </table>
          </div>

          <div className="card card-flush section-gap">
            <div className="toolbar"><span className="card-title">Recent in-game actions</span><span className="tiny muted">kicks, staff reports and item grants</span></div>
            <table className="tbl lar-static">
              <thead><tr><th>When</th><th>Staff</th><th>Action</th><th>Player</th><th>Detail</th></tr></thead>
              <tbody>
                {data.actions.map((a, i) => (
                  <tr key={`${a.action}-${a.at}-${i}`}>
                    <td className="muted" title={fmtDate(larIso(a.at))}>{timeSince(larIso(a.at))}</td>
                    <td><a className="p-name" href={`#players/${a.staffId}`}>{a.staffName}</a></td>
                    <td style={{fontWeight:600}}>{LAR_STAFF_ACTIONS[a.action] || a.action}</td>
                    <td>{a.target ? <a href={`#players/${a.target}`}>{a.targetName || a.target}</a> : "—"}</td>
                    <td className="muted mono">{larStaffDetail(a)}</td>
                  </tr>
                ))}
                {data.actions.length === 0 && <tr><td colSpan={5}><div className="empty"><h3>Nothing yet</h3><p>Kicks show up once staff play on a build with the new backend.</p></div></td></tr>}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { LarStaffPage });
