// Solkart — Norway choropleth + animated kommune spotlight
const { useEffect, useMemo, useRef, useState } = React;

// Heat scale: cool low → bright sun mid → warm coral high
// Using oklch for harmonious gradient
function heatColor(intensity) {
  // intensity 0..1
  const t = Math.max(0, Math.min(1, intensity));
  if (t < 0.001) return "oklch(0.78 0.02 90)"; // night/no-prod = pale sand
  // Stops:
  // 0.0  pale butter
  // 0.4  amber
  // 0.7  warm orange
  // 1.0  coral red
  let l, c, h;
  if (t < 0.4) {
    const k = t / 0.4;
    l = 0.92 - 0.08 * k;
    c = 0.05 + 0.10 * k;
    h = 90 - 15 * k;
  } else if (t < 0.7) {
    const k = (t - 0.4) / 0.3;
    l = 0.84 - 0.08 * k;
    c = 0.15 + 0.05 * k;
    h = 75 - 25 * k;
  } else {
    const k = (t - 0.7) / 0.3;
    l = 0.76 - 0.10 * k;
    c = 0.20 - 0.02 * k;
    h = 50 - 25 * k;
  }
  return `oklch(${l.toFixed(3)} ${c.toFixed(3)} ${h.toFixed(1)})`;
}

window.SOLKART_HEAT = heatColor;

function formatMW(kW) {
  if (kW >= 1000) return (kW / 1000).toFixed(1) + " MW";
  if (kW >= 1) return Math.round(kW) + " kW";
  return "0";
}

// Short display names so labels fit inside small fylker
const SHORT_NAMES = {
  "more": "Møre og R.",
  "vestfold": "Vestfold",
  "telemark": "Telemark",
  "buskerud": "Buskerud",
  "akershus": "Akershus",
  "ostfold": "Østfold",
  "innlandet": "Innlandet",
  "oslo": "Oslo",
};

