// MapHUD — Türkiye haritası, tıklanabilir şehirler.
// Default: temiz harita, sadece pulsing şehir noktaları.
// Şehre tık → o şehrin layer'ları (MARKET / QUAKE / WX / NEWS / FIRE / SAT) açılır.
// "Tüm Türkiye" görünümüne dönmek için ESC ya da haritada boş yere tık.

const CITIES = [
  // x/y in 0..100 of map viewBox (Türkiye envelope).
  // Konya = HQ (amber, always lit).
  { id: "KON", name: "KONYA",     hq: true,  x: 49.5, y: 60,  divisions: ["MTR", "EML", "SYS"], pop: "2.27M" },
  { id: "IST", name: "İSTANBUL",  hq: false, x: 36,   y: 22,  divisions: ["MTR", "SYS"],        pop: "15.8M" },
  { id: "ANK", name: "ANKARA",    hq: false, x: 53,   y: 38,  divisions: ["SYS"],               pop: "5.78M" },
  { id: "IZM", name: "İZMİR",     hq: false, x: 22,   y: 52,  divisions: ["MTR", "EML"],        pop: "4.48M" },
  { id: "ANT", name: "ANTALYA",   hq: false, x: 42,   y: 78,  divisions: ["EML"],               pop: "2.69M" },
  { id: "BUR", name: "BURSA",     hq: false, x: 33,   y: 32,  divisions: ["MTR"],               pop: "3.21M" },
  { id: "ADN", name: "ADANA",     hq: false, x: 64,   y: 70,  divisions: ["MTR"],               pop: "2.27M" },
  { id: "GAZ", name: "GAZİANTEP", hq: false, x: 73,   y: 68,  divisions: ["EML"],               pop: "2.15M" },
  { id: "TRA", name: "TRABZON",   hq: false, x: 78,   y: 26,  divisions: ["SYS"],               pop: "0.81M" },
  { id: "DBK", name: "DİYARBAKIR",hq: false, x: 82,   y: 56,  divisions: ["EML"],               pop: "1.80M" },
  { id: "ESK", name: "ESKİŞEHİR", hq: false, x: 41,   y: 36,  divisions: ["MTR"],               pop: "0.91M" },
  { id: "VAN", name: "VAN",       hq: false, x: 92,   y: 50,  divisions: ["SYS"],               pop: "1.13M" },
];

// Türkiye envelope (rough): lon 26-45 → x 0-100, lat 36-42 → y 100-0.
// Stylized landmass path (not topographic; recognizable silhouette).
const TR_PATH = "M3,52 L8,42 L14,38 L20,40 L26,44 L30,40 L36,18 L44,16 L52,22 L60,18 L68,24 L76,20 L86,22 L94,28 L98,40 L96,52 L94,62 L88,72 L80,76 L72,80 L62,82 L52,86 L42,90 L32,86 L22,80 L14,72 L8,62 Z";

const LAYER_DEFS = [
  { key: "MKT",  label: "MARKET",   color: "var(--amber)",     desc: "Borsa & FX feed",  unit: "BIST" },
  { key: "EQ",   label: "QUAKE",    color: "var(--alert)",     desc: "Sismik · USGS",     unit: "M3.2" },
  { key: "WX",   label: "WEATHER",  color: "var(--wire-cyan)", desc: "Hava · wttr",       unit: "12°C" },
  { key: "NEWS", label: "NEWS",     color: "var(--bone-soft)", desc: "GDELT akışı",       unit: "47" },
  { key: "FIRE", label: "FIRE",     color: "var(--alert)",     desc: "Yangın · FIRMS",    unit: "0" },
  { key: "SAT",  label: "SAT",      color: "var(--phosphor)",  desc: "Uydu görüntü",      unit: "z14" },
];

