// Animated Earth — dotted globe with recognizable continents
// Continents are defined as lat/lon polygons; we sample a dense grid of point
// inside each polygon so the rotating sphere reads as real landmasses.
const CONTINENTS = [
  // North America (including Alaska, Canada, USA, Mexico, Central America)
  [[70,-156],[70,-140],[69,-128],[68,-110],[71,-95],[72,-80],[67,-62],[60,-58],[52,-55],[47,-52],
   [45,-60],[42,-66],[40,-72],[35,-75],[30,-80],[25,-80],[22,-86],[18,-88],[15,-83],[10,-84],
   [8,-77],[12,-70],[18,-90],[20,-97],[23,-106],[30,-114],[33,-117],[40,-124],[48,-125],[55,-130],
   [60,-140],[60,-150],[65,-165],[68,-166],[70,-156]],
  // South America
  [[12,-72],[10,-62],[5,-52],[0,-50],[-5,-36],[-12,-38],[-22,-41],[-30,-50],[-38,-58],[-45,-66],
   [-52,-70],[-54,-72],[-50,-74],[-42,-73],[-33,-72],[-20,-71],[-10,-78],[-2,-81],[2,-78],[8,-77],[12,-72]],
  // Europe (western + central, connects to Asia below visually)
  [[71,25],[70,30],[66,42],[60,48],[55,40],[52,32],[48,32],[45,40],[44,28],[42,18],[40,22],
   [37,24],[36,15],[38,8],[43,3],[43,-2],[48,-5],[51,-6],[55,-8],[58,-3],[60,5],[63,6],[66,14],[68,20],[71,25]],
  // UK + Ireland (small polygon)
  [[58,-5],[57,-2],[54,1],[51,1],[50,-4],[52,-6],[55,-8],[58,-7],[58,-5]],
  // Africa
  [[36,-6],[35,10],[32,22],[31,32],[28,34],[22,37],[12,43],[10,51],[2,46],[-4,40],[-11,40],
   [-18,37],[-25,33],[-30,31],[-34,25],[-34,19],[-30,17],[-22,14],[-14,13],[-6,9],[-2,5],
   [4,-2],[5,-8],[10,-15],[14,-17],[20,-17],[27,-12],[31,-9],[35,-6],[36,-6]],
  // Asia (large — Middle East through Siberia, India, SE Asia, China, Korea, Russia far east)
  [[66,40],[70,55],[71,70],[72,85],[72,100],[72,115],[72,135],[70,145],[68,170],[65,178],[60,170],
   [58,160],[54,142],[50,140],[45,142],[42,134],[39,128],[35,129],[32,122],[28,122],[22,115],[18,109],
   [12,108],[10,104],[5,100],[2,102],[1,110],[6,117],[10,125],[14,122],[18,121],[22,114],[24,105],
   [20,95],[15,94],[10,80],[8,77],[12,72],[20,69],[25,62],[28,58],[26,52],[22,55],[17,54],[14,48],
   [22,38],[28,34],[32,36],[37,42],[40,48],[45,50],[48,55],[52,60],[58,60],[62,50],[66,45],[66,40]],
  // India extra bulge (already partially covered — leave to Asia)
  // Indonesia / Philippines — small islands chain
  [[-2,100],[-6,106],[-8,115],[-9,125],[-8,140],[-4,135],[0,125],[4,120],[8,124],[13,122],[10,115],[3,108],[-2,100]],
  // Japan
  [[45,142],[42,141],[37,140],[34,135],[33,130],[35,129],[38,138],[42,142],[45,142]],
  // Australia
  [[-12,131],[-11,142],[-16,145],[-20,149],[-28,153],[-34,151],[-38,146],[-39,142],[-34,135],
   [-32,120],[-28,114],[-22,114],[-17,122],[-14,128],[-12,131]],
  // New Zealand — two small blobs
  [[-34,173],[-37,175],[-40,176],[-42,174],[-41,172],[-38,171],[-34,173]],
  [[-42,170],[-44,169],[-46,167],[-47,168],[-46,171],[-43,173],[-42,170]],
  // Greenland
  [[78,-30],[77,-18],[74,-12],[70,-22],[62,-42],[70,-52],[77,-52],[78,-42],[78,-30]],
  // Antarctica (ring near south pole, drawn as a latitude band)
  [[-66,-180],[-66,-140],[-68,-100],[-70,-60],[-72,-20],[-70,20],[-68,60],[-68,100],[-70,140],[-66,180],
   [-80,180],[-85,90],[-88,0],[-85,-90],[-80,-180],[-66,-180]],
];

