import { useState } from "react";
import MaskedIcon from "./maskedicon";
import { playerColors, teamEnum } from "../utilities/utilities";

const hpColor = hp => hp > 60 ? "#3dd68c" : hp > 30 ? "#f0b429" : "#e05252";

/* ─── C4 Carrier badge — animated pulse red ────────────────────────── */
const C4Badge = () => (
  <>
    <style>{`
      @keyframes c4pulse {
        0%   { box-shadow: 0 0 0 0 rgba(239,68,68,0.9), 0 0 8px rgba(239,68,68,0.6); opacity: 1; }
        50%  { box-shadow: 0 0 0 5px rgba(239,68,68,0), 0 0 16px rgba(239,68,68,0.3); opacity: 0.85; }
        100% { box-shadow: 0 0 0 0 rgba(239,68,68,0), 0 0 8px rgba(239,68,68,0.6); opacity: 1; }
      }
      @keyframes c4glow {
        0%,100% { opacity: 1; transform: scale(1); }
        50%     { opacity: 0.75; transform: scale(0.96); }
      }
    `}</style>
    <div style={{
      display: "flex", alignItems: "center", gap: 4,
      padding: "3px 6px", borderRadius: 4,
      background: "rgba(239,68,68,0.18)",
      border: "1.5px solid #ef4444",
      animation: "c4pulse 1.1s ease-in-out infinite",
      flexShrink: 0,
    }}>
      <div style={{
        width: 12, height: 12,
        background: "#ef4444",
        WebkitMask: "url('./assets/icons/c4.svg') no-repeat center/contain",
        mask: "url('./assets/icons/c4.svg') no-repeat center/contain",
        animation: "c4glow 1.1s ease-in-out infinite",
        flexShrink: 0,
      }} />
      <span style={{
        fontSize: 9, fontWeight: 900, color: "#ef4444",
        letterSpacing: "0.08em", lineHeight: 1,
      }}>C4</span>
    </div>
  </>
);

/* ─── Colors ─────────────────────────────────────────────────────────── */
const A  = "rgba(245,166,35,1)";   // active — amber
const IA = "rgba(255,255,255,0.45)"; // inactive — muted white

/* ─── Dot (space placeholder in 4-cell row) ────────────────────────── */
const Dot = () => <div style={{ width:6, height:6, borderRadius:"50%", background:IA, flexShrink:0 }} />;

/* ─── Portrait ─────────────────────────────────────────────────────── */
const Portrait = ({ model, isDead, accentColor, isRight }) => {
  const [err, setErr] = useState(false);
  return (
    <div style={{
      position:"relative", width:85, flexShrink:0, alignSelf:"stretch", overflow:"hidden",
      background:`linear-gradient(${isRight?"720deg":"90deg"},${accentColor}0a,transparent)`,
      borderLeft:  isRight  ? `2px solid ${accentColor}30` : "none",
      borderRight: !isRight ? `2px solid ${accentColor}30` : "none",
    }}>
      <img
        src={`./assets/characters/${model}.png`}
        alt=""
        onError={() => setErr(true)}
        style={{
          position:"absolute",inset:0,width:"100%",height:"100%",
          objectFit:"cover",objectPosition:"top center",
          transform:"scale(1.7) translateY(-6%)",transformOrigin:"top center",
          display: err?"none":undefined,
          filter: isDead?"grayscale(1) brightness(0.3)":"saturate(0.85)", opacity: isDead?0.5:1,
        }}
      />
      {err && (
        <div style={{ position:"absolute",inset:0, display:"flex", alignItems:"center", justifyContent:"center" }}>
          <span style={{ fontSize:20, color:accentColor, opacity:0.2 }}>?</span>
        </div>
      )}
      <div style={{
        position:"absolute",top:0,bottom:0,width:24,
        [isRight?"left":"right"]:0,
        background:`linear-gradient(${isRight?"90deg":"270deg"},var(--bg-card) 0%,transparent 100%)`,
        pointerEvents:"none",
      }} />
    </div>
  );
};