function NorwayMap({ snapshot, spotlight, onPickFylke, hoveredFylke, setHoveredFylke }) {
  const { FYLKER, KOMMUNER, FYLKE_CENTROIDS } = window.SOLKART_DATA;

  // Compute intensity per fylke: fraction of its installed capacity producing right now
  const intensities = useMemo(() => {
    const out = {};
    FYLKER.forEach((f) => {
      const kW = snapshot.perFylke[f.id] || 0;
      const kWp = f.capacity * 1000;
      out[f.id] = kWp > 0 ? kW / kWp : 0;
    });
    return out;
  }, [snapshot, FYLKER]);

  return (
    <svg
      viewBox="0 0 1000 1200"
      xmlns="http://www.w3.org/2000/svg"
      style={{ width: "100%", height: "100%", display: "block" }}
      aria-label="Norgeskart med live solproduksjon per fylke"
    >
      <defs>
        <filter id="softShadow" x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur in="SourceAlpha" stdDeviation="6" />
          <feOffset dx="0" dy="6" result="off" />
          <feComponentTransfer><feFuncA type="linear" slope="0.18" /></feComponentTransfer>
          <feMerge><feMergeNode /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
        <radialGradient id="sunGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="oklch(0.95 0.18 85)" stopOpacity="0.85" />
          <stop offset="60%" stopColor="oklch(0.9 0.12 75)" stopOpacity="0.4" />
          <stop offset="100%" stopColor="oklch(0.9 0.12 75)" stopOpacity="0" />
        </radialGradient>
        <pattern id="dotsBg" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
          <circle cx="2" cy="2" r="0.6" fill="oklch(0.85 0.04 80)" opacity="0.5" />
        </pattern>
      </defs>

      {/* Sea / background */}
      <rect width="1000" height="1200" fill="url(#dotsBg)" />

      {/* Soft sun halo behind the south where most production lives */}
      <circle cx="450" cy="1000" r="360" fill="url(#sunGlow)" />

      {/* Country shadow underlay — single blob to give the map depth */}
      <g filter="url(#softShadow)">
        {FYLKER.map((f) => (
          <path key={"shadow-" + f.id} d={f.d} fill="#000" opacity="0.001" />
        ))}
      </g>

      {/* Fylker */}
      <g>
        {FYLKER.map((f) => {
          const intensity = intensities[f.id] || 0;
          const isHovered = hoveredFylke === f.id;
          return (
            <path
              key={f.id}
              d={f.d}
              fill={heatColor(intensity)}
              stroke={isHovered ? "oklch(0.3 0.05 50)" : "oklch(0.98 0.01 80)"}
              strokeWidth={isHovered ? 2.5 : 1.5}
              style={{
                cursor: "pointer",
                transition: "fill 1.2s ease, stroke 0.15s ease, stroke-width 0.15s ease",
              }}
              onMouseEnter={() => setHoveredFylke(f.id)}
              onMouseLeave={() => setHoveredFylke(null)}
              onClick={() => onPickFylke && onPickFylke(f.id)}
            />
          );
        })}
      </g>

      {/* Live production labels per fylke */}
      <g style={{ pointerEvents: "none" }}>
        {FYLKER.map((f) => {
          const c = FYLKE_CENTROIDS[f.id];
          if (!c) return null;
          const kW = snapshot.perFylke[f.id] || 0;
          const label = SHORT_NAMES[f.id] || f.name;

          // Oslo: external label with connector line
          if (f.id === "oslo") {
            const pinX = c.x;
            const pinY = c.y;
            const labelX = pinX + 80;
            const labelY = pinY - 20;
            return (
              <g key={"label-oslo"}>
                <line x1={pinX} y1={pinY} x2={labelX - 48} y2={labelY + 6}
                  stroke="oklch(0.5 0.05 55)" strokeWidth="1" opacity="0.6" />
                <rect x={labelX - 48} y={labelY - 10} width={96} height={30} rx="6"
                  fill="oklch(0.99 0.005 80 / 0.92)"
                  stroke="oklch(0.8 0.04 65 / 0.5)" strokeWidth="0.8" />
                <text x={labelX} y={labelY + 3} textAnchor="middle"
                  fontFamily="'DM Sans', system-ui, sans-serif" fontSize="11"
                  fontWeight="600" fill="oklch(0.35 0.05 55)">
                  Oslo
                </text>
                {kW > 0 && (
                  <text x={labelX} y={labelY + 16} textAnchor="middle"
                    fontFamily="'DM Sans', system-ui, sans-serif" fontSize="12"
                    fontWeight="700" fill="oklch(0.3 0.12 40)"
                    style={{ fontVariantNumeric: "tabular-nums" }}>
                    {formatMW(kW)}
                  </text>
                )}
              </g>
            );
          }

          return (
            <g key={"label-" + f.id}>
              <rect
                x={c.x - 52} y={c.y - 14}
                width={104} height={30}
                rx="6"
                fill="oklch(0.99 0.005 80 / 0.85)"
                stroke="oklch(0.8 0.04 65 / 0.5)"
                strokeWidth="0.8"
              />
              <text
                x={c.x} y={c.y}
                textAnchor="middle"
                fontFamily="'DM Sans', system-ui, sans-serif"
                fontSize="11"
                fontWeight="600"
                fill="oklch(0.35 0.05 55)"
                letterSpacing="0.02em"
              >
                {label}
              </text>
              {kW > 0 && (
                <text
                  x={c.x} y={c.y + 13}
                  textAnchor="middle"
                  fontFamily="'DM Sans', system-ui, sans-serif"
                  fontSize="12"
                  fontWeight="700"
                  fill="oklch(0.3 0.12 40)"
                  style={{ fontVariantNumeric: "tabular-nums" }}
                >
                  {formatMW(kW)}
                </text>
              )}
            </g>
          );
        })}
      </g>

      {/* Animated spotlight pin — radar pulse + label */}
      {spotlight && (
        <SpotlightPin
          key={spotlight.id}
          k={spotlight.kommune}
          kW={spotlight.kW}
          intensityPct={spotlight.intensityPct}
        />
      )}
    </svg>
  );
}

