// Route map — editorial infographic with REAL country silhouettes (Natural Earth)
// Source SVG viewBox: 800x307, equirectangular projection, lon_0=90
const { useEffect, useState } = React;

const X_SCALE = 3.98, X_ORIGIN = 399.3;
const Y_SCALE = 4.67, Y_ORIGIN = 348.4;
const proj = (lon, lat) => ({
  x: X_ORIGIN + (lon - 90) * X_SCALE,
  y: Y_ORIGIN - lat * Y_SCALE,
});

function RouteMap(){
  const rawCities = [
    { id: "spb", name: "Санкт-Петербург", lon: 30.31, lat: 59.94, side: "ru", hub: true, tag: "головной офис", labelDir: "up" },
    { id: "msk", name: "Москва",         lon: 37.62, lat: 55.75, side: "ru", hub: true, labelDir: "down" },
    { id: "ekb", name: "Екатеринбург",   lon: 60.61, lat: 56.84, side: "ru", labelDir: "up" },
    { id: "nsk", name: "Новосибирск",    lon: 82.93, lat: 55.03, side: "ru", labelDir: "up" },
    { id: "alm", name: "Алматы",         lon: 76.95, lat: 43.26, side: "kz", labelDir: "left" },
    { id: "ur",  name: "Урумчи",         lon: 87.62, lat: 43.83, side: "cn", labelDir: "right" },
    { id: "bla", name: "Благовещенск",   lon: 127.5, lat: 50.27, side: "ru", labelDir: "left" },
    { id: "hh",  name: "Хэйхэ",          lon: 127.5, lat: 50.24, side: "cn", labelDir: "right" },
    { id: "bj",  name: "Пекин",          lon: 116.4, lat: 39.9,  side: "cn", labelDir: "right" },
    { id: "yw",  name: "Иу",             lon: 120.07, lat: 29.31, side: "cn", labelDir: "right" },
    { id: "sh",  name: "Шанхай",         lon: 121.47, lat: 31.23, side: "cn", labelDir: "right" },
    { id: "gz",  name: "Гуанчжоу",       lon: 113.27, lat: 23.13, side: "cn", hub: true, tag: "наш склад", labelDir: "left" },
  ];
  const cities = rawCities.map(c => ({ ...c, ...proj(c.lon, c.lat) }));

  const lanes = [
    { from: "gz", to: "msk", mode: "auto" },
    { from: "gz", to: "spb", mode: "auto" },
    { from: "yw", to: "ekb", mode: "auto" },
    { from: "ur", to: "alm", mode: "auto" },
    { from: "hh", to: "bla", mode: "auto" },
    { from: "sh", to: "msk", mode: "sea" },
    { from: "gz", to: "spb", mode: "air" },
    { from: "bj", to: "nsk", mode: "auto" },
  ];

  const find = id => cities.find(c => c.id === id);

  const [t, setT] = useState(0);
  useEffect(() => {
    let raf; const start = performance.now();
    const tick = (now) => { setT(((now - start) / 8000) % 1); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  function curvePath(a, b){
    const mx = (a.x + b.x) / 2;
    const my = Math.min(a.y, b.y) - Math.abs(a.x - b.x) * 0.18 - 16;
    return { d: `M ${a.x} ${a.y} Q ${mx} ${my} ${b.x} ${b.y}`, mx, my };
  }
  function pointOn(a, b, p, cx, cy){
    const x = (1-p)*(1-p)*a.x + 2*(1-p)*p*cx + p*p*b.x;
    const y = (1-p)*(1-p)*a.y + 2*(1-p)*p*cy + p*p*b.y;
    return { x, y };
  }

  // River paths (approximations using lon/lat sequences)
  const rivers = [
    { name: "Волга",  pts: [[37.5,57.3],[44.5,55.7],[47.5,53.4],[48.0,49.5],[47.0,46.4]] },
    { name: "Обь",    pts: [[83.0,54.3],[78.7,57.8],[72.0,62.0],[68.5,66.5],[68.0,71.0]] },
    { name: "Енисей", pts: [[91.4,53.7],[92.8,58.5],[88.0,66.5],[83.0,71.0],[82.0,73.5]] },
    { name: "Лена",   pts: [[105.0,53.5],[114.0,58.5],[126.0,63.5],[127.0,71.0]] },
    { name: "Амур",   pts: [[117.0,49.6],[127.5,50.3],[135.0,48.5],[140.7,53.0]] },
    { name: "Янцзы",  pts: [[103.0,29.5],[110.0,30.6],[115.0,30.0],[121.5,31.7]] },
    { name: "Хуанхэ", pts: [[103.0,36.0],[108.5,35.5],[112.0,34.8],[115.0,37.5],[119.0,37.8]] },
    { name: "Меконг", pts: [[101.0,21.0],[103.5,18.0],[105.5,15.5],[106.0,11.5]] },
  ];

  const countryLabels = [
    { iso: "RUS", name: "РОССИЯ",       sub: "RUSSIAN FEDERATION", lon: 75, lat: 60, primary: true },
    { iso: "CHN", name: "КИТАЙ",        sub: "中华人民共和国",       lon: 100, lat: 35, primary: true },
    { iso: "KAZ", name: "КАЗАХСТАН",    sub: null, lon: 67, lat: 49, hint: true },
    { iso: "MNG", name: "МОНГОЛИЯ",     sub: null, lon: 103, lat: 47, hint: true },
    { iso: "JPN", name: "ЯПОНИЯ",       sub: null, lon: 138, lat: 37, hint: true },
    { iso: "IND", name: "ИНДИЯ",        sub: null, lon: 79, lat: 23, hint: true, tiny: true },
  ];

  // Seas / oceans
  const seaLabels = [
    { name: "К А С П И Й С К О Е   М О Р Е", lon: 51, lat: 41 },
    { name: "А Р А Л", lon: 60, lat: 45 },
    { name: "ЖЁЛТОЕ МОРЕ", lon: 123, lat: 36 },
    { name: "ЯПОНСКОЕ МОРЕ", lon: 134, lat: 41 },
    { name: "ОХОТСКОЕ МОРЕ", lon: 148, lat: 56 },
    { name: "Ю.-КИТ. МОРЕ", lon: 117, lat: 17 },
  ];

  const C = (window.COUNTRIES || {});
  const allIso = Object.keys(C);
  const highlightSet = new Set(["RUS", "CHN"]);

  // Helper: build smooth river path through points (catmull-rom-ish via quadratic mids)
  function riverPath(pts){
    const proj_pts = pts.map(([lon,lat]) => proj(lon, lat));
    if (proj_pts.length < 2) return "";
    let d = `M ${proj_pts[0].x} ${proj_pts[0].y}`;
    for (let i = 1; i < proj_pts.length; i++){
      const p = proj_pts[i];
      const prev = proj_pts[i-1];
      const mx = (prev.x + p.x) / 2;
      const my = (prev.y + p.y) / 2;
      d += ` Q ${prev.x} ${prev.y} ${mx} ${my}`;
    }
    const last = proj_pts[proj_pts.length-1];
    d += ` T ${last.x} ${last.y}`;
    return d;
  }

  // Label position helpers
  function cityLabelPos(c){
    const dir = c.labelDir || (c.lon < 90 ? "left" : "right");
    if (dir === "right") return { tx: 5, ty: 1.5, anchor: "start", tagY: 8 };
    if (dir === "left")  return { tx: -5, ty: 1.5, anchor: "end", tagY: 8 };
    if (dir === "up")    return { tx: 0, ty: -11, anchor: "middle", tagY: -5 };
    if (dir === "down")  return { tx: 0, ty: 9, anchor: "middle", tagY: 16 };
    return { tx: 5, ty: 1.5, anchor: "start", tagY: 8 };
  }

  return (
    <div className="map-wrap">
      <svg viewBox="100 30 580 230" className="map-svg" preserveAspectRatio="xMidYMid meet" aria-label="Маршруты Китай — Россия">
        <defs>
          <pattern id="grid-fine" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="currentColor" strokeOpacity="0.05" strokeWidth="0.4"/>
          </pattern>
          <pattern id="grid-coarse" width="80" height="80" patternUnits="userSpaceOnUse">
            <path d="M 80 0 L 0 0 0 80" fill="none" stroke="currentColor" strokeOpacity="0.08" strokeWidth="0.4"/>
          </pattern>
          <pattern id="land-hatch" width="3" height="3" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="3" stroke="var(--ink)" strokeOpacity="0.05" strokeWidth="0.6"/>
          </pattern>
          <pattern id="land-hatch-strong" width="3" height="3" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="3" stroke="var(--accent)" strokeOpacity="0.07" strokeWidth="0.6"/>
          </pattern>
          <radialGradient id="hub-glow">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.32"/>
            <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.07"/>
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
          </radialGradient>
          <linearGradient id="lane-grad">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.95"/>
            <stop offset="100%" stopColor="var(--ink)" stopOpacity="0.4"/>
          </linearGradient>
          {/* Curve filter for warping the whole map area */}
          <filter id="paper-warp" x="-2%" y="-2%" width="104%" height="104%">
            <feTurbulence type="fractalNoise" baseFrequency="0.012" numOctaves="2" seed="3" result="noise"/>
            <feDisplacementMap in="SourceGraphic" in2="noise" scale="1.4"/>
          </filter>
        </defs>

        {/* Background grids */}
        <rect x="170" y="55" width="470" height="180" fill="url(#grid-fine)" style={{color: 'var(--ink)'}}/>
        <rect x="170" y="55" width="470" height="180" fill="url(#grid-coarse)" style={{color: 'var(--ink)'}}/>

        {/* Latitude / longitude reference */}
        <g style={{fontFamily: 'var(--mono)', fontSize: '4.5px'}} fill="var(--muted)" opacity="0.5">
          {[60, 50, 40, 30].map(lat => {
            const y = Y_ORIGIN - lat * Y_SCALE;
            return (
              <g key={lat}>
                <line x1="170" y1={y} x2="640" y2={y} stroke="var(--ink)" strokeOpacity="0.05" strokeDasharray="1 2"/>
                <text x="173" y={y - 1.6}>{lat}°</text>
              </g>
            );
          })}
          {[40, 60, 80, 100, 120, 140].map(lon => {
            const x = X_ORIGIN + (lon - 90) * X_SCALE;
            return (
              <g key={lon}>
                <line x1={x} y1="55" x2={x} y2="235" stroke="var(--ink)" strokeOpacity="0.04" strokeDasharray="1 2"/>
                <text x={x + 1.5} y="62">{lon}°</text>
              </g>
            );
          })}
        </g>

        {/* Sea labels (under land) */}
        {seaLabels.map((s, i) => {
          const p = proj(s.lon, s.lat);
          return <text key={i} x={p.x} y={p.y} className="cc-sea" textAnchor="middle">{s.name}</text>;
        })}

        {/* All countries — base layer */}
        <g className="countries-base">
          {allIso.filter(iso => !highlightSet.has(iso)).map(iso => {
            const c = C[iso];
            return (
              <path key={iso} d={c.d} fill="var(--bg-2)" stroke="var(--ink)" strokeOpacity="0.18" strokeWidth="0.35" fillRule={c.fillRule || "nonzero"}/>
            );
          })}
          {allIso.filter(iso => !highlightSet.has(iso)).map(iso => {
            const c = C[iso];
            return (
              <path key={iso + "-h"} d={c.d} fill="url(#land-hatch)" fillRule={c.fillRule || "nonzero"}/>
            );
          })}
        </g>

        {/* Highlighted countries */}
        <g className="countries-hi">
          {["RUS", "CHN"].map(iso => {
            const c = C[iso];
            if (!c) return null;
            return (
              <g key={iso}>
                <path d={c.d} fill="var(--bg-2)" stroke="var(--ink)" strokeOpacity="0.42" strokeWidth="0.55" fillRule={c.fillRule || "nonzero"}/>
                <path d={c.d} fill="url(#land-hatch-strong)" fillRule={c.fillRule || "nonzero"}/>
              </g>
            );
          })}
        </g>

        {/* Rivers — disabled */}
        <g className="rivers" style={{display:'none'}}>
          {rivers.map((r, i) => {
            const d = riverPath(r.pts);
            const mid = proj(r.pts[Math.floor(r.pts.length/2)][0], r.pts[Math.floor(r.pts.length/2)][1]);
            return (
              <g key={i}>
                <path d={d} fill="none" stroke="var(--ink)" strokeOpacity="0.32" strokeWidth="0.5" strokeLinecap="round"/>
                <text x={mid.x} y={mid.y - 1.6} className="river-tx" textAnchor="middle">{r.name}</text>
              </g>
            );
          })}
        </g>

        {/* Country labels */}
        {countryLabels.map(l => {
          const p = proj(l.lon, l.lat);
          if (l.primary) {
            return (
              <g key={l.iso}>
                <text x={p.x} y={p.y} className="cc-label" textAnchor="middle">{l.name}</text>
                {l.sub && <text x={p.x} y={p.y + 7} className="cc-sub" textAnchor="middle">{l.sub}</text>}
              </g>
            );
          }
          return <text key={l.iso} x={p.x} y={p.y} className={l.tiny ? "cc-neighbour-tiny" : "cc-neighbour"} textAnchor="middle">{l.name}</text>;
        })}

        {/* Hub halos */}
        {cities.filter(c => c.hub).map(c => (
          <circle key={`h-${c.id}`} cx={c.x} cy={c.y} r="14" fill="url(#hub-glow)"/>
        ))}

        {/* Lanes */}
        {lanes.map((ln, i) => {
          const a = find(ln.from), b = find(ln.to);
          if (!a || !b) return null;
          const { d, mx, my } = curvePath(a, b);
          const dash = ln.mode === "sea" ? "2.5 2.5" : ln.mode === "air" ? "0.5 2.5" : "none";
          const p = (t + i * 0.09) % 1;
          const pt = pointOn(a, b, p, mx, my);
          return (
            <g key={i}>
              <path d={d} fill="none" stroke="url(#lane-grad)" strokeWidth="0.8" strokeDasharray={dash} strokeLinecap="round"/>
              <circle cx={pt.x} cy={pt.y} r="5" fill="var(--accent)" opacity="0.14"/>
              <circle cx={pt.x} cy={pt.y} r="1.6" fill="var(--accent)"/>
            </g>
          );
        })}

        {/* Cities */}
        {cities.map(c => {
          const lp = cityLabelPos(c);
          return (
            <g key={c.id} transform={`translate(${c.x} ${c.y})`}>
              {c.hub ? (
                <>
                  <circle r="3.8" fill="var(--bg)" stroke="var(--accent)" strokeWidth="0.9"/>
                  <circle r="1.6" fill="var(--accent)"/>
                </>
              ) : (
                <>
                  <circle r="1.7" fill="var(--bg)" stroke="var(--ink)" strokeWidth="0.4"/>
                  <circle r="0.7" fill="var(--ink)"/>
                </>
              )}
              <text x={lp.tx} y={lp.ty} textAnchor={lp.anchor} className="city-name">{c.name}</text>
              {c.tag && (
                <text x={lp.tx} y={lp.tagY} textAnchor={lp.anchor} className="city-tag">{c.tag}</text>
              )}
            </g>
          );
        })}

        {/* Compass */}
        <g transform="translate(660 50)">
          <circle r="6" fill="var(--bg)" stroke="var(--ink)" strokeOpacity="0.2" strokeWidth="0.4"/>
          <line x1="0" y1="-4.5" x2="0" y2="4.5" stroke="var(--ink)" strokeOpacity="0.4" strokeWidth="0.4"/>
          <line x1="-4.5" y1="0" x2="4.5" y2="0" stroke="var(--ink)" strokeOpacity="0.25" strokeWidth="0.4"/>
          <polygon points="0,-4.5 -1,0 0,-2.6 1,0" fill="var(--accent)"/>
          <text y="-7.5" textAnchor="middle" className="compass-n">N</text>
        </g>

        {/* Scale bar */}
        <g transform="translate(115 250)">
          <line x1="0" y1="0" x2="60" y2="0" stroke="var(--ink)" strokeWidth="0.5"/>
          <line x1="0" y1="-2" x2="0" y2="2" stroke="var(--ink)" strokeWidth="0.5"/>
          <line x1="30" y1="-1.5" x2="30" y2="1.5" stroke="var(--ink)" strokeWidth="0.5"/>
          <line x1="60" y1="-2" x2="60" y2="2" stroke="var(--ink)" strokeWidth="0.5"/>
          <text x="0" y="7" className="scale-tx">0</text>
          <text x="30" y="7" textAnchor="middle" className="scale-tx">1500</text>
          <text x="60" y="7" textAnchor="middle" className="scale-tx">3000 км</text>
        </g>

        {/* Legend */}
        <g transform="translate(540 250)">
          <text className="legend-t">РЕЖИМЫ</text>
          <g transform="translate(0 6)">
            <line x1="0" y1="0" x2="8" y2="0" stroke="var(--accent)" strokeWidth="0.8"/>
            <text x="11" y="1.5" className="legend-tx">авто</text>
            <line x1="32" y1="0" x2="40" y2="0" stroke="var(--accent)" strokeWidth="0.8" strokeDasharray="2.5 2.5"/>
            <text x="43" y="1.5" className="legend-tx">море</text>
            <line x1="64" y1="0" x2="72" y2="0" stroke="var(--accent)" strokeWidth="0.8" strokeDasharray="0.5 2.5"/>
            <text x="75" y="1.5" className="legend-tx">авиа</text>
          </g>
        </g>

        <text x="390" y="45" textAnchor="middle" className="map-meta-tx">C/ONE · СЕТЬ МАРШРУТОВ · 2026.Q2</text>
        <text x="675" y="258" textAnchor="end" className="map-meta-tx">Natural Earth · eqc 90°</text>
      </svg>

      <style>{`
        .map-wrap{ width: 100%; position: relative; }
        .map-svg{ width: 100%; height: auto; display: block; }
        .cc-label{ font-family: var(--mono); font-size: 7px; fill: var(--ink); letter-spacing: 0.32em; font-weight: 500; }
        .cc-sub{ font-family: var(--mono); font-size: 4.2px; fill: var(--muted); letter-spacing: 0.2em; }
        .cc-neighbour{ font-family: var(--mono); font-size: 5px; fill: var(--muted); letter-spacing: 0.22em; opacity: 0.78; }
        .cc-neighbour-tiny{ font-family: var(--mono); font-size: 4px; fill: var(--muted); letter-spacing: 0.18em; opacity: 0.6; }
        .cc-sea{ font-family: var(--mono); font-size: 3.6px; fill: var(--muted); opacity: 0.55; letter-spacing: 0.14em; font-style: italic; }
        .city-name{ font-family: var(--sans); font-size: 5.4px; fill: var(--ink); font-weight: 500; }
        .city-tag{ font-family: var(--mono); font-size: 4px; fill: var(--accent); letter-spacing: 0.08em; text-transform: uppercase; }
        .river-tx{ font-family: var(--sans); font-style: italic; font-size: 3.4px; fill: var(--ink); fill-opacity: 0.42; letter-spacing: 0.04em; }
        .compass-n{ font-family: var(--mono); font-size: 4px; fill: var(--muted); letter-spacing: 0.1em; }
        .scale-tx{ font-family: var(--mono); font-size: 4.2px; fill: var(--muted); }
        .legend-t{ font-family: var(--mono); font-size: 4.2px; fill: var(--muted); letter-spacing: 0.14em; }
        .legend-tx{ font-family: var(--mono); font-size: 4.2px; fill: var(--ink-2); }
        .map-meta-tx{ font-family: var(--mono); font-size: 4.2px; fill: var(--muted); letter-spacing: 0.16em; }
      `}</style>
    </div>
  );
}

window.RouteMap = RouteMap;
