import { getRadarPosition } from "../utilities/utilities";

// ─── Grenade trajectory physics constants (from external cheat docs) ────────────
const GRAVITY = 320; // CS2 gravity: sv_gravity (800) × grenade scale (0.4)
const HE_FLIGHT_TIME = 1.5;  // HE/Flash: 1.5s fuse
const SMOKE_FLIGHT_TIME = 1.8; // Smoke bounces before deploy
const FLASH_FLIGHT_TIME = 1.3; // Flash is fastest
const MOLOTOV_FLIGHT_TIME = 1.5; // Molotov shatters on first impact

// ─── Parse trajectory points from backend JSON ─────────────────────────────────
const parseTrajectoryPoints = (trajectoryJson) => {
  if (!trajectoryJson) return [];
  try {
    const points = JSON.parse(trajectoryJson);
    if (!Array.isArray(points) || points.length < 4) return [];
    // Points are stored as [x1, y1, x2, y2, ...] pairs
    const result = [];
    for (let i = 0; i < points.length - 1; i += 2) {
      result.push({ x: points[i], y: points[i + 1] });
    }
    return result;
  } catch {
    return [];
  }
};

// ─── Generate simplified trajectory for grenades without backend data ──────────
const generateFallbackTrajectory = (startX, startY, vx, vy, grenadeType) => {
  const points = [];
  const flightTime = grenadeType === "smoke" ? SMOKE_FLIGHT_TIME
    : grenadeType === "flashbang" ? FLASH_FLIGHT_TIME
    : grenadeType === "molotov" || grenadeType === "incendiary" ? MOLOTOV_FLIGHT_TIME
    : HE_FLIGHT_TIME;

  const numPoints = 8;
  for (let i = 0; i <= numPoints; i++) {
    const t = (i / numPoints) * flightTime;
    // Parabolic arc: peaks at middle of trajectory
    const arcOffset = Math.sin((i / numPoints) * Math.PI) * -25;
    const x = startX + vx * t;
    const y = startY + vy * t + arcOffset;
    points.push({ x, y });
  }
  return points;
};

