#!/usr/bin/env python3
"""
PinLoc - make your iPhone think it's anywhere on Earth.

  * Pin mode:   drop a pin, hit Teleport, the phone sits there.
  * Route mode: pick a start and end, choose Walk / Drive / Bus, and the phone
                travels the route at a believable pace - braking for corners,
                waiting at red lights, stopping at bus stops, and (optionally)
                crawling through live traffic.

Run on your Mac with the iPhone plugged in:
    python3 pinloc.py

Close the browser tab (or press Ctrl+C here) and the real location comes back.

Needs: pip3 install pymobiledevice3   (iOS 17+, Developer Mode on)
Privacy: runs on your Mac. Outside requests only go to the map, search and
routing services (OpenFreeMap, Photon, OpenStreetMap) and TomTom (only if you
add a traffic key).

Use it for fun and testing. You are responsible for following the law and the
terms of any app you use it with. Not affiliated with Apple.

MIT License

Copyright (c) 2026 Miles Vibecode

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import bisect
import json
import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
import webbrowser
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT = 8765
PING_TIMEOUT = 150          # seconds without a ping from the page = tab gone, stop faking
MAX_ROUTE_POINTS = 8 * 3600  # 8 hours at one point per second
PMD = [sys.executable, "-m", "pymobiledevice3"]

lock = threading.Lock()
ready = threading.Event()   # set when the helper says the location is live
state = {
    "proc": None, "starting": None, "lat": None, "lon": None,
    "msg": "Not faking. Using your real location.", "error": False,
    "route": None,  # {"coords": [...], "times": [...], "count": 0, "started": t, "gpx": path}
}
last_ping = time.time()
log_tail = []


# ---------------------------------------------------------------- helpers

def log(line):
    line = line.rstrip()
    if not line:
        return
    if "Press Ctrl+C" in line or "set location to" in line:
        ready.set()
    if "Press Ctrl+C" in line:
        return
    if "set location to" in line:          # one per second during routes, count it quietly
        r = state["route"]
        if r is not None:
            r["count"] += 1
        return
    if "waiting for" in line:
        return
    print("  [phone] " + line)
    log_tail.append(line)
    del log_tail[:-20]


def reader(proc):
    for line in proc.stdout:
        log(line)


def set_msg(msg, error=False):
    state["msg"], state["error"] = msg, error
    print(("! " if error else "> ") + msg)


def last_error():
    errs = [l for l in log_tail if "ERROR" in l] or log_tail or ["unknown error"]
    return errs[-1].split("ERROR", 1)[-1].strip()


def stop_fake(reason="Stopped. Real location is back.", clear=True):
    with lock:
        proc = state["proc"]
        route = state["route"]
        state["proc"] = None
        state["route"] = None
        was_active = state["lat"] is not None or route is not None
        state["lat"] = state["lon"] = None
    if proc and proc.poll() is None:
        try:
            proc.send_signal(signal.SIGINT)  # same as Ctrl+C, lets it close cleanly
            proc.wait(timeout=8)
        except Exception:
            proc.kill()
    if route and route.get("gpx"):
        try:
            os.remove(route["gpx"])
        except OSError:
            pass
    if (was_active or proc) and clear:
        try:
            subprocess.run(PMD + ["developer", "dvt", "simulate-location", "clear"],
                           capture_output=True, text=True, timeout=40)
        except Exception as e:
            log(f"clear failed: {e}")
        set_msg(reason)


def launch(args):
    """Start a pymobiledevice3 command and return once the location is live, it fails, or it was stopped.

    The process is registered in `state` straight away, so Stop / End Trip can kill it even while it's
    still connecting. Returns (proc, mine): mine is False if someone stopped it in the meantime.
    """
    log_tail.clear()
    ready.clear()
    proc = subprocess.Popen(PMD + args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
    with lock:
        state["proc"] = proc
        state["starting"] = proc
    threading.Thread(target=reader, args=(proc,), daemon=True).start()
    deadline = time.time() + 45          # the first connection can take a while
    while time.time() < deadline:
        if ready.wait(0.1) or proc.poll() is not None or state["proc"] is not proc:
            break
    with lock:
        mine = state["proc"] is proc
        if state.get("starting") is proc:
            state["starting"] = None
    if not mine and proc.poll() is None:   # stopped while connecting: make sure it never runs on
        try:
            proc.send_signal(signal.SIGINT)
            proc.wait(timeout=8)
        except Exception:
            proc.kill()
    return proc, mine


def start_fake(lat, lon):
    stop_fake("Switching pin...", clear=False)   # the new pin replaces the old one, no need to clear first
    proc, mine = launch(["developer", "dvt", "simulate-location", "set", "--", f"{lat:.6f}", f"{lon:.6f}"])
    if not mine:
        set_msg("Stopped. Real location is back.")
        return False                              # Stop was pressed while connecting
    if proc.poll() is not None:
        with lock:
            state["proc"] = None
        set_msg(f"Couldn't reach the iPhone: {last_error()}", error=True)
        return False
    with lock:
        state["lat"], state["lon"] = lat, lon
    set_msg(f"Faking {lat:.5f}, {lon:.5f}")
    return True


def start_route(points, label):
    stop_fake("Switching to route...", clear=False)
    t0 = datetime.now(timezone.utc)
    fd, path = tempfile.mkstemp(prefix="pinloc_", suffix=".gpx")
    with os.fdopen(fd, "w") as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n<gpx version="1.1" creator="PinLoc" '
                'xmlns="http://www.topografix.com/GPX/1/1"><trk><trkseg>\n')
        for lat, lon, t in points:
            ts = (t0 + timedelta(seconds=t)).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
            f.write(f'<trkpt lat="{lat:.7f}" lon="{lon:.7f}"><time>{ts}</time></trkpt>\n')
        f.write("</trkseg></trk></gpx>\n")
    route = {"coords": [(p[0], p[1]) for p in points], "times": [p[2] for p in points],
             "count": 0, "started": None, "gpx": path, "label": label}
    with lock:
        state["route"] = route
    # 250 = +/-250 ms of random timing wobble between points, so it isn't metronome-perfect
    set_msg(f"Connecting to the iPhone: {label}")
    proc, mine = launch(["developer", "dvt", "simulate-location", "play", path, "250"])
    if not mine:
        set_msg("Stopped. Real location is back.")
        return False                              # End Trip was pressed while connecting
    if proc.poll() is not None:
        with lock:
            state["route"] = None
            state["proc"] = None
        try:
            os.remove(path)
        except OSError:
            pass
        set_msg(f"Couldn't reach the iPhone: {last_error()}", error=True)
        return False
    with lock:
        route["started"] = time.time()
    set_msg(f"On the move: {label}")
    return True


def route_position():
    """Where along the route the phone is right now."""
    r = state["route"]
    if not r:
        return None
    n = len(r["coords"])
    if r["count"] > 0:                         # pymobiledevice3 told us how many points it has set
        i = min(r["count"], n) - 1
    elif r["started"] is None:                 # still connecting to the phone
        i = 0
    else:                                      # fall back to the clock
        elapsed = time.time() - r["started"] - 2
        i = max(0, bisect.bisect_right(r["times"], elapsed) - 1)
    i = max(0, min(i, n - 1))
    lat, lon = r["coords"][i]
    left = r["times"][-1] - r["times"][i]
    return {"i": i, "n": n, "lat": lat, "lon": lon, "left": left, "done": i >= n - 1, "label": r["label"],
            "connecting": r["started"] is None}


def watchdog():
    while True:
        time.sleep(5)
        with lock:
            proc = state["proc"]
            active = state["lat"] is not None or state["route"] is not None
        if active and time.time() - last_ping > PING_TIMEOUT:
            stop_fake("Page closed, so faking stopped. Real location is back.")
        elif active and proc and proc.poll() is not None and state.get("starting") is not proc:
            with lock:
                state["proc"] = None
                state["route"] = None
                state["lat"] = state["lon"] = None
            set_msg("Lost the iPhone (unplugged or locked?). Real location is back.", error=True)


# ---------------------------------------------------------------- web server

class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def send(self, code, body, ctype="application/json"):
        data = body.encode() if isinstance(body, str) else body
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(data)

    def status(self):
        route = route_position()
        lat, lon = state["lat"], state["lon"]
        msg = state["msg"]
        if route:
            lat, lon = route["lat"], route["lon"]
            if route["done"]:
                msg = f"Arrived: {route['label']}. Holding at the destination."
        return json.dumps({"lat": lat, "lon": lon, "msg": msg, "error": state["error"], "route": route})

    def do_GET(self):
        global last_ping
        if self.path == "/":
            self.send(200, PAGE, "text/html; charset=utf-8")
        elif self.path == "/ping":
            last_ping = time.time()
            self.send(200, self.status())
        else:
            self.send(404, "{}")

    def do_POST(self):
        global last_ping
        origin = self.headers.get("Origin")
        if origin and origin not in (f"http://127.0.0.1:{PORT}", f"http://localhost:{PORT}"):
            return self.send(403, "{}")
        length = int(self.headers.get("Content-Length") or 0)
        if length > 5_000_000:
            return self.send(413, "{}")
        body = self.rfile.read(length) if length else b""
        if self.path == "/set":
            try:
                d = json.loads(body)
                lat, lon = float(d["lat"]), float(d["lon"])
                assert -90 <= lat <= 90 and -180 <= lon <= 180
            except Exception:
                return self.send(400, json.dumps({"msg": "Bad coordinates", "error": True}))
            last_ping = time.time()
            set_msg("Teleporting...")
            start_fake(lat, lon)
            self.send(200, self.status())
        elif self.path == "/route":
            try:
                d = json.loads(body)
                pts = [(float(a), float(b), float(t)) for a, b, t in d["points"]]
                assert 2 <= len(pts) <= MAX_ROUTE_POINTS
                assert all(-90 <= a <= 90 and -180 <= b <= 180 for a, b, _ in pts)
                assert all(pts[i][2] <= pts[i + 1][2] for i in range(len(pts) - 1))
                label = str(d.get("label", "route"))[:80]
            except Exception:
                return self.send(400, json.dumps({"msg": "Bad route", "error": True}))
            last_ping = time.time()
            set_msg("Starting route...")
            start_route(pts, label)
            self.send(200, self.status())
        elif self.path == "/stop":
            stop_fake()
            self.send(200, self.status())
        else:
            self.send(404, "{}")


PAGE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>PinLoc</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@5.24.0/dist/maplibre-gl.css">
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.24.0/dist/maplibre-gl.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-leaflet@0.1.4/dist/leaflet-maplibre-gl.js"></script>
<style>
  :root {
    --blue: #1d5fd6; --on-blue: #ffffff; --green: #34c759; --red: #ff3b30; --orange: #ff9500;
    --label: rgba(0,0,0,.88); --label2: rgba(60,60,67,.62); --label3: rgba(60,60,67,.36);
    --fill: rgba(120,120,128,.12); --fill2: rgba(120,120,128,.2); --sep: rgba(60,60,67,.14);
    --material: rgba(246,246,248,.72); --material-solid: #f6f6f8; --card: rgba(255,255,255,.7);
    --shadow: 0 12px 40px rgba(0,0,0,.16), 0 1px 3px rgba(0,0,0,.08);
    --edge: rgba(255,255,255,.6);
    --r: 16px;
    --font: -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
    --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, monospace;
    font: 100%/1.4 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
    -webkit-font-smoothing: antialiased;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --blue: #6b9cf2; --on-blue: #0b0d14; --green: #30d158; --red: #ff453a; --orange: #ff9f0a;
      --label: rgba(255,255,255,.92); --label2: rgba(235,235,245,.6); --label3: rgba(235,235,245,.3);
      --fill: rgba(120,120,128,.24); --fill2: rgba(120,120,128,.36); --sep: rgba(84,84,88,.6);
      --material: rgba(30,30,32,.72); --material-solid: #1e1e20; --card: rgba(255,255,255,.06);
      --shadow: 0 12px 40px rgba(0,0,0,.5), 0 1px 3px rgba(0,0,0,.3);
      --edge: rgba(255,255,255,.1);
    }
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; height: 100%; color: var(--label); background: #dfe3e6; overflow: hidden; }
  @media (prefers-color-scheme: dark) { html, body { background: #1b1d21; } }
  #map { position: absolute; inset: 0; background: inherit; }
  .leaflet-container { font: inherit; }
  .leaflet-control-attribution { background: var(--material) !important; color: var(--label2) !important; backdrop-filter: blur(10px); border-radius: 6px 0 0 0; font-size: 10px; }
  .leaflet-control-attribution a { color: var(--label2) !important; }

  /* ---------- materials ---------- */
  .glass { background: var(--material); backdrop-filter: blur(28px) saturate(180%); -webkit-backdrop-filter: blur(28px) saturate(180%);
           box-shadow: var(--shadow), inset 0 1px 0 var(--edge); }

  /* ---------- sidebar ---------- */
  .side { position: absolute; z-index: 1000; top: 12px; left: 12px; bottom: 12px; width: 360px; border-radius: 20px;
          display: flex; flex-direction: column; overflow: hidden; }
  .side-head { padding: 16px 16px 10px; }
  .side-body { flex: 1; overflow-y: auto; padding: 0 16px 16px; overscroll-behavior: contain; }
  .brand { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
  .brand h1 { font-size: 20px; line-height: 1.1; letter-spacing: -.01em; font-weight: 600; margin: 0; }
  .brand h1 span { color: inherit; }

  /* segmented control */
  .seg { position: relative; display: flex; background: var(--fill); border-radius: 9px; padding: 2px; }
  .seg button { position: relative; z-index: 1; flex: 1; border: 0; background: none; color: var(--label); font: 500 13px/1 var(--font);
                padding: 7px 6px; border-radius: 7px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 6px; }
  .seg .thumb { position: absolute; z-index: 0; top: 2px; bottom: 2px; left: 2px; border-radius: 7px; background: #fff;
                box-shadow: 0 3px 8px rgba(0,0,0,.12), 0 1px 1px rgba(0,0,0,.04); transition: transform .35s cubic-bezier(.2,.9,.25,1), width .35s cubic-bezier(.2,.9,.25,1); }
  @media (prefers-color-scheme: dark) { .seg .thumb { background: #636366; } }
  .seg button.on { font-weight: 600; }
  .seg svg { width: 15px; height: 15px; }

  /* search field */
  .field { position: relative; display: flex; align-items: center; background: var(--fill); border-radius: 10px; height: 36px; padding: 0 8px 0 30px; }
  .field > svg.lead { position: absolute; left: 9px; width: 15px; height: 15px; color: var(--label2); }
  .field input { flex: 1; min-width: 0; border: 0; background: none; outline: none; color: var(--label); font: 400 15px var(--font); letter-spacing: -.01em; }
  .field input::placeholder { color: var(--label2); }
  .field:focus-within { box-shadow: 0 0 0 3.5px color-mix(in srgb, var(--blue) 35%, transparent); }
  .clear { width: 18px; height: 18px; border-radius: 50%; border: 0; background: var(--label3); color: var(--material-solid); display: none; place-items: center; padding: 0; cursor: pointer; }
  .clear svg { width: 8px; height: 8px; }
  .field.has .clear { display: grid; }

  /* suggestions */
  .suggest { margin-top: 8px; border-radius: 12px; background: var(--card); overflow: hidden; display: none; }
  .suggest.show { display: block; animation: rise .22s cubic-bezier(.2,.9,.25,1); }
  @keyframes rise { from { opacity: 0; transform: translateY(-4px); } }
  .sg-head { font: 600 12px var(--font); color: var(--label2); padding: 10px 12px 4px; letter-spacing: .01em; }
  .sg { display: flex; align-items: center; gap: 11px; padding: 8px 12px; cursor: pointer; position: relative; }
  .sg + .sg::before { content: ""; position: absolute; top: 0; left: 52px; right: 0; border-top: .5px solid var(--sep); }
  .sg.sel, .sg:hover { background: var(--fill); }
  .sg:active { background: var(--fill2); }
  .sg .ic { flex: none; width: 30px; height: 30px; border-radius: 50%; display: grid; place-items: center; color: var(--label2); background: var(--fill) !important; }
  .sg .ic.accent { color: var(--on-blue); background: var(--blue) !important; }
  .sg .ic svg { width: 15px; height: 15px; }
  .sg .tx { min-width: 0; }
  .sg .t1 { font-size: 15px; letter-spacing: -.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--label2); }
  .sg .t1 b { color: var(--label); font-weight: 500; }
  .sg .t1.plain { color: var(--label); }
  .sg .t2 { font-size: 12.5px; color: var(--label2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .sg-empty { padding: 14px 12px; font-size: 14px; color: var(--label2); }

  /* cards */
  .card { background: var(--card); border-radius: 14px; padding: 14px; margin-top: 12px; }
  .card h2 { margin: 0; font-size: 20px; line-height: 1.2; letter-spacing: -.01em; font-weight: 600; }
  .card .sub { color: var(--label2); font-size: 13px; margin-top: 4px; }
  .coord { font-family: var(--mono); font-size: 12px; font-variant-numeric: tabular-nums; color: var(--label2); }
  .hint { color: var(--label2); font-size: 14px; text-align: center; padding: 26px 10px 8px; line-height: 1.5; }
  .hint svg { width: 34px; height: 34px; color: var(--label3); display: block; margin: 0 auto 8px; }

  /* buttons */
  .btn { border: 0; border-radius: 12px; font: 600 15px var(--font); letter-spacing: -.01em; padding: 12px 14px; cursor: pointer;
         display: flex; align-items: center; justify-content: center; gap: 7px; width: 100%; transition: transform .1s ease-out, opacity .2s; }
  .btn:active:not(:disabled) { transform: scale(.97); }
  .btn:disabled { opacity: .4; cursor: default; }
  .btn.primary { background: var(--blue); color: var(--on-blue); }
  .btn.go { background: var(--blue); color: var(--on-blue); }
  .btn.danger { background: color-mix(in srgb, var(--red) 15%, transparent); color: var(--red); }
  .btn.plain { background: var(--fill); color: var(--blue); }
  .btn svg { width: 17px; height: 17px; }
  .btns { display: flex; gap: 8px; margin-top: 12px; }
  .spin { width: 16px; height: 16px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent; animation: sp .7s linear infinite; }
  @keyframes sp { to { transform: rotate(360deg); } }

  /* route form */
  .stops { background: var(--card); border-radius: 12px; position: relative; margin-top: 12px; }
  .stop-row { display: flex; align-items: center; gap: 12px; padding: 0 48px 0 12px; height: 44px; position: relative; }
  .stop-row + .stop-row::before { content: ""; position: absolute; top: 0; left: 36px; right: 52px; border-top: .5px solid var(--sep); }
  .dotc { width: 12px; height: 12px; border-radius: 50%; flex: none; position: relative; z-index: 1; }
  .stop-row input { flex: 1; min-width: 0; border: 0; background: none; outline: none; color: var(--label); font: 400 15px var(--font); }
  .stop-row input::placeholder { color: var(--label2); }
  .swap { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); width: 30px; height: 30px; border-radius: 50%; border: 0; background: var(--fill); color: var(--blue); cursor: pointer; display: grid; place-items: center; transition: transform .1s ease-out; }
  .swap:active { transform: translateY(-50%) scale(.92); }
  .swap svg { width: 15px; height: 15px; }
  .line-conn { position: absolute; left: 17px; top: 28px; bottom: 28px; border-left: 2px dotted var(--label3); pointer-events: none; }

  .list { background: var(--card); border-radius: 12px; margin-top: 12px; }
  .li { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 44px; padding: 0 12px; font-size: 15px; position: relative; }
  .li + .li::before { content: ""; position: absolute; top: 0; left: 12px; right: 0; border-top: .5px solid var(--sep); }
  .li small { display: block; color: var(--label2); font-size: 12.5px; }
  details.li { display: block; padding: 0; }
  details.li summary { list-style: none; display: flex; align-items: center; justify-content: space-between; min-height: 44px; padding: 0 12px; cursor: pointer; }
  details.li summary::-webkit-details-marker { display: none; }
  details.li summary .chev { width: 12px; height: 12px; color: var(--label3); transition: transform .25s cubic-bezier(.2,.9,.25,1); }
  details.li[open] summary .chev { transform: rotate(90deg); }
  .li-body { padding: 0 12px 12px; font-size: 12.5px; color: var(--label2); line-height: 1.45; }
  .li-body a { color: var(--blue); text-decoration: none; }
  .li-body input { width: 100%; margin-top: 8px; height: 34px; border: 0; border-radius: 9px; padding: 0 10px; background: var(--fill); color: var(--label); font: 14px ui-monospace, SFMono-Regular, Menlo, monospace; outline: none; }

  /* iOS switch */
  .sw { position: relative; width: 51px; height: 31px; flex: none; }
  .sw input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; z-index: 1; }
  .sw i { position: absolute; inset: 0; border-radius: 16px; background: var(--fill2); transition: background .25s; }
  .sw i::after { content: ""; position: absolute; top: 2px; left: 2px; width: 27px; height: 27px; border-radius: 50%; background: #fff;
                 box-shadow: 0 3px 8px rgba(0,0,0,.15), 0 3px 1px rgba(0,0,0,.06); transition: transform .3s cubic-bezier(.2,.9,.25,1); }
  .sw input:checked + i { background: var(--green); }
  .sw input:checked + i::after { transform: translateX(20px); }
  .sw input:active + i::after { width: 31px; }
  .sw input:checked:active + i::after { transform: translateX(16px); }

  /* trip summary */
  .eta { display: flex; align-items: baseline; gap: 8px; }
  .eta b { font-size: 28px; letter-spacing: -.02em; line-height: 1; font-weight: 600; font-variant-numeric: tabular-nums; }
  .eta span { color: var(--label2); font-size: 15px; }
  .chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
  .chip { display: inline-flex; align-items: center; gap: 5px; background: var(--fill); border-radius: 20px; padding: 4px 9px; font-size: 12.5px; font-weight: 500; }
  .chip i { width: 8px; height: 8px; border-radius: 50%; }
  .note { color: var(--label2); font-size: 12px; margin-top: 8px; }
  .progress { height: 6px; background: var(--fill2); border-radius: 3px; margin-top: 12px; overflow: hidden; }
  .progress i { display: block; height: 100%; width: 0; background: var(--blue); border-radius: 3px; transition: width .9s linear; }

  .foot { padding: 10px 16px 14px; border-top: .5px solid var(--sep); font-size: 11.5px; color: var(--label2); line-height: 1.4; }

  /* status pill */
  .pill { position: absolute; z-index: 1000; top: 12px; left: calc(50% + 186px); transform: translateX(-50%); border-radius: 20px; padding: 8px 16px 8px 12px;
          display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 500; font-family: var(--mono); font-variant-numeric: tabular-nums; max-width: min(520px, calc(100% - 420px)); white-space: nowrap; }
  .pill span { overflow: hidden; text-overflow: ellipsis; }
  .pill .led { width: 9px; height: 9px; border-radius: 50%; background: var(--label3); flex: none; }
  .pill.live .led { background: var(--blue); box-shadow: 0 0 0 0 color-mix(in srgb, var(--blue) 50%, transparent); animation: pulse 2s infinite; }
  .pill.err .led { background: var(--orange); }
  @keyframes pulse { 70% { box-shadow: 0 0 0 7px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }

  /* map controls */
  .mapctl { position: absolute; z-index: 1000; right: 12px; bottom: 28px; display: flex; flex-direction: column; gap: 10px; align-items: flex-end; }
  .stack { border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; }
  .stack button { width: 40px; height: 40px; border: 0; background: none; color: var(--label); cursor: pointer; display: grid; place-items: center; transition: background .15s; }
  .stack button + button { border-top: .5px solid var(--sep); }
  .stack button:active { background: var(--fill2); }
  .stack button svg { width: 17px; height: 17px; }
  .stack button.on { color: var(--blue); }
  .seg.glass { background: var(--material); }

  /* markers */
  .mk-pin { transform: translate(-50%, -100%); filter: drop-shadow(0 3px 4px rgba(0,0,0,.3)); }
  .mk-live { width: 22px; height: 22px; border-radius: 50%; background: #1d5fd6; border: 3px solid #fff; transform: translate(-50%,-50%);
             box-shadow: 0 0 0 0 rgba(29,95,214,.4), 0 2px 6px rgba(0,0,0,.3); animation: halo 2.2s infinite; }
  @keyframes halo { 0% { box-shadow: 0 0 0 0 rgba(29,95,214,.45), 0 2px 6px rgba(0,0,0,.3); } 100% { box-shadow: 0 0 0 22px rgba(29,95,214,0), 0 2px 6px rgba(0,0,0,.3); } }
  .mk-end { width: 16px; height: 16px; border-radius: 50%; border: 3px solid #fff; transform: translate(-50%,-50%); box-shadow: 0 1px 4px rgba(0,0,0,.35); }
  .mk-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid #fff; transform: translate(-50%,-50%); box-shadow: 0 1px 3px rgba(0,0,0,.3); }

  .hidden { display: none !important; }
  .fade { animation: fadein .25s ease; }
  @keyframes fadein { from { opacity: 0; transform: translateY(4px); } }

  @media (max-width: 760px) {
    .side { top: auto; height: 55%; left: 8px; right: 8px; bottom: 8px; width: auto; }
    .pill { left: 50%; max-width: calc(100% - 24px); }
    .mapctl { bottom: calc(55% + 20px); }
  }
  @media (prefers-reduced-motion: reduce) {
    *, *::before, *::after { animation: none !important; transition-duration: .01ms !important; }
  }
  @media (prefers-reduced-transparency: reduce) {
    .glass { background: var(--material-solid); backdrop-filter: none; -webkit-backdrop-filter: none; }
  }
  @media (prefers-contrast: more) {
    .glass { background: var(--material-solid); border: 1px solid var(--label3); }
  }
</style>
</head>
<body>
<div id="map"></div>

<!-- SVG icons -->
<svg width="0" height="0" style="position:absolute">
  <symbol id="i-search" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" d="M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15ZM16 16l5 5"/></symbol>
  <symbol id="i-x" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" d="M5 5l14 14M19 5 5 19"/></symbol>
  <symbol id="i-pin" viewBox="0 0 24 24"><path fill="currentColor" d="M12 2a7 7 0 0 0-7 7c0 5.2 7 13 7 13s7-7.8 7-13a7 7 0 0 0-7-7Zm0 9.6A2.6 2.6 0 1 1 12 6.4a2.6 2.6 0 0 1 0 5.2Z"/></symbol>
  <symbol id="i-route" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" d="M6 19a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM18 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM6 15V9a3 3 0 0 1 3-3h4M18 9v6a3 3 0 0 1-3 3h-4"/></symbol>
  <symbol id="i-walk" viewBox="0 0 24 24"><g fill="currentColor"><circle cx="13" cy="4" r="2.2"/><path d="M10.2 8.3 13.6 7.5c.9-.2 1.7.3 2 1.1l.9 2.6 2.4 1.2-.8 1.6-3-1.4-.6-1.6-1.2 4.1 2.6 2.7v4.3h-1.8v-3.5l-3-2.9-1 3.8-3.2 2.6-1.1-1.4 2.7-2.3 1.9-6.6-1.6.6v2.7H6.8V9.7Z"/></g></symbol>
  <symbol id="i-car" viewBox="0 0 24 24"><path fill="currentColor" d="M5.6 6.2A2 2 0 0 1 7.5 5h9a2 2 0 0 1 1.9 1.2l1.8 4.3A2 2 0 0 1 21 12v5a1 1 0 0 1-1 1h-1v1.5a1.5 1.5 0 0 1-3 0V18H8v1.5a1.5 1.5 0 0 1-3 0V18H4a1 1 0 0 1-1-1v-5a2 2 0 0 1 .8-1.5Zm1.6.8-1.4 3.5h12.4L16.8 7ZM6.5 15.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm11 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"/></symbol>
  <symbol id="i-bus" viewBox="0 0 24 24"><path fill="currentColor" d="M7 2h10a3 3 0 0 1 3 3v12a2 2 0 0 1-1 1.7v1.8a1.5 1.5 0 0 1-3 0V19H8v1.5a1.5 1.5 0 0 1-3 0v-1.8A2 2 0 0 1 4 17V5a3 3 0 0 1 3-3Zm-1 4v5h12V6ZM7.5 16.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm9 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"/></symbol>
  <symbol id="i-swap" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" d="M8 4v16M8 4 4.5 7.5M8 4l3.5 3.5M16 20V4M16 20l-3.5-3.5M16 20l3.5-3.5"/></symbol>
  <symbol id="i-plus" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" d="M12 5v14M5 12h14"/></symbol>
  <symbol id="i-minus" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" d="M5 12h14"/></symbol>
  <symbol id="i-loc" viewBox="0 0 24 24"><path fill="currentColor" d="M20.6 3.4 3.8 10.3c-.9.4-.8 1.7.2 1.9l7 1.5 1.5 7c.2 1 1.5 1.1 1.9.2l6.9-16.8c.3-.6-.3-1.1-.7-.7Z"/></symbol>
  <symbol id="i-chev" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="m9 5 7 7-7 7"/></symbol>
  <symbol id="i-city" viewBox="0 0 24 24"><path fill="currentColor" d="M3 21V10l5-3v3l5-3v3h1V4h7v17Zm13-14v2h2V7Zm0 4v2h2v-2Zm0 4v2h2v-2ZM6 13v2h2v-2Zm0 4v2h2v-2Zm4-4v2h2v-2Zm0 4v2h2v-2Z"/></symbol>
  <symbol id="i-house" viewBox="0 0 24 24"><path fill="currentColor" d="M12 3 2.5 11h2.7v9.5h5.3v-6h3v6h5.3V11h2.7Z"/></symbol>
  <symbol id="i-star" viewBox="0 0 24 24"><path fill="currentColor" d="m12 2.8 2.8 5.9 6.4.8-4.7 4.4 1.2 6.4L12 17.2l-5.7 3.1 1.2-6.4-4.7-4.4 6.4-.8Z"/></symbol>
  <symbol id="i-road" viewBox="0 0 24 24"><path fill="currentColor" d="M8.5 3h2l-.5 18H5Zm5 0h2L19 21h-5ZM11.5 5h1v3h-1Zm0 5h1v4h-1Zm0 6h1v4h-1Z"/></symbol>
  <symbol id="i-clock" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-13v4.5l3 2"/></symbol>
  <symbol id="i-hash" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" d="M5 9h15M4 15h15M10 4 8 20M16 4l-2 16"/></symbol>
</svg>

<aside class="side glass">
  <div class="side-head">
    <div class="brand"><h1>Pin<span>Loc</span></h1></div>
    <div class="seg" id="tabs">
      <div class="thumb"></div>
      <button data-v="pin" class="on"><svg><use href="#i-pin"/></svg>Pin</button>
      <button data-v="route"><svg><use href="#i-route"/></svg>Route</button>
    </div>
  </div>

  <div class="side-body">
    <!-- ================= PIN ================= -->
    <section id="pinUI">
      <div class="field" id="pinField">
        <svg class="lead"><use href="#i-search"/></svg>
        <input id="q" placeholder="Search Maps" autocomplete="off" spellcheck="false">
        <button class="clear" aria-label="Clear"><svg><use href="#i-x"/></svg></button>
      </div>
      <div class="suggest" id="qList"></div>

      <div id="pinEmpty" class="hint">
        <svg><use href="#i-pin"/></svg>
        Search for a place, or click anywhere on the map to drop a pin.
      </div>
      <div id="pinCard" class="card hidden">
        <h2 id="pinTitle">Dropped Pin</h2>
        <div class="sub" id="pinSub"></div>
        <div class="btns">
          <button class="btn primary" id="go"><svg><use href="#i-loc"/></svg>Teleport Here</button>
        </div>
      </div>
      <div id="pinLive" class="btns hidden">
        <button class="btn danger" id="stop">Stop Faking</button>
      </div>
    </section>

    <!-- ================= ROUTE ================= -->
    <section id="routeUI" class="hidden">
      <div class="seg" id="modes">
        <div class="thumb"></div>
        <button data-v="walk" class="on"><svg><use href="#i-walk"/></svg>Walk</button>
        <button data-v="drive"><svg><use href="#i-car"/></svg>Drive</button>
        <button data-v="bus"><svg><use href="#i-bus"/></svg>Bus</button>
      </div>

      <div class="stops">
        <div class="line-conn"></div>
        <div class="stop-row"><i class="dotc" style="background:var(--green)"></i><input id="fromQ" placeholder="Start: search or click map" autocomplete="off" spellcheck="false"></div>
        <div class="stop-row"><i class="dotc" style="background:var(--red)"></i><input id="toQ" placeholder="End: search or click map" autocomplete="off" spellcheck="false"></div>
        <button class="swap" id="swap" aria-label="Swap start and end"><svg><use href="#i-swap"/></svg></button>
      </div>
      <div class="suggest" id="rList"></div>

      <div class="list">
        <label class="li"><span>Traffic lights &amp; bus stops<small>Stops at red lights like a real trip</small></span>
          <span class="sw"><input type="checkbox" id="lights" checked><i></i></span></label>
        <details class="li" id="trafficBox">
          <summary><span>Live traffic<small id="ttState">Off</small></span><svg class="chev"><use href="#i-chev"/></svg></summary>
          <div class="li-body">Drives and bus rides slow down in real traffic jams. Needs a free TomTom key from
            <a href="https://developer.tomtom.com" target="_blank" rel="noopener">developer.tomtom.com</a> (no card). Stored only in this browser.
            <input id="ttKey" placeholder="Paste TomTom key" autocomplete="off" spellcheck="false"></div>
        </details>
      </div>

      <div id="planCard" class="card hidden"></div>
      <div class="btns" id="planBtns">
        <button class="btn plain" id="plan" disabled>Get Directions</button>
      </div>
    </section>

    <!-- live trip -->
    <div id="tripCard" class="card hidden">
      <div class="eta"><b id="tripLeft">—</b><span>left</span></div>
      <div class="sub" id="tripLabel"></div>
      <div class="progress"><i id="tripBar"></i></div>
      <div class="btns"><button class="btn danger" id="endTrip">End Trip</button></div>
    </div>

    <div id="recentWrap" class="hidden">
      <div class="sg-head" style="padding-left:2px;margin-top:16px">Recents</div>
      <div class="suggest show" id="recent" style="animation:none"></div>
    </div>
  </div>

  <div class="foot">Close this tab or press Ctrl+C in Terminal to go back to your real location. Keep the iPhone plugged in and the Mac awake.</div>
</aside>

<div class="pill glass" id="pill"><i class="led"></i><span id="pillText">Connecting…</span></div>

<div class="mapctl">
  <div class="stack glass">
    <button id="recenter" title="Show fake location"><svg><use href="#i-loc"/></svg></button>
  </div>
  <div class="stack glass">
    <button id="zin" title="Zoom in"><svg><use href="#i-plus"/></svg></button>
    <button id="zout" title="Zoom out"><svg><use href="#i-minus"/></svg></button>
  </div>
</div>

<script>
const $ = id => document.getElementById(id);
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const dark = matchMedia('(prefers-color-scheme: dark)');
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const svg = id => `<svg><use href="#${id}"/></svg>`;

/* ================= map ================= */
const map = L.map('map', { zoomControl: false, worldCopyJump: true, attributionControl: true }).setView([51.505, -0.09], 4);
// Map: OpenFreeMap vector tiles (free, no API key, no sign-up). Falls back to plain OpenStreetMap tiles
// if the vector map can't start (for example with WebGL switched off).
const OSM_ATTR = '&copy; <a href="https://openfreemap.org" target="_blank" rel="noopener">OpenFreeMap</a> &copy; <a href="https://www.openmaptiles.org/" target="_blank" rel="noopener">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a>';
const STYLE = { light: 'https://tiles.openfreemap.org/styles/liberty', dark: 'https://tiles.openfreemap.org/styles/dark' };
let glLayer = null, glStyle = null, glBroken = false;
const canGL = (() => { try { const c = document.createElement('canvas'); return !!(window.maplibregl && L.maplibreGL && (c.getContext('webgl2') || c.getContext('webgl'))); } catch { return false; } })();
const tiles = {
  osm: L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>' }),
};
function vectorLayer() {
  const want = dark.matches ? STYLE.dark : STYLE.light;
  if (!glLayer) { glLayer = L.maplibreGL({ style: want, attribution: OSM_ATTR }); glStyle = want; }
  else if (glStyle !== want) { try { glLayer.getMaplibreMap().setStyle(want); glStyle = want; } catch {} }
  return glLayer;
}
function applyTiles() {
  [tiles.osm, glLayer].forEach(t => t && map.removeLayer(t));
  if (canGL && !glBroken) {
    try { vectorLayer().addTo(map); return; }
    catch {
      // Some browsers and preview windows block what the vector map needs. Quietly use plain tiles instead.
      glBroken = true;
      try { if (glLayer) map.removeLayer(glLayer); } catch {}
      glLayer = null;
      document.querySelectorAll('#map .leaflet-gl-layer').forEach(el => el.remove());
    }
  }
  tiles.osm.addTo(map);
}
applyTiles();
dark.addEventListener('change', applyTiles);
$('zin').onclick = () => map.zoomIn();
$('zout').onclick = () => map.zoomOut();

/* ================= segmented controls ================= */
function segmented(el, onChange) {
  const thumb = el.querySelector('.thumb'), btns = [...el.querySelectorAll('button')];
  const place = b => { thumb.style.width = b.offsetWidth + 'px'; thumb.style.transform = `translateX(${b.offsetLeft - 2}px)`; };
  const set = (v, silent) => {
    const cur = el.querySelector('button.on');
    if (!silent && cur && cur.dataset.v === v) return;
    btns.forEach(b => b.classList.toggle('on', b.dataset.v === v));
    place(btns.find(b => b.dataset.v === v));
    if (!silent) onChange(v);
  };
  btns.forEach(b => { b.addEventListener('pointerdown', () => set(b.dataset.v)); b.addEventListener('click', () => set(b.dataset.v)); }); // respond on press
  requestAnimationFrame(() => place(el.querySelector('button.on')));
  addEventListener('resize', () => place(el.querySelector('button.on')));
  return set;
}

/* ================= markers ================= */
const icon = (html) => L.divIcon({ html, className: '', iconSize: [0, 0] });
const pinIcon = color => icon(`<svg class="mk-pin" width="30" height="40" viewBox="0 0 30 40"><path d="M15 1C7.3 1 1 7.2 1 14.8 1 25.3 15 39 15 39s14-13.7 14-24.2C29 7.2 22.7 1 15 1Z" fill="${color}" stroke="#fff" stroke-width="2"/><circle cx="15" cy="14.5" r="5" fill="#fff"/></svg>`);
const endIcon = color => icon(`<div class="mk-end" style="background:${color}"></div>`);
const dotIcon = color => icon(`<div class="mk-dot" style="background:${color}"></div>`);
const liveIcon = icon('<div class="mk-live"></div>');
const COL = { red: '#e5484d', green: '#34a865', blue: '#1d5fd6', gray: '#8e8e93', orange: '#8e8e93', purple: '#8e8e93', teal: '#8e8e93' };

/* ================= search with suggestions (Photon) ================= */
function placeKind(p) {
  const k = p.osm_key, v = p.osm_value, t = p.type;
  if (['city', 'town', 'village', 'hamlet', 'suburb', 'neighbourhood', 'locality', 'district', 'county', 'state', 'country'].includes(t) || k === 'place')
    return { ic: 'i-city', c: COL.teal };
  if (['amenity', 'shop', 'tourism', 'leisure', 'historic', 'railway', 'aeroway', 'natural'].includes(k)) return { ic: 'i-star', c: k === 'shop' ? COL.orange : k === 'tourism' || k === 'historic' ? COL.purple : COL.red };
  if (k === 'highway' || t === 'street') return { ic: 'i-road', c: COL.gray };
  if (k === 'building' || t === 'house') return { ic: 'i-house', c: COL.gray };
  return { ic: 'i-pin', c: COL.red };
}
function fromPhoton(f) {
  const p = f.properties, [lon, lat] = f.geometry.coordinates;
  const name = p.name || [p.housenumber, p.street].filter(Boolean).join(' ') || p.city || p.country || 'Unnamed place';
  const parts = [];
  if (p.name && p.street) parts.push([p.housenumber, p.street].filter(Boolean).join(' '));
  for (const x of [p.city || p.town || p.village || p.district, p.state, p.country]) if (x && x !== name && !parts.includes(x)) parts.push(x);
  return { lat, lon, name, sub: parts.join(', '), ...placeKind(p) };
}
function hl(text, q) {
  const i = text.toLowerCase().indexOf(q.toLowerCase().trim());
  if (!q.trim() || i < 0) return `<span class="plain">${esc(text)}</span>`;
  return esc(text.slice(0, i)) + '<b>' + esc(text.slice(i, i + q.trim().length)) + '</b>' + esc(text.slice(i + q.trim().length));
}
const coordRe = /^\s*(-?\d{1,2}(?:\.\d+)?)\s*[, ]\s*(-?\d{1,3}(?:\.\d+)?)\s*$/;

function autocomplete(input, list, onPick, extras) {
  let ctl = null, timer = null, items = [], sel = -1, lastQ = '';
  const field = input.closest('.field');
  const render = (groups) => {
    items = []; sel = -1;
    let html = '';
    for (const g of groups) {
      if (!g.items.length) continue;
      if (g.head) html += `<div class="sg-head">${esc(g.head)}</div>`;
      for (const it of g.items) {
        const i = items.push(it) - 1;
        html += `<div class="sg" data-i="${i}"><div class="ic${it.c === COL.blue ? ' accent' : ''}">${svg(it.ic)}</div>
                 <div class="tx"><div class="t1">${g.q != null ? hl(it.name, g.q) : `<span class="plain">${esc(it.name)}</span>`}</div>${it.sub ? `<div class="t2">${esc(it.sub)}</div>` : ''}</div></div>`;
      }
    }
    if (!html && groups.empty) html = `<div class="sg-empty">${esc(groups.empty)}</div>`;
    list.innerHTML = html;
    list.classList.toggle('show', !!html);
    list.querySelectorAll('.sg').forEach(el => el.addEventListener('pointerdown', e => { e.preventDefault(); choose(+el.dataset.i); }));
  };
  const choose = i => {
    const it = items[i]; if (!it) return;
    input.value = it.name; field && field.classList.add('has');
    hide(); input.blur(); onPick(it);
  };
  const hide = () => { list.classList.remove('show'); list.innerHTML = ''; items = []; };
  const showDefault = () => {
    const ex = extras ? extras() : [];
    const rec = loadRecent().map(r => ({ ...r, ic: 'i-clock', c: COL.gray, sub: r.sub || `${r.lat.toFixed(4)}, ${r.lon.toFixed(4)}` }));
    render([{ items: ex }, { head: 'Recents', items: rec }]);
  };
  const query = () => {
    const q = input.value; lastQ = q;
    field && field.classList.toggle('has', !!q);
    if (!q.trim()) return showDefault();
    const m = q.match(coordRe);
    if (m && Math.abs(+m[1]) <= 90 && Math.abs(+m[2]) <= 180) {
      return render([{ items: [{ lat: +m[1], lon: +m[2], name: `${(+m[1]).toFixed(5)}, ${(+m[2]).toFixed(5)}`, sub: 'Coordinates', ic: 'i-hash', c: COL.blue }] }]);
    }
    clearTimeout(timer);
    timer = setTimeout(async () => {   // short pause so we don't hit the server on every key
      ctl && ctl.abort(); ctl = new AbortController();
      const c = map.getCenter();
      try {
        const r = await fetch(`https://photon.komoot.io/api/?q=${encodeURIComponent(q)}&limit=7&lang=en&lat=${c.lat.toFixed(3)}&lon=${c.lng.toFixed(3)}&location_bias_scale=0.3`, { signal: ctl.signal });
        const j = await r.json();
        if (q !== lastQ) return;
        const out = [], seen = new Set();
        for (const f of j.features || []) { const it = fromPhoton(f); const key = it.name + '|' + it.sub; if (!seen.has(key)) { seen.add(key); out.push(it); } }
        const g = [{ items: out, q }]; g.empty = 'No results'; render(g);
      } catch (e) { if (e.name !== 'AbortError') { const g = []; g.empty = 'Search is offline right now. You can paste coordinates instead.'; render(g); } }
    }, 160);
  };
  input.addEventListener('input', query);
  input.addEventListener('focus', () => { input.value ? query() : showDefault(); });
  input.addEventListener('blur', () => setTimeout(hide, 120));
  input.addEventListener('keydown', e => {
    const n = items.length;
    if (e.key === 'ArrowDown' && n) { e.preventDefault(); sel = (sel + 1) % n; }
    else if (e.key === 'ArrowUp' && n) { e.preventDefault(); sel = (sel - 1 + n) % n; }
    else if (e.key === 'Enter') { e.preventDefault(); choose(sel >= 0 ? sel : 0); return; }
    else if (e.key === 'Escape') { hide(); input.blur(); return; }
    else return;
    list.querySelectorAll('.sg').forEach((el, i) => el.classList.toggle('sel', i === sel));
    const s = list.querySelector('.sg.sel'); s && s.scrollIntoView({ block: 'nearest' });
  });
  if (field) field.querySelector('.clear').addEventListener('pointerdown', e => { e.preventDefault(); input.value = ''; field.classList.remove('has'); input.focus(); showDefault(); });
}

async function reverse(lat, lon) {
  try {
    const r = await fetch(`https://photon.komoot.io/reverse?lat=${lat}&lon=${lon}&lang=en`);
    const f = (await r.json()).features?.[0];
    if (f) { const it = fromPhoton(f); return { name: it.name, sub: it.sub }; }
  } catch {}
  return null;
}

/* ================= recents ================= */
function loadRecent() { try { return JSON.parse(localStorage.getItem('pinloc_recent') || '[]'); } catch { return []; } }
function saveRecent(p) {
  let list = loadRecent().filter(x => Math.abs(x.lat - p.lat) > 1e-5 || Math.abs(x.lon - p.lon) > 1e-5);
  list.unshift({ lat: p.lat, lon: p.lon, name: p.name || 'Dropped Pin', sub: p.sub || '' }); list = list.slice(0, 6);
  try { localStorage.setItem('pinloc_recent', JSON.stringify(list)); } catch {}
  renderRecent();
}
function renderRecent() {
  const list = loadRecent();
  $('recentWrap').classList.toggle('hidden', !list.length || tab !== 'pin');
  $('recent').innerHTML = list.map((r, i) => `<div class="sg" data-i="${i}"><div class="ic">${svg('i-clock')}</div>
    <div class="tx"><div class="t1 plain">${esc(r.name)}</div><div class="t2">${esc(r.sub || `${r.lat.toFixed(4)}, ${r.lon.toFixed(4)}`)}</div></div></div>`).join('');
  $('recent').querySelectorAll('.sg').forEach(el => el.onclick = () => { const r = list[+el.dataset.i]; setPin(r); map.flyTo([r.lat, r.lon], 15, { duration: reduceMotion ? 0 : .8 }); });
}

/* ================= tabs ================= */
let tab = 'pin';
segmented($('tabs'), v => {
  tab = v;
  $('pinUI').classList.toggle('hidden', v !== 'pin');
  $('routeUI').classList.toggle('hidden', v !== 'route');
  [$('pinUI'), $('routeUI')].forEach(el => el.classList.add('fade'));
  if (pinMk) (v === 'pin' ? pinMk.addTo(map) : map.removeLayer(pinMk));
  [aMk, bMk, routeLine, ...extras].forEach(l => l && (v === 'route' ? l.addTo(map) : map.removeLayer(l)));
  if (v === 'route') requestAnimationFrame(() => setMode(mode, true));   // place the mode highlight now it's visible
  if (v === 'route' && !A && live) { const ll = live.getLatLng(); setEnd('A', { lat: ll.lat, lon: ll.lng, name: 'Current Fake Location' }); }
  renderRecent(); refreshTrip();
});

/* ================= PIN mode ================= */
let picked = null, pinMk = null, live = null;
function setPin(p) {
  picked = { lat: p.lat, lon: ((p.lon + 180) % 360 + 360) % 360 - 180, name: p.name || null, sub: p.sub || '' };
  if (pinMk) pinMk.setLatLng([picked.lat, picked.lon]); else pinMk = L.marker([picked.lat, picked.lon], { icon: pinIcon(COL.blue) }).addTo(map);
  $('pinEmpty').classList.add('hidden');
  $('pinCard').classList.remove('hidden'); $('pinCard').classList.add('fade');
  $('pinTitle').textContent = picked.name || 'Dropped Pin';
  $('pinSub').innerHTML = (picked.sub ? esc(picked.sub) + '<br>' : '') + `<span class="coord">${picked.lat.toFixed(5)}, ${picked.lon.toFixed(5)}</span>`;
  if (!picked.name) reverse(picked.lat, picked.lon).then(r => {
    if (r && picked && Math.abs(picked.lat - p.lat) < 1e-9) { picked.sub = [r.name, r.sub].filter(Boolean).join(', '); $('pinSub').innerHTML = esc(picked.sub) + `<br><span class="coord">${picked.lat.toFixed(5)}, ${picked.lon.toFixed(5)}</span>`; }
  });
}
autocomplete($('q'), $('qList'), it => { setPin(it); map.flyTo([it.lat, it.lon], 15, { duration: reduceMotion ? 0 : .8 }); });

$('go').onclick = async () => {
  if (!picked) return;
  const b = $('go'); b.disabled = true; b.innerHTML = '<i class="spin"></i>Teleporting…';
  try { const s = await post('/set', { lat: picked.lat, lon: picked.lon }); showStatus(s); if (!s.error) saveRecent(picked); }
  catch { showStatus({ msg: 'PinLoc isn’t running. Start it in Terminal.', error: true }); }
  b.disabled = false; b.innerHTML = svg('i-loc') + 'Teleport Here';
};

/* ================= ROUTE mode ================= */
let mode = 'walk', A = null, B = null, aMk = null, bMk = null, routeLine = null, extras = [], plan = null;
const setMode = segmented($('modes'), v => { mode = v; invalidatePlan(); });

function setEnd(which, p, fromMap) {
  const pt = { lat: p.lat, lon: ((p.lon + 180) % 360 + 360) % 360 - 180, name: p.name || null };
  const input = which === 'A' ? $('fromQ') : $('toQ');
  if (which === 'A') { A = pt; aMk ? aMk.setLatLng([pt.lat, pt.lon]) : (aMk = mkEnd(pt, COL.green, 'A')); }
  else { B = pt; bMk ? bMk.setLatLng([pt.lat, pt.lon]) : (bMk = mkEnd(pt, COL.red, 'B')); }
  input.value = pt.name || `${pt.lat.toFixed(5)}, ${pt.lon.toFixed(5)}`;
  if (fromMap || !pt.name) reverse(pt.lat, pt.lon).then(r => { const cur = which === 'A' ? A : B; if (r && cur === pt) { pt.name = r.name; input.value = r.name; } });
  invalidatePlan();
}
function mkEnd(p, color, which) {
  const m = L.marker([p.lat, p.lon], { icon: endIcon(color), draggable: true }).addTo(map);
  m.on('dragend', e => { const ll = e.target.getLatLng(); setEnd(which, { lat: ll.lat, lon: ll.lng }, true); });
  return m;
}
let activeField = null;
['fromQ', 'toQ'].forEach(id => $(id).addEventListener('focus', () => activeField = id));
const liveExtra = () => live ? [{ lat: live.getLatLng().lat, lon: live.getLatLng().lng, name: 'Current Fake Location', sub: 'Where your iPhone thinks it is', ic: 'i-loc', c: COL.blue }] : [];
autocomplete($('fromQ'), $('rList'), it => { setEnd('A', it); map.flyTo([it.lat, it.lon], 14, { duration: reduceMotion ? 0 : .8 }); if (!B) $('toQ').focus(); }, liveExtra);
autocomplete($('toQ'), $('rList'), it => { setEnd('B', it); if (A) fitBoth(); else map.flyTo([it.lat, it.lon], 14, { duration: reduceMotion ? 0 : .8 }); });
function fitBoth() { map.flyToBounds(L.latLngBounds([[A.lat, A.lon], [B.lat, B.lon]]), { padding: [80, 80], paddingTopLeft: [420, 80], duration: reduceMotion ? 0 : .8 }); }

$('swap').onclick = () => {
  const a = A, b = B;
  A = B = null; if (aMk) { map.removeLayer(aMk); aMk = null; } if (bMk) { map.removeLayer(bMk); bMk = null; }
  $('fromQ').value = $('toQ').value = '';
  if (b) setEnd('A', b); if (a) setEnd('B', a);
};

map.on('click', e => {
  const p = { lat: e.latlng.lat, lon: e.latlng.lng };
  if (tab === 'pin') return setPin(p);
  if (activeField === 'toQ' || (A && activeField !== 'fromQ')) setEnd('B', p, true); else setEnd('A', p, true);
  activeField = A ? 'toQ' : 'fromQ';
});

function invalidatePlan() {
  plan = null;
  if (routeLine) { map.removeLayer(routeLine); routeLine = null; }
  extras.forEach(l => map.removeLayer(l)); extras = [];
  $('planCard').classList.add('hidden');
  $('planBtns').innerHTML = '<button class="btn plain" id="plan">Get Directions</button>';
  $('plan').disabled = !(A && B);
  $('plan').onclick = planRoute;
}
invalidatePlan();

/* TomTom key */
try { $('ttKey').value = localStorage.getItem('pinloc_tt') || ''; } catch {}
const ttLabel = () => $('ttState').textContent = $('ttKey').value.trim() ? 'On (TomTom)' : 'Off';
ttLabel();
$('ttKey').addEventListener('input', () => { try { localStorage.setItem('pinloc_tt', $('ttKey').value.trim()); } catch {} ttLabel(); invalidatePlan(); });
$('lights').addEventListener('change', invalidatePlan);

const RAD = Math.PI / 180, ER = 6371000;
function dist(a, b) {
  const dLat = (b[0] - a[0]) * RAD, dLon = (b[1] - a[1]) * RAD;
  const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[0] * RAD) * Math.cos(b[0] * RAD) * Math.sin(dLon / 2) ** 2;
  return 2 * ER * Math.asin(Math.sqrt(h));
}
const rand = (a, b) => a + Math.random() * (b - a);
const gauss = () => { let u = 0, v = 0; while (!u) u = Math.random(); while (!v) v = Math.random(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); };

const MODES = {
  walk:  { accel: 1.0, decel: 1.5, lightChance: 0.45, lightWait: [6, 40],  corner: null, stopBefore: 2 },
  drive: { accel: 2.0, decel: 2.8, lightChance: 0.5,  lightWait: [10, 60], corner: 7,    stopBefore: 6 },
  bus:   { accel: 1.1, decel: 1.6, lightChance: 0.5,  lightWait: [10, 60], corner: 5,    stopBefore: 8, stopChance: 0.6, dwell: [10, 35] },
};

// Route geometry + base speed for every segment (m/s), plus traffic info if TomTom is used
async function fetchRoute() {
  const key = $('ttKey').value.trim();
  if (key && mode !== 'walk') return fetchTomTom(key);
  const profile = mode === 'walk' ? 'routed-foot/route/v1/foot' : 'routed-car/route/v1/driving';
  const url = `https://routing.openstreetmap.de/${profile}/${A.lon},${A.lat};${B.lon},${B.lat}?overview=full&geometries=geojson&annotations=true`;
  const r = await fetch(url);
  if (!r.ok) throw new Error('Route service error ' + r.status);
  const j = await r.json();
  if (!j.routes || !j.routes.length) throw new Error('No route found between those points');
  const route = j.routes[0];
  const coords = route.geometry.coordinates.map(c => [c[1], c[0]]);
  const n = coords.length - 1;
  const ann = route.legs[0] && route.legs[0].annotation;
  const avg = route.distance / Math.max(1, route.duration);
  let speeds = (ann && ann.speed && ann.speed.length === n) ? ann.speed.slice() : new Array(n).fill(avg);
  if (mode === 'walk') {
    const pace = rand(1.25, 1.45);             // each walk gets its own personal pace
    speeds = speeds.map(() => pace);
  } else if (mode === 'drive') {
    speeds = speeds.map(v => Math.min(33, Math.max(3, v * 1.08)));
  } else {
    speeds = speeds.map(v => Math.min(20, Math.max(3, v * 0.85)));
  }
  return { coords, speeds, trafficDelay: 0, source: 'OpenStreetMap' };
}

async function fetchTomTom(key) {
  const url = `https://api.tomtom.com/routing/1/calculateRoute/${A.lat},${A.lon}:${B.lat},${B.lon}/json` +
    `?key=${encodeURIComponent(key)}&traffic=true&travelMode=car&routeType=fastest&computeTravelTimeFor=all&sectionType=traffic&sectionType=speedLimit`;
  let r = await fetch(url);
  if (r.status === 400) r = await fetch(url.replace('&sectionType=speedLimit', ''));   // older API versions lack speed limits
  if (r.status === 403 || r.status === 401) throw new Error('TomTom key was rejected');
  if (!r.ok) throw new Error('TomTom error ' + r.status);
  const j = await r.json();
  const route = j.routes && j.routes[0];
  if (!route) throw new Error('No route found between those points');
  const coords = route.legs.flatMap(l => l.points.map(p => [p.latitude, p.longitude]));
  const n = coords.length - 1;
  const lens = []; for (let i = 0; i < n; i++) lens.push(dist(coords[i], coords[i + 1]));
  const sum = route.summary;
  const freeAvg = sum.lengthInMeters / Math.max(1, sum.noTrafficTravelTimeInSeconds || sum.travelTimeInSeconds);
  // start from speed limits where TomTom gives them, else the average
  let speeds = new Array(n).fill(freeAvg);
  (route.sections || []).filter(s => s.sectionType === 'SPEED_LIMIT' && s.maxSpeedLimitInKmh).forEach(s => {
    for (let i = s.startPointIndex; i < s.endPointIndex && i < n; i++) speeds[i] = s.maxSpeedLimitInKmh / 3.6 * 0.92;
  });
  // calibrate so the no-traffic time roughly matches TomTom's own estimate
  const t0 = lens.reduce((t, l, i) => t + l / speeds[i], 0);
  const target = sum.noTrafficTravelTimeInSeconds || t0;
  const k = Math.min(1.4, Math.max(0.7, t0 / target));
  speeds = speeds.map(v => v * k);
  if (mode === 'bus') speeds = speeds.map(v => Math.min(20, v * 0.85));
  speeds = speeds.map(v => Math.min(36, Math.max(2.5, v)));
  // squeeze each traffic jam's delay into its stretch of road
  let delay = 0;
  (route.sections || []).filter(s => s.sectionType === 'TRAFFIC' && s.delayInSeconds > 0).forEach(s => {
    const a = s.startPointIndex, b = Math.min(s.endPointIndex, n);
    let ts = 0; for (let i = a; i < b; i++) ts += lens[i] / speeds[i];
    if (ts <= 0) return;
    const m = ts / (ts + s.delayInSeconds);
    for (let i = a; i < b; i++) speeds[i] = Math.max(0.8, speeds[i] * m);
    delay += s.delayInSeconds;
  });
  return { coords, speeds, trafficDelay: delay, source: 'TomTom live traffic' };
}

// Find traffic lights / bus stops along the route (OpenStreetMap data)
async function fetchStops(coords) {
  const kept = [coords[0]];
  for (const c of coords) if (dist(kept[kept.length - 1], c) >= 20) kept.push(c);
  kept.push(coords[coords.length - 1]);
  const chunks = [];
  for (let i = 0; i < kept.length - 1; i += 150) chunks.push(kept.slice(i, i + 151));
  let q = '[out:json][timeout:25];(';
  for (const ch of chunks) {
    const line = ch.map(c => c[0].toFixed(6) + ',' + c[1].toFixed(6)).join(',');
    q += `node(around:20,${line})["highway"="traffic_signals"];node(around:20,${line})["crossing"="traffic_signals"];`;
    if (mode === 'bus') q += `node(around:25,${line})["highway"="bus_stop"];`;
  }
  q += ');out;';
  const r = await fetch('https://overpass-api.de/api/interpreter', { method: 'POST', body: 'data=' + encodeURIComponent(q), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
  if (!r.ok) throw new Error('Overpass ' + r.status);
  const j = await r.json();
  return j.elements || [];
}

// Distance along the route of the closest point to p (or null if too far away)
function project(p, coords, cum, maxD) {
  const lat0 = p[0] * RAD, kx = Math.cos(lat0) * ER * RAD, ky = ER * RAD;
  let best = null, bestD = maxD;
  for (let i = 0; i < coords.length - 1; i++) {
    const ax = (coords[i][1] - p[1]) * kx, ay = (coords[i][0] - p[0]) * ky;
    const bx = (coords[i + 1][1] - p[1]) * kx, by = (coords[i + 1][0] - p[0]) * ky;
    const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy;
    let t = L2 ? -(ax * dx + ay * dy) / L2 : 0;
    t = Math.max(0, Math.min(1, t));
    const cx = ax + t * dx, cy = ay + t * dy, d = Math.hypot(cx, cy);
    if (d < bestD) { bestD = d; best = cum[i] + t * (cum[i + 1] - cum[i]); }
  }
  return best;
}

function bearing(a, b) {
  const y = Math.sin((b[1] - a[1]) * RAD) * Math.cos(b[0] * RAD);
  const x = Math.cos(a[0] * RAD) * Math.sin(b[0] * RAD) - Math.sin(a[0] * RAD) * Math.cos(b[0] * RAD) * Math.cos((b[1] - a[1]) * RAD);
  return Math.atan2(y, x) / RAD;
}

// Turn route + stops into one GPS point per second, like a real trip
function simulate(coords, speeds, cons, cfg) {
  const n = coords.length - 1;
  const cum = [0]; for (let i = 0; i < n; i++) cum.push(cum[i] + dist(coords[i], coords[i + 1]));
  const total = cum[n];
  let seg = 0;
  const segAt = s => { while (seg < n - 1 && cum[seg + 1] < s) seg++; return seg; };
  const posAt = (s, i) => {
    const L = cum[i + 1] - cum[i], t = L > 0 ? (s - cum[i]) / L : 0;
    return [coords[i][0] + (coords[i + 1][0] - coords[i][0]) * t, coords[i][1] + (coords[i + 1][1] - coords[i][1]) * t];
  };
  // GPS wobble: a few metres, drifting smoothly like the real thing
  let nx = 0, ny = 0;
  const jitter = (p, scale = 1) => {
    nx = 0.95 * nx + gauss() * 0.5 * scale; ny = 0.95 * ny + gauss() * 0.5 * scale;
    return [p[0] + ny / (ER * RAD), p[1] + nx / (ER * RAD * Math.cos(p[0] * RAD))];
  };
  cons.sort((a, b) => a.dist - b.dist);
  const pts = [[coords[0][0], coords[0][1], 0]];
  let s = 0, v = 0, t = 0, k = 0, drift = 1;
  const nextStop = () => { for (let j = k; j < cons.length; j++) if (cons[j].v === 0) return cons[j]; return null; };
  while (s < total - 0.5 && pts.length < 8 * 3600) {
    while (k < cons.length && cons[k].v > 0 && cons[k].dist < s) k++;
    const c = cons[k];
    if (c && c.v === 0 && s >= c.dist - 0.01) {           // waiting at a light / bus stop / pause
      const i = segAt(s), p = posAt(s, i);
      for (let w = 0; w < c.wait; w++) { t++; const q = jitter(p, 0.4); pts.push([q[0], q[1], t]); }
      k++; v = 0; continue;
    }
    const i = segAt(s);
    drift = Math.min(1.1, Math.max(0.9, drift + (Math.random() - 0.5) * 0.03));
    let vt = speeds[i] * drift;
    for (let j = k; j < cons.length && cons[j].dist - s < 400; j++) {
      if (cons[j].dist < s) continue;
      vt = Math.min(vt, Math.sqrt(cons[j].v ** 2 + 2 * cfg.decel * Math.max(0, cons[j].dist - s - 1)));
    }
    v = v < vt ? Math.min(vt, v + cfg.accel) : Math.max(vt, v - cfg.decel * 1.3);
    v = Math.max(v, 0.6);
    let ns = s + v;
    const st = nextStop();
    if (st && ns >= st.dist) { ns = st.dist; v = 0; }
    s = Math.min(ns, total);
    t++;
    const q = jitter(posAt(s, segAt(s)));
    pts.push([q[0], q[1], t]);
  }
  pts.push([coords[n][0], coords[n][1], t + 1]);
  return { pts, total, cum };
}



async function planRoute() {
  if (!A || !B) return;
  const cfg = MODES[mode];
  const btn = $('plan'); btn.disabled = true; btn.innerHTML = '<i class="spin"></i>Finding route…';
  try {
    const { coords, speeds, trafficDelay, source } = await fetchRoute();
    const n = coords.length - 1;
    const cum = [0]; for (let i = 0; i < n; i++) cum.push(cum[i] + dist(coords[i], coords[i + 1]));
    const total = cum[n];
    if (total < 5) throw new Error('Start and end are basically the same spot');
    const cons = [];
    let lightsFound = 0, lightsRed = 0, busStops = 0, note = '';
    if (cfg.corner) {
      for (let i = 1; i < n; i++) {
        if (cum[i] - cum[i - 1] < 3 || cum[i + 1] - cum[i] < 3) continue;
        let d = Math.abs(bearing(coords[i - 1], coords[i]) - bearing(coords[i], coords[i + 1]));
        if (d > 180) d = 360 - d;
        if (d > 55) cons.push({ dist: cum[i], v: cfg.corner * (d > 110 ? 0.7 : 1) });
      }
    }
    if (mode === 'walk') for (let d = 80; d < total - 20; d += 100) if (Math.random() < 0.03) cons.push({ dist: d, v: 0, wait: Math.round(rand(3, 12)) });
    if ($('lights').checked) {
      btn.innerHTML = '<i class="spin"></i>Finding traffic lights…';
      try {
        const els = await fetchStops(coords);
        const lights = [], stops = [];
        for (const e of els) {
          const isStop = e.tags && e.tags.highway === 'bus_stop';
          const along = project([e.lat, e.lon], coords, cum, isStop ? 25 : 20);
          if (along == null || along < 10 || along > total - 10) continue;
          (isStop ? stops : lights).push({ along, lat: e.lat, lon: e.lon });
        }
        const dedup = (arr, gap) => { arr.sort((a, b) => a.along - b.along); const out = []; for (const x of arr) if (!out.length || x.along - out[out.length - 1].along > gap) out.push(x); return out; };
        for (const lt of dedup(lights, 35)) {
          lightsFound++;
          const red = Math.random() < cfg.lightChance;
          if (red) { lightsRed++; cons.push({ dist: Math.max(1, lt.along - cfg.stopBefore), v: 0, wait: Math.round(rand(...cfg.lightWait)) }); }
          extras.push(L.marker([lt.lat, lt.lon], { icon: dotIcon(red ? COL.red : COL.green), interactive: false }).addTo(map));
        }
        if (mode === 'bus') for (const S of dedup(stops, 60)) if (Math.random() < cfg.stopChance) {
          busStops++;
          cons.push({ dist: S.along, v: 0, wait: Math.round(rand(...cfg.dwell)) });
          extras.push(L.marker([S.lat, S.lon], { icon: dotIcon(COL.blue), interactive: false }).addTo(map));
        }
      } catch { note = 'Couldn’t load traffic lights right now, so this trip has none.'; }
    }
    const sim = simulate(coords, speeds, cons, cfg);
    if (sim.pts.length >= 8 * 3600) throw new Error('That trip is over 8 hours. Pick somewhere closer.');
    const secs = sim.pts[sim.pts.length - 1][2];
    const verb = { walk: 'Walking', drive: 'Driving', bus: 'Bus' }[mode];
    plan = { points: sim.pts.map(p => [+p[0].toFixed(7), +p[1].toFixed(7), p[2]]), label: `${verb} to ${B.name || 'destination'}` };

    routeLine = L.polyline(coords, { color: dark.matches ? '#6b9cf2' : '#1d5fd6', weight: 7, opacity: .9, lineCap: 'round', dashArray: mode === 'walk' ? '1 11' : null }).addTo(map);
    routeLine.bringToBack();
    map.flyToBounds(routeLine.getBounds(), { paddingTopLeft: [400, 70], paddingBottomRight: [70, 70], duration: reduceMotion ? 0 : .9 });

    let chips = '';
    if ($('lights').checked && !note) chips += `<span class="chip"><i style="background:${COL.red}"></i>${lightsRed} of ${lightsFound} lights red</span>`;
    if (mode === 'bus' && busStops) chips += `<span class="chip"><i style="background:${COL.blue}"></i>${busStops} bus stops</span>`;
    if (trafficDelay > 30) chips += `<span class="chip"><i style="background:${COL.orange}"></i>+${fmtDur(trafficDelay)} traffic</span>`;
    else if (source.startsWith('TomTom')) chips += `<span class="chip"><i style="background:${COL.green}"></i>Traffic clear</span>`;
    $('planCard').innerHTML = `<div class="eta"><b>${fmtDur(secs)}</b><span>${(total / 1000).toFixed(1)} km</span></div>
      <div class="sub">${esc(verb)} · via ${esc(source)}</div>${chips ? `<div class="chips">${chips}</div>` : ''}${note ? `<div class="note">${esc(note)}</div>` : ''}`;
    $('planCard').classList.remove('hidden'); $('planCard').classList.add('fade');
    $('planBtns').innerHTML = '<button class="btn go" id="startRoute">Go</button>';
    $('startRoute').onclick = startRoute;
  } catch (e) {
    $('planCard').innerHTML = `<div class="sub" style="margin:0">Couldn’t get directions: ${esc(e.message)}</div>`;
    $('planCard').classList.remove('hidden');
    btn.disabled = false; btn.textContent = 'Try Again';
  }
}

async function startRoute() {
  if (!plan) return;
  const b = $('startRoute'); b.disabled = true; b.innerHTML = '<i class="spin"></i>Starting…';
  try { showStatus(await post('/route', plan)); }
  catch { showStatus({ msg: 'PinLoc isn’t running. Start it in Terminal.', error: true }); }
  b.disabled = false; b.textContent = 'Go';
}

/* ================= live position (smoothed with a spring) ================= */
let target = null, pos = null, vel = [0, 0], raf = 0, follow = false;
function moveLive(lat, lon) {
  if (lat == null) { if (live) { map.removeLayer(live); live = null; } target = pos = null; return; }
  if (!live) { live = L.marker([lat, lon], { icon: liveIcon, zIndexOffset: 1000, interactive: false }).addTo(map); pos = [lat, lon]; vel = [0, 0]; target = [lat, lon]; return; }
  target = [lat, lon];
  if (reduceMotion || dist(pos, target) > 2000) { pos = target.slice(); vel = [0, 0]; live.setLatLng(pos); return; } // teleports jump; short moves glide
  if (!raf) { let last = performance.now(); const step = now => {
    const dt = Math.min(.05, (now - last) / 1000); last = now;
    const w = 2 * Math.PI / 0.9;                               // critically damped, independent per axis
    for (let k = 0; k < 2; k++) { const a = -2 * w * vel[k] - w * w * (pos[k] - target[k]); vel[k] += a * dt; pos[k] += vel[k] * dt; }
    live.setLatLng(pos);
    if (follow) map.panTo(pos, { animate: false });
    if (Math.abs(pos[0] - target[0]) + Math.abs(pos[1] - target[1]) > 1e-8 || Math.abs(vel[0]) + Math.abs(vel[1]) > 1e-8) raf = requestAnimationFrame(step); else raf = 0;
  }; raf = requestAnimationFrame(step); }
}
$('recenter').onclick = () => { if (live) { map.flyTo(live.getLatLng(), Math.max(map.getZoom(), 16), { duration: reduceMotion ? 0 : .8 }); } };

/* ================= status ================= */
let routeState = null;
function fmtDur(sec) {
  sec = Math.round(sec);
  if (sec < 60) return sec + ' sec';
  const m = Math.round(sec / 60);
  return m < 60 ? m + ' min' : Math.floor(m / 60) + ' hr ' + (m % 60) + ' min';
}
function showStatus(s) {
  const pill = $('pill');
  pill.className = 'pill glass' + (s.error ? ' err' : s.lat != null ? ' live' : '');
  routeState = s.route;
  let text = s.msg;
  if (s.route && !s.route.done) text = s.route.connecting ? 'Connecting to the iPhone…' : s.route.label;
  $('pillText').textContent = text;
  moveLive(s.lat, s.lon);
  $('pinLive').classList.toggle('hidden', s.lat == null || !!s.route);
  refreshTrip();
}
function refreshTrip() {
  const r = routeState;
  $('tripCard').classList.toggle('hidden', !r);
  if (!r) return;
  $('tripLeft').textContent = r.connecting ? 'Connecting…' : r.done ? 'Arrived' : fmtDur(r.left);
  $('tripCard').querySelector('.eta span').textContent = r.done || r.connecting ? '' : 'left';
  $('tripLabel').textContent = r.done ? `${r.label} · holding at the destination` : r.label;
  $('tripBar').style.width = (100 * r.i / Math.max(1, r.n - 1)).toFixed(1) + '%';
}
async function post(path, data) {
  const r = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: data ? JSON.stringify(data) : '' });
  return r.json();
}
async function stopAll(btn) { btn.disabled = true; try { showStatus(await post('/stop')); } catch {} btn.disabled = false; }
$('stop').onclick = () => stopAll($('stop'));
$('endTrip').onclick = () => stopAll($('endTrip'));

async function ping() {
  try { showStatus(await (await fetch('/ping')).json()); }
  catch { showStatus({ msg: 'PinLoc isn’t running. Start it in Terminal.', error: true }); }
  setTimeout(ping, routeState && !routeState.done ? 1000 : 3000);
}
ping();
renderRecent();

addEventListener('keydown', e => { if (e.key === '/' && document.activeElement.tagName !== 'INPUT') { e.preventDefault(); (tab === 'pin' ? $('q') : $('fromQ')).focus(); } });

// Closing the tab = "swiping the app away": stop faking right away.
addEventListener('pagehide', () => navigator.sendBeacon('/stop'));
</script>
</body>
</html>
"""


