// ===== Interactive world map with great-circle routes =====

const { useState: _useState1, useEffect: _useEffect1, useRef: _useRef1, useMemo: _useMemo1 } = React;
const useState = _useState1;
const useEffect = _useEffect1;
const useRef = _useRef1;
const useMemo = _useMemo1;

// Stylized continent outlines (simplified polygons in lat/lon).
// Deliberately impressionistic — this is a nostalgic chart, not a survey map.
const CONTINENTS = [
  // ---- Europe (incl. British Isles, Scandinavia, Iberia, Italy, Greece) ----
  [[58,-10],[60,-5],[63,5],[66,12],[68,22],[70,30],[68,38],[60,40],[55,38],[50,40],
   [46,42],[42,40],[38,36],[36,30],[36,24],[37,20],[40,18],[40,14],[38,16],[37,12],
   [40,8],[42,3],[43,-1],[43,-9],[40,-9],[38,-9],[37,-6],[36,-5],[38,0],[44,-1],
   [47,-3],[48,-5],[50,-5],[52,-9],[55,-7],[58,-10]],
  // ---- Africa ----
  [[36,-6],[34,0],[33,10],[32,20],[31,25],[31,32],[27,34],[22,37],[15,40],[11,43],
   [3,46],[-4,40],[-12,40],[-22,35],[-30,32],[-34,25],[-34,20],[-32,18],[-26,15],
   [-18,12],[-10,13],[-2,9],[4,5],[6,-3],[5,-10],[10,-15],[15,-17],[20,-17],
   [25,-15],[30,-10],[34,-7],[36,-6]],
  // ---- Asia (roughly: Turkey east through Siberia, India, SE Asia, Japan) ----
  [[42,40],[50,45],[60,55],[68,65],[72,80],[74,100],[72,130],[68,145],[60,155],
   [55,160],[50,155],[44,140],[40,140],[36,140],[32,131],[30,122],[22,113],
   [20,107],[10,107],[5,103],[1,103],[5,98],[12,95],[18,95],[22,90],[24,88],
   [22,82],[18,76],[12,77],[8,77],[12,73],[20,72],[24,70],[28,65],[30,60],
   [28,55],[27,50],[28,45],[34,44],[37,44],[42,40]],
  // ---- North America ----
  [[71,-156],[72,-140],[70,-128],[68,-125],[60,-138],[55,-130],[50,-125],[48,-123],
   [40,-124],[34,-120],[32,-117],[28,-114],[23,-110],[18,-104],[15,-96],[18,-94],
   [21,-90],[25,-83],[30,-82],[33,-80],[36,-76],[40,-74],[44,-66],[47,-60],
   [52,-57],[56,-60],[60,-65],[62,-72],[66,-78],[70,-85],[72,-95],[74,-110],
   [72,-125],[71,-156]],
  // ---- South America ----
  [[12,-72],[10,-62],[5,-52],[-5,-35],[-15,-39],[-23,-43],[-30,-50],[-38,-58],
   [-45,-66],[-52,-69],[-54,-71],[-50,-74],[-42,-74],[-32,-71],[-22,-70],
   [-15,-75],[-5,-80],[2,-78],[8,-77],[12,-72]],
  // ---- Australia ----
  [[-12,131],[-12,138],[-15,145],[-22,151],[-28,153],[-33,151],[-37,145],[-38,141],
   [-35,137],[-32,134],[-32,125],[-34,116],[-32,115],[-22,114],[-15,123],[-12,131]],
  // ---- Greenland ----
  [[83,-30],[80,-15],[75,-18],[70,-22],[63,-42],[68,-55],[75,-58],[80,-50],[83,-30]],
];

// Light graticule lines
const GRATICULE = (function () {
  const lines = [];
  for (let lat = -60; lat <= 75; lat += 15) {
    lines.push({ type: "lat", at: lat });
  }
  for (let lon = -150; lon <= 150; lon += 30) {
    lines.push({ type: "lon", at: lon });
  }
  return lines;
})();

function continentPath(poly, w, h) {
  return (
    poly
      .map(([la, lo], i) => {
        const [x, y] = project(la, lo, w, h);
        return (i === 0 ? "M" : "L") + x.toFixed(1) + " " + y.toFixed(1);
      })
      .join(" ") + " Z"
  );
}

