// Right-hand player drawer with tabs: Profile / Chat history / Kill history / Notes

const PlayerDrawer = ({ player, server, notes, onClose, openModal, addNote, live = false }) => {
  const [tab, setTab] = React.useState("profile");
  const [draft, setDraft] = React.useState("");
  const auth = useAuth();

  if (!player) {
    return (
      <div className="drawer">
        <div className="drawer-empty">
          <div>
            <div style={{ marginBottom: 8, opacity: 0.7 }}><Icon name="users" size={28}/></div>
            Select a player to inspect<br/>
            <span style={{ fontSize: 11 }}>Click any row in the roster.</span>
          </div>
        </div>
      </div>
    );
  }

  const playerChat = (DATA.CHAT[server.id]||[]).filter(c => c.playerId === player.id).slice().reverse();
  const playerKills = (DATA.KILLS[server.id]||[]).filter(k => k.killerId === player.id || k.victimId === player.id).slice().reverse();
  const playerNotes = notes[player.id] || [];

  const submitNote = () => {
    if (!draft.trim()) return;
    addNote(player.id, draft.trim());
    setDraft("");
  };

  return (
    <div className="drawer">
      <div className="drawer-head">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 36, height: 36, borderRadius: 8,
            background: "linear-gradient(135deg, #2a2c33, #1a1c21)",
            display: "grid", placeItems: "center",
            fontWeight: 600, fontSize: 13, color: "var(--text-2)"
          }}>{player.name.slice(0,2).toUpperCase()}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="name" style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{player.name}</span>
              <Platform p={player.platform} />
            </div>
            <div className="id">{auth.maskGUID(player.guid)}</div>
          </div>
          <button className="btn sm" onClick={onClose} title="Close"><Icon name="x"/></button>
        </div>

        <div className="drawer-meta">
          {<><span className="k">IP</span><span className="v">{player.ip ? auth.maskIP(player.ip) : "—"}</span></>}
          {!live && <><span className="k">Ping</span><span className="v">{player.ping != null ? player.ping + " ms" : "—"}</span></>}
          <span className="k">Session</span><span className="v">{DATA.timeAgoStr(player.sessionMin).replace(" ago", " on server")}</span>
          {!live && <><span className="k">Faction</span><span className="v">{player.faction}</span></>}
          {!live && <><span className="k">Score</span><span className="v">{player.score} · {player.kills}/{player.deaths}</span></>}
          <span className="k">Flagged</span><span className="v">{player.flagged ? "Yes" : "No"}</span>
        </div>

        <div className="drawer-actions">
          <GatedButton action="player.kick" className="btn warn" onClick={() => openModal({ type: "kick", player })}><Icon name="kick"/> Kick</GatedButton>
          <GatedButton action="player.tempban" className="btn danger" onClick={() => openModal({ type: "ban", player })}><Icon name="ban"/> Ban</GatedButton>
          <GatedButton action="player.pm" className="btn" onClick={() => openModal({ type: "pm", player })}><Icon name="send"/> Message</GatedButton>
          <GatedButton action="player.note" className="btn" onClick={() => setTab("notes")}><Icon name="note"/> Add note</GatedButton>
        </div>
      </div>

      <div className="drawer-tabs">
        <button className={"t " + (tab==="profile"?"active":"")} onClick={() => setTab("profile")}>Profile</button>
        <button className={"t " + (tab==="chat"?"active":"")} onClick={() => setTab("chat")}>Chat{!live && ` (${playerChat.length})`}</button>
        <button className={"t " + (tab==="kills"?"active":"")} onClick={() => setTab("kills")}>Kills{!live && ` (${playerKills.length})`}</button>
        <button className={"t " + (tab==="notes"?"active":"")} onClick={() => setTab("notes")}>Notes ({playerNotes.length})</button>
      </div>

      <div className="drawer-body">
        {tab === "profile" && <PlayerProfile player={player} live={live} />}
        {tab === "chat" && (
          live
            ? <FeedUnavailable what="Player chat" />
            : playerChat.length === 0
            ? <div className="empty">No chat from this player on {server.name}.</div>
            : playerChat.map(m => (
              <div className="log-row" key={m.id}>
                <span className="ts">{DATA.fmtClockShort(m.ts)}</span>
                <span className="body">{m.text}</span>
              </div>
            ))
        )}
        {tab === "kills" && (
          live
            ? <FeedUnavailable what="Kill feed" />
            : playerKills.length === 0
            ? <div className="empty">No combat events recorded.</div>
            : playerKills.map(k => {
                const isKiller = k.killerId === player.id;
                return (
                  <div className="log-row kill" key={k.id}>
                    <span className="ts">{DATA.fmtClockShort(k.ts)}</span>
                    <span className="body">
                      {isKiller
                        ? <><span className="killer">{player.name}</span><span className="muted" style={{margin:"0 6px"}}>killed</span><span className="victim">{k.victimName}</span></>
                        : <><span className="victim">{player.name}</span><span className="muted" style={{margin:"0 6px"}}>killed by</span><span className="killer">{k.killerName}</span></>}
                      <div className="weap">{k.weapon} · {k.distance}m {k.tk && "· TEAM-KILL"}</div>
                    </span>
                  </div>
                );
            })
        )}
        {tab === "notes" && (
          <>
            {playerNotes.length === 0 && <div className="empty">No staff notes yet — add the first one below.</div>}
            {playerNotes.map(n => (
              <div className="note" key={n.id}>
                <div className="meta">{n.author} · {DATA.timeAgoStr(Math.floor((Date.now()-n.ts)/60000))}</div>
                {n.body}
              </div>
            ))}
          </>
        )}
      </div>

      {tab === "notes" && (
        <div className="note-composer">
          <textarea value={draft} onChange={e => setDraft(e.target.value)}
            placeholder="Internal note (visible to all staff)"
            onKeyDown={e => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) submitNote(); }} />
          <button className="btn primary" onClick={submitNote} disabled={!draft.trim()}>Add</button>
        </div>
      )}
    </div>
  );
};