/* ─── HP bar ──────────────────────────────────────────────────────── */
const HpBar = ({ hp, isDead, settings }) => {
  if (settings && !settings.showHealthBars) return null;
  return (
    <div style={{ position:"absolute",bottom:0,left:0,right:0,height:2,background:"rgba(0,0,0,0.4)" }}>
      <div style={{ height:"100%",width:`${isDead?0:hp}%`,background:hpColor(hp),transition:"width 0.4s ease" }} />
    </div>
  );
};

/* ─── DEBUG: show backend weapon data ──────────────────────────────── */
const DEBUG = false;
const DebugWeapon = ({ playerData }) => {
  const w = playerData.m_weapons ?? {};
  return (
    <div style={{ position:"fixed",bottom:8,left:8,zIndex:99999,
      background:"black",color:"lime",fontSize:11,fontFamily:"monospace",
      padding:8,border:"1px solid lime",borderRadius:4, maxWidth:320 }}>
      <div>active: <b>{w.m_active}</b></div>
      <div>primary: <b>{w.m_primary}</b></div>
      <div>secondary: <b>{w.m_secondary}</b></div>
      <div>melee: <b>{JSON.stringify(w.m_melee)}</b></div>
      <div>utils: <b>{JSON.stringify(w.m_utilities)}</b></div>
      <div>ammo: <b>{w.m_ammo_clip}/{w.m_ammo_max_clip}</b></div>
      <div>m_has_bomb: <b>{String(playerData.m_has_bomb)}</b></div>
    </div>
  );
};
const WSlot = ({ name, isActive, h = 28 }) => {
  if (!name) return null;
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: "3px 6px", borderRadius: 4,
      background: isActive ? "rgba(245,166,35,0.15)" : "rgba(255,255,255,0.04)",
      border: `1px solid ${isActive ? "rgba(245,166,35,0.4)" : "rgba(255,255,255,0.07)"}`,
    }}>
      <MaskedIcon path={`./assets/icons/${name}.svg`} height={h} color={isActive ? A : IA} />
    </div>
  );
};

/* ─── Utility slot ─────────────────────────────────────────────────── */
const USlot = ({ name, isActive }) =>
  name
    ? <MaskedIcon path={`./assets/icons/${name}.svg`} height={28} color={isActive ? A : IA} />
    : null;

/* ─── Info panel ────────────────────────────────────────────────────── */
/*
 * Layout (rebirth):
 *   Row 1: [name]                    [HP]
 *   Row 2: $money | K/D/A | armor | ping
 *   Row 3: [primary] [secondary] [knife]        ← loadout: active weapon UPDATE icon + highlight
 *   Row 4: [util ×4] ··· dots ··· [defuser/C4]  ← 4 fixed slots; dots fill remainder
 *   Row 5: [ammo bar clip/max]
 *
 * Rules:
 *   • Never duplicate the active weapon as a separate icon
 *   • Active weapon HIGHLIGHTS the matching loadout slot; that slot icon = activeW when active
 *   • Inventory slots (primary/secondary/melee) are the LOADOUT, always shown from backend data
 *   • Grenades row: 4 fixed slots. Backend sends what player has; backend fills leftover with "knife_t"
 */
