/* global React, d3, topojson, iraqTopology, IRAQ_CITIES */
// Iraq map — uses d3-geo + topojson-client (loaded as UMD globals from unpkg).
// Mirrors apps/admin/components/IraqMap.tsx so the demo projection matches
// the real platform. Branches are lit by activity intensity; no animated pulses.

function IraqMap({ width = 420, height = 460, branches = [] }) {
  const { pathD, cities } = React.useMemo(() => {
    const geo = topojson.feature(window.iraqTopology, window.iraqTopology.objects.iraq);
    const projection = d3.geoMercator().fitSize([width - 20, height - 20], geo);
    const pathBuilder = d3.geoPath(projection);
    const d = pathBuilder(geo) ?? '';
    const round = (n) => Math.round(n * 100) / 100;
    const positions = window.IRAQ_CITIES.map((c) => {
      const p = projection([c.lon, c.lat]);
      return { ...c, x: p ? round(p[0] + 10) : 0, y: p ? round(p[1] + 10) : 0 };
    });
    return { pathD: d, cities: positions };
  }, [width, height]);

  const branchByCity = React.useMemo(() => {
    const m = new Map();
    for (const b of branches) m.set(b.cityCode, b);
    return m;
  }, [branches]);

  const bgw = cities.find((c) => c.code === 'BGW');

  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{display:'block'}} role="img" aria-label="Iraq map">
      <defs>
        <radialGradient id="iraq-intensity">
          <stop offset="0%" stopColor="#c6a15b" stopOpacity="0.5"/>
          <stop offset="60%" stopColor="#c6a15b" stopOpacity="0.12"/>
          <stop offset="100%" stopColor="#c6a15b" stopOpacity="0"/>
        </radialGradient>
      </defs>
      <path d={pathD} fill="#12151c" stroke="#353c4b" strokeWidth={1} strokeLinejoin="round"/>
      <path d={pathD} fill="none" stroke="#c6a15b" strokeOpacity={0.08} strokeWidth={6} strokeLinejoin="round"/>
      {bgw && cities.filter((c) => c.code !== 'BGW' && branchByCity.get(c.code)?.active).map((c) => (
        <line key={'l'+c.code} x1={bgw.x} y1={bgw.y} x2={c.x} y2={c.y} stroke="#c6a15b" strokeOpacity={0.3} strokeWidth={1} strokeDasharray="3 3"/>
      ))}
      {cities.map((c) => {
        const b = branchByCity.get(c.code);
        const active = !!b?.active;
        const intensity = b?.intensity ?? 0.5;
        return (
          <g key={c.code} transform={`translate(${c.x},${c.y})`}>
            {active && <circle r={20 + intensity * 14} fill="url(#iraq-intensity)"/>}
            <circle r={active ? 4 : 2.5} fill={active ? '#c6a15b' : '#6f7585'} stroke={active ? '#e3c06a' : '#4b5260'} strokeWidth={1}/>
            <text y={active ? -10 : -8} textAnchor="middle" style={{fontFamily:'var(--font-mono)', fontSize: 9, letterSpacing:'0.08em', fill: active ? '#e3c06a' : '#6f7585'}}>{c.code}</text>
          </g>
        );
      })}
    </svg>
  );
}

window.IraqMap = IraqMap;
