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

// ─── Normalize fire position data (backend sends [[fx,fy],...] or [{x,y},...]) ─
const parseFirePositions = (raw) => {
  if (!raw || !Array.isArray(raw)) 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 OVERLAY — multi-blob animated cloud with time countdown ─────────────
// Pass either imgSize (for radar context) or use inline bounds.height/w for sizing.
export const SmokeOverlay = ({ smokeData, mapData, imgSize }) => {
  if (!smokeData || !mapData) return null;

  const position = { x: smokeData.x ?? smokeData.m_x, y: smokeData.y ?? smokeData.m_y };
  if (!position.x && !position.y) return null;

  const radarPos = getRadarPosition(mapData, position);
  if (!radarPos || radarPos.x <= 0 || radarPos.y <= 0) return null;

  const rw = imgSize?.w ?? imgSize?.width ?? 500;
  const rh = imgSize?.h ?? imgSize?.height ?? 500;
  const ml = imgSize?.ml ?? 0;
  const mt = imgSize?.mt ?? 0;
  if (!rw || !rh) return null;

  const tx = ml + rw * radarPos.x;
  const ty = mt + rh * radarPos.y;
  const diamPx = Math.max(50, rw * 0.11); // smoke cloud ~176 units
  const timeLeft = smokeData.m_smoke_time_left ?? smokeData.smoke_time_left ?? null;
  const countdown = timeLeft != null ? Number(timeLeft).toFixed(1) : null;

  return (
    <>
      <style>{`
        @keyframes smokeRotate2 { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
        @keyframes smokePulse2  { 0%,100%{opacity:.8;transform:scale(1)} 50%{opacity:.95;transform:scale(1.04)} }
        @keyframes smokeBlobA   { 0%,100%{transform:translate(0,0)} 50%{transform:translate(6px,-5px)} }
        @keyframes smokeBlobB   { 0%,100%{transform:translate(0,0)} 50%{transform:translate(-5px,6px)} }
        @keyframes smokeBlobC   { 0%,100%{transform:translate(0,0)} 50%{transform:translate(4px,4px)} }
        @keyframes smokeBlobD   { 0%,100%{transform:translate(0,0)} 50%{transform:translate(-4px,-4px)} }
      `}</style>
      <div
        className="absolute pointer-events-none"
        style={{ left: tx, top: ty, transform: "translate(-50%,-50%)", zIndex: 115 }}
      >
        {/* Smoke cloud container */}
        <div style={{
          position: "relative", width: diamPx, height: diamPx,
          borderRadius: "50%",
        }}>
          {/* Rotating ring */}
          <div style={{
            position: "absolute", inset: 0, borderRadius: "50%",
            border: "2px solid rgba(200,210,220,0.5)",
            boxShadow: "0 0 14px rgba(180,190,200,0.3), inset 0 0 20px rgba(180,190,200,0.12)",
            animation: "smokeRotate2 20s linear infinite",
          }} />
          {/* Inner radial gradient cloud */}
          <div style={{
            position: "absolute", inset: "4%", borderRadius: "50%",
            background: "radial-gradient(circle at 50% 50%, rgba(215,225,233,0.88) 0%, rgba(192,206,218,0.80) 35%, rgba(165,180,192,0.68) 65%, rgba(130,145,158,0.40) 85%, transparent 100%)",
            backdropFilter: "blur(2px)",
            animation: "smokePulse2 4.5s ease-in-out infinite",
          }} />
          {/* Blob sub-element A */}
          <div style={{
            position: "absolute", width: "48%", height: "48%", top: "15%", left: "26%",
            borderRadius: "50%",
            background: "radial-gradient(circle, rgba(230,240,248,0.72) 0%, rgba(210,222,232,0.48) 50%, transparent 100%)",
            animation: "smokeBlobA 5.5s ease-in-out infinite",
          }} />
          {/* Blob sub-element B */}
          <div style={{
            position: "absolute", width: "44%", height: "44%", bottom: "10%", right: "10%",
            borderRadius: "50%",
            background: "radial-gradient(circle, rgba(200,212,224,0.64) 0%, rgba(165,178,190,0.38) 55%, transparent 100%)",
            animation: "smokeBlobB 6.5s ease-in-out infinite",
          }} />
          {/* Blob sub-element C */}
          <div style={{
            position: "absolute", width: "40%", height: "40%", top: "30%", right: "8%",
            borderRadius: "50%",
            background: "radial-gradient(circle, rgba(205,215,226,0.60) 0%, transparent 70%)",
            animation: "smokeBlobC 5s ease-in-out infinite",
          }} />
          {/* Blob sub-element D */}
          <div style={{
            position: "absolute", width: "36%", height: "36%", bottom: "16%", left: "8%",
            borderRadius: "50%",
            background: "radial-gradient(circle, rgba(195,207,218,0.55) 0%, transparent 70%)",
            animation: "smokeBlobD 7s ease-in-out infinite",
          }} />
          {/* Center icon */}
          <div style={{
            position: "absolute", top: "50%", left: "50%",
            transform: "translate(-50%,-50%)",
            fontSize: Math.max(8, diamPx * 0.13),
            fontWeight: 900, color: "rgba(70,80,90,0.85)",
            textShadow: "0 1px 3px rgba(255,255,255,0.6)",
            letterSpacing: "0.06em", lineHeight: 1,
            pointerEvents: "none", zIndex: 3,
          }}>
            {countdown != null ? `SMK ${countdown}s` : "SMK"}
          </div>
        </div>
      </div>
    </>
  );
};

// ─── INFERNO OVERLAY — multi-zone fire spread with time countdown ─────────────
// Renders each burning zone from m_fire_positions as a fire blob on the radar.
// Also renders the primary inferno center position.
export const InfernoOverlay = ({ infernoData, mapData, imgSize }) => {
  if (!infernoData || !mapData) return null;

  const primaryPos = { x: infernoData.x ?? infernoData.m_x, y: infernoData.y ?? infernoData.m_y };
  const rawPositions = infernoData.m_fire_positions ?? infernoData.fire_positions ?? [];
  const firePositions = parseFirePositions(rawPositions);
  const timeLeft = infernoData.m_fire_time_left ?? infernoData.fire_time_left ?? null;
  const countdown = timeLeft != null ? Number(timeLeft).toFixed(1) : null;

  const rw = imgSize?.w ?? imgSize?.width ?? 500;
  const rh = imgSize?.h ?? imgSize?.height ?? 500;
  const ml = imgSize?.ml ?? 0;
  const mt = imgSize?.mt ?? 0;
  if (!rw || !rh) return null;

  // Fire zone radius in pixels
  const zoneDiamPx = Math.max(16, rw * 0.016);

  // Use a set to deduplicate primary + spread positions
  const seen = new Set();
  const uniquePositions = [];
  if (primaryPos?.x || primaryPos?.y) {
    const key = `${primaryPos.x?.toFixed(1)},${primaryPos.y?.toFixed(1)}`;
    if (!seen.has(key)) { seen.add(key); uniquePositions.push(primaryPos); }
  }
  for (const pos of firePositions) {
    const key = `${pos.x?.toFixed(1)},${pos.y?.toFixed(1)}`;
    if (!seen.has(key)) { seen.add(key); uniquePositions.push(pos); }
  }
  if (uniquePositions.length === 0) return null;

  return (
    <>
      <style>{`
        @keyframes fireGlow2   { from{opacity:.7;transform:scale(0.92)} to{opacity:1;transform:scale(1.06)} }
        @keyframes fireRing2   { 0%{transform:translate(-50%,-50%)scale(1);opacity:.55} 100%{transform:translate(-50%,-50%)scale(1.7);opacity:0} }
        @keyframes firePulse2  { 0%,100%{opacity:.75} 50%{opacity:1} }
      `}</style>
      {uniquePositions.map((pos, idx) => {
        const radarPos = getRadarPosition(mapData, pos);
        if (!radarPos || radarPos.x <= 0 || radarPos.y <= 0) return null;
        const tx = ml + rw * radarPos.x;
        const ty = mt + rh * radarPos.y;

        return (
          <div
            key={`inferno-${idx}-${pos.x?.toFixed(0)}`}
            className="absolute pointer-events-none"
            style={{ left: tx, top: ty, transform: "translate(-50%,-50%)", zIndex: 115 }}
          >
            {/* Expanding ring */}
            <div style={{
              position: "absolute", width: zoneDiamPx * 2, height: zoneDiamPx * 2,
              left: "50%", top: "50%", borderRadius: "50%",
              border: "2px solid rgba(255,140,0,0.65)",
              animation: "fireRing2 1.2s ease-out infinite",
              animationDelay: `${idx * 150}ms`,
            }} />
            {/* Glow fill */}
            <div style={{
              position: "absolute", width: zoneDiamPx, height: zoneDiamPx,
              left: "50%", top: "50%", borderRadius: "50%",
              background: "radial-gradient(circle, rgba(255,130,0,0.75) 0%, rgba(220,60,0,0.55) 40%, rgba(180,30,0,0.30) 70%, transparent 90%)",
              boxShadow: `0 0 ${zoneDiamPx * 0.5}px ${zoneDiamPx * 0.25}px rgba(255,90,0,0.35)`,
              animation: "fireGlow2 1.3s ease-in-out infinite alternate",
              animationDelay: `${idx * 80}ms`,
            }} />
            {/* Fire emoji indicator */}
            <div style={{
              position: "absolute", top: "50%", left: "50%",
              transform: "translate(-50%,-50%)",
              fontSize: Math.max(8, zoneDiamPx * 0.6),
              animation: "firePulse2 1.8s ease-in-out infinite",
              filter: "drop-shadow(0 0 4px rgba(255,100,0,0.8))",
            }}>🔥</div>
          </div>
        );
      })}

      {/* ── Fire time countdown label — placed above the first zone ── */}
      {uniquePositions.length > 0 && countdown != null && (() => {
        const firstPos = uniquePositions[0];
        const frp = getRadarPosition(mapData, firstPos);
        if (!frp || frp.x <= 0 || frp.y <= 0) return null;
        const lx = ml + rw * frp.x;
        const ly = mt + rh * frp.y;
        return (
          <div className="absolute pointer-events-none"
            style={{ left: lx, top: ly - zoneDiamPx * 1.4, transform: "translateX(-50%)", zIndex: 125 }}>
            <div style={{
              background: "rgba(0,0,0,0.72)", border: "1px solid rgba(255,130,0,0.75)",
              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 {countdown}s
            </div>
          </div>
        );
      })()}
    </>
  );
};