// ─── Trajectory Line Component (renders dots + landing prediction) ───────────
const TrajectoryLine = ({ grenadeData, mapData, imgSize, settings }) => {
  if (!mapData || !imgSize) return null;

  const showTrajectory = settings?.showGrenadeTrajectory !== false;
  if (!showTrajectory) return null;

  const type = grenadeData.type;
  const posX = grenadeData.x;
  const posY = grenadeData.y;
  const vx = grenadeData.vx || 0;
  const vy = grenadeData.vy || 0;

  // Only show for grenades in flight with velocity
  if (Math.abs(vx) < 50 && Math.abs(vy) < 50) return null;
  if (type === "inferno" || type === "smoke") return null; // These have effect rendering

  const dotSize = Math.max(3, (imgSize.w || 1024) / 400);
  const color = CFG[type]?.dotColor || '#ffffff';

  // Try to use real trajectory from backend, fallback to generated
  let trajectoryPoints;
  if (grenadeData.m_trajectory && grenadeData.m_has_trajectory) {
    trajectoryPoints = parseTrajectoryPoints(grenadeData.m_trajectory);
  } else {
    trajectoryPoints = generateFallbackTrajectory(posX, posY, vx, vy, type);
  }

  if (trajectoryPoints.length < 2) return null;

  // Convert world positions to radar screen positions
  const radarPoints = trajectoryPoints.map(p => {
    const rp = getRadarPosition(mapData, { x: p.x, y: p.y });
    if (!rp) return null;
    return {
      screenX: (imgSize.ml ?? 0) + (imgSize.w || 0) * rp.x,
      screenY: (imgSize.mt ?? 0) + (imgSize.h || 0) * rp.y,
      x: p.x,
      y: p.y
    };
  }).filter(Boolean);

  if (radarPoints.length < 2) return null;

  // Landing position (last point or calculated from m_land_x/m_land_y)
  const landingPos = grenadeData.m_land_x && grenadeData.m_land_y
    ? { x: grenadeData.m_land_x, y: grenadeData.m_land_y }
    : radarPoints[radarPoints.length - 1];

  const landingRadar = getRadarPosition(mapData, landingPos);
  const landingScreen = landingRadar ? {
    screenX: (imgSize.ml ?? 0) + (imgSize.w || 0) * landingRadar.x,
    screenY: (imgSize.mt ?? 0) + (imgSize.h || 0) * landingRadar.y
  } : radarPoints[radarPoints.length - 1];

  return (
    <>
      <style>{`
        @keyframes trajectoryPulse {
          0%, 100% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
          50% { opacity: 0.7; transform: translate(-50%, -50%) scale(1.2); }
        }
        @keyframes landingGlow {
          0%, 100% { box-shadow: 0 0 6px ${color}, 0 0 12px ${color}; }
          50% { box-shadow: 0 0 12px ${color}, 0 0 20px ${color}; }
        }
      `}</style>

      {/* ── Trajectory dots (from start to landing) ── */}
      {radarPoints.slice(0, -1).map((rp, idx) => {
        const progress = idx / (radarPoints.length - 1);
        const size = dotSize * (0.6 + 0.4 * (1 - progress)); // Dots get smaller along path
        const opacity = 0.95 - progress * 0.6;

        return (
          <div
            key={`traj-${idx}`}
            className="absolute pointer-events-none"
            style={{
              width: size,
              height: size,
              borderRadius: "50%",
              backgroundColor: color,
              opacity: opacity,
              left: rp.screenX - size / 2,
              top: rp.screenY - size / 2,
              boxShadow: `0 0 3px ${color}`,
              zIndex: 115,
            }}
          />
        );
      })}

      {/* ── Landing position marker (diamond shape) ── */}
      <div
        className="absolute pointer-events-none"
        style={{
          width: dotSize * 2.5,
          height: dotSize * 2.5,
          left: landingScreen.screenX,
          top: landingScreen.screenY,
          transform: "translate(-50%, -50%) rotate(45deg)",
          backgroundColor: color,
          border: `2px solid rgba(255,255,255,0.8)`,
          boxShadow: `0 0 10px ${color}, 0 0 20px ${color}40`,
          zIndex: 125,
          animation: "landingGlow 1.5s ease-in-out infinite",
        }}
      />

      {/* ── Landing position label ── */}
      <div
        className="absolute pointer-events-none"
        style={{
          left: landingScreen.screenX,
          top: landingScreen.screenY - 20,
          transform: "translateX(-50%)",
          fontSize: Math.max(8, dotSize * 1.5),
          fontWeight: 700,
          color: color,
          textShadow: "0 0 4px rgba(0,0,0,0.9), 0 0 8px rgba(0,0,0,0.7)",
          zIndex: 126,
          whiteSpace: "nowrap",
        }}
      >
        {CFG[type]?.label}
      </div>
    </>
  );
};

const radiusToPx = (gameUnits, imgWidth, scale) => {
  if (!imgWidth || !scale) return 0;
  return (gameUnits / scale / 1024) * imgWidth * 2;
};

// Fire spread data: backend sends [[fx, fy], ...] arrays, normalize to {x, y} objects
const parseFirePositions = (raw) => {
  if (!Array.isArray(raw) || raw.length === 0) return [];
  return raw.map(p => {
    if (Array.isArray(p)) return { x: p[0], y: p[1] };
    if (typeof p === 'object' && p !== null) return { x: p.x ?? p.m_x ?? 0, y: p.y ?? p.m_y ?? 0 };
    return null;
  }).filter(Boolean);
};