// Point-in-polygon test (ray casting) in lat/lon space
function inPolygon(lat, lon, poly) {
  let inside = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [yi, xi] = poly[i];
    const [yj, xj] = poly[j];
    const intersect = ((yi > lat) !== (yj > lat)) &&
      (lon < ((xj - xi) * (lat - yi)) / ((yj - yi) || 1e-9) + xi);
    if (intersect) inside = !inside;
  }
  return inside;
}

const LAND = (() => {
  const pts = [];
  // Equal-area sampling: step lon by 2/cos(lat) so dot density stays uniform
  // across the sphere instead of bunching at the poles.
  for (let lat = -85; lat <= 80; lat += 2) {
    const cosLat = Math.max(0.1, Math.cos(lat * Math.PI / 180));
    const lonStep = 2 / cosLat;
    for (let lon = -180; lon <= 180; lon += lonStep) {
      for (let c = 0; c < CONTINENTS.length; c++) {
        if (inPolygon(lat, lon, CONTINENTS[c])) {
          const jlat = lat + (Math.random() - 0.5) * 1.4;
          const jlon = lon + (Math.random() - 0.5) * 1.4 / cosLat;
          pts.push([jlat, jlon]);
          break;
        }
      }
    }
  }
  return pts;
})();

const CITY_COORDS = [
  [40.7, -74.0],   // NYC
  [53.3, -6.2],    // Dublin
  [31.2, 121.5],   // Shanghai
  [22.5, 114.0],   // Shenzhen
  [10.8, 106.7],   // HCMC
  [6.2, -75.6],    // Medellín
  [34.0, -118.2],  // LA
  [51.9, 4.5],     // Rotterdam
  [33.7, -84.4],   // Atlanta
  [-33.9, 151.2],  // Sydney
  [1.3, 103.8],    // Singapore
  [19.4, -99.1],   // Mexico City
];