function SpotlightPin({ k, kW, intensityPct }) {
  // Decide whether label goes left or right of pin so it doesn't fall off the map
  const labelOnLeft = k.x > 600;
  const labelX = labelOnLeft ? k.x - 18 : k.x + 18;
  const textAnchor = labelOnLeft ? "end" : "start";

  // Bigger label card
  const cardW = 340;
  const cardH = 96;
  const cardOffset = 28; // gap between pin and card
  const cardX = labelOnLeft ? k.x - cardOffset - cardW : k.x + cardOffset;
  const cardY = k.y - cardH / 2;
  const padX = 18;
  const textX = labelOnLeft ? cardX + padX : cardX + padX;
  const valueX = labelOnLeft ? cardX + cardW - padX : cardX + cardW - padX;
  const kWText = kW >= 1000
    ? (kW / 1000).toFixed(1) + " MW"
    : Math.round(kW).toLocaleString("nb-NO") + " kW";

  return (
    <g style={{ pointerEvents: "none" }}>
      {/* radar pulse — larger */}
      <circle cx={k.x} cy={k.y} r="14" fill="none" stroke="oklch(0.55 0.18 30)" strokeWidth="2.5">
        <animate attributeName="r" from="12" to="90" dur="2.4s" repeatCount="indefinite" />
        <animate attributeName="opacity" from="0.9" to="0" dur="2.4s" repeatCount="indefinite" />
      </circle>
      <circle cx={k.x} cy={k.y} r="14" fill="none" stroke="oklch(0.55 0.18 30)" strokeWidth="2.5">
        <animate attributeName="r" from="12" to="90" dur="2.4s" begin="1.2s" repeatCount="indefinite" />
        <animate attributeName="opacity" from="0.9" to="0" dur="2.4s" begin="1.2s" repeatCount="indefinite" />
      </circle>

      {/* solid pin — larger */}
      <circle cx={k.x} cy={k.y} r="11" fill="oklch(0.6 0.21 35)" stroke="white" strokeWidth="3.5" />
      <circle cx={k.x} cy={k.y} r="3.5" fill="white" />

      {/* Connector line */}
      <line
        x1={k.x}
        y1={k.y}
        x2={labelOnLeft ? cardX + cardW : cardX}
        y2={k.y}
        stroke="oklch(0.55 0.18 30)"
        strokeWidth="1.5"
        opacity="0.6"
      />

      {/* Label card — larger, two rows */}
      <rect
        x={cardX}
        y={cardY}
        width={cardW}
        height={cardH}
        rx="12"
        fill="oklch(0.99 0.005 80)"
        stroke="oklch(0.82 0.05 65)"
        strokeWidth="1.5"
        style={{ filter: "drop-shadow(0 8px 18px oklch(0.4 0.08 60 / 0.18))" }}
      />
      {/* kicker — LIVE · FYLKE */}
      <text
        x={textX}
        y={cardY + 24}
        fontFamily="'DM Sans', system-ui, sans-serif"
        fontSize="15"
        fontWeight="700"
        letterSpacing="2.4"
        fill="oklch(0.55 0.18 35)"
      >
        LIVE · {k.fylke.toUpperCase()}
      </text>
      {/* kommune name */}
      <text
        x={textX}
        y={cardY + 56}
        fontFamily="'Newsreader', Georgia, serif"
        fontSize="32"
        fontWeight="600"
        fill="oklch(0.22 0.05 55)"
        letterSpacing="-0.01em"
      >
        {k.name}
      </text>
      {/* kW value */}
      <text
        x={textX}
        y={cardY + 82}
        fontFamily="'DM Sans', system-ui, sans-serif"
        fontSize="19"
        fontWeight="600"
        fill="oklch(0.4 0.05 60)"
        style={{ fontVariantNumeric: "tabular-nums" }}
      >
        {kWText}
        <tspan fontSize="14" fontWeight="500" fill="oklch(0.55 0.04 60)">  produserer akkurat nå</tspan>
      </text>
    </g>
  );
}

window.NorwayMap = NorwayMap;
