// network-map.jsx — Interactive US network map (About page hero).
//
// A dot-matrix map of the contiguous United States with city nodes linked by
// animated arcs. Hover or focus a city to highlight its connections.
//
// No external data or libraries: the outline is a simplified boundary
// (lon/lat) projected with an Albers equal-area conic, then filled with a
// dot grid. Accuracy is illustrative, not cartographic.
//
// CITIES: dots only (no visible names), per the brief. Add or remove entries here.

const NET_CITIES = [
  { id: 'nyc', lon: -74.0, lat: 40.71, hq: true },   // New York, NY (HQ)
  { id: 'de', lon: -75.55, lat: 39.74 },             // Wilmington, DE
  { id: 'det', lon: -83.05, lat: 42.33 },            // Detroit, MI
  { id: 'kc', lon: -94.58, lat: 39.1 },              // Kansas City
  { id: 'chi', lon: -87.63, lat: 41.88 },            // Chicago, IL
  { id: 'sf', lon: -122.42, lat: 37.77 },            // San Francisco, CA
  { id: 'sea', lon: -122.33, lat: 47.61 }            // Seattle, WA
];

// Simplified contiguous-US boundary, clockwise from Cape Flattery.
const NET_OUTLINE = [
  [-124.7, 48.4], [-123.1, 49.0], [-95.2, 49.0], [-94.8, 48.7], [-92.0, 48.3], [-89.5, 48.0],
  [-88.4, 48.3], [-84.6, 46.5], [-83.5, 46.1], [-82.5, 45.3], [-82.4, 43.0], [-83.1, 42.0],
  [-82.5, 41.7], [-79.0, 42.8], [-79.2, 43.4], [-76.3, 43.5], [-75.0, 44.8], [-71.5, 45.0],
  [-70.8, 45.4], [-69.2, 47.4], [-67.8, 47.1], [-67.8, 45.6], [-67.0, 44.9], [-68.8, 44.3],
  [-70.2, 43.6], [-70.8, 42.9], [-71.0, 42.3], [-70.0, 41.8], [-70.6, 41.5], [-71.9, 41.3],
  [-73.6, 41.0], [-74.0, 40.6], [-74.1, 39.8], [-74.9, 38.9], [-75.1, 38.8], [-75.97, 37.1],
  [-76.3, 37.0], [-75.5, 35.3], [-76.5, 34.7], [-77.9, 33.9], [-79.2, 33.2], [-80.8, 32.2],
  [-81.4, 30.9], [-81.3, 29.9], [-80.6, 28.4], [-80.0, 26.7], [-80.4, 25.2], [-81.1, 25.1],
  [-81.8, 26.1], [-82.7, 27.6], [-82.8, 29.0], [-84.0, 30.0], [-85.4, 29.7], [-86.5, 30.4],
  [-88.1, 30.4], [-89.6, 30.2], [-89.4, 29.0], [-90.3, 29.2], [-91.8, 29.5], [-93.8, 29.7],
  [-94.8, 29.3], [-96.4, 28.4], [-97.4, 27.4], [-97.2, 25.9], [-99.1, 26.4], [-99.5, 27.5],
  [-100.3, 28.3], [-101.4, 29.8], [-102.7, 29.7], [-103.1, 29.0], [-104.5, 29.6], [-106.5, 31.8],
  [-108.2, 31.8], [-108.2, 31.3], [-111.1, 31.3], [-114.8, 32.5], [-117.1, 32.5], [-118.5, 34.0],
  [-120.6, 34.6], [-121.9, 36.6], [-122.5, 37.8], [-123.7, 38.9], [-124.2, 40.4], [-124.2, 41.9],
  [-124.5, 42.8], [-124.0, 46.3], [-124.7, 48.4]
];
// Lake Michigan, cut out of the fill so Michigan reads correctly.
const NET_LAKE = [
  [-87.8, 42.0], [-87.5, 41.65], [-86.6, 41.9], [-86.3, 43.0], [-86.4, 44.0], [-85.6, 45.1],
  [-85.0, 45.8], [-86.6, 45.9], [-87.6, 44.9], [-87.8, 44.4], [-87.6, 43.5], [-87.9, 43.0]
];

// Albers equal-area conic (USA parameters)
function netAlbers(lon, lat) {
  const r = Math.PI / 180;
  const p1 = 29.5 * r, p2 = 45.5 * r, p0 = 37.5 * r, l0 = -96 * r;
  const n = (Math.sin(p1) + Math.sin(p2)) / 2;
  const C = Math.cos(p1) ** 2 + 2 * n * Math.sin(p1);
  const rho0 = Math.sqrt(C - 2 * n * Math.sin(p0)) / n;
  const rho = Math.sqrt(C - 2 * n * Math.sin(lat * r)) / n;
  const th = n * (lon * r - l0);
  return [rho * Math.sin(th), -(rho0 - rho * Math.cos(th))];
}

function netInPoly(x, y, poly) {
  let inside = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
  }
  return inside;
}

const NET_W = 1000, NET_H = 620, NET_PAD = 20, NET_STEP = 12;