// ─── SMOKE — solid, opaque cloud ──────────────────────────────────────────────
const SmokeEffect = ({ diameter, timeLeft }) => {
  const countdown = timeLeft != null ? timeLeft.toFixed(1) : null;
  return (
    <>
    <style>{`
      @keyframes smokeRotate { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
      @keyframes smokePulse  { 0%,100%{opacity:.92;transform:scale(1)} 50%{opacity:1;transform:scale(1.03)} }
      @keyframes smokeBlob1  { 0%,100%{transform:translate(0,0)scale(1)} 50%{transform:translate(5px,-4px)scale(1.07)} }
      @keyframes smokeBlob2  { 0%,100%{transform:translate(0,0)scale(1)} 50%{transform:translate(-4px,5px)scale(1.06)} }
      @keyframes smokeBlob3  { 0%,100%{transform:translate(0,0)scale(1)} 50%{transform:translate(3px,3px)scale(1.05)} }
      @keyframes smokeBlob4  { 0%,100%{transform:translate(0,0)scale(1)} 50%{transform:translate(-3px,-3px)scale(1.04)} }
    `}</style>
    <div style={{
      position: "absolute", width: diameter, height: diameter,
      left: "50%", top: "50%",
      transform: "translate(-50%, -50%)",
      borderRadius: "50%", overflow: "visible", zIndex: 1,
    }}>
      <div style={{
        position: "absolute", inset: 0, borderRadius: "50%",
        border: "2px solid rgba(200,210,220,0.55)",
        boxShadow: "0 0 12px rgba(180,190,200,0.35), inset 0 0 20px rgba(180,190,200,0.15)",
        animation: "smokeRotate 18s linear infinite",
      }} />
      <div style={{
        position: "absolute", inset: "3%", borderRadius: "50%",
        background: "radial-gradient(circle at 50% 50%, rgba(210,220,228,0.88) 0%, rgba(185,198,208,0.82) 30%, rgba(155,170,180,0.72) 60%, rgba(120,135,145,0.45) 80%, transparent 100%)",
        backdropFilter: "blur(2px)",
        animation: "smokePulse 4s ease-in-out infinite",
      }} />
      <div style={{
        position: "absolute", width: "50%", height: "50%", top: "15%", left: "25%",
        borderRadius: "50%",
        background: "radial-gradient(circle, rgba(235,242,248,0.75) 0%, rgba(210,222,232,0.50) 50%, transparent 100%)",
        animation: "smokeBlob1 5s ease-in-out infinite",
      }} />
      <div style={{
        position: "absolute", width: "52%", height: "52%", bottom: "6%", right: "8%",
        borderRadius: "50%",
        background: "radial-gradient(circle, rgba(200,212,222,0.65) 0%, rgba(165,178,188,0.40) 60%, transparent 100%)",
        animation: "smokeBlob2 6s ease-in-out infinite",
      }} />
      <div style={{
        position: "absolute", width: "42%", height: "42%", top: "28%", right: "6%",
        borderRadius: "50%",
        background: "radial-gradient(circle, rgba(195,207,216,0.60) 0%, transparent 70%)",
        animation: "smokeBlob3 5.5s ease-in-out infinite",
      }} />
      <div style={{
        position: "absolute", width: "38%", height: "38%", bottom: "12%", left: "6%",
        borderRadius: "50%",
        background: "radial-gradient(circle, rgba(188,200,210,0.55) 0%, transparent 70%)",
        animation: "smokeBlob4 7s ease-in-out infinite",
      }} />
      <div style={{
        position: "absolute", top: "50%", left: "50%",
        transform: "translate(-50%, -50%)",
        fontSize: Math.max(9, diameter * 0.12),
        fontWeight: 900,
        color: "rgba(80,95,105,0.9)",
        textShadow: "0 1px 3px rgba(255,255,255,0.5)",
        letterSpacing: "0.06em",
        lineHeight: 1,
        pointerEvents: "none",
        zIndex: 3,
      }}>{countdown != null ? `SMK ${countdown}s` : "SMK"}</div>
    </div>
  </>
  );
};