const PlayerProfile = ({ player, live = false }) => {
  const auth = useAuth();
  return (
  <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 12 }}>
    <div>
      <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.4, marginBottom: 4 }}>Identity</div>
      <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "5px 12px", fontSize: 12 }}>
        <span className="muted">In-game name</span><span>{player.name}</span>
        {!live && <><span className="muted">Platform</span>
        <span>
          {player.platform === "steam" && "PC (Steam)"}
          {player.platform === "xbox" && "Xbox console"}
          {player.platform === "ps" && "PlayStation console"}
        </span></>}
        {live && <><span className="muted">Platform</span><span>{player.platform === "steam" ? "PC (Steam)" : (player.platform || "—")}</span></>}
        <span className="muted">GUID</span><span className="mono" style={{ wordBreak: "break-all" }}>{auth.maskGUID(player.guid)}</span>
        {<><span className="muted">IP</span><span className="mono">{player.ip ? auth.maskIP(player.ip) : "—"}{!auth.can("view.ip") && player.ip && <span className="muted" style={{marginLeft:6, fontFamily:"var(--font)", fontSize: 11}}>(masked at your tier)</span>}</span></>}
      </div>
    </div>

    {!live && <div>
      <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.4, marginBottom: 4 }}>Connection</div>
      <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "5px 12px", fontSize: 12 }}>
        <span className="muted">Ping</span><span className={"mono ping " + pingClass(player.ping)}>{player.ping} ms</span>
        <span className="muted">Session</span><span className="mono">{DATA.timeAgoStr(player.sessionMin).replace(" ago","")}</span>
        <span className="muted">Joined at</span><span className="mono">{DATA.fmtClock(Date.now() - player.sessionMin*60000)}</span>
      </div>
    </div>}

    <div>
      <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.4, marginBottom: 4 }}>External lookups</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {!live && player.platform === "steam" && (
          <button className="btn sm" onClick={() => alert("Would open: https://steamcommunity.com/profiles/" + player.guid)}>
            <Icon name="external"/> Steam profile
          </button>
        )}
        <button className="btn sm"><Icon name="external"/> Battlemetrics</button>
        <button className="btn sm"><Icon name="external"/> Ban history</button>
      </div>
    </div>
  </div>
  );
};

Object.assign(window, { PlayerDrawer, PlayerProfile });
