// pc-global2.jsx v8 — map-led, immersive coverage moment.
// Large near-full-bleed world map as a background canvas (cropping is fine).
// Copy is overlaid on the left over a soft scrim. No connecting lines (that read
// as a flight route) — just pink active dots with breathing halos + small labels,
// communicating worldwide operational coverage, same Sayso standard everywhere.

const GLB2_CSS = `
  .glb2-sec { position: relative; background: #EAEBE7; overflow: hidden;
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    padding: 72px 0; }
  /* faint world map sits behind everything as a light texture */
  .glb2-mapbg { position: absolute; inset: 0; z-index: 0; pointer-events: none;
    display: flex; align-items: center; justify-content: center; }
  .glb2-mapbg .glb2-mapband { width: 100%; max-width: 1100px; aspect-ratio: 1000 / 330; }
  .glb2-mapbg::after { content: ""; position: absolute; inset: 0; pointer-events: none;
    background:
      linear-gradient(to right, #EAEBE7 0%, rgba(234,235,231,0) 18%, rgba(234,235,231,0) 82%, #EAEBE7 100%),
      radial-gradient(120% 130% at 50% 50%, rgba(234,235,231,0.45) 34%, rgba(234,235,231,0) 78%); }
  .glb2-head { position: relative; z-index: 2; text-align: center; width: 100%;
    max-width: 760px; margin: 0 auto; padding: 0 var(--pc-pad);
    display: flex; flex-direction: column; align-items: center; }
  .glb2-sub { max-width: 52ch; margin: 14px auto 0; text-align: center; }
  .glb2-pills { display: flex; flex-wrap: wrap; gap: 9px; margin-top: 24px; justify-content: center; }
  .glb2-pill { display: inline-flex; align-items: center; gap: 8px; font: 600 12.5px/1 var(--font-sans);
    letter-spacing: -0.005em; color: var(--text-primary); background: #fff; border: 1px solid var(--line);
    border-radius: 999px; padding: 9px 15px 9px 13px; box-shadow: var(--shadow-card); }
  .glb2-pill::before { content: ""; width: 7px; height: 7px; border-radius: 999px; background: var(--brand-600); flex: none; }
  .glb2-micro { margin-top: 16px; max-width: 52ch; text-align: center;
    font: 400 13px/1.5 var(--font-sans); color: var(--text-tertiary); }

  .glb2-mapband { position: relative; width: 100%; height: 100%; }

  .sayso-coverage-map {
    --sayso-land:   #FBFCFA;
    position: relative; width: 100%; height: 100%;
  }
  .sayso-coverage-map svg.world { overflow: visible; }
  .sayso-coverage-map .land path { fill: var(--sayso-land); stroke: none; }
  @media (max-width: 760px) {
    .glb2-sec { padding: 56px 0; }
  }
`;