// ─── FIRE — fire zone (single unit) ───────────────────────────────────────────
const FireEffect = ({ diameter, delay = 0 }) => {
  return (
    <>
      <style>{`
        @keyframes fireGlow     { from{opacity:.75;transform:scale(0.97)} to{opacity:1;transform:scale(1.03)} }
        @keyframes fireFlicker  { from{transform:scale(0.91)rotate(-3deg);opacity:.78} to{transform:scale(1.07)rotate(3deg);opacity:1} }
        @keyframes flameTongue1 { from{transform:rotate(-10deg)scaleY(0.85)} to{transform:rotate(7deg)scaleY(1.15)} }
        @keyframes flameTongue2 { from{transform:rotate(8deg)scaleY(0.88)} to{transform:rotate(-6deg)scaleY(1.12)} }
        @keyframes flameTongue3 { from{transform:rotate(-5deg)scaleY(0.80)} to{transform:rotate(5deg)scaleY(1.20)} }
        @keyframes ember        { 0%{transform:translateY(0)scale(1);opacity:1} 80%{transform:translateY(-18px)scale(0.4);opacity:.5} 100%{transform:translateY(-22px)scale(0);opacity:0} }
        @keyframes fireRing     { 0%{transform:translate(-50%,-50%)scale(1);opacity:.5} 100%{transform:translate(-50%,-50%)scale(1.4);opacity:0} }
      `}</style>
      <div style={{
        position: "absolute", width: diameter, height: diameter,
        left: "50%", top: "50%",
        transform: "translate(-50%, -50%)",
        borderRadius: "50%", overflow: "visible", zIndex: 1,
        animationDelay: `${delay}ms`,
      }}>
        {/* Expanding ring */}
        <div style={{
          position: "absolute", width: diameter, height: diameter,
          left: "50%", top: "50%",
          borderRadius: "50%",
          border: "2px solid rgba(255,140,0,0.6)",
          animation: "fireRing 1s ease-out infinite",
        }} />
        {/* Outer glow */}
        <div style={{
          position: "absolute", inset: 0, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(255,130,0,0.55) 0%, rgba(220,65,0,0.35) 45%, rgba(180,30,0,0.15) 70%, transparent 90%)",
          boxShadow: `0 0 ${diameter * 0.4}px ${diameter * 0.2}px rgba(255,100,0,0.3)`,
          animation: "fireGlow 1.2s ease-in-out infinite alternate",
        }} />
        {/* Flame core */}
        <div style={{
          position: "absolute", inset: "10%", borderRadius: "50%",
          background: "radial-gradient(ellipse at 50% 65%, rgba(255,220,60,0.90) 0%, rgba(255,140,0,0.75) 30%, rgba(220,60,0,0.50) 60%, transparent 100%)",
          animation: "fireFlicker 0.8s ease-in-out infinite alternate",
        }} />
        {/* Flame tongues */}
        <div style={{
          position: "absolute", width: "32%", height: "55%", bottom: "22%", left: "18%",
          borderRadius: "50% 50% 28% 28%",
          background: "linear-gradient(to top, rgba(255,220,50,0.90), rgba(255,130,0,0.55), transparent)",
          transformOrigin: "50% 100%",
          animation: "flameTongue1 1s ease-in-out infinite alternate",
        }} />
        <div style={{
          position: "absolute", width: "30%", height: "48%", bottom: "22%", right: "16%",
          borderRadius: "50% 50% 28% 28%",
          background: "linear-gradient(to top, rgba(255,200,40,0.85), rgba(255,110,0,0.45), transparent)",
          transformOrigin: "50% 100%",
          animation: "flameTongue2 1.25s ease-in-out infinite alternate",
        }} />
        <div style={{
          position: "absolute", width: "24%", height: "62%", bottom: "22%", left: "38%",
          borderRadius: "50% 50% 28% 28%",
          background: "linear-gradient(to top, rgba(255,240,90,0.95), rgba(255,160,20,0.60), transparent)",
          transformOrigin: "50% 100%",
          animation: "flameTongue3 0.75s ease-in-out infinite alternate",
        }} />
        {/* Ground char */}
        <div style={{
          position: "absolute", inset: "20%", borderRadius: "50%",
          background: "radial-gradient(circle, rgba(30,10,0,0.45) 0%, transparent 70%)",
        }} />
        {/* Embers */}
        {[
          { left: "28%", delay: "0s", dur: "1.6s" },
          { left: "52%", delay: "0.3s", dur: "1.9s" },
          { left: "42%", delay: "0.6s", dur: "1.4s" },
        ].map((e, i) => (
          <div key={i} style={{
            position: "absolute", width: 2, height: 2, borderRadius: "50%",
            background: "rgba(255,230,80,0.95)",
            bottom: "28%", left: e.left,
            boxShadow: "0 0 4px 1px rgba(255,170,0,0.7)",
            animation: `ember ${e.dur} ${e.delay} ease-out infinite`,
          }} />
        ))}
      </div>
    </>
  );
};

