// Renders Switzerland with REAL canton boundaries (GeoJSON) + topographic shaded relief.
// Loads window.CH_GEO from ch-geo.js.

const { useMemo, useState, useEffect, useRef } = React;

// --- Mercator-ish projection tuned to Switzerland's bbox ---
// We compute viewport-fit transform from the country bbox.
function computeProjection(geo, width, height, padding = 0) {
  // Find bbox of country feature
  const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  function visit(coords) {
    if (typeof coords[0] === 'number') {
      if (coords[0] < bbox[0]) bbox[0] = coords[0];
      if (coords[1] < bbox[1]) bbox[1] = coords[1];
      if (coords[0] > bbox[2]) bbox[2] = coords[0];
      if (coords[1] > bbox[3]) bbox[3] = coords[1];
    } else {
      coords.forEach(visit);
    }
  }
  visit(geo.country.geometry.coordinates);

  const [minX, minY, maxX, maxY] = bbox;
  // simple equirectangular with latitude correction (Switzerland ~46.5°N)
  const latC = (minY + maxY) / 2;
  const lonScale = Math.cos(latC * Math.PI / 180);

  const dataW = (maxX - minX) * lonScale;
  const dataH = (maxY - minY);
  const innerW = width - padding * 2;
  const innerH = height - padding * 2;
  const scale = Math.min(innerW / dataW, innerH / dataH);

  const offsetX = padding + (innerW - dataW * scale) / 2;
  const offsetY = padding + (innerH - dataH * scale) / 2;

  function project(lon, lat) {
    const x = (lon - minX) * lonScale * scale + offsetX;
    // flip y because lat increases northward but svg y goes down
    const y = (maxY - lat) * scale + offsetY;
    return [x, y];
  }
  return { project, bbox, scale, lonScale };
}

function geomToPath(geom, project) {
  function ringPath(ring) {
    return ring.map((pt, i) => {
      const [x, y] = project(pt[0], pt[1]);
      return (i === 0 ? 'M' : 'L') + x.toFixed(2) + ',' + y.toFixed(2);
    }).join('') + 'Z';
  }
  if (geom.type === 'Polygon') {
    return geom.coordinates.map(ringPath).join('');
  }
  if (geom.type === 'MultiPolygon') {
    return geom.coordinates.map(poly => poly.map(ringPath).join('')).join('');
  }
  return '';
}

// Generate hill-shading dots based on Swiss alpine topography
// We use deterministic positions for stable rendering — denser in the high south/center
function generateReliefDots(width, height, project, geo) {
  const dots = [];
  // Approx high-elevation regions (lon, lat, intensity radius)
  const peaks = [
    // Bernese / Valais Alps
    { lon: 7.86, lat: 45.94, r: 0.35, i: 1.0 }, // Monte Rosa
    { lon: 7.66, lat: 45.98, r: 0.25, i: 0.95 }, // Matterhorn
    { lon: 8.13, lat: 46.54, r: 0.45, i: 1.0 },  // Finsteraarhorn
    { lon: 7.96, lat: 46.56, r: 0.30, i: 0.9 },  // Jungfrau
    { lon: 7.20, lat: 46.34, r: 0.25, i: 0.85 }, // Diablerets
    { lon: 8.43, lat: 46.77, r: 0.30, i: 0.9 },  // Titlis
    { lon: 8.41, lat: 46.64, r: 0.35, i: 0.95 }, // Dammastock
    { lon: 8.91, lat: 46.81, r: 0.30, i: 0.9 },  // Tödi
    { lon: 9.91, lat: 46.38, r: 0.40, i: 1.0 },  // Bernina
    { lon: 9.91, lat: 46.50, r: 0.30, i: 0.85 }, // Engadine
    { lon: 9.30, lat: 46.88, r: 0.25, i: 0.85 }, // Ringelspitz
    { lon: 9.12, lat: 46.50, r: 0.30, i: 0.85 }, // Rheinwaldhorn
    { lon: 9.34, lat: 47.25, r: 0.18, i: 0.7 },  // Säntis
    // Jura ridge
    { lon: 7.06, lat: 47.13, r: 0.20, i: 0.5 },
    { lon: 7.45, lat: 47.24, r: 0.18, i: 0.5 },
    { lon: 6.40, lat: 46.85, r: 0.15, i: 0.4 },
  ];

  // Sample a grid and emit dots whose density corresponds to elevation field
  const step = 0.06; // degrees
  for (let lon = 5.95; lon < 10.5; lon += step) {
    for (let lat = 45.85; lat < 47.85; lat += step) {
      let elev = 0;
      for (const p of peaks) {
        const dlon = (lon - p.lon) * Math.cos(46.5 * Math.PI / 180);
        const dlat = (lat - p.lat);
        const d = Math.sqrt(dlon * dlon + dlat * dlat);
        if (d < p.r) {
          elev += p.i * (1 - d / p.r);
        }
      }
      if (elev > 0.05) {
        const [x, y] = project(lon, lat);
        // jittered slightly for organic feel using deterministic hash
        const h = (Math.sin(lon * 137.31 + lat * 89.21) * 43758.5453);
        const jx = (h - Math.floor(h)) - 0.5;
        const jy = (Math.sin(h * 12.9898) * 0.5);
        dots.push({
          x: x + jx * 2,
          y: y + jy * 2,
          r: 0.4 + elev * 1.2,
          o: Math.min(1, elev * 1.3),
        });
      }
    }
  }
  return dots;
}

