aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/routes/map.tsx
blob: af94509ae4e8b9be9d666eb1a651c4d820d907e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import { Check, MapPin, X } from "lucide-react";
import type { FilterSpecification } from "maplibre-gl";
import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Layer,
  Source,
  type MapLayerMouseEvent,
  type MapRef,
} from "react-map-gl/maplibre";
import { useNavigate } from "react-router";
import { useApp } from "~/AppContext";
import {
  StopSummarySheet,
  type StopSheetProps,
} from "~/components/map/StopSummarySheet";
import { PlannerOverlay } from "~/components/PlannerOverlay";
import { AppMap } from "~/components/shared/AppMap";
import { usePageTitle } from "~/contexts/PageTitleContext";
import { reverseGeocode } from "~/data/PlannerApi";
import { usePlanner } from "~/hooks/usePlanner";
import StopDataProvider from "../data/StopDataProvider";
import "../tailwind-full.css";
import "./map.css";

// Componente principal del mapa
export default function StopMap() {
  const { t } = useTranslation();
  const {
    showBusStops: showCitybusStops,
    showCoachStops: showIntercityBusStops,
    showTrainStops,
  } = useApp();
  const navigate = useNavigate();
  usePageTitle(t("navbar.map", "Mapa"));
  const [selectedStop, setSelectedStop] = useState<
    StopSheetProps["stop"] | null
  >(null);
  const [isSheetOpen, setIsSheetOpen] = useState(false);
  const [disambiguationStops, setDisambiguationStops] = useState<
    Array<StopSheetProps["stop"]>
  >([]);
  const mapRef = useRef<MapRef>(null);

  const {
    searchRoute,
    pickingMode,
    setPickingMode,
    setOrigin,
    setDestination,
    addRecentPlace,
  } = usePlanner({ autoLoad: false });

  const [isConfirming, setIsConfirming] = useState(false);

  const handleConfirmPick = async () => {
    if (!mapRef.current || !pickingMode) return;
    const center = mapRef.current.getCenter();
    setIsConfirming(true);

    try {
      const result = await reverseGeocode(center.lat, center.lng);
      const finalResult = {
        name:
          result?.name || `${center.lat.toFixed(5)}, ${center.lng.toFixed(5)}`,
        label: result?.label || "Map location",
        lat: center.lat,
        lon: center.lng,
        layer: "map-pick",
      };

      if (pickingMode === "origin") {
        setOrigin(finalResult);
      } else {
        setDestination(finalResult);
      }
      addRecentPlace(finalResult);
      setPickingMode(null);
    } catch (err) {
      console.error("Failed to reverse geocode:", err);
    } finally {
      setIsConfirming(false);
    }
  };

  const onMapInteraction = () => {
    if (!pickingMode) {
      window.dispatchEvent(new CustomEvent("plannerOverlay:collapse"));
    }
  };

  const favouriteIds = useMemo(() => StopDataProvider.getFavouriteIds(), []);

  const favouriteFilter = useMemo(() => {
    if (favouriteIds.length === 0) return ["boolean", false];
    return ["match", ["get", "id"], favouriteIds, true, false];
  }, [favouriteIds]);

  // Handle click events on clusters and individual stops
  const onMapClick = (e: MapLayerMouseEvent) => {
    const features = e.features;
    if (!features || features.length === 0) {
      console.debug(
        "No features found on map click. Position:",
        e.lngLat,
        "Point:",
        e.point
      );
      return;
    }

    // Collect only stop-layer features with valid properties
    const stopFeatures = features.filter(
      (f) => f.layer?.id?.startsWith("stops") && f.properties?.id
    );

    if (stopFeatures.length === 0) return;

    if (stopFeatures.length === 1) {
      // Single unambiguous stop – open the sheet directly
      handlePointClick(stopFeatures[0]);
      return;
    }

    // Multiple overlapping stops – deduplicate by stop id and ask the user
    const seen = new Set<string>();
    const candidates: Array<StopSheetProps["stop"]> = [];
    for (const f of stopFeatures) {
      const id: string = f.properties!.id;
      if (!seen.has(id)) {
        seen.add(id);
        candidates.push({
          stopId: id,
          stopCode: f.properties!.code,
          name: f.properties!.name || "Unknown Stop",
        });
      }
    }

    if (candidates.length === 1) {
      // After deduplication only one stop remains
      setSelectedStop(candidates[0]);
      setIsSheetOpen(true);
    } else {
      setDisambiguationStops(candidates);
    }
  };

  const stopLayerFilter = useMemo(() => {
    const filter: any[] = ["any", ["==", ["get", "transitKind"], "unknown"]];
    if (showCitybusStops) {
      filter.push(["==", ["get", "transitKind"], "bus"]);
    }
    if (showIntercityBusStops) {
      filter.push(["==", ["get", "transitKind"], "coach"]);
    }
    if (showTrainStops) {
      filter.push(["==", ["get", "transitKind"], "train"]);
    }
    return filter as FilterSpecification;
  }, [showCitybusStops, showIntercityBusStops, showTrainStops]);

  const handlePointClick = (feature: any) => {
    const props: {
      id: string;
      code: string;
      name: string;
      routes: string;
    } = feature.properties;
    // TODO: Move ID to constant, improve type checking
    if (!props || feature.layer.id.startsWith("stops") === false) {
      console.warn("Invalid feature properties:", props);
      return;
    }

    setSelectedStop({
      stopId: props.id,
      stopCode: props.code,
      name: props.name || "Unknown Stop",
    });
    setIsSheetOpen(true);
  };

  return (
    <div className="relative h-full">
      {!pickingMode && (
        <PlannerOverlay
          onSearch={(o, d, time, arriveBy) => searchRoute(o, d, time, arriveBy)}
          onNavigateToPlanner={() => navigate("/planner")}
          clearPickerOnOpen={true}
          showLastDestinationWhenCollapsed={false}
          cardBackground="bg-white/95 dark:bg-slate-900/90"
          autoLoad={false}
        />
      )}

      {pickingMode && (
        <div className="absolute top-4 left-0 right-0 z-20 flex justify-center px-4 pointer-events-none">
          <div className="bg-white/95 dark:bg-slate-900/90 backdrop-blur p-4 rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 w-full max-w-md pointer-events-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-bold text-slate-900 dark:text-slate-100">
                {pickingMode === "origin"
                  ? t("planner.pick_origin", "Select origin")
                  : t("planner.pick_destination", "Select destination")}
              </h3>
              <button
                onClick={() => setPickingMode(null)}
                className="p-1 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              {t(
                "planner.pick_instruction",
                "Move the map to place the target on the desired location"
              )}
            </p>
            <button
              onClick={handleConfirmPick}
              disabled={isConfirming}
              className="w-full bg-primary-600 hover:bg-primary-700 text-white font-bold py-3 rounded-xl flex items-center justify-center gap-2 transition-colors disabled:opacity-50"
            >
              {isConfirming ? (
                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
              ) : (
                <>
                  <Check className="w-5 h-5" />
                  {t("planner.confirm_location", "Confirm location")}
                </>
              )}
            </button>
          </div>
        </div>
      )}

      {pickingMode && (
        <div className="absolute inset-0 pointer-events-none z-10 flex items-center justify-center">
          <div className="relative flex items-center justify-center">
            {/* Modern discrete target */}
            <div className="w-1 h-1 bg-primary-600 rounded-full shadow-[0_0_0_4px_rgba(37,99,235,0.1)]" />
            <div className="absolute w-6 h-[1px] bg-primary-600/30" />
            <div className="absolute w-[1px] h-6 bg-primary-600/30" />
          </div>
        </div>
      )}

      <AppMap
        ref={mapRef}
        syncState={true}
        showNavigation={true}
        showGeolocate={true}
        showTraffic={pickingMode ? false : undefined}
        interactiveLayerIds={["stops", "stops-label"]}
        onClick={onMapClick}
        onDragStart={onMapInteraction}
        onZoomStart={onMapInteraction}
        attributionControl={{ compact: false }}
      >
        <Source
          id="stops-source"
          type="vector"
          tiles={[StopDataProvider.getTileUrlTemplate()]}
          minzoom={11}
          maxzoom={20}
        />

        {!pickingMode && (
          <Layer
            id="stops-favourite-highlight"
            type="circle"
            minzoom={11}
            source="stops-source"
            source-layer="stops"
            filter={["all", stopLayerFilter, favouriteFilter]}
            paint={{
              "circle-color": "#FFD700",
              "circle-radius": [
                "interpolate",
                ["linear"],
                ["zoom"],
                13,
                10,
                16,
                12,
                18,
                16,
              ],
              "circle-opacity": 0.4,
              "circle-stroke-color": "#FFD700",
              "circle-stroke-width": 2,
            }}
          />
        )}

        <Layer
          id="stops"
          type="symbol"
          minzoom={11}
          source="stops-source"
          source-layer="stops"
          filter={stopLayerFilter}
          layout={{
            "icon-image": ["get", "icon"],
            "icon-size": [
              "interpolate",
              ["linear"],
              ["zoom"],
              13,
              0.7,
              16,
              0.8,
              18,
              1.2,
            ],
            "icon-allow-overlap": true,
            "icon-ignore-placement": true,
            "symbol-sort-key": [
              "match",
              ["get", "transitKind"],
              "bus",
              3,
              "coach",
              2,
              "train",
              1,
              0,
            ],
          }}
        />

        <Layer
          id="stops-label"
          type="symbol"
          source="stops-source"
          source-layer="stops"
          minzoom={16}
          filter={stopLayerFilter}
          layout={{
            "text-field": ["get", "name"],
            "text-font": ["Noto Sans Bold"],
            "text-offset": [0, 3],
            "text-anchor": "center",
            "text-justify": "center",
            "text-size": ["interpolate", ["linear"], ["zoom"], 11, 8, 22, 16],
            "symbol-sort-key": [
              "match",
              ["get", "transitKind"],
              "coach",
              3,
              "train",
              2,
              "bus",
              1,
              0,
            ],
            "text-allow-overlap": false,
          }}
          paint={{
            "text-color": [
              "match",
              ["get", "feed"],
              "vitrasa",
              "#81D002",
              "tussa",
              "#508096",
              "tranvias",
              "#E61C29",
              "xunta",
              "#007BC4",
              "renfe",
              "#870164",
              "feve",
              "#EE3D32",
              "#27187D",
            ],
            "text-halo-color": "#FFF",
            "text-halo-width": 1,
          }}
        />

        {selectedStop && (
          <StopSummarySheet
            isOpen={isSheetOpen}
            onClose={() => setIsSheetOpen(false)}
            stop={selectedStop}
          />
        )}

        {disambiguationStops.length > 1 && (
          <div className="fixed inset-x-0 bottom-0 z-30 flex justify-center pointer-events-none pb-safe">
            <div className="pointer-events-auto w-full max-w-md bg-white dark:bg-slate-900 rounded-t-2xl shadow-2xl border border-slate-200 dark:border-slate-700 p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-semibold text-slate-900 dark:text-slate-100 text-base">
                  {t("map.select_nearby_stop", "Seleccionar parada")}
                </h3>
                <button
                  onClick={() => setDisambiguationStops([])}
                  className="p-1 rounded-full hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                  aria-label={t("planner.close", "Cerrar")}
                >
                  <X className="w-5 h-5 text-slate-500" />
                </button>
              </div>
              <ul className="divide-y divide-slate-100 dark:divide-slate-800">
                {disambiguationStops.map((stop) => (
                  <li key={stop.stopId}>
                    <button
                      className="w-full flex items-center gap-3 py-3 text-left hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors rounded-lg px-2"
                      onClick={() => {
                        setDisambiguationStops([]);
                        setSelectedStop(stop);
                        setIsSheetOpen(true);
                      }}
                    >
                      <MapPin className="w-4 h-4 flex-shrink-0 text-primary-600" />
                      <div>
                        <div className="font-medium text-slate-900 dark:text-slate-100 text-sm">
                          {stop.name}
                        </div>
                        {stop.stopCode && (
                          <div className="text-xs text-slate-500 dark:text-slate-400">
                            {stop.stopCode}
                          </div>
                        )}
                      </div>
                    </button>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        )}
      </AppMap>
    </div>
  );
}