const InfoPanel = ({ playerData, isRight, settings }) => {
  const isDead  = playerData.m_is_dead;
  const hp      = playerData.m_health   ?? 0;
  const kills   = playerData.m_kills    ?? 0;
  const deaths  = playerData.m_deaths   ?? 0;
  const assists = playerData.m_assists  ?? 0;
  const money   = playerData.m_money    ?? 0;
  const team    = playerData.m_team;
  const w       = playerData.m_weapons   ?? {};
  const activeW = isDead ? "" : (w.m_active ?? "");

  /* ── Loadout slots from backend ─────────────────────────────────── */
  const primary   = w.m_primary   ?? "";
  const secondary = w.m_secondary ?? "";
  const knifeName = !isDead && w.m_melee?.length > 0 ? w.m_melee[0] : "";

  /* ── Utilities & ammo ───────────────────────────────────────────── */
  const utils      = w.m_utilities ?? [];
  const hasBomb    = !isDead && team === teamEnum.terrorist && playerData.m_has_bomb;
  const hasDefuser = !isDead && team === teamEnum.counterTerrorist && playerData.m_has_defuser;
  const clip  = w.m_ammo_clip      ?? 0;
  const maxCl = w.m_ammo_max_clip ?? 0;

  const RD = isRight ? "row-reverse" : "row";
  const JA = isRight ? "flex-end"     : "flex-start";
  const TA = isRight ? "right"         : "left";

  return (
    <div style={{
      flex:1, display:"flex", flexDirection:"column",
      padding:"4px 10px 60px", gap:3, minWidth:0,
      alignItems:JA, position:"relative",
    }}>
      {/* Flash overlay */}
      {playerData.m_flash_alpha > 0 && settings?.showFlashEffect !== false && (
        <div style={{
          position:"absolute",inset:0,
          background:"rgba(255,255,255,0.18)",
          opacity:Math.min(playerData.m_flash_alpha,1),
          pointerEvents:"none",borderRadius:10,
        }} />
      )}

      {/* Row 1: name + HP */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", width:"100%", gap:6, flexDirection:RD }}>
        <span style={{
          fontSize:12, fontWeight:800, lineHeight:1,
          color: isDead?"rgba(255,255,255,0.22)":"var(--text-primary)",
          overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",
          flex:1, textAlign:TA,
        }}>{playerData.m_name}</span>
        <div style={{
          display:"flex", alignItems:"center", justifyContent:"center",
          minWidth:28, padding:"2px 5px", borderRadius:3, flexShrink:0,
          background: isDead?"rgba(255,255,255,0.03)":`${hpColor(hp)}14`,
          border:`1px solid ${isDead?"rgba(255,255,255,0.06)":`${hpColor(hp)}35`}`,
        }}>
          <span style={{ fontSize:12, fontWeight:800, fontFamily:"monospace", lineHeight:1, color: isDead?"rgba(255,255,255,0.2)":hpColor(hp) }}>
            {isDead ? "✕" : hp}
          </span>
        </div>
      </div>

      {/* Row 2: money | KDA | armor | ping */}
      <div style={{ display:"flex", alignItems:"center", gap:8, flexDirection:RD }}>
        {settings?.showMoney !== false && (
          <span style={{ fontSize:14, fontFamily:"monospace", fontWeight:700, lineHeight:1, color: isDead?"rgba(61,214,140,0.25)":"var(--money)" }}>
            ${money.toLocaleString()}
          </span>
        )}
        <span style={{ fontSize:14, fontFamily:"monospace", fontWeight:700, lineHeight:1 }}>
          <span style={{color:"#3dd68c"}}>{kills}</span>
          <span style={{color:"rgba(255,255,255,0.12)"}}>/</span>
          <span style={{color:"#e05252"}}>{deaths}</span>
          <span style={{color:"rgba(255,255,255,0.12)"}}>/</span>
          <span style={{color:"#60a5fa"}}>{assists}</span>
        </span>
        {!isDead && playerData.m_armor>0 && settings?.showArmor !== false && (
          <div style={{ display:"flex", alignItems:"center", gap:2 }}>
            <MaskedIcon path={`./assets/icons/${playerData.m_has_helmet?"kevlar_helmet":"kevlar"}.svg`} height={10} color="bg-blue-400/50" />
            <span style={{ fontSize:16, fontFamily:"monospace", fontWeight:700, color:"rgba(96,165,250,0.6)", lineHeight:1 }}>
              {playerData.m_armor}
            </span>
          </div>
        )}
        {settings?.showPing !== false && playerData.m_iPing>0 && playerData.m_iPing<999 && (
          <span style={{ fontSize:16, fontFamily:"monospace", fontWeight:700, lineHeight:1,
            color: playerData.m_iPing<40?"rgba(61,214,140,0.6)":playerData.m_iPing<60?"rgba(240,180,41,0.6)":"rgba(224,82,82,0.6)" }}>
            {playerData.m_iPing}ms
          </span>
        )}
      </div>

      {/* ══ Row 3: Weapons + Knife + C4/Defuser badge ═════════════════ */}
      {!isDead && (
        <div style={{ display:"flex", alignItems:"center", gap:4, flexDirection:RD, marginTop:1 }}>
          {primary    && <WSlot name={primary}   isActive={activeW === primary}   h={16} />}
          {secondary  && <WSlot name={secondary} isActive={activeW === secondary} h={12} />}
          {knifeName  && <WSlot name={knifeName} isActive={activeW.startsWith("knife") || activeW === "taser"} h={12} />}
          {hasBomb    && <C4Badge />}
          {hasDefuser && (
            <div style={{ padding: "3px 4px", borderRadius: 3, background: "rgba(74,158,255,0.1)", border: "1px solid rgba(74,158,255,0.3)", display: "flex", alignItems: "center" }}>
              <MaskedIcon path="./assets/icons/defuser.svg" height={12} color="bg-blue-400/80" />
            </div>
          )}
        </div>
      )}

      {/* ══ Row 4: Utilities (grenades) alone ════════════════════ */}
      {!isDead && utils.length > 0 && (
        <div style={{ display:"flex", alignItems:"center", gap:3, flexDirection:RD }}>
          {utils.map(u => <USlot key={u} name={u} isActive={activeW === u} />)}
        </div>
      )}

      {/* ══ Row 5: Ammo bar alone ════════════════════════════════ */}
      {!isDead && maxCl > 0 && settings?.showAmmo !== false && <AmmoBar clip={clip} maxCl={maxCl} />}
    </div>
  );
};

/* ─── Ammo bar (row 5) ───────────────────────────────────────────────── */
const AmmoBar = ({ clip, maxCl }) => {
  const pct   = maxCl > 0 ? clip / maxCl : 0;
  const color = pct > 0.5 ? "#3dd68c" : pct > 0.25 ? "#f0b429" : "#e05252";
  const cnt  = Math.min(maxCl, 20);
  return (
    <div style={{ display:"flex", alignItems:"center", gap:2, marginTop:1 }}>
      {Array.from({length:cnt}).map((_,i) => (
        <div key={i} style={{
          width:2, height:i%5===4?7:4, borderRadius:1, flexShrink:0,
          background: pct > i/cnt ? color : "rgba(255,255,255,0.07)",
        }} />
      ))}
      <span style={{ fontSize:16, fontFamily:"monospace", fontWeight:700, color:"rgba(255,255,255,0.3)", marginLeft:2, lineHeight:1 }}>
        {clip}
      </span>
    </div>
  );
};

/* ─── Player card ───────────────────────────────────────────────────── */
const PlayerCard = ({ playerData, isOnRightSide, settings }) => {
  const isDead    = playerData.m_is_dead;
  const isT       = playerData.m_team === 2;
  const hp        = playerData.m_health ?? 0;
  const accentHex = isT ? "#f5a623" : "#4a9eff";

  return (
    <li style={{
      position:"relative", display:"flex", alignItems:"stretch",
      overflow:"hidden", listStyle:"none", borderRadius:10, minHeight:74,
      background: isDead
        ? "var(--bg-panel)"
        : isT
        ? "linear-gradient(90deg,rgba(245,166,35,0.07) 0%,var(--bg-card) 100%)"
        : "linear-gradient(270deg,rgba(74,158,255,0.07) 0%,var(--bg-card) 100%)",
      border:`1px solid ${isDead?"var(--bg-border-dim)":isT?"var(--t-border)":"var(--ct-border)"}`,
      opacity: isDead ? 0.4 : 1,
      transition:"opacity 0.35s",
    }}>
      {isOnRightSide ? (
        <>
          <InfoPanel playerData={playerData} isRight={isOnRightSide} settings={settings} />
          <Portrait model={playerData.m_model_name||null} isDead={isDead} accentColor={accentHex} isRight={isOnRightSide} />
        </>
      ) : (
        <>
          <Portrait model={playerData.m_model_name||null} isDead={isDead} accentColor={accentHex} isRight={isOnRightSide} />
          <InfoPanel playerData={playerData} isRight={isOnRightSide} settings={settings} />
        </>
      )}
      <HpBar hp={hp} isDead={isDead} settings={settings} />
      {DEBUG && <DebugWeapon playerData={playerData} />}
    </li>
  );
};

export default PlayerCard;