// screens-park.jsx — select a car, capture current location, adjust pin + notes, save.

function ParkScreen({ state, store, units, dark }) {
  const car = state.cars.find((c) => c.id === state.selectedCarId) || state.cars[0];
  const [capturing, setCapturing] = React.useState(false);
  const [draft, setDraft] = React.useState(null); // { lat,lng,note,accuracy,simulated }

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

  const parked = car.current;

  const capture = async (existingNote) => {
    setCapturing(true);
    const pos = await getPosition();
    setCapturing(false);
    setDraft({ lat: pos.lat, lng: pos.lng, accuracy: pos.accuracy, simulated: pos.simulated, note: existingNote || "" });
  };

  const commit = () => {
    store.parkCar(car.id, {
      lat: draft.lat, lng: draft.lng, note: draft.note.trim(),
      accuracy: draft.accuracy, timestamp: Date.now(),
    });
    setDraft(null);
    toast("Parking spot saved", { icon: <IconCheck size={17} sw={2.6} /> });
  };

  // While the capture/adjust sheet is open, blur the background. A real CSS
  // `filter` (unlike the sheet's `backdrop-filter`) also blurs the Leaflet
  // tiles behind it, so the two maps don't read as overlapping.
  const sheetOpen = !!draft;

  return (
    <div className="wmc-screen">
      <div style={{
        filter: sheetOpen ? "blur(7px)" : "none",
        transition: "filter .26s ease",
        pointerEvents: sheetOpen ? "none" : "auto",
      }}>
        <ScreenHeader title="Park" subtitle="Save where you left a car" />

        <CarSelector cars={state.cars} selectedId={car.id} onSelect={store.selectCar} />

        <div style={{ height: 16 }} />

        {parked ? (
          <ParkedSummary car={car} units={units} dark={dark} store={store}
            onUpdate={() => capture(parked.note)} onEdit={() => setDraft({ ...parked, note: parked.note || "" })} />
        ) : (
          <NotParked car={car} dark={dark} capturing={capturing} onPark={() => capture("")} />
        )}
      </div>

      {/* capture / adjust sheet */}
      <Sheet open={!!draft} onClose={() => setDraft(null)} title={parked ? "Adjust parking spot" : "Confirm parking spot"}
        footer={<AppButton full onClick={commit} icon={<IconPin size={19} sw={2} />}>Save this spot</AppButton>}>
        {draft && (
          <>
            <div style={{ fontSize: 13.5, color: "var(--text-2)", marginBottom: 12, display: "flex", alignItems: "center", gap: 7 }}>
              <IconCrosshair size={16} />
              Drag the pin to fine-tune. {draft.simulated ? "Using a demo location." : `GPS accurate to ±${Math.round(draft.accuracy || 10)}m.`}
            </div>
            <LeafletMap
              carSpot={{ lat: draft.lat, lng: draft.lng }} emoji={car.emoji} dark={dark}
              center={{ lat: draft.lat, lng: draft.lng }} zoom={17} draggable
              onPinMove={(ll) => setDraft((d) => ({ ...d, lat: ll.lat, lng: ll.lng }))}
              style={{ height: 240, marginBottom: 16 }} />
            <Field label="NOTE (optional)" hint="e.g. floor, bay number, nearest landmark">
              <TextArea value={draft.note} placeholder="Level 3 · Bay 42…" maxLength={120}
                onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value }))} />
            </Field>
          </>
        )}
      </Sheet>
    </div>
  );
}

function NotParked({ car, dark, capturing, onPark }) {
  const Glyph = carGlyph(car.emoji);
  return (
    <div>
      <Card pad={0} style={{ overflow: "hidden", marginBottom: 18 }}>
        <div style={{ position: "relative" }}>
          <LeafletMap me={null} carSpot={null} center={SIM_LOCATION} zoom={15} dark={dark} interactive={false} style={{ height: 200, borderRadius: 0, border: "none" }} />
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", pointerEvents: "none" }}>
            <div style={{ background: "var(--surface)", color: "var(--text-2)", padding: "8px 14px", borderRadius: 999, fontSize: 13, fontWeight: 600, boxShadow: "0 4px 14px rgba(0,0,0,.3)", display: "flex", alignItems: "center", gap: 7 }}>
              <span style={{ width: 22, height: 22, borderRadius: 6, background: car.color, color: pickInk(car.color), display: "grid", placeItems: "center" }}><Glyph size={14} sw={2} /></span>
              {car.name} isn't parked yet
            </div>
          </div>
        </div>
      </Card>

      <div style={{ textAlign: "center", marginBottom: 8 }}>
        <div style={{ fontSize: 15, color: "var(--text-2)", lineHeight: 1.5, maxWidth: 280, margin: "0 auto 20px" }}>
          When you leave the {car.name}, tap below to drop a pin at your current spot.
        </div>
        <button className="wmc-park-btn" onClick={onPark} disabled={capturing} style={{
          width: 184, height: 184, borderRadius: "50%", border: "none", cursor: capturing ? "wait" : "pointer",
          background: "var(--accent)", color: "var(--on-accent)", margin: "0 auto",
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 10,
          boxShadow: "0 14px 40px var(--accent-glow), inset 0 1px 0 rgba(255,255,255,.25)",
          WebkitTapHighlightColor: "transparent",
        }}>
          {capturing ? <span className="wmc-spinner" /> : <IconPinPlus size={48} sw={1.7} />}
          <span style={{ fontSize: 19, fontWeight: 750, letterSpacing: -0.2 }}>{capturing ? "Locating…" : "Park Here"}</span>
        </button>
      </div>
    </div>
  );
}

function ParkedSummary({ car, units, dark, store, onUpdate, onEdit }) {
  const spot = car.current;
  return (
    <div>
      <Card pad={0} style={{ overflow: "hidden", marginBottom: 14 }}>
        <LeafletMap carSpot={spot} emoji={car.emoji} center={spot} zoom={16} dark={dark} interactive={false} style={{ height: 200, borderRadius: 0, border: "none" }} />
        <div style={{ padding: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--accent-ink)", fontWeight: 700, fontSize: 14 }}>
            <IconPin size={17} sw={2} /> Parked {relativeTime(spot.timestamp)}
          </div>
          <div style={{ fontSize: 13, color: "var(--text-3)", marginTop: 4 }}>
            {dateLabel(spot.timestamp)} · {clockTime(spot.timestamp)}
          </div>
          {spot.note && (
            <div style={{ display: "flex", gap: 9, marginTop: 12, padding: 12, borderRadius: "var(--radius-sm)", background: "var(--surface-2)", color: "var(--text)", fontSize: 14.5 }}>
              <span style={{ color: "var(--text-3)", flexShrink: 0, marginTop: 1 }}><IconNote size={17} /></span>
              {spot.note}
            </div>
          )}
        </div>
      </Card>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <AppButton full onClick={onUpdate} icon={<IconPinPlus size={20} sw={1.9} />}>Re-park at my current spot</AppButton>
        <div style={{ display: "flex", gap: 10 }}>
          <AppButton variant="secondary" full onClick={onEdit} icon={<IconEdit size={18} />}>Edit pin & note</AppButton>
          <AppButton variant="ghost" full onClick={() => { store.clearSpot(car.id); toast("Spot cleared"); }} icon={<IconTrash size={18} />} style={{ color: "var(--danger)", boxShadow: "inset 0 0 0 1.5px var(--danger-bg)" }}>Clear</AppButton>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ParkScreen });