// Per-city snapshot data (illustrative — production: live feeds).
const CITY_DATA = {
  KON: { MKT: "BIST 9,847 ▼0.42%", EQ: "—",        WX: "8°C · clear",  NEWS: "12 · low",  FIRE: "0",     SAT: "z14 · 14:32" },
  IST: { MKT: "BIST 9,847 ▼0.42%", EQ: "M2.1 ESE",  WX: "11°C · rain",  NEWS: "84 · high", FIRE: "0",     SAT: "z13 · 14:31" },
  ANK: { MKT: "—",                  EQ: "—",        WX: "5°C · clear",  NEWS: "31 · med",  FIRE: "0",     SAT: "z14 · 14:30" },
  IZM: { MKT: "—",                  EQ: "M2.8 W",   WX: "14°C · windy", NEWS: "22 · med",  FIRE: "1 · F03", SAT: "z13 · 14:29" },
  ANT: { MKT: "—",                  EQ: "—",        WX: "17°C · clear", NEWS: "9 · low",   FIRE: "2 · F11", SAT: "z14 · 14:28" },
  BUR: { MKT: "—",                  EQ: "M2.2 N",   WX: "9°C · cloud",  NEWS: "11 · low",  FIRE: "0",     SAT: "z13 · 14:27" },
  ADN: { MKT: "—",                  EQ: "—",        WX: "16°C · clear", NEWS: "14 · low",  FIRE: "0",     SAT: "z13 · 14:26" },
  GAZ: { MKT: "—",                  EQ: "M3.0 SE",  WX: "13°C · cloud", NEWS: "27 · med",  FIRE: "0",     SAT: "z13 · 14:25" },
  TRA: { MKT: "—",                  EQ: "—",        WX: "10°C · rain",  NEWS: "8 · low",   FIRE: "0",     SAT: "z13 · 14:24" },
  DBK: { MKT: "—",                  EQ: "M2.6 E",   WX: "12°C · clear", NEWS: "19 · med",  FIRE: "0",     SAT: "z13 · 14:23" },
  ESK: { MKT: "—",                  EQ: "—",        WX: "6°C · cloud",  NEWS: "5 · low",   FIRE: "0",     SAT: "z13 · 14:22" },
  VAN: { MKT: "—",                  EQ: "M3.4 NE",  WX: "2°C · snow",   NEWS: "11 · low",  FIRE: "0",     SAT: "z13 · 14:21" },
};