function pointInRing(pt, ring) {
  let inside = false;
  for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
    const xi = ring[i][0], yi = ring[i][1];
    const xj = ring[j][0], yj = ring[j][1];
    const intersect = ((yi > pt[1]) !== (yj > pt[1])) &&
      (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }
  return inside;
}
function pointInGeom(pt, geom) {
  if (geom.type === 'Polygon') {
    if (!pointInRing(pt, geom.coordinates[0])) return false;
    for (let i = 1; i < geom.coordinates.length; i++) {
      if (pointInRing(pt, geom.coordinates[i])) return false;
    }
    return true;
  }
  if (geom.type === 'MultiPolygon') {
    return geom.coordinates.some(poly => {
      if (!pointInRing(pt, poly[0])) return false;
      for (let i = 1; i < poly.length; i++) {
        if (pointInRing(pt, poly[i])) return false;
      }
      return true;
    });
  }
  return false;
}

function SwissMap({ peaks, hovered, selected, onHover, onSelect, paletteObj, mapStyle, showGrid }) {
  const VIEW_W = 1000;
  const VIEW_H = 1000;
  const PAD = 50;

  const geo = window.CH_GEO;
  if (!geo) return <div style={{ padding: 40, fontFamily: 'monospace' }}>Loading map…</div>;

  const proj = useMemo(() => computeProjection(geo, VIEW_W, VIEW_H, PAD), [geo]);
  const reliefDots = useMemo(
    () => mapStyle === 'relief' ? generateReliefDots(VIEW_W, VIEW_H, proj.project, geo) : [],
    [proj, mapStyle]
  );

  // Filter relief dots to only inside country
  const filteredDots = useMemo(() => {
    if (!reliefDots.length) return [];
    // We use lon/lat-space test for performance; project back not needed since we know they were generated in lon/lat
    // But we generated in lon/lat, then projected, so we need original coords. Re-do simply:
    const out = [];
    const step = 0.06;
    const projFn = proj.project;
    for (let lon = 5.95; lon < 10.5; lon += step) {
      for (let lat = 45.85; lat < 47.85; lat += step) {
        if (!pointInGeom([lon, lat], geo.country.geometry)) continue;
        // compute elevation field again
        const peaksHi = [
          [7.86, 45.94, 0.35, 1.0], [7.66, 45.98, 0.25, 0.95], [8.13, 46.54, 0.45, 1.0],
          [7.96, 46.56, 0.30, 0.9], [7.20, 46.34, 0.25, 0.85], [8.43, 46.77, 0.30, 0.9],
          [8.41, 46.64, 0.35, 0.95], [8.91, 46.81, 0.30, 0.9], [9.91, 46.38, 0.40, 1.0],
          [9.91, 46.50, 0.30, 0.85], [9.30, 46.88, 0.25, 0.85], [9.12, 46.50, 0.30, 0.85],
          [9.34, 47.25, 0.18, 0.7], [7.06, 47.13, 0.20, 0.5], [7.45, 47.24, 0.18, 0.5],
          [6.40, 46.85, 0.15, 0.4],
        ];
        let elev = 0;
        for (const [pl, pa, pr, pi] of peaksHi) {
          const dlon = (lon - pl) * Math.cos(46.5 * Math.PI / 180);
          const dlat = (lat - pa);
          const d = Math.sqrt(dlon * dlon + dlat * dlat);
          if (d < pr) elev += pi * (1 - d / pr);
        }
        if (elev > 0.05) {
          const [x, y] = projFn(lon, lat);
          const h = (Math.sin(lon * 137.31 + lat * 89.21) * 43758.5453);
          const jx = (h - Math.floor(h)) - 0.5;
          const jy = (Math.sin(h * 12.9898) * 0.5);
          out.push({ x: x + jx * 2.5, y: y + jy * 2.5, r: 0.5 + elev * 1.3, o: Math.min(1, elev * 1.4) });
        }
      }
    }
    return out;
  }, [proj, geo]);

  // Hatched lines for high-elevation (alternative)
  const hatchedLines = useMemo(() => {
    if (mapStyle !== 'hatched') return [];
    const lines = [];
    const step = 0.05;
    for (let lat = 45.85; lat < 47.85; lat += step) {
      let inHigh = false;
      let segStart = null;
      for (let lon = 5.95; lon < 10.5; lon += 0.02) {
        const peaksHi = [
          [7.86, 45.94, 0.35], [8.13, 46.54, 0.45], [7.96, 46.56, 0.30],
          [8.43, 46.77, 0.30], [8.41, 46.64, 0.35], [8.91, 46.81, 0.30],
          [9.91, 46.38, 0.40], [9.30, 46.88, 0.25], [9.12, 46.50, 0.30],
          [7.20, 46.34, 0.25], [9.91, 46.50, 0.30],
        ];
        let high = false;
        for (const [pl, pa, pr] of peaksHi) {
          const dlon = (lon - pl) * Math.cos(46.5 * Math.PI / 180);
          const dlat = (lat - pa);
          if (dlon * dlon + dlat * dlat < pr * pr * 0.6) { high = true; break; }
        }
        if (high && pointInGeom([lon, lat], geo.country.geometry)) {
          if (!inHigh) { segStart = lon; inHigh = true; }
        } else {
          if (inHigh) {
            const a = proj.project(segStart, lat);
            const b = proj.project(lon, lat);
            lines.push([a, b]);
            inHigh = false;
          }
        }
      }
      if (inHigh) {
        const a = proj.project(segStart, lat);
        const b = proj.project(10.5, lat);
        lines.push([a, b]);
      }
    }
    return lines;
  }, [proj, mapStyle, geo]);

  const countryPath = useMemo(() => geomToPath(geo.country.geometry, proj.project), [proj, geo]);
  const cantonPaths = useMemo(
    () => geo.cantons.features.map(f => ({ id: f.properties.id, d: geomToPath(f.geometry, proj.project) })),
    [proj, geo]
  );
  const lakePaths = useMemo(
    () => geo.lakes.features.map(f => ({ id: f.properties.id, d: geomToPath(f.geometry, proj.project) })),
    [proj, geo]
  );

  const summitedBfs = new Set(peaks.filter(p => p.status === 'summited').map(p => p.bfs));

  return (
    <svg viewBox={`0 0 ${VIEW_W} ${VIEW_H}`} className="map-svg" preserveAspectRatio="xMidYMid meet">
      <defs>
        {/* Inner shadow / vignette via radial gradient on the country */}
        <radialGradient id="countryFill" cx="50%" cy="50%" r="60%">
          <stop offset="0%" stopColor={paletteObj.land} />
          <stop offset="100%" stopColor={paletteObj.paperDeep} />
        </radialGradient>
        <pattern id="hatchPat" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="6" stroke={paletteObj.contour} strokeWidth="0.6" opacity="0.4" />
        </pattern>
        <filter id="paperGrain">
          <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" />
          <feColorMatrix values="0 0 0 0 0
                                 0 0 0 0 0
                                 0 0 0 0 0
                                 0 0 0 0.04 0" />
          <feComposite in2="SourceGraphic" operator="in" />
        </filter>
        <clipPath id="countryClip">
          <path d={countryPath} />
        </clipPath>
      </defs>

      {/* Optional grid */}
      {showGrid && (
        <g opacity="0.2">
          {Array.from({ length: 50 }).map((_, i) => (
            <line key={`v${i}`} x1={i * (VIEW_W / 50)} y1="0" x2={i * (VIEW_W / 50)} y2={VIEW_H}
              stroke={paletteObj.contour} strokeWidth="0.4" />
          ))}
          {Array.from({ length: 32 }).map((_, i) => (
            <line key={`h${i}`} x1="0" y1={i * (VIEW_H / 32)} x2={VIEW_W} y2={i * (VIEW_H / 32)}
              stroke={paletteObj.contour} strokeWidth="0.4" />
          ))}
        </g>
      )}

      {/* Country fill */}
      <path d={countryPath} fill="url(#countryFill)" />

      {/* Hatched terrain pattern over whole country */}
      {mapStyle === 'hatched' && (
        <g clipPath="url(#countryClip)">
          {hatchedLines.map(([a, b], i) => (
            <line key={i} x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]}
              stroke={paletteObj.contourDark} strokeWidth="0.5" opacity="0.5" />
          ))}
        </g>
      )}

      {/* Stippled relief shading */}
      {mapStyle === 'relief' && (
        <g clipPath="url(#countryClip)">
          {filteredDots.map((d, i) => (
            <circle key={i} cx={d.x} cy={d.y} r={d.r} fill={paletteObj.contourDark} opacity={d.o * 0.55} />
          ))}
        </g>
      )}

      {/* Canton boundaries */}
      <g>
        {cantonPaths.map(c => {
          const isSummitedCanton = summitedBfs.has(c.id);
          return (
            <path
              key={c.id}
              d={c.d}
              fill={isSummitedCanton ? paletteObj.accent : 'transparent'}
              fillOpacity={isSummitedCanton ? 0.10 : 0}
              stroke={paletteObj.contourDark}
              strokeWidth="0.8"
              strokeOpacity="0.55"
              strokeLinejoin="round"
            />
          );
        })}
      </g>

      {/* Country outer line */}
      <path d={countryPath} fill="none" stroke={paletteObj.ink} strokeWidth="1.4" strokeLinejoin="round" />

      {/* Lakes */}
      <g>
        {lakePaths.map(l => (
          <path key={l.id} d={l.d}
            fill={paletteObj.water}
            stroke={paletteObj.ink}
            strokeWidth="0.5"
            strokeOpacity="0.6" />
        ))}
      </g>

      {/* Peaks */}
      <g>
        {peaks.map(p => {
          const [x, y] = proj.project(p.lon, p.lat);
          const isSel = selected?.id === p.id;
          const isHov = hovered?.id === p.id;
          const isSummited = p.status === 'summited';
          const baseSize = isSummited ? 15 : 12;
          const size = (isSel || isHov) ? baseSize * 1.4 : baseSize;
          const color = isSummited ? paletteObj.summited : paletteObj.planned;
          return (
            <g key={p.id}
              transform={`translate(${x}, ${y})`}
              style={{ cursor: 'pointer' }}
              onMouseEnter={() => onHover(p)}
              onMouseLeave={() => onHover(null)}
              onClick={() => onSelect(p)}>
              {(isSel || isHov) && <circle r={size * 2.2} fill={color} opacity="0.18" />}
              <polygon
                points={`0,${-size} ${size * 0.86},${size * 0.5} ${-size * 0.86},${size * 0.5}`}
                fill={isSummited ? color : paletteObj.paper}
                stroke={color}
                strokeWidth={isSummited ? 1 : 1.6}
                strokeLinejoin="round"
              />
              {isSummited && <circle r={size * 0.25} cy={size * 0.05} fill={paletteObj.paper} />}
              <text
                y={size + 11}
                textAnchor="middle"
                fontFamily="JetBrains Mono, monospace"
                fontSize={isHov || isSel ? 12 : 10}
                fontWeight={isSummited ? 700 : 500}
                fill={paletteObj.ink}
                style={{ pointerEvents: 'none', paintOrder: 'stroke', stroke: paletteObj.paper, strokeWidth: 2.5 }}
              >
                {p.cantonCode}
              </text>
              {isHov && !isSel && (
                <g style={{ pointerEvents: 'none' }} transform="translate(10, -10)">
                  <rect x="0" y="-22" width="180" height="42" fill={paletteObj.ink} rx="2" />
                  <text x="8" y="-9" fontSize="11" fill={paletteObj.paper} fontWeight="700"
                    fontFamily="Inter, sans-serif">{p.canton}</text>
                  <text x="8" y="4" fontSize="10" fill={paletteObj.paper} opacity="0.78"
                    fontFamily="Inter, sans-serif">{p.name} · {p.elevation.toLocaleString()}m</text>
                  <text x="8" y="16" fontSize="9" fill={isSummited ? paletteObj.accentSoft : paletteObj.contour}
                    fontFamily="JetBrains Mono, monospace" letterSpacing="1">
                    {isSummited ? '● SUMMITED' : '○ PLANNED'}
                  </text>
                </g>
              )}
            </g>
          );
        })}
      </g>

      {/* Compass rose */}
      <g transform={`translate(${VIEW_W - 70}, 60)`}>
        <circle r="22" fill="none" stroke={paletteObj.contourDark} strokeWidth="1" />
        <line x1="0" y1="-22" x2="0" y2="22" stroke={paletteObj.contourDark} strokeWidth="0.6" />
        <line x1="-22" y1="0" x2="22" y2="0" stroke={paletteObj.contourDark} strokeWidth="0.6" />
        <polygon points="0,-22 4,-8 -4,-8" fill={paletteObj.accent} />
        <text x="0" y="-26" fontSize="9" textAnchor="middle" fill={paletteObj.ink}
          fontFamily="JetBrains Mono, monospace" fontWeight="700">N</text>
      </g>

      {/* Scale bar — 50km approx */}
      <g transform={`translate(50, ${VIEW_H - 50})`}>
        <line x1="0" y1="0" x2="80" y2="0" stroke={paletteObj.ink} strokeWidth="1.2" />
        <line x1="0" y1="-4" x2="0" y2="4" stroke={paletteObj.ink} strokeWidth="1.2" />
        <line x1="40" y1="-2" x2="40" y2="2" stroke={paletteObj.ink} strokeWidth="1" />
        <line x1="80" y1="-4" x2="80" y2="4" stroke={paletteObj.ink} strokeWidth="1.2" />
        <text x="0" y="-8" fontSize="9" fill={paletteObj.ink} fontFamily="JetBrains Mono, monospace">0</text>
        <text x="80" y="-8" fontSize="9" fill={paletteObj.ink} fontFamily="JetBrains Mono, monospace">~50 km</text>
      </g>
    </svg>
  );
}

window.SwissMap = SwissMap;
window.computeProjection = computeProjection;
window.geomToPath = geomToPath;