// ─── FIRE SPREAD ZONE — 3x3 grid for molotov/incendiary ───────────────────────
// Each fire zone is ~100x100 game units, spread in a grid pattern
const FireSpreadGrid = ({ x, y, mapData, imgSize, isActive }) => {
  if (!imgSize || !imgSize.w) return null;

  const iw = imgSize.w;
  const ih = imgSize.h;
  const ml = imgSize.ml ?? 0;
  const mt = imgSize.mt ?? 0;

  // Fire zone unit size in pixels (≈100 units per zone)
  const zoneSizePx = radiusToPx(100, iw, mapData.scale);

  // 3x3 grid positions: offset from center (-1, 0, 1)
  const offsets = [
    [-1, -1], [0, -1], [1, -1],
    [-1,  0], [0,  0], [1,  0],
    [-1,  1], [0,  1], [1,  1],
  ];

  const basePos = getRadarPosition(mapData, { x, y });
  if (!basePos) return null;

  const baseX = ml + iw * basePos.x;
  const baseY = mt + ih * basePos.y;

  // Grid sizing reduced to match smoke overlay size (~92px at 1024px width)
  const CELL_MULT = 0.9;
  const SPACE_MULT = 0.5;

  return (
    <>
      {offsets.map(([dx, dy], i) => (
        <div
          key={i}
          className={`absolute pointer-events-none ${isActive ? 'fire-overlay' : ''}`}
          style={{
            width: zoneSizePx * CELL_MULT,
            height: zoneSizePx * CELL_MULT,
            left: baseX + dx * zoneSizePx * SPACE_MULT - zoneSizePx * SPACE_MULT,
            top: baseY + dy * zoneSizePx * SPACE_MULT - zoneSizePx * SPACE_MULT,
            zIndex: 115,
            opacity: isActive ? 1 : 0.4,
            transition: "opacity 0.3s ease",
          }}
        >
          {/* Fire zone fill - orange/red gradient */}
          <div style={{
            position: "absolute",
            inset: 0,
            borderRadius: "20%",
            background: isActive
              ? "radial-gradient(ellipse, rgba(255,140,0,0.7) 0%, rgba(230,70,0,0.5) 50%, rgba(180,30,0,0.25) 80%, transparent 100%)"
              : "rgba(100,40,0,0.3)",
            animation: isActive ? `fireZonePulse ${1 + (i % 3) * 0.2}s ease-in-out infinite` : "none",
          }}>
            <style>{`
              @keyframes fireZonePulse {
                0%, 100% { opacity: 0.75; transform: scale(0.98); }
                50% { opacity: 1; transform: scale(1.02); }
              }
            `}</style>
          </div>
          {/* Border */}
          <div style={{
            position: "absolute",
            inset: 0,
            borderRadius: "20%",
            border: isActive ? "2px solid rgba(255,140,0,0.8)" : "1px solid rgba(255,100,0,0.3)",
            boxShadow: isActive ? "0 0 10px rgba(255,100,0,0.5)" : "none",
          }} />
        </div>
      ))}
    </>
  );
};