const MapHUD = () => {
  const [active, setActive] = React.useState(null); // city id
  const [hover, setHover] = React.useState(null);
  const [pulse, setPulse] = React.useState(0);

  React.useEffect(() => {
    const onKey = e => { if (e.key === "Escape") setActive(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  React.useEffect(() => {
    const i = setInterval(() => setPulse(p => (p + 1) % CITIES.length), 320);
    return () => clearInterval(i);
  }, []);

  const activeCity = CITIES.find(c => c.id === active);

  return (
    <div style={{
      position: "relative", height: "100%", minHeight: 360,
      background: "radial-gradient(ellipse at 50% 55%, #0F1A22 0%, #060A0F 65%, #05070A 100%)",
      overflow: "hidden",
      cursor: active ? "default" : "crosshair",
    }} onClick={() => setActive(null)}>
      {/* fine grid */}
      <div style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        backgroundImage: `linear-gradient(to right, rgba(31,42,54,.45) 1px, transparent 1px),
                          linear-gradient(to bottom, rgba(31,42,54,.45) 1px, transparent 1px)`,
        backgroundSize: "48px 48px",
      }} />

      {/* Türkiye landmass */}
      <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        <defs>
          <radialGradient id="hqRadial">
            <stop offset="0%" stopColor="rgba(255,176,0,.55)"/>
            <stop offset="100%" stopColor="rgba(255,176,0,0)"/>
          </radialGradient>
          <radialGradient id="cityRadial">
            <stop offset="0%" stopColor="rgba(124,213,255,.45)"/>
            <stop offset="100%" stopColor="rgba(124,213,255,0)"/>
          </radialGradient>
          <pattern id="landTex" width="2" height="2" patternUnits="userSpaceOnUse">
            <rect width="2" height="2" fill="#0B1218"/>
            <circle cx="0.5" cy="0.5" r="0.08" fill="#1F2A36"/>
          </pattern>
        </defs>

        <path d={TR_PATH} fill="url(#landTex)" stroke="rgba(124,213,255,.35)" strokeWidth=".25"/>
        <path d={TR_PATH} fill="none" stroke="rgba(255,176,0,.12)" strokeWidth=".6"/>

        {/* lat/lon graticule (light) */}
        {[20,40,60,80].map(x => (
          <line key={"vx"+x} x1={x} y1="0" x2={x} y2="100" stroke="rgba(31,42,54,.6)" strokeWidth=".08" strokeDasharray=".5 .5"/>
        ))}
        {[20,40,60,80].map(y => (
          <line key={"hy"+y} x1="0" y1={y} x2="100" y2={y} stroke="rgba(31,42,54,.6)" strokeWidth=".08" strokeDasharray=".5 .5"/>
        ))}

        {/* connection wires (only when a city is active, drawn from HQ) */}
        {active && active !== "KON" && activeCity && (
          <line x1="49.5" y1="60" x2={activeCity.x} y2={activeCity.y}
            stroke="rgba(255,176,0,.55)" strokeWidth=".18" strokeDasharray="1 .6">
            <animate attributeName="stroke-dashoffset" from="0" to="3" dur="1.6s" repeatCount="indefinite"/>
          </line>
        )}

        {/* city nodes */}
        {CITIES.map((c, i) => {
          const isActive = c.id === active;
          const isHover = c.id === hover;
          const lit = c.hq || isActive || isHover || (i % CITIES.length) === pulse;
          const r = c.hq ? 1.3 : (isActive ? 1.1 : 0.75);
          const color = c.hq ? "var(--amber)" : (isActive ? "var(--amber)" : "var(--wire-cyan)");
          return (
            <g key={c.id}
              style={{ cursor: "pointer" }}
              onClick={(e) => { e.stopPropagation(); setActive(c.id); }}
              onMouseEnter={() => setHover(c.id)}
              onMouseLeave={() => setHover(null)}>
              {/* glow */}
              {(c.hq || isActive) && <circle cx={c.x} cy={c.y} r="6" fill={c.hq ? "url(#hqRadial)" : "url(#hqRadial)"}/>}
              {!c.hq && <circle cx={c.x} cy={c.y} r="4.5" fill="url(#cityRadial)" opacity={lit ? 0.8 : 0.25}/>}
              {/* pulse ring */}
              {(c.hq || isActive) && (
                <circle cx={c.x} cy={c.y} r={r} fill="none" stroke={color} strokeWidth=".18">
                  <animate attributeName="r" from={r} to={r + 4} dur="2s" repeatCount="indefinite"/>
                  <animate attributeName="opacity" from="1" to="0" dur="2s" repeatCount="indefinite"/>
                </circle>
              )}
              {/* core dot */}
              <circle cx={c.x} cy={c.y} r={r} fill={color}/>
              {/* invisible bigger hit area */}
              <circle cx={c.x} cy={c.y} r="3.5" fill="transparent"/>
              {/* label */}
              {(c.hq || isActive || isHover) && (
                <text x={c.x + 1.8} y={c.y + 0.6}
                  fontFamily="var(--font-mono)" fontSize="2.2"
                  fill={c.hq || isActive ? "var(--amber)" : "var(--bone)"}
                  letterSpacing=".15">
                  {c.name}{c.hq ? " · HQ" : ""}
                </text>
              )}
            </g>
          );
        })}
      </svg>

      {/* scan sweep */}
      <div style={{
        position: "absolute", left: 0, right: 0, height: 80,
        background: "linear-gradient(to bottom, transparent, rgba(124,213,255,.10), transparent)",
        animation: "sweep 8s linear infinite", pointerEvents: "none",
      }} />
      <style>{`@keyframes sweep { 0% { top: -80px; } 100% { top: 100%; } }`}</style>

      {/* corner labels */}
      <span style={{ position: "absolute", top: 8, left: 10, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ash-deep)", letterSpacing: ".16em", pointerEvents: "none" }}>
        SAT_LAYER · TR · z6 · 1:2,500,000
      </span>
      <span style={{ position: "absolute", bottom: 8, left: 10, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ash-deep)", letterSpacing: ".16em", pointerEvents: "none" }}>
        SCALE · 0————500KM
      </span>
      <span style={{ position: "absolute", bottom: 8, right: 10, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ash-deep)", letterSpacing: ".16em", pointerEvents: "none" }}>
        {active ? "ESC · DEAKTİVE / DESELECT" : `${CITIES.length} ŞEHİR · TIKLA`}
      </span>

      {/* hint when nothing selected */}
      {!active && (
        <div style={{
          position: "absolute", left: "50%", top: 60, transform: "translateX(-50%)",
          fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--amber)",
          letterSpacing: ".18em", textTransform: "uppercase",
          background: "rgba(10,14,19,.85)", border: "1px solid var(--amber)",
          padding: "6px 14px", pointerEvents: "none",
        }}>
          ŞEHRE TIKLA · LAYER'LARI AÇ
        </div>
      )}

      {/* layer overlay panel — shown only when a city is active */}
      {active && activeCity && (
        <div onClick={(e) => e.stopPropagation()} style={{
          position: "absolute", right: 16, top: 50, width: 280, zIndex: 5,
          background: "rgba(10,14,19,.95)", border: "1px solid var(--amber)",
          boxShadow: "0 0 24px rgba(255,176,0,.18)",
          fontFamily: "var(--font-mono)",
        }}>
          <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--edge)", display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ color: "var(--amber)", fontSize: 11, fontWeight: 700, letterSpacing: ".12em" }}>
              {activeCity.name}{activeCity.hq ? " · HQ" : ""}
            </span>
            <span style={{ color: "var(--ash-deep)", fontSize: 9, marginLeft: "auto" }}>POP {activeCity.pop}</span>
            <button onClick={() => setActive(null)} style={{
              background: "none", border: "none", color: "var(--ash)",
              cursor: "pointer", fontSize: 14, padding: 0, marginLeft: 4,
            }}>×</button>
          </div>
          <div style={{ padding: "6px 12px 4px", borderBottom: "1px solid var(--edge)", fontSize: 9, color: "var(--ash-deep)", letterSpacing: ".12em" }}>
            DİVİZYON · {activeCity.divisions.map(d => `DIV.${d}`).join(" · ")}
          </div>
          <div style={{ padding: "6px 0" }}>
            {LAYER_DEFS.map(L => {
              const val = CITY_DATA[active]?.[L.key] || "—";
              const muted = val === "—";
              return (
                <div key={L.key} style={{
                  display: "grid", gridTemplateColumns: "60px 1fr auto",
                  gap: 8, padding: "4px 12px", fontSize: 10, alignItems: "center",
                  borderTop: "1px dashed var(--edge)",
                }}>
                  <span style={{ color: muted ? "var(--ash-deep)" : L.color, fontWeight: 700, letterSpacing: ".14em" }}>{L.label}</span>
                  <span style={{ color: muted ? "var(--ash-deep)" : "var(--bone)", fontFeatureSettings: '"tnum" 1' }}>{val}</span>
                  <span style={{ color: "var(--ash-deep)", fontSize: 8, letterSpacing: ".12em" }}>{L.desc}</span>
                </div>
              );
            })}
          </div>
          <div style={{ padding: "6px 12px", borderTop: "1px solid var(--edge)", fontSize: 9, color: "var(--ash-deep)", letterSpacing: ".12em", display: "flex", gap: 6 }}>
            <span>↳ DRILL</span>
            <span style={{ color: "var(--amber)" }}>SAT</span>
            <span>·</span>
            <span style={{ color: "var(--amber)" }}>LEDGER</span>
            <span>·</span>
            <span style={{ color: "var(--amber)" }}>INTEL</span>
          </div>
        </div>
      )}
    </div>
  );
};

window.MapHUD = MapHUD;
