import React from "react";

const T_COLOR  = "#f97316";
const CT_COLOR = "#60a5fa";

/**
 * PovPlayerList — popup showing alive players, with self player pinned.
 * Appears above the POV button in the zoom controls bar.
 *
 * Props:
 *   playerArray           — full player array from radar state
 *   lockedPlayerIdx       — m_idx of currently locked player, or null
 *   onSelect(idx)         — called when user clicks a player row
 *   onUnlock()            — called when user clicks the Unlock button
 *   selfSteamId           — whichPlayerAreYou (steam id string)
 *   selfMIdx              — m_idx of self player, or null
 *   followYourselfRotation — bool
 *   onToggleRotation()    — called to toggle rotation
 *   isSelfChosen          — whether user has selected themselves
 *   cumulativeRotRef      — ref for initialising rotation on first lock
 *   rawTarget             — current raw yaw for rotation init
 *   onUpdateSettings      — settings patch callback
 *   isSelfAlive           — whether self player is alive
 */
const PovPlayerList = ({
  playerArray, lockedPlayerIdx, onSelect, onUnlock,
  selfSteamId, selfMIdx, followYourselfRotation, onToggleRotation,
  isSelfChosen, cumulativeRotRef, rawTarget, onUpdateSettings,
  isSelfAlive,
}) => {
  const allPlayers = (playerArray || []);
  const alivePlayers = allPlayers.filter(p => !p.m_is_dead);

  const renderPlayerRow = (player) => {
    const isLocked = player.m_idx === lockedPlayerIdx;
    const hp = Math.max(0, Math.min(100, player.m_health ?? 100));
    const teamColor = player.m_team === 2 ? T_COLOR : CT_COLOR;
    const isSelf = isSelfChosen && selfMIdx !== null && player.m_idx === selfMIdx;
    const isDead = player.m_is_dead === true;

    return (
      <div
        key={player.m_idx}
        onClick={isDead ? undefined : () => onSelect(player.m_idx)}
        style={{
          display: "flex",
          alignItems: "center",
          gap: 6,
          padding: "5px 10px",
          cursor: isDead ? "default" : "pointer",
          borderBottom: "1px solid rgba(255,255,255,0.04)",
          opacity: isDead ? 0.4 : 1,
          background: isLocked
            ? "rgba(74,158,255,0.1)"
            : isSelf
              ? "rgba(74,158,255,0.04)"
              : "transparent",
          transition: "background 0.1s",
        }}
        onMouseEnter={e => { if (!isLocked && !isDead) e.currentTarget.style.background = "rgba(255,255,255,0.05)"; }}
        onMouseLeave={e => { if (!isLocked) e.currentTarget.style.background = isSelf ? "rgba(74,158,255,0.04)" : "transparent"; }}
      >
        {/* Team color dot */}
        <div style={{
          width: 7, height: 7, borderRadius: "50%",
          background: teamColor, flexShrink: 0,
        }} />

        {/* Lock indicator */}
        {isLocked && (
          <span style={{ fontSize: 9, color: "#7dd3fc", flexShrink: 0 }}>🔒</span>
        )}

        {/* Player name */}
        <span style={{
          flex: 1, fontSize: 11, fontWeight: isLocked ? 700 : 500,
          color: isLocked ? "#fff" : "rgba(255,255,255,0.8)",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
          minWidth: 0,
        }}>
          {player.m_name || `Player ${player.m_idx}`}
        </span>

        {/* Dead label */}
        {isDead && (
          <span style={{
            fontSize: 8, color: "rgba(255,255,255,0.35)", fontWeight: 600,
            flexShrink: 0,
          }}>dead</span>
        )}

        {/* BẠN badge for self player */}
        {isSelf && (
          <span style={{
            fontSize: 8, color: "#7dd3fc", fontWeight: 800,
            padding: "1px 4px", borderRadius: 3,
            background: "rgba(74,158,255,0.15)", flexShrink: 0,
          }}>BẠN</span>
        )}

        {/* Health bar */}
        <div style={{
          width: 36, height: 4, borderRadius: 2,
          background: "rgba(255,255,255,0.15)", flexShrink: 0, overflow: "hidden",
        }}>
          <div style={{
            height: "100%", borderRadius: 2,
            width: `${hp}%`,
            background: hp > 50 ? "#4ade80" : hp > 25 ? "#facc15" : "#f87171",
            transition: "width 0.2s",
          }} />
        </div>

        {/* HP number */}
        <span style={{
          fontSize: 9, fontFamily: "monospace", fontWeight: 700,
          color: "rgba(255,255,255,0.55)", flexShrink: 0, minWidth: 20, textAlign: "right",
        }}>
          {hp}
        </span>
      </div>
    );
  };

  const tPlayers  = allPlayers.filter(p => p.m_team === 2);
  const ctPlayers = allPlayers.filter(p => p.m_team === 3);
  const hasAnyPlayers = tPlayers.length > 0 || ctPlayers.length > 0;

  return (
    <div
      style={{
        position: "absolute",
        bottom: "calc(100% + 6px)",
        right: 0,
        zIndex: 200,
        pointerEvents: "auto",
        background: "rgba(10,14,20,0.96)",
        border: "1px solid rgba(255,255,255,0.12)",
        borderRadius: 6,
        boxShadow: "0 8px 32px rgba(0,0,0,0.7)",
        minWidth: 200,
        maxWidth: 240,
        backdropFilter: "blur(8px)",
        userSelect: "none",
        overflow: "hidden",
      }}
      onMouseDown={e => e.stopPropagation()}
    >
      {/* ── Self player pinned section ─────────────────────── */}
      {isSelfChosen && selfMIdx !== null && (() => {
        const selfPlayer = playerArray.find(p => p.m_idx === selfMIdx);
        if (!selfPlayer) return null;
        const isSelfLocked = lockedPlayerIdx !== null && lockedPlayerIdx === selfMIdx;

        return (
          <div style={{
            background: isSelfLocked ? "rgba(74,158,255,0.06)" : "rgba(74,158,255,0.03)",
            borderBottom: "1px solid rgba(74,158,255,0.1)",
          }}>
            <div style={{
              padding: "6px 10px 2px", fontSize: 8, fontWeight: 800,
              letterSpacing: "0.15em", color: "rgba(74,158,255,0.6)",
              textTransform: "uppercase",
            }}>Bạn chọn</div>
            <div
              onClick={isSelfAlive ? () => onSelect(selfMIdx) : undefined}
              style={{
                display: "flex", alignItems: "center", gap: 6,
                padding: "2px 10px 6px",
                cursor: isSelfAlive ? "pointer" : "default",
              }}
            >
              <div style={{
                width: 7, height: 7, borderRadius: "50%",
                background: "rgba(74,158,255,0.7)", flexShrink: 0,
                boxShadow: isSelfLocked ? "0 0 6px rgba(74,158,255,0.6)" : "none",
              }} />
              <span style={{
                flex: 1, fontSize: 11, fontWeight: isSelfLocked ? 700 : 500,
                color: "#fff",
              }}>
                {selfPlayer.m_name}
              </span>
              {isSelfAlive ? null : <span style={{ fontSize: 9, color: "rgba(255,255,255,0.3)" }}>dead</span>}
            </div>

            {/* Action buttons row */}
            <div style={{
              display: "flex", gap: 4, padding: "0 10px 6px",
            }}>
              <button
                onClick={() => {
                  if (!isSelfAlive) return;
                  const enable = !isSelfLocked || !followYourselfRotation;
                  if (enable && !isSelfLocked) {
                    // Lock + enable rotation
                    cumulativeRotRef.current = 0;
                    onSelect(selfMIdx);
                    if (!followYourselfRotation) {
                      onUpdateSettings?.({ followYourselfRotation: true });
                    }
                  } else if (isSelfLocked) {
                    // Toggle rotation only
                    if (!followYourselfRotation) {
                      cumulativeRotRef.current = 0;
                    }
                    onToggleRotation?.();
                  } else {
                    onSelect(selfMIdx);
                  }
                }}
                style={{
                  flex: 1, padding: "5px 0", borderRadius: 4,
                  fontSize: 10, fontWeight: 700, letterSpacing: "0.06em",
                  textTransform: "uppercase", cursor: "pointer",
                  fontFamily: "inherit",
                  background: isSelfLocked
                    ? "rgba(74,158,255,0.2)"
                    : "rgba(74,158,255,0.08)",
                  color: "#7dd3fc",
                  border: `1px solid ${
                    isSelfLocked
                      ? "rgba(74,158,255,0.5)"
                      : "rgba(74,158,255,0.2)"
                  }`,
                }}
              >
                ▶ {isSelfLocked ? "Đang theo" : "Follow"}
              </button>
              {isSelfLocked && (
                <button
                  onClick={onToggleRotation}
                  style={{
                    padding: "5px 8px", borderRadius: 4,
                    fontSize: 10, fontWeight: 700, cursor: "pointer",
                    fontFamily: "inherit",
                    background: followYourselfRotation
                      ? "rgba(74,158,255,0.18)"
                      : "rgba(255,255,255,0.04)",
                    color: followYourselfRotation ? "#38bdf8" : "rgba(255,255,255,0.45)",
                    border: `1px solid ${
                      followYourselfRotation
                        ? "rgba(74,158,255,0.5)"
                        : "rgba(255,255,255,0.08)"
                    }`,
                  }}
                >
                  🔄 {followYourselfRotation ? "Tắt xoay" : "Xoay"}
                </button>
              )}
            </div>
          </div>
        );
      })()}

      {/* ── All players sections ──────────────────────────── */}
      {hasAnyPlayers && (
        <div style={{ paddingTop: isSelfChosen ? 0 : 6 }}>
          {/* T side */}
          {tPlayers.map(p => renderPlayerRow(p))}

          {/* CT header */}
          {ctPlayers.length > 0 && (
            <div style={{
              fontSize: 8, fontWeight: 800, letterSpacing: "0.15em",
              color: CT_COLOR, textTransform: "uppercase",
              padding: "4px 10px 2px", marginTop: tPlayers.length > 0 ? 2 : 0,
            }}>
              CT — Chống khủng bố
            </div>
          )}
          {ctPlayers.map(p => renderPlayerRow(p))}
        </div>
      )}

      {/* Empty state */}
      {!hasAnyPlayers && (
        <div style={{
          padding: "10px 10px 8px",
          fontSize: 11, color: "rgba(255,255,255,0.35)",
          textAlign: "center",
        }}>
          Không có người chơi sống
        </div>
      )}

      {/* ── Action buttons row (rotate + unlock) ────────────── */}
      {lockedPlayerIdx !== null && (
        <div style={{ display: "flex", gap: 4, padding: "6px 10px", borderTop: "1px solid rgba(255,255,255,0.06)" }}>
          <button
            onClick={onToggleRotation}
            style={{
              flex: 1, padding: "5px 0", borderRadius: 4,
              fontSize: 10, fontWeight: 700, letterSpacing: "0.06em",
              textTransform: "uppercase", cursor: "pointer",
              fontFamily: "inherit", transition: "all 0.15s",
              background: followYourselfRotation
                ? "rgba(74,158,255,0.18)"
                : "rgba(255,255,255,0.04)",
              color: followYourselfRotation ? "#38bdf8" : "rgba(255,255,255,0.45)",
              border: `1px solid ${
                followYourselfRotation
                  ? "rgba(74,158,255,0.5)"
                  : "rgba(255,255,255,0.08)"
              }`,
            }}
            onMouseEnter={e => { e.currentTarget.style.background = followYourselfRotation ? "rgba(74,158,255,0.25)" : "rgba(255,255,255,0.1)"; }}
            onMouseLeave={e => { e.currentTarget.style.background = followYourselfRotation ? "rgba(74,158,255,0.18)" : "rgba(255,255,255,0.04)"; }}
          >
            🔄 {followYourselfRotation ? "Tắt xoay" : "Xoay theo"}
          </button>
          <button
            onClick={onUnlock}
            style={{
              flex: 1, padding: "5px 0", borderRadius: 4,
              background: "rgba(255,255,255,0.06)",
              border: "1px solid rgba(255,255,255,0.12)",
              color: "rgba(255,255,255,0.7)",
              fontSize: 10, fontWeight: 700, letterSpacing: "0.1em",
              textTransform: "uppercase", cursor: "pointer",
              fontFamily: "inherit", transition: "all 0.15s",
            }}
            onMouseEnter={e => { e.currentTarget.style.background = "rgba(255,255,255,0.12)"; }}
            onMouseLeave={e => { e.currentTarget.style.background = "rgba(255,255,255,0.06)"; }}
          >
            Bỏ chọn
          </button>
        </div>
      )}
    </div>
  );
};

export default PovPlayerList;