// Primary markets get a larger dot, a quiet ring, and a label.
// [lon, lat, name, anchor, labelDX, labelDY, showLabel]
// Labelled hubs anchor each region. Most filming happens in big US/EU cities, but
// named anchors on every populated continent make the global footprint obvious.
const GLB2_PRIMARY = [
  [-122.42, 37.77, 'San Francisco', 'start',   9, -10, true],
  [-74.01,  40.71, 'New York',      'end',    -9, -10, true],
  [-0.13,   51.51, 'London',        'end',    -9,  16, true],
  [13.40,   52.52, 'Berlin',        'start',  10,  16, true],
  [-46.63, -23.55, 'São Paulo',     'start',   9,  15, true],
  [103.82,   1.35, 'Singapore',     'end',    -9,  15, true],
  [151.21, -33.87, 'Sydney',        'end',    -9,  15, true],
];
// Density map of 1,000 films. Each HUB is [lon, lat, weight, spread°]: weight =
// roughly how many films we've shot there, so big metros become dense clusters of
// many dots while remote locations get a single lonely dot. Points are scattered
// with a seeded gaussian jitter around each hub (deterministic — same every load).
const GLB2_HUBS = [
  // ── North America (big clusters) ──
  [-74.01, 40.71, 46, 1.7], [-118.24, 34.05, 40, 1.8], [-122.42, 37.77, 34, 1.5],
  [-87.63, 41.88, 22, 1.4], [-97.74, 30.27, 16, 1.3], [-122.33, 47.61, 15, 1.3],
  [-71.06, 42.36, 15, 1.2], [-80.19, 25.76, 16, 1.4], [-84.39, 33.75, 12, 1.3],
  [-96.80, 32.78, 11, 1.3], [-104.99, 39.74, 9, 1.3], [-79.38, 43.65, 16, 1.4],
  [-123.12, 49.28, 10, 1.3], [-99.13, 19.43, 12, 1.5],
  // ── Europe (big clusters) ──
  [-0.13, 51.51, 44, 1.5], [2.35, 48.86, 28, 1.4], [13.40, 52.52, 30, 1.5],
  [4.90, 52.37, 17, 1.2], [-3.70, 40.42, 14, 1.4], [2.17, 41.39, 12, 1.2],
  [9.19, 45.46, 12, 1.3], [11.58, 48.14, 12, 1.2], [-6.26, 53.35, 8, 1.1],
  [18.07, 59.33, 8, 1.2], [-9.14, 38.72, 7, 1.2], [8.54, 47.37, 7, 1.1],
  [12.50, 41.90, 10, 1.3], [12.57, 55.68, 7, 1.1], [21.01, 52.23, 6, 1.2],
  // ── Asia + Middle East (medium) ──
  [34.78, 32.08, 10, 1.2], [55.27, 25.20, 12, 1.4], [72.88, 19.08, 11, 1.5],
  [77.21, 28.61, 8, 1.4], [100.50, 13.76, 9, 1.4], [103.82, 1.35, 12, 1.0],
  [114.17, 22.32, 10, 1.0], [121.47, 31.23, 10, 1.3], [116.40, 39.90, 8, 1.3],
  [126.98, 37.57, 9, 1.2], [139.69, 35.68, 18, 1.3], [120.98, 14.60, 6, 1.2],
  [106.85, -6.21, 7, 1.3],
  // ── South America (medium + remote) ──
  [-46.63, -23.55, 14, 1.5], [-43.20, -22.91, 8, 1.3], [-58.38, -34.60, 9, 1.4],
  [-74.07, 4.71, 6, 1.3], [-77.04, -12.05, 5, 1.2], [-70.65, -33.45, 5, 1.2],
  [-71.97, -13.53, 1, 0], [-75.56, 6.25, 2, 0.6],
  // ── Africa (medium + remote) ──
  [18.42, -33.92, 7, 1.3], [28.05, -26.20, 6, 1.3], [36.82, -1.29, 3, 0.8],
  [3.38, 6.52, 4, 1.0], [31.24, 30.04, 5, 1.2], [-7.98, 31.63, 1, 0], [-0.19, 5.60, 1, 0],
  // ── Oceania (medium + remote) ──
  [151.21, -33.87, 14, 1.4], [144.96, -37.81, 9, 1.3], [174.76, -36.85, 6, 1.2],
  [115.86, -31.95, 4, 1.1], [115.22, -8.65, 1, 0],
  // ── Lonely single dots in remote places ──
  [-157.86, 21.31, 1, 0], [85.32, 27.71, 1, 0], [-149.43, -17.65, 1, 0],
  [178.44, -18.14, 1, 0], [-90.97, -0.74, 1, 0], [-149.90, 61.22, 1, 0], [106.92, 47.92, 1, 0],
];
const GLB2_SECONDARY = (function () {
  function mulberry32(a) { return function () { a |= 0; a = a + 0x6D2B79F5 | 0; var t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
  var rng = mulberry32(20260622);
  function gauss() { var u = rng() || 1e-9, v = rng(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); }
  var pts = [];
  GLB2_HUBS.forEach(function (h) {
    var n = h[2], sp = h[3] || 0;
    for (var i = 0; i < n; i++) {
      if (sp === 0) pts.push([h[0], h[1]]);
      else pts.push([h[0] + gauss() * sp, h[1] + gauss() * sp * 0.62]);
    }
  });
  return pts;
})();

// static marker sizes — clear two-tier hierarchy (primary clearly larger than secondary)
const GLB2_DOT_R = 1.2, GLB2_PRIMARY_R = 3.4, GLB2_PRIMARY_RING = 8.2;

// render space + viewbox. Half-height world band: a wide, short window centred on
// the inhabited latitudes (~63°N → ~42°S) so every continent shows but the strip
// is shallow. meet + a matching container aspect-ratio = exact fill, no gaps.
const GLB2_W = 1000, GLB2_RENDER_H = 480, GLB2_VB_Y = 78, GLB2_VB_H = 330;

function initSaysoMap(container) {
  if (typeof d3 === 'undefined' || typeof topojson === 'undefined') return null;
  var SVG_NS = 'http://www.w3.org/2000/svg';
  var gLand   = container.querySelector('.land');
  var gCities = container.querySelector('.cities');

  // Labels are kept visible (copy no longer overlaps the map). We only hide a label
  // if it would spill outside the visible SVG horizontally.
  function refineLabels() {
    var svg = container.querySelector('svg.world');
    if (!svg) return;
    var sb = svg.getBoundingClientRect();
    var pad = 4;
    container.querySelectorAll('.city-label').forEach(function(lb) {
      lb.style.visibility = 'visible';
      var b = lb.getBoundingClientRect();
      if (b.left < sb.left + pad || b.right > sb.right - pad) lb.style.visibility = 'hidden';
    });
  }
  var onResize = function() { refineLabels(); };
  window.addEventListener('resize', onResize);

  fetch('https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json')
    .then(function(r) { return r.json(); })
    .then(function(world) {
      var countries = topojson.feature(world, world.objects.countries);
      countries.features = countries.features.filter(function(f) { return f.id !== '010'; }); // drop Antarctica
      // Whole world, centred ~lon 15 so the Americas (left) and Asia/Oceania (right)
      // both stay in frame. Southern hemisphere kept (only Antarctica is dropped).
      var proj = d3.geoNaturalEarth1().fitExtent([[10, 10], [GLB2_W - 10, GLB2_RENDER_H - 10]], countries);
      var fc = proj([15, 15]); var ft = proj.translate();
      proj.translate([ft[0] + (GLB2_W / 2 - fc[0]), ft[1]]);
      var pathGen = d3.geoPath(proj);

      countries.features.forEach(function(c) {
        var dStr = pathGen(c); if (!dStr) return;
        var path = document.createElementNS(SVG_NS, 'path');
        path.setAttribute('d', dStr);
        gLand.appendChild(path);
      });
      // dots + labels intentionally omitted — map reads as a faint background texture.
    })
    .catch(function(err) { console.error('Sayso map: failed to load world data.', err); });

  return function cleanup() { window.removeEventListener('resize', onResize); };
}

function SaysoMap({ shown }) {
  const mapRef = React.useRef(null);
  const cleanupRef = React.useRef(null);
  React.useEffect(() => {
    if (!shown || !mapRef.current || cleanupRef.current) return;
    const cleanup = initSaysoMap(mapRef.current);
    if (cleanup) cleanupRef.current = cleanup;
    return () => { if (cleanupRef.current) { cleanupRef.current(); cleanupRef.current = null; } };
  }, [shown]);
  return (
    <div ref={mapRef} className="sayso-coverage-map" role="img" aria-label="Sayso global coverage map with active markers across North America, Europe and worldwide">
      <svg className="world" viewBox={`0 ${GLB2_VB_Y} ${GLB2_W} ${GLB2_VB_H}`} preserveAspectRatio="xMidYMid meet">
        <g className="land"></g>
        <g className="cities"></g>
      </svg>
    </div>
  );
}

function PcGlobal() {
  const [ref, shown] = usePcReveal();
  return (
    <section className="pc-sec glb2-sec" ref={ref}>
      <div className="glb2-mapbg"><div className="glb2-mapband"><SaysoMap shown={shown} /></div></div>
      <div className="glb2-head">
        <h2 className="pc-h2" style={rise(shown, 0)}>Global coverage.<br />Same <span className="pc-pink">standard.</span></h2>
        <p className="pc-lead glb2-sub" style={rise(shown, 60)}>Film customer stories across your key markets, then turn the same shoot into ads your teams can run.</p>
        <div className="glb2-pills" style={rise(shown, 120)}>
          <span className="glb2-pill">Local crews</span>
          <span className="glb2-pill">Same workflow</span>
          <span className="glb2-pill">Ready-to-run ads</span>
        </div>
        <p className="glb2-micro" style={rise(shown, 170)}>1,000+ films shot worldwide. Wherever your customers are, we film.</p>
      </div>
    </section>
  );
}

Object.assign(window, { GLB2_CSS, PcGlobal });
