// geo-hooks.jsx — location + distance helpers shared by the screens.
// Exposes: window.useUserLocation, window.geoDistM, window.geoMiles
//
// useUserLocation() returns { user:{lat,lng}, live } — starts at a simulated
// WWDC-area location and upgrades to a real GPS fix (live:true) when available.

// Simulated "current location" near De Anza College / WWDC area, Cupertino.
const SIM_LOC = { lat: 37.3190, lng: -122.0450 };

function geoDistM(a, b) {
  const R = 6371000, toR = Math.PI / 180;
  const dLat = (b.lat - a.lat) * toR, dLng = (b.lng - a.lng) * toR;
  const la1 = a.lat * toR, la2 = b.lat * toR;
  const h = Math.sin(dLat / 2) ** 2 + Math.cos(la1) * Math.cos(la2) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}

function geoMiles(m) {
  const mi = m / 1609.34;
  if (mi < 0.19) return { v: String(Math.round(mi * 5280 / 10) * 10), u: "ft" };
  return { v: mi.toFixed(1), u: "mi" };
}

// A debug override (set by the localhost-only DebugPanel via window.__DEBUG_LOC)
// stands in for a real GPS fix so the claim UX can be tested without geolocation.
function _readLoc() {
  return window.__DEBUG_LOC
    ? { user: window.__DEBUG_LOC, live: true }
    : { user: SIM_LOC, live: false };
}

function useUserLocation() {
  const [loc, setLoc] = React.useState(_readLoc);
  React.useEffect(() => {
    const onDbg = () => setLoc(_readLoc());
    window.addEventListener("debug:loc", onDbg);
    // When a debug location is active, skip real GPS entirely.
    if (window.__DEBUG_LOC) return () => window.removeEventListener("debug:loc", onDbg);
    let id = null;
    if ("geolocation" in navigator) {
      id = navigator.geolocation.watchPosition(
        (p) => { if (!window.__DEBUG_LOC) setLoc({ user: { lat: p.coords.latitude, lng: p.coords.longitude }, live: true }); },
        () => {},
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 5000 }
      );
    }
    return () => {
      window.removeEventListener("debug:loc", onDbg);
      if (id != null) navigator.geolocation.clearWatch(id);
    };
  }, []);
  return loc;
}

// Debug: animate the spoofed location from ~0.4 mi out toward `target` so the
// radar plays its full navigating → arrived animation (used by the walk-claim
// flow). Each step dispatches "debug:loc" which useUserLocation re-reads.
window.__debugWalk = function (target, durationMs) {
  if (window.__debugWalkTimer) clearInterval(window.__debugWalkTimer);
  const start = { lat: target.lat - 0.005, lng: target.lng - 0.005 };
  const steps = 48, dur = durationMs || 5200;
  let i = 0;
  const set = (loc) => { window.__DEBUG_LOC = loc; window.dispatchEvent(new Event("debug:loc")); };
  set({ lat: start.lat, lng: start.lng });
  window.__debugWalkTimer = setInterval(() => {
    i++;
    const f = i / steps;
    const e = 1 - Math.pow(1 - f, 2); // ease-out — slows as it arrives
    set({ lat: start.lat + (target.lat - start.lat) * e, lng: start.lng + (target.lng - start.lng) * e });
    if (i >= steps) { clearInterval(window.__debugWalkTimer); window.__debugWalkTimer = null; }
  }, dur / steps);
};
window.__debugWalkStop = function () {
  if (window.__debugWalkTimer) { clearInterval(window.__debugWalkTimer); window.__debugWalkTimer = null; }
};

Object.assign(window, { useUserLocation, geoDistM, geoMiles, SIM_LOC });