// ─── Config per type ──────────────────────────────────────────────────────────
const CFG = {
  smoke:      { dotColor: "#94a3b8", border: "rgba(148,163,184,0.7)", auraRadius: 160, label: "SMK", trajectory: "#64748b" },
  flashbang:  { dotColor: "#fef08a", border: "rgba(254,240,138,0.8)", auraRadius: 0,   label: "FLB", trajectory: "#fde047" },
  he:         { dotColor: "#fb923c", border: "rgba(251,146,60,0.8)",  auraRadius: 0,   label: "HE",  trajectory: "#fb923c" },
  molotov:    { dotColor: "#ef4444", border: "rgba(239,68,68,0.8)",   auraRadius: 120, label: "MOL", trajectory: "#dc2626" },
  incendiary: { dotColor: "#ef4444", border: "rgba(239,68,68,0.8)",   auraRadius: 150, label: "INC", trajectory: "#dc2626" },
  decoy:      { dotColor: "#a78bfa", border: "rgba(167,139,250,0.8)", auraRadius: 0,   label: "DCY", trajectory: "#8b5cf6" },
  inferno:    { dotColor: "#f97316", border: "rgba(249,115,22,0.9)",  auraRadius: 120, label: "FIRE", trajectory: "#f97316"},
};

const Grenade = ({ grenadeData, mapData, imgSize, settings }) => {
  if (!grenadeData || !mapData) return null;
  if (settings && !settings.showGrenades) return null;

  const type = grenadeData.type;
  const cfg  = CFG[type];
  if (!cfg) return null;

  // Calculate position - support both old and new data formats
  let posX = grenadeData.x;
  let posY = grenadeData.y;

  // Try inferno positions if available (fire spread positions)
  if (type === "inferno" && grenadeData.m_x !== undefined && grenadeData.m_y !== undefined) {
    posX = grenadeData.m_x;
    posY = grenadeData.m_y;
  }

  const radarPos = getRadarPosition(mapData, { x: posX, y: posY });
  if (!radarPos || (radarPos.x <= 0 && radarPos.y <= 0)) return null;

  const iw = imgSize?.w || 0;
  const ih = imgSize?.h || 0;
  const ml = imgSize?.ml ?? 0;
  const mt = imgSize?.mt ?? 0;

  if (!iw || !ih) return null;

  const tx = ml + iw * radarPos.x;
  const ty = mt + ih * radarPos.y;

  // ─── Read velocity data for trajectory calculation ─────────────────────────
  const vx = grenadeData.vx || grenadeData.v_x || 0;
  const vy = grenadeData.vy || grenadeData.v_y || 0;
  const hasVelocity = Math.abs(vx) > 1 || Math.abs(vy) > 1; // Only show trajectory if moving

  // ─── Determine if grenade is in flight or deployed ────────────────────────
  // Grenades in flight have velocity, deployed effects don't (they're static)
  const isInFlight = type !== "inferno" && type !== "smoke" && hasVelocity;

  // ─── SMOKE: show smoke cloud when grenade is deployed (not just when in flight) ───
  // Show smoke cloud when: grenade exists AND (smoke_effect OR just deployed)
  // In CS2, smoke grenade becomes visible immediately after landing
  const smokeDeployed = type === "smoke" && (
    grenadeData.m_did_smoke_effect ||
    grenadeData.m_is_deployed ||
    // Fallback: show smoke if grenade type is smoke and has valid position
    grenadeData.m_nade_type === 4
  );

  const showSmoke  = smokeDeployed && (settings?.showSmoke !== false);
  const showFire   = type === "inferno" && (settings?.showFire !== false);
  const showDot    = !showSmoke && !showFire; // Don't show dot when smoke/fire effect is active
  const isDecoyActive = type === "decoy" && grenadeData.m_is_active;

  // Fire spread states: molotov/incendiary can spread to 3x3 grid
  const isFireActive = type === "inferno" || type === "molotov" || type === "incendiary";
  const fireSpreadData = parseFirePositions(grenadeData.m_fire_positions);

  const diamPx = radiusToPx(cfg.auraRadius, iw, mapData.scale);

  return (
    <>
      {/* ─── TRAJECTORY LINE (disabled — too cluttered) ─── */}
      {false && isInFlight && (
        <TrajectoryLine
          grenadeData={{
            type: type,
            x: posX,
            y: posY,
            vx: vx,
            vy: vy,
            m_land_x: grenadeData.m_land_x ?? null,
            m_land_y: grenadeData.m_land_y ?? null,
            m_trajectory: grenadeData.m_trajectory ?? null,
            m_has_trajectory: grenadeData.m_has_trajectory ?? false,
          }}
          mapData={mapData}
          imgSize={imgSize}
          settings={settings}
        />
      )}

      {/* ─── FIRE SPREAD ZONES (3x3 grid for molotov/incendiary) ─── */}
      {/* FireSpreadGrid renders grid at each fire position from m_fire_positions + center */}
      {isFireActive && showFire && fireSpreadData.length > 0 && fireSpreadData.map((pos, idx) => (
        <FireSpreadGrid
          key={`fire-${idx}`}
          x={pos.x} y={pos.y}
          mapData={mapData}
          imgSize={imgSize}
          isActive={true}
        />
      ))}

      {/* Primary zone grid — only show when fireSpreadData is empty (fallback) */}
      {isFireActive && showFire && fireSpreadData.length === 0 && diamPx > 0 && (
        <FireSpreadGrid x={posX} y={posY} mapData={mapData} imgSize={imgSize} isActive={true} />
      )}

      {/* ─── Fire time countdown ─── */}
      {showFire && grenadeData.m_fire_time_left != null && (
        <div className="absolute pointer-events-none"
          style={{ left: tx, top: ty - diamPx * 0.7, transform: "translateX(-50%)", zIndex: 125 }}>
          <div style={{
            background: "rgba(0,0,0,0.7)", border: "1px solid rgba(255,130,0,0.65)",
            borderRadius: 4, padding: "2px 7px", fontSize: 11, fontWeight: 900,
            color: "#fb923c", fontFamily: "monospace", letterSpacing: "0.04em",
            whiteSpace: "nowrap", boxShadow: "0 0 8px rgba(255,100,0,0.4)",
          }}>
            FIRE {Number(grenadeData.m_fire_time_left).toFixed(1)}s
          </div>
        </div>
      )}

      {/* ─── SMOKE CLOUD ─── */}
      <div
        className="absolute pointer-events-none"
        style={{
          left: tx,
          top: ty,
          zIndex: 120,
        }}
      >
        {showSmoke && diamPx > 0 && <SmokeEffect diameter={diamPx} timeLeft={grenadeData.m_smoke_time_left ?? null} />}

        {/* SMOKE PROJECTILE - show dot in flight */}
        {smokeDeployed && showDot && (
          <div style={{
            width: 14, height: 14, borderRadius: "50%",
            background: cfg.dotColor,
            border: `2px solid ${cfg.border}`,
            boxShadow: `0 0 8px ${cfg.dotColor}, 0 0 3px rgba(0,0,0,0.9)`,
            position: "relative",
            zIndex: 2,
          }} />
        )}

        {/* GRENADE DOTS — show for all flying projectiles, including molotov/incendiary.
            For inferno (deployed fire) and deployed smoke, the effect renders instead. */}
        {!showSmoke && !showFire && type !== "inferno" && (
          <>
            <div style={{
              width: 14, height: 14, borderRadius: "50%",
              background: cfg.dotColor,
              border: `2px solid ${cfg.border}`,
              boxShadow: `0 0 8px ${cfg.dotColor}, 0 0 3px rgba(0,0,0,0.9)`,
              position: "relative",
              zIndex: 2,
            }} />
          </>
        )}

        {/* Decoy ping ring */}
        {isDecoyActive && (
          <>
            <style>{`@keyframes decoyPing{0%{transform:translate(-50%,-50%)scale(1);opacity:.8}100%{transform:translate(-50%,-50%)scale(2.5);opacity:0}}`}</style>
            <div style={{
              position: "absolute", width: 32, height: 32, left: "50%", top: "50%",
              transform: "translate(-50%, -50%)", borderRadius: "50%",
              border: `2px solid ${cfg.border}`,
              animation: "decoyPing 1.2s ease-out infinite",
            }} />
          </>
        )}
      </div>
    </>
  );
};

export default Grenade;