def main():
    try:
        import pymobiledevice3  # noqa: F401
    except ImportError:
        print("pymobiledevice3 isn't installed. Run:\n\n    pip3 install pymobiledevice3\n")
        sys.exit(1)

    print("PinLoc starting...")
    print("> Preparing the iPhone (first time can take a minute)...")
    try:
        r = subprocess.run(PMD + ["mounter", "auto-mount"], capture_output=True, text=True, timeout=180)
        out = (r.stdout + r.stderr).strip().splitlines()
        if r.returncode != 0 and out:
            print("  [phone] " + out[-1])
    except Exception as e:
        print(f"  [phone] auto-mount skipped: {e}")

    try:
        server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
    except OSError:
        url = f"http://127.0.0.1:{PORT}/"
        print(f"> PinLoc is already running. Opening {url}")
        print("  (To restart it, press Ctrl+C in the other Terminal window first.)")
        webbrowser.open(url)
        sys.exit(0)
    threading.Thread(target=watchdog, daemon=True).start()

    def shutdown(*_):
        print("\n> Shutting down, restoring real location...")
        stop_fake()
        os._exit(0)

    signal.signal(signal.SIGINT, shutdown)
    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGHUP, shutdown)

    url = f"http://127.0.0.1:{PORT}/"
    print(f"> Map is at {url}  (Ctrl+C to quit)")
    webbrowser.open(url)
    server.serve_forever()


if __name__ == "__main__":
    main()
