// EuropeMap.jsx — atlas-style SVG map with country outlines + city dots
const { useMemo, useState, useRef, useEffect } = React;

function EuropeMap({ cities, weights, selectedId, hoveredId, onSelect, onHover, theme, lang }) {
  const t = window.I18N[lang];
  const ranked = useMemo(() => {
    return cities.map(c => ({ ...c, fit: window.scoreCity(c, weights) }));
  }, [cities, weights]);

  const fitRange = useMemo(() => {
    let min = 100, max = 0;
    for (const c of ranked) { if (c.fit < min) min = c.fit; if (c.fit > max) max = c.fit; }
    return { min, max };
  }, [ranked]);

  const ramp = (fit) => {
    // normalize relative to current scenario range so changes are visible
    const span = Math.max(1, fitRange.max - fitRange.min);
    const norm = ((fit - fitRange.min) / span) * 100;
    return window.scoreColor(norm, theme);
  };

  const sizeFor = (fit, pop) => {
    const span = Math.max(1, fitRange.max - fitRange.min);
    const norm = (fit - fitRange.min) / span;
    const popBoost = Math.min(1.6, 0.6 + Math.log10(1 + (pop || 0.2)) * 0.55);
    return 1.8 + norm * 5.5 * popBoost;
  };

  const W = window.MAP_VIEW.w;
  const H = window.MAP_VIEW.h;

  // Sort dots so high-fit render on top
  const drawOrder = [...ranked].sort((a,b) => a.fit - b.fit);
  const top1 = [...ranked].sort((a,b) => b.fit - a.fit)[0];

  return (
    <div className="map-wrap">
      <div className="map-frame">
        <div className="map-corner tl">N</div>
        <div className="map-corner tr">↑</div>
        <div className="map-corner bl">{t.cityCount}</div>
        <div className="map-corner br">World · stylized</div>
        <svg viewBox={`0 0 ${W} ${H}`} className="europe-svg" preserveAspectRatio="xMidYMid meet">
          <defs>
            <pattern id="hatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke="var(--ink-30)" strokeWidth="0.6" />
            </pattern>
            <pattern id="dots" patternUnits="userSpaceOnUse" width="14" height="14">
              <circle cx="1" cy="1" r="0.7" fill="var(--ink-20)" />
            </pattern>
            <radialGradient id="seaGrad" cx="50%" cy="50%" r="70%">
              <stop offset="0%" stopColor="var(--paper)" />
              <stop offset="100%" stopColor="var(--paper-2)" />
            </radialGradient>
            <filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="3" result="b" />
              <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
            </filter>
          </defs>

          {/* Sea */}
          <rect x="0" y="0" width={W} height={H} fill="url(#seaGrad)" />
          <rect x="0" y="0" width={W} height={H} fill="url(#dots)" opacity="0.5" />

          {/* Lat/Lon graticule */}
          <g className="graticule">
            {Array.from({length: 8}).map((_, i) => {
              const y = (H / 7) * i;
              return <line key={`h${i}`} x1="0" y1={y} x2={W} y2={y} />;
            })}
            {Array.from({length: 9}).map((_, i) => {
              const x = (W / 8) * i;
              return <line key={`v${i}`} x1={x} y1="0" x2={x} y2={H} />;
            })}
          </g>

          {/* Countries */}
          <g className="countries">
            {(window.WORLD_FEATURES || window.EUROPE_FEATURES).map((f, i) => (
              <g key={i} className={`country-group ${f.rim ? "is-rim" : ""}`}>
                {f.paths.map((d, j) => (
                  <path key={j} d={d} className={`country ${f.rim ? "country-rim" : ""}`} />
                ))}
              </g>
            ))}
          </g>

          {/* Compass rose */}
          <g transform={`translate(60, ${H - 80})`} className="compass">
            <circle r="32" />
            <path d="M0,-26 L4,0 L0,26 L-4,0 Z" />
            <path d="M-26,0 L0,-4 L26,0 L0,4 Z" />
            <text y="-36" textAnchor="middle">N</text>
          </g>

          {/* Scale bar */}
          <g transform={`translate(${W - 200}, ${H - 50})`} className="scalebar">
            <line x1="0" y1="0" x2="160" y2="0" />
            <line x1="0" y1="-4" x2="0" y2="4" />
            <line x1="80" y1="-4" x2="80" y2="4" />
            <line x1="160" y1="-4" x2="160" y2="4" />
            <text x="0" y="18">0</text>
            <text x="80" y="18" textAnchor="middle">2500</text>
            <text x="160" y="18" textAnchor="end">5000 km</text>
          </g>

          {/* City dots */}
          <g className="cities">
            {drawOrder.map(c => {
              const p = window.project(c.lonlat);
              const r = sizeFor(c.fit, c.pop);
              const isSel = c.id === selectedId;
              const isHov = c.id === hoveredId;
              const isTop = top1 && c.id === top1.id;
              return (
                <g key={c.id}
                   className={`city ${isSel ? "is-selected" : ""} ${isHov ? "is-hovered" : ""} ${isTop ? "is-top" : ""}`}
                   transform={`translate(${p.x},${p.y})`}
                   onClick={() => onSelect(c.id)}
                   onMouseEnter={() => onHover(c.id)}
                   onMouseLeave={() => onHover(null)}
                   tabIndex={0}
                   role="button"
                   aria-label={`${c.name} — ${t.fit} ${Math.round(c.fit)}`}
                   onKeyDown={(e)=>{ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); onSelect(c.id);} }}
                >
                  {isTop && <circle r={r + 8} className="halo" fill={ramp(c.fit)} opacity="0.18" />}
                  <circle r={r + 1.6} className="dot-ring" />
                  <circle r={r} className="dot" fill={ramp(c.fit)} />
                  {(isSel || isHov || isTop) && (
                    <g transform={`translate(0,${-r - 8})`} className="city-tip">
                      <rect x="-58" y="-26" width="116" height="22" rx="2" className="tip-bg"/>
                      <text y="-12" textAnchor="middle" className="tip-name">{c.name}</text>
                      <text y="-2" textAnchor="middle" className="tip-fit">{t.fit} {Math.round(c.fit)} · {c.country}</text>
                    </g>
                  )}
                </g>
              );
            })}
          </g>
        </svg>
      </div>

      <div className="map-legend">
        <div className="legend-title">{t.legend}</div>
        <div className="legend-bar">
          <div className="bar" />
          <div className="ticks">
            <span>{t.low}</span><span>{t.mid}</span><span>{t.high}</span>
          </div>
        </div>
        <div className="legend-note">— {t.notes}</div>
      </div>
    </div>
  );
}

window.EuropeMap = EuropeMap;