function Globe() {
  const [rot, setRot] = React.useState(0);
  React.useEffect(() => {
    let raf;
    let last = performance.now();
    const tick = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      setRot(r => r + dt * 6); // 6 deg/sec
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const R = 340;
  const cx = 400, cy = 400;
  const tilt = -0.35;
  const cosT = Math.cos(tilt), sinT = Math.sin(tilt);

  // Project [lat, lon] to screen, return {px, py, z}
  const project = (lat, lon) => {
    const phi = (90 - lat) * Math.PI / 180;
    const theta = (lon + rot) * Math.PI / 180;
    const x3 = Math.sin(phi) * Math.cos(theta);
    const y3 = Math.cos(phi);
    const z3 = Math.sin(phi) * Math.sin(theta);
    const y3b = y3 * cosT - z3 * sinT;
    const z3b = y3 * sinT + z3 * cosT;
    return { px: cx + x3 * R, py: cy + y3b * R, z: z3b };
  };

  // Latitude circles (static, don't rotate)
  const lats = [-60, -30, 0, 30, 60].map(lat => {
    const rad = lat * Math.PI / 180;
    const y = cy + R * Math.sin(rad) * cosT;
    const rx = R * Math.cos(rad);
    const ry = rx * Math.abs(sinT);
    return { y, rx, ry };
  });

  // Landmass dots
  const landDots = LAND.map(([lat, lon], i) => {
    const p = project(lat, lon);
    if (p.z < -0.05) return null;
    const op = Math.max(0.15, Math.min(1, (p.z + 0.3) / 1.3));
    return { ...p, op, key: i };
  }).filter(Boolean);

  // Cities
  const cities = CITY_COORDS.map(([lat, lon], i) => {
    const p = project(lat, lon);
    return { ...p, key: i };
  });

  // Arcs between visible city pairs (recompute as they rotate in)
  const pairs = [[0,3],[0,5],[3,6],[1,0],[4,0],[7,1],[2,3],[10,3],[2,9]];
  const arcs = pairs.map(([a, b]) => {
    const na = cities[a], nb = cities[b];
    if (na.z < 0.05 || nb.z < 0.05) return null;
    const mx = (na.px + nb.px) / 2;
    const my = (na.py + nb.py) / 2;
    const dx = nb.px - na.px, dy = nb.py - na.py;
    const dist = Math.sqrt(dx*dx + dy*dy);
    if (dist < 1) return null;
    const ux = -dy / dist, uy = dx / dist;
    const lift = Math.min(80, dist * 0.3);
    return { a: na, b: nb, cx: mx + ux * lift, cy: my + uy * lift, key: `${a}-${b}` };
  }).filter(Boolean);

  return (
    <svg viewBox="0 0 800 800" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <radialGradient id="globeGlow" cx="50%" cy="50%" r="50%">
          <stop offset="60%" stopColor="oklch(0.35 0.08 220)" stopOpacity="0"/>
          <stop offset="85%" stopColor="oklch(0.55 0.12 210)" stopOpacity="0.20"/>
          <stop offset="100%" stopColor="oklch(0.55 0.12 210)" stopOpacity="0"/>
        </radialGradient>
        <radialGradient id="oceanGrad" cx="45%" cy="40%" r="55%">
          <stop offset="0" stopColor="oklch(0.28 0.05 220)" stopOpacity="0.75"/>
          <stop offset="100%" stopColor="oklch(0.15 0.04 230)" stopOpacity="0.9"/>
        </radialGradient>
        <linearGradient id="arcGrad" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0" stopColor="oklch(0.88 0.11 200)" stopOpacity="0"/>
          <stop offset="0.5" stopColor="oklch(0.88 0.11 200)" stopOpacity="0.75"/>
          <stop offset="1" stopColor="oklch(0.88 0.11 200)" stopOpacity="0"/>
        </linearGradient>
        <filter id="nodeGlow" x="-200%" y="-200%" width="500%" height="500%">
          <feGaussianBlur stdDeviation="4"/>
        </filter>
      </defs>

      {/* Atmospheric glow */}
      <circle cx={cx} cy={cy} r={R + 40} fill="url(#globeGlow)" />

      {/* Ocean sphere */}
      <circle cx={cx} cy={cy} r={R} fill="url(#oceanGrad)" />

      {/* Latitude circles */}
      {lats.map((l, i) => (
        <ellipse key={`lat${i}`} cx={cx} cy={l.y} rx={l.rx} ry={l.ry}
          fill="none" stroke="oklch(0.55 0.08 215)" strokeWidth="0.5" strokeOpacity="0.14" />
      ))}

      {/* Longitude meridians (static frame) */}
      {[0, 30, 60, 90, 120, 150].map((deg, i) => {
        const rad = deg * Math.PI / 180;
        const rx = R * Math.abs(Math.sin(rad));
        return (
          <ellipse key={`lon${i}`} cx={cx} cy={cy} rx={rx || 0.5} ry={R}
            fill="none" stroke="oklch(0.55 0.08 215)" strokeWidth="0.5" strokeOpacity="0.10" />
        );
      })}

      {/* Landmass dots */}
      {landDots.map(d => (
        <circle key={d.key} cx={d.px} cy={d.py} r={1.5}
          fill="oklch(0.78 0.12 195)" opacity={d.op * 0.9} />
      ))}

      {/* Connection arcs */}
      {arcs.map(arc => (
        <g key={arc.key}>
          <path d={`M ${arc.a.px} ${arc.a.py} Q ${arc.cx} ${arc.cy} ${arc.b.px} ${arc.b.py}`}
            fill="none" stroke="url(#arcGrad)" strokeWidth="0.8" opacity="0.55" />
          <circle r="2.2" fill="oklch(0.92 0.10 200)">
            <animateMotion dur="4s" repeatCount="indefinite"
              path={`M ${arc.a.px} ${arc.a.py} Q ${arc.cx} ${arc.cy} ${arc.b.px} ${arc.b.py}`}/>
          </circle>
        </g>
      ))}

      {/* City nodes */}
      {cities.filter(c => c.z >= -0.05).map(n => {
        const vis = Math.max(0, Math.min(1, (n.z + 0.05) / 0.3));
        return (
          <g key={n.key} opacity={vis}>
            <circle cx={n.px} cy={n.py} r="5" fill="oklch(0.85 0.14 200)" opacity="0.25" filter="url(#nodeGlow)"/>
            <circle cx={n.px} cy={n.py} r="2.4" fill="oklch(0.94 0.10 195)" opacity="0.98"/>
            <circle cx={n.px} cy={n.py} r="2.4" fill="none" stroke="oklch(0.88 0.12 200)" strokeWidth="0.6" opacity="0.7">
              <animate attributeName="r" values="2.4;14;2.4" dur={`${3 + (n.key % 3)}s`} repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0.7;0;0.7" dur={`${3 + (n.key % 3)}s`} repeatCount="indefinite"/>
            </circle>
          </g>
        );
      })}

      {/* Terminator shading — subtle dark edge */}
      <circle cx={cx} cy={cy} r={R} fill="none" stroke="oklch(0.10 0.02 230)" strokeWidth="2" strokeOpacity="0.4"/>
    </svg>
  );
}

const HERO_VARIANTS = {
  os: {
    eyebrow: 'AI-Native Supply Chain · As a Service',
    h1: (<>Your <span className="italic">AI-powered</span> Supply Chain.</>),
    sub: 'AI-native infrastructure that gives your brand the supply chain power and pricing once reserved for the giants.',
  },
  precision: {
    eyebrow: 'Precision Supply Chain · As a Service',
    h1: (<>Supply chain, with <span className="italic">precision.</span></>),
    sub: 'The first AI-native supply chain service for modern brands. From factory to front door, with software-defined controls and a guaranteed 10% lower cost.',
  },
  autopilot: {
    eyebrow: 'Supply Chain · On Autopilot',
    h1: (<>Put your supply chain on <span className="italic">autopilot.</span></>),
    sub: 'Fully-managed, AI-native supply chain for e-commerce and DTC brands. One partner, one platform, total visibility, and a guaranteed 10% cost reduction.',
  },
};

function Hero({ variant }) {
  const v = HERO_VARIANTS[variant] || HERO_VARIANTS.os;
  return (
    <section className="hero">
      <div className="hero-globe">
        <iframe src="uploads/globe/index.html" title="Global supply chain network" frameBorder="0" scrolling="no" style={{position:'absolute', inset:0, width:'100%', height:'100%', border:0, pointerEvents:'none'}}></iframe>
      </div>
      <div className="hero-vignette" />
      <div className="container hero-inner">
        <div className="hero-pill">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M6 1.5L7.2 4.8L10.5 6L7.2 7.2L6 10.5L4.8 7.2L1.5 6L4.8 4.8L6 1.5Z" fill="currentColor"/>
          </svg>
          {v.eyebrow}
        </div>
        <h1>{v.h1}</h1>
        <p className="hero-sub">{v.sub}</p>
        <div className="hero-ctas">
          <a href="contact-us.html" onClick={(e) => { if (window.__setView) { e.preventDefault(); window.__setView('contact'); window.scrollTo({top:0}); } }} className="btn btn-primary btn-lg">
            Talk to an expert
            <svg className="arr" width="12" height="12" viewBox="0 0 10 10" fill="none"><path d="M2 5h6m0 0L5.5 2.5M8 5 5.5 7.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </a>
        </div>
      </div>
      <div className="hero-inline-stats">
        <span className="item">POWERING <b>1M+</b> HOME DELIVERIES / MONTH</span>
        <span className="item"><b>$300M+</b> REVENUE MANAGED</span>
        <span className="item"><b>45+</b> SUPPLY CHAIN EXPERTS</span>
      </div>
    </section>
  );
}

window.Hero = Hero;
