// screens-find.jsx — find a parked car: live distance + bearing dial, map, Open in Maps.

const DIR_WORDS = { N: "north", NE: "north-east", E: "east", SE: "south-east", S: "south", SW: "south-west", W: "west", NW: "north-west" };

function FindScreen({ state, store, units, dark, onGoPark, simKey }) {
  const car = state.cars.find((c) => c.id === state.selectedCarId) || state.cars[0];
  const me = useLivePosition(true, simKey);

  if (!car) {
    return (
      <div className="wmc-screen">
        <ScreenHeader title="Find" />
        <EmptyState icon={<IconCompass size={30} />} title="No car selected" body="Add a car in the Garage first." />
      </div>
    );
  }

  const spot = car.current;

  return (
    <div className="wmc-screen">
      <ScreenHeader title="Find My Car" subtitle={car.name} />
      <CarSelector cars={state.cars} selectedId={car.id} onSelect={store.selectCar} />
      <div style={{ height: 16 }} />

      {!spot ? (
        <EmptyState icon={<IconPinPlus size={30} />} title={`${car.name} isn't parked`}
          body="Save a parking spot for this car and it'll show up here with live directions."
          action={<AppButton icon={<IconPinPlus size={20} sw={1.9} />} onClick={onGoPark}>Park this car</AppButton>} />
      ) : (
        <FindDetail car={car} spot={spot} me={me} units={units} dark={dark} />
      )}
    </div>
  );
}

function FindDetail({ car, spot, me, units, dark }) {
  const dist = me ? haversine(me, spot) : null;
  const brg = me ? bearing(me, spot) : null;
  const point = brg != null ? compassPoint(brg) : null;
  const arrived = dist != null && dist < 25;

  return (
    <div>
      {/* hero: distance + direction dial */}
      <Card style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
          <DirectionDial bearing={brg} arrived={arrived} />
          <div style={{ flex: 1, minWidth: 0 }}>
            {arrived ? (
              <>
                <div style={{ fontSize: 26, fontWeight: 800, color: "var(--accent-ink)", letterSpacing: -0.6 }}>You're here</div>
                <div style={{ fontSize: 14, color: "var(--text-2)", marginTop: 3 }}>Within {formatDistance(dist, units)} of {car.name}</div>
              </>
            ) : (
              <>
                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span style={{ fontSize: 38, fontWeight: 820, color: "var(--text)", letterSpacing: -1.4, lineHeight: 1 }}>{dist != null ? formatDistance(dist, units) : "—"}</span>
                </div>
                <div style={{ fontSize: 14.5, color: "var(--text-2)", marginTop: 6, fontWeight: 550 }}>
                  {point ? <>Head <strong style={{ color: "var(--text)" }}>{DIR_WORDS[point]}</strong></> : "Locating you…"}
                </div>
              </>
            )}
            <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 8, display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 7, height: 7, borderRadius: 999, background: me && !me.simulated ? "#3ddc84" : "var(--text-3)", boxShadow: me && !me.simulated ? "0 0 0 3px rgba(61,220,132,.18)" : "none" }} />
              {me ? (me.simulated ? "Demo location" : "Live location") : "Getting location…"}
            </div>
          </div>
        </div>
      </Card>

      {/* map */}
      <Card pad={0} style={{ overflow: "hidden", marginBottom: 14 }}>
        <LeafletMap carSpot={spot} me={me} emoji={car.emoji} dark={dark} fit interactive style={{ height: 252, borderRadius: 0, border: "none" }} />
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px", fontSize: 13 }}>
          <span style={{ color: "var(--text-2)", display: "flex", alignItems: "center", gap: 7 }}>
            <IconClock size={15} /> Parked {relativeTime(spot.timestamp)}
          </span>
          <span style={{ color: "var(--text-3)" }}>{clockTime(spot.timestamp)}</span>
        </div>
      </Card>

      {spot.note && (
        <Card style={{ marginBottom: 14, display: "flex", gap: 10, alignItems: "flex-start" }}>
          <span style={{ color: "var(--accent-ink)", flexShrink: 0, marginTop: 1 }}><IconNote size={19} /></span>
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.6, color: "var(--text-3)", marginBottom: 3 }}>Note</div>
            <div style={{ fontSize: 15.5, color: "var(--text)", lineHeight: 1.4 }}>{spot.note}</div>
          </div>
        </Card>
      )}

      <AppButton full onClick={() => window.open(mapsUrl(spot), "_blank")} icon={<IconExternal size={19} />}>
        Walking directions in Maps
      </AppButton>
    </div>
  );
}

function DirectionDial({ bearing, arrived }) {
  const ticks = [];
  for (let i = 0; i < 12; i++) ticks.push(i);
  return (
    <div style={{
      width: 104, height: 104, borderRadius: "50%", flexShrink: 0, position: "relative",
      background: "var(--surface-2)", border: "1px solid var(--hairline)",
      display: "grid", placeItems: "center",
      boxShadow: "inset 0 2px 8px rgba(0,0,0,.25)",
    }}>
      {/* ticks */}
      {ticks.map((i) => (
        <span key={i} style={{
          position: "absolute", top: 6, left: "50%", width: 2, height: i % 3 === 0 ? 9 : 5,
          background: i % 3 === 0 ? "var(--text-3)" : "var(--hairline)", borderRadius: 2,
          transform: `translateX(-50%) rotate(${i * 30}deg)`, transformOrigin: "50% 46px",
        }} />
      ))}
      {/* N label */}
      <span style={{ position: "absolute", top: 13, left: "50%", transform: "translateX(-50%)", fontSize: 10, fontWeight: 800, color: "var(--text-3)" }}>N</span>
      {/* arrow */}
      {arrived ? (
        <span style={{ color: "var(--accent)", display: "grid", placeItems: "center" }}><IconPin size={40} sw={1.7} /></span>
      ) : (
        <div style={{
          transition: "transform .5s cubic-bezier(.34,1.3,.5,1)",
          transform: `rotate(${bearing == null ? 0 : bearing}deg)`,
          display: "grid", placeItems: "center", opacity: bearing == null ? 0.4 : 1,
        }}>
          <svg width="44" height="44" viewBox="0 0 44 44">
            <path d="M22 5 L31 30 L22 24 L13 30 Z" fill="var(--accent)" stroke="var(--accent)" strokeWidth="1.5" strokeLinejoin="round" />
          </svg>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { FindScreen, FindDetail, DirectionDial });