function WorldMap() {
  // ViewBox: we crop antarctic & far north to focus on Moritz' world.
  const W = 1600, H = 800;
  // Visible window in lat (top→bottom) and lon (left→right):
  const visTopY = ((90 - 75) / 180) * H;   // y for lat 75
  const visBotY = ((90 - -45) / 180) * H;  // y for lat -45
  const visH = visBotY - visTopY;
  const viewBox = `0 ${visTopY} ${W} ${visH}`;

  const [hover, setHover] = useState(null); // route key
  const [focusCode, setFocusCode] = useState(null); // airport code on tap

  // Pre-compute route paths
  const routePaths = useMemo(() => {
    return ROUTEN.map((r) => {
      const a = airport(r.from);
      const b = airport(r.to);
      const d = gcSvgPath(a.lat, a.lon, b.lat, b.lon, W, H);
      const key = `${r.from}-${r.to}`;
      return { ...r, key, a, b, d };
    });
  }, []);

  const airports = useMemo(() => {
    // Combine hubs + destinations + extremes, dedup by code
    const seen = new Map();
    [...HUBS, ...ZIELE, ...ECKPUNKTE].forEach((p) => {
      if (!seen.has(p.code)) seen.set(p.code, p);
    });
    return [...seen.values()];
  }, []);

  const isHub = (c) => HUBS.some((h) => h.code === c);
  const isExtrem = (c) => ECKPUNKTE.some((e) => e.code === c);

  const hoverInfo = useMemo(() => {
    if (!hover) return null;
    const r = routePaths.find((x) => x.key === hover);
    if (!r) return null;
    return r;
  }, [hover, routePaths]);

  return (
    <div className="relative w-full">
      {/* Map container */}
      <div className="relative w-full rounded-sm border border-cream/15 overflow-hidden">
        <div className="absolute inset-0 starry opacity-95" />
        {/* Compass rose - corner decoration */}
        <div className="absolute top-4 right-4 z-10 text-amber/70">
          <svg viewBox="0 0 80 80" width="56" height="56">
            <circle cx="40" cy="40" r="34" fill="none" stroke="currentColor" strokeWidth="0.8" />
            <circle cx="40" cy="40" r="26" fill="none" stroke="currentColor" strokeWidth="0.4" strokeDasharray="2 3" />
            <path d="M40 8 L44 40 L40 72 L36 40 Z" fill="currentColor" opacity="0.8" />
            <path d="M8 40 L40 36 L72 40 L40 44 Z" fill="currentColor" opacity="0.4" />
            <text x="40" y="6" textAnchor="middle" fontSize="6" fill="currentColor" fontFamily="JetBrains Mono">N</text>
          </svg>
        </div>
        {/* Legend */}
        <div className="absolute bottom-4 left-4 z-10 text-cream/80 font-mono text-[10px] uppercase tracking-[0.2em] space-y-1.5">
          <div className="flex items-center gap-2"><span className="inline-block w-3 h-3 rounded-full bg-amber border border-amber-soft" /> Hub MUC / FRA</div>
          <div className="flex items-center gap-2"><span className="inline-block w-2.5 h-2.5 rounded-full bg-cream border border-cream/40" /> Ziel</div>
          <div className="flex items-center gap-2"><span className="inline-block w-2.5 h-2.5 rounded-full border-2 border-amber" /> geografischer Eckpunkt</div>
        </div>

        <svg viewBox={viewBox} className="w-full h-full block" style={{ aspectRatio: `${W}/${visH}` }}
             onMouseLeave={() => setHover(null)}>
          <defs>
            <linearGradient id="routeAmber" x1="0" x2="1" y1="0" y2="0">
              <stop offset="0%" stopColor="#f9b000" stopOpacity="0.85" />
              <stop offset="50%" stopColor="#ffd066" stopOpacity="1" />
              <stop offset="100%" stopColor="#f9b000" stopOpacity="0.85" />
            </linearGradient>
            <linearGradient id="routeCream" x1="0" x2="1" y1="0" y2="0">
              <stop offset="0%" stopColor="#f6f0e2" stopOpacity="0.7" />
              <stop offset="50%" stopColor="#f6f0e2" stopOpacity="1" />
              <stop offset="100%" stopColor="#f6f0e2" stopOpacity="0.7" />
            </linearGradient>
            <radialGradient id="dotGlow">
              <stop offset="0%" stopColor="#f9b000" stopOpacity="0.85" />
              <stop offset="100%" stopColor="#f9b000" stopOpacity="0" />
            </radialGradient>
          </defs>

          {/* Graticule */}
          <g stroke="#f6f0e2" strokeOpacity="0.07" strokeWidth="0.6">
            {GRATICULE.map((g, i) => {
              if (g.type === "lat") {
                const [, y] = project(g.at, 0, W, H);
                return <line key={i} x1="0" y1={y} x2={W} y2={y} />;
              }
              const [x] = project(0, g.at, W, H);
              return <line key={i} x1={x} y1={visTopY} x2={x} y2={visBotY} />;
            })}
          </g>

          {/* Continents - soft fills */}
          <g>
            {CONTINENTS.map((poly, i) => (
              <path
                key={i}
                d={continentPath(poly, W, H)}
                fill="#f6f0e2"
                fillOpacity="0.05"
                stroke="#f6f0e2"
                strokeOpacity="0.18"
                strokeWidth="0.6"
                strokeLinejoin="round"
              />
            ))}
          </g>

          {/* Routes — Doppel-Stroke: breiter Glow-Underlay + scharfe Hauptlinie */}
          <g fill="none" strokeLinecap="round" strokeLinejoin="round">
            {routePaths.map((r) => {
              const isHov = hover === r.key;
              const isFocusedAirport = focusCode && (focusCode === r.from || focusCode === r.to);
              const dim = (hover && !isHov) || (focusCode && !isFocusedAirport);

              const mainColor = r.extrem ? "#f6f0e2" : "#ffd066";
              const glowColor = r.extrem ? "#f6f0e2" : "#f9b000";

              const glowW = isHov ? r.w * 3.5 + 5 : r.w * 2.4 + 3.5;
              const mainW = isHov ? r.w + 2.5 : r.w + 1.3;

              const glowOp = dim ? 0.08 : isHov ? 0.55 : 0.35;
              const mainOp = dim ? 0.30 : isHov ? 1    : 0.95;

              return (
                <g key={r.key} className="cursor-pointer"
                   onMouseEnter={() => setHover(r.key)}
                   onClick={() => setHover(r.key)}>
                  {/* invisible hit-area for easier hover */}
                  <path d={r.d} stroke="transparent" strokeWidth={Math.max(10, r.w * 5)} />
                  {/* glow underlay */}
                  <path
                    d={r.d}
                    stroke={glowColor}
                    strokeWidth={glowW}
                    strokeOpacity={glowOp}
                    strokeDasharray={r.extrem ? "8 9" : "0"}
                    style={{ transition: "stroke-opacity .25s, stroke-width .25s" }}
                  />
                  {/* main stroke */}
                  <path
                    d={r.d}
                    stroke={mainColor}
                    strokeWidth={mainW}
                    strokeOpacity={mainOp}
                    strokeDasharray={r.extrem ? "8 9" : "0"}
                    style={{ transition: "stroke-opacity .25s, stroke-width .25s" }}
                  />
                </g>
              );
            })}
          </g>

          {/* Airport dots */}
          <g>
            {airports.map((a) => {
              const [x, y] = project(a.lat, a.lon, W, H);
              const hub = isHub(a.code);
              const ext = isExtrem(a.code);
              const isFoc = focusCode === a.code;
              return (
                <g key={a.code}
                   onMouseEnter={() => setFocusCode(a.code)}
                   onMouseLeave={() => setFocusCode(null)}
                   className="cursor-pointer">
                  {hub && <circle cx={x} cy={y} r="32" fill="url(#dotGlow)" />}
                  <circle
                    cx={x}
                    cy={y}
                    r={hub ? 6 : ext ? 5 : 3.6}
                    fill={hub ? "#f9b000" : ext ? "transparent" : "#f6f0e2"}
                    stroke={hub ? "#fbf6ea" : ext ? "#f9b000" : "#05164d"}
                    strokeWidth={hub ? 1.5 : ext ? 2 : 0.8}
                  />
                  {(hub || ext || isFoc) && (
                    <text
                      x={x + (hub ? 10 : 8)}
                      y={y + 4}
                      fill={hub ? "#ffd066" : "#f6f0e2"}
                      fontSize={hub ? "13" : "11"}
                      fontFamily="JetBrains Mono"
                      letterSpacing="0.08em"
                    >
                      {a.code}
                    </text>
                  )}
                </g>
              );
            })}
          </g>
        </svg>
      </div>

      {/* Read-out under map: extreme points + hover info */}
      <div className="mt-6 grid md:grid-cols-2 gap-6">
        <div className="ticket-dark text-cream px-6 py-5 rounded-sm relative">
          <div className="absolute top-3 right-4 font-mono text-[10px] uppercase tracking-[0.25em] text-amber/70">
            {hoverInfo ? "Strecke" : "Tipp"}
          </div>
          {hoverInfo ? (
            <div>
              <div className="font-mono text-[11px] tracking-[0.2em] text-cream/60 uppercase">
                {hoverInfo.a.stadt} ↔ {hoverInfo.b.stadt}
              </div>
              <div className="font-display text-3xl md:text-4xl mt-1">
                {hoverInfo.from} → {hoverInfo.to}
              </div>
              <div className="mt-3 flex items-baseline gap-4">
                <div>
                  <div className="font-display text-3xl text-amber">{hoverInfo.n}</div>
                  <div className="font-mono text-[10px] tracking-[0.2em] uppercase text-cream/60">geflogen</div>
                </div>
                {hoverInfo.extrem && (
                  <Pill tone="inv">geografischer Eckpunkt</Pill>
                )}
              </div>
            </div>
          ) : (
            <div className="text-cream/80 text-sm leading-relaxed">
              Über eine Linie fahren, dann zeigt sich Strecke und Anzahl.
              Gestrichelte Linien sind die vier geografischen Eckpunkte:
              Tokio im Osten, Vancouver im Westen, Helsinki im Norden, Johannesburg im Süden.
            </div>
          )}
        </div>

        <div className="grid grid-cols-2 gap-3">
          {ECKPUNKTE.map((e) => (
            <button
              key={e.code}
              onMouseEnter={() => setFocusCode(e.code)}
              onMouseLeave={() => setFocusCode(null)}
              className="text-left ticket-dark text-cream px-4 py-3 rounded-sm border border-amber/30 hover:border-amber transition-colors"
            >
              <div className="font-mono text-[10px] tracking-[0.2em] uppercase text-amber">
                {e.label}
              </div>
              <div className="font-display text-2xl mt-1">{e.stadt}</div>
              <div className="font-mono text-[10px] text-cream/55 mt-0.5">{e.code}</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

window.WorldMap = WorldMap;
