aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/routes/home.tsx
blob: 0a13fe68fb332289d7ef0a09f9b0a1f83e9ac65e (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
import { Clock, History, MapPin, Star } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router";
import { usePageTitle } from "~/contexts/PageTitleContext";
import { usePlanner } from "~/hooks/usePlanner";
import StopItem from "../components/StopItem";
import StopDataProvider, { type Stop } from "../data/StopDataProvider";
import "../tailwind-full.css";

export default function StopList() {
  const { t } = useTranslation();
  usePageTitle(t("navbar.stops", "Paradas"));
  const navigate = useNavigate();
  const { history, loadRoute } = usePlanner({ autoLoad: false });
  const [data, setData] = useState<Stop[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchResults, setSearchResults] = useState<Stop[] | null>(null);
  const [favouriteStops, setFavouriteStops] = useState<Stop[]>([]);
  const [recentStops, setRecentStops] = useState<Stop[]>([]);
  const searchTimeout = useRef<NodeJS.Timeout | null>(null);

  const randomPlaceholder = useMemo(
    () => t("stoplist.search_placeholder"),
    [t]
  );

  // Load stops from network
  const loadStops = useCallback(async () => {
    try {
      setLoading(true);

      const favouriteIds = StopDataProvider.getFavouriteIds();
      const recentIds = StopDataProvider.getRecent();
      const allIds = Array.from(new Set([...favouriteIds, ...recentIds]));

      const stopsMap = await StopDataProvider.fetchStopsByIds(allIds);

      const favStops = favouriteIds
        .map((id) => stopsMap[id])
        .filter(Boolean)
        .map((stop) => ({ ...stop, favourite: true }));
      setFavouriteStops(favStops);

      const recStops = recentIds
        .map((id) => stopsMap[id])
        .filter(Boolean)
        .map((stop) => ({
          ...stop,
          favourite: favouriteIds.includes(stop.stopId),
        }));
      setRecentStops(recStops);

      setData(Object.values(stopsMap));
    } catch (error) {
      console.error("Failed to load stops:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadStops();
  }, [loadStops]);

  const handleStopSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    const searchQuery = event.target.value || "";

    if (searchTimeout.current) {
      clearTimeout(searchTimeout.current);
    }

    searchTimeout.current = setTimeout(async () => {
      if (searchQuery.length === 0) {
        setSearchResults(null);
        return;
      }

      try {
        const response = await fetch(
          `/api/stops/search?q=${encodeURIComponent(searchQuery)}`
        );
        if (response.ok) {
          const results = await response.json();
          setSearchResults(results);
        } else {
          setSearchResults([]);
        }
      } catch (error) {
        console.error("Search failed:", error);
        setSearchResults([]);
      }
    }, 300);
  };

  return (
    <div className="flex flex-col gap-4 py-4 pb-8">
      {/* Planner Section */}
      <div className="w-full px-4">
        <button
          type="button"
          onClick={() => navigate("/planner")}
          className="w-full flex items-center gap-3 p-3 rounded-xl bg-surface border border-slate-200 dark:border-slate-700 shadow-sm hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors text-left"
        >
          <MapPin className="w-5 h-5 text-primary-600 dark:text-primary-400 shrink-0" />
          <span className="font-semibold text-text">
            {t("planner.where_to", "¿A dónde quieres ir?")}
          </span>
        </button>

        {history.length > 0 && (
          <div className="mt-3 flex flex-col gap-2">
            <h4 className="text-xs font-bold uppercase tracking-wider text-muted px-1">
              {t("planner.recent_routes", "Rutas recientes")}
            </h4>
            <div className="flex flex-col gap-1">
              {history.map((route, idx) => (
                <button
                  key={idx}
                  onClick={() => {
                    loadRoute(route);
                    navigate("/planner");
                  }}
                  className="flex items-center gap-3 p-3 rounded-xl bg-surface border border-border hover:bg-surface/80 transition-colors text-left"
                >
                  <History className="w-4 h-4 text-muted shrink-0" />
                  <div className="flex flex-col min-w-0">
                    <span className="text-sm font-semibold text-text truncate">
                      {route.destination.name}
                    </span>
                    <span className="text-xs text-muted truncate">
                      {t("planner.from_to", {
                        from: route.origin.name,
                        to: route.destination.name,
                      })}
                    </span>
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Search Section */}
      <div className="w-full px-4">
        <h3 className="text-xs font-bold uppercase tracking-wider text-muted mb-2 px-1">
          {t("stoplist.search_label", "Buscar paradas")}
        </h3>
        <input
          type="search"
          placeholder={randomPlaceholder}
          onChange={handleStopSearch}
          className="w-full px-4 py-3 rounded-xl border border-border bg-surface text-text focus:outline-none focus:ring-2 focus:ring-primary shadow-sm placeholder-gray-500"
        />
      </div>

      {/* Search Results */}
      {searchResults && searchResults.length > 0 ? (
        <div className="w-full px-4 flex flex-col gap-2">
          <h2 className="text-lg font-semibold text-text">
            {t("stoplist.search_results", "Resultados de la búsqueda")}
          </h2>
          <ul className="list-none p-0 m-0 flex flex-col gap-2 md:grid md:grid-cols-[repeat(auto-fill,minmax(300px,1fr))] lg:grid-cols-[repeat(auto-fill,minmax(320px,1fr))]">
            {searchResults.map((stop: Stop, index) => (
              <StopItem
                key={stop.stopId}
                stop={stop}
                showArrivals={index < 3}
              />
            ))}
          </ul>
        </div>
      ) : searchResults !== null ? (
        <div className="w-full px-4 flex flex-col gap-2">
          <p className="text-center text-gray-600 dark:text-gray-400 py-8">
            {t("stoplist.no_results", "No se encontraron resultados")}
          </p>
        </div>
      ) : (
        <>
          {/* Favourites List */}
          {!loading && favouriteStops.length > 0 && (
            <div className="w-full px-4 flex flex-col gap-2">
              <div className="flex items-center gap-2 mb-1 pl-1">
                <Star className="text-yellow-500 w-4 h-4" />
                <h3 className="text-xs font-bold uppercase tracking-wider text-muted m-0">
                  {t("stoplist.favourites")}
                </h3>
              </div>
              <ul className="list-none p-0 m-0 flex flex-col gap-2 md:grid md:grid-cols-[repeat(auto-fill,minmax(300px,1fr))] lg:grid-cols-[repeat(auto-fill,minmax(320px,1fr))]">
                {favouriteStops
                  .sort((a, b) => a.stopId.localeCompare(b.stopId))
                  .map((stop, index) => (
                    <StopItem
                      key={stop.stopId}
                      stop={stop}
                      showArrivals={index < 3}
                    />
                  ))}
              </ul>
            </div>
          )}

          {!loading && favouriteStops.length === 0 && (
            <div className="w-full px-4 flex flex-col gap-2">
              <div className="flex items-center gap-2 mb-1 pl-1">
                <Star className="text-yellow-500 w-4 h-4" />
                <h3 className="text-xs font-bold uppercase tracking-wider text-muted m-0">
                  {t("stoplist.favourites")}
                </h3>
              </div>
              <div className="text-center bg-surface border border-slate-200 dark:border-slate-700 shadow-sm rounded-xl p-4">
                <p className="text-sm text-muted">
                  {t("stoplist.no_favourites")}
                </p>
              </div>
            </div>
          )}

          {/* Recent Stops List - only show if no favourites */}
          {!loading &&
            favouriteStops.length === 0 &&
            recentStops.length > 0 && (
              <div className="w-full px-4 flex flex-col gap-2 mt-4">
                <div className="flex items-center gap-2 mb-1 pl-1">
                  <Clock className="text-blue-500 w-4 h-4" />
                  <h3 className="text-xs font-bold uppercase tracking-wider text-muted m-0">
                    {t("stoplist.recents")}
                  </h3>
                </div>
                <ul className="list-none p-0 m-0 flex flex-col gap-2 md:grid md:grid-cols-[repeat(auto-fill,minmax(300px,1fr))] lg:grid-cols-[repeat(auto-fill,minmax(320px,1fr))]">
                  {recentStops.slice(0, 5).map((stop, index) => (
                    <StopItem
                      key={stop.stopId}
                      stop={stop}
                      showArrivals={index < 5}
                    />
                  ))}
                </ul>
              </div>
            )}
        </>
      )}
    </div>
  );
}