function netBuild() {
  const raw = NET_OUTLINE.map(([lo, la]) => netAlbers(lo, la));
  const xs = raw.map((p) => p[0]), ys = raw.map((p) => p[1]);
  const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys);
  const s = Math.min((NET_W - NET_PAD * 2) / (maxX - minX), (NET_H - NET_PAD * 2) / (maxY - minY));
  const ox = (NET_W - (maxX - minX) * s) / 2, oy = (NET_H - (maxY - minY) * s) / 2;
  const proj = (lo, la) => { const [x, y] = netAlbers(lo, la); return [ox + (x - minX) * s, oy + (y - minY) * s]; };
  const outline = NET_OUTLINE.map(([lo, la]) => proj(lo, la));
  const lake = NET_LAKE.map(([lo, la]) => proj(lo, la));
  const dots = [];
  for (let y = NET_STEP / 2; y < NET_H; y += NET_STEP) {
    for (let x = NET_STEP / 2; x < NET_W; x += NET_STEP) {
      if (netInPoly(x, y, outline) && !netInPoly(x, y, lake)) dots.push([x, y]);
    }
  }
  const cities = NET_CITIES.map((c) => { const [x, y] = proj(c.lon, c.lat); return { ...c, x, y }; });
  const links = [];
  for (let i = 0; i < cities.length; i++) {
    for (let j = i + 1; j < cities.length; j++) {
      const a = cities[i], b = cities[j];
      const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
      const dx = b.x - a.x, dy = b.y - a.y, len = Math.hypot(dx, dy);
      // bow each arc upward, proportional to its length
      let nx = -dy / len, ny = dx / len;
      if (ny > 0) { nx = -nx; ny = -ny; }
      const bow = Math.min(140, Math.max(18, len * 0.28));
      links.push({ a: a.id, b: b.id, len,
        d: `M${a.x.toFixed(1)} ${a.y.toFixed(1)} Q${(mx + nx * bow).toFixed(1)} ${(my + ny * bow).toFixed(1)} ${b.x.toFixed(1)} ${b.y.toFixed(1)}` });
    }
  }
  return { dots, cities, links };
}

function NetworkMap() {
  const data = React.useMemo(netBuild, []);
  const [focus, setFocus] = React.useState(null);
  const reduced = React.useMemo(() => window.matchMedia &&
    window.matchMedia('(prefers-reduced-motion: reduce)').matches, []);
  // Start the build-in animation when the map scrolls into view
  const ref = React.useRef(null);
  const [live, setLive] = React.useState(reduced);
  React.useEffect(() => {
    if (live || !ref.current) return;
    if (!('IntersectionObserver' in window)) { setLive(true); return; }
    const io = new IntersectionObserver((es) => {
      if (es.some((e) => e.isIntersecting)) { setLive(true); io.disconnect(); }
    }, { threshold: 0.25 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [live]);
  const lit = (l) => !focus || l.a === focus || l.b === focus;
  return (
    <figure ref={ref} className={'net-map' + (focus ? ' has-focus' : '') + (live ? ' is-live' : '')}
      role="img" aria-label="Map of the United States with connected points showing where CriterionMD's team and clinicians are based">
      <svg viewBox={`0 0 ${NET_W} ${NET_H}`} aria-hidden="true">
        <g className="net-dots" aria-hidden="true">
          {data.dots.map(([x, y], i) => <circle key={i} cx={x} cy={y} r="2.6" />)}
        </g>
        <g className="net-links" aria-hidden="true">
          {data.links.map((l, i) => (
            <g key={l.a + l.b} className={'net-link' + (lit(l) ? ' is-lit' : '')}
              style={{ '--ld': (0.9 + i * 0.09) + 's' }}>
              <path className="net-link-base" d={l.d} pathLength="1" />
              <path className="net-link-flow" d={l.d} style={{ animationDelay: (i * -0.7) + 's' }} />
              {/* A bright pulse travels each connection, staggered */}
              {live && !reduced && (
                <circle className="net-packet" r="3">
                  <animateMotion dur={(2.6 + (i % 5) * 0.45) + 's'} begin={(2.6 + (i * 0.53) % 4) + 's'}
                    repeatCount="indefinite" path={l.d} keyPoints={i % 2 ? '1;0' : '0;1'} keyTimes="0;1" calcMode="linear" />
                </circle>
              )}
            </g>
          ))}
        </g>
        <g className="net-cities">
          {data.cities.map((c, i) => (
            <g key={c.id} className={'net-city' + (c.hq ? ' is-hq' : '') + (focus === c.id ? ' is-on' : '')}
              transform={`translate(${c.x.toFixed(1)} ${c.y.toFixed(1)})`}
              style={{ '--cd': (0.35 + i * 0.12) + 's' }}
              onMouseEnter={() => setFocus(c.id)} onMouseLeave={() => setFocus(null)}>
              <circle className="net-hit" r="22" />
              <circle className="net-pulse" r="7" style={{ animationDelay: (i * 0.37) + 's' }} />
              <circle className="net-node" r={c.hq ? 7 : 6} />
            </g>
          ))}
        </g>
      </svg>
    </figure>
  );
}

Object.assign(window, { NetworkMap });
