aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/routes/routes.tsx
blob: 128bbc49b170df464fc085ce204a1a492f4f2be7 (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
import { useQuery } from "@tanstack/react-query";
import { ChevronDown, ChevronRight, Star } from "lucide-react";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { fetchRoutes } from "~/api/transit";
import RouteIcon from "~/components/RouteIcon";
import { usePageTitle } from "~/contexts/PageTitleContext";
import { useFavorites } from "~/hooks/useFavorites";
import "../tailwind-full.css";

export default function RoutesPage() {
  const { t } = useTranslation();
  usePageTitle(t("navbar.routes", "Rutas"));
  const [searchQuery, setSearchQuery] = useState("");
  const { toggleFavorite: toggleFavoriteRoute, isFavorite: isFavoriteRoute } =
    useFavorites("favouriteRoutes");
  const { toggleFavorite: toggleFavoriteAgency, isFavorite: isFavoriteAgency } =
    useFavorites("favouriteAgencies");

  const [expandedAgencies, setExpandedAgencies] = useState<
    Record<string, boolean>
  >({});

  const toggleAgencyExpanded = (agency: string) => {
    setExpandedAgencies((prev) => ({ ...prev, [agency]: !prev[agency] }));
  };

  const orderedAgencies = [
    "vitrasa",
    "tranvias",
    "tussa",
    "ourense",
    "feve",
    "shuttle",
  ];

  const { data: routes, isLoading } = useQuery({
    queryKey: ["routes"],
    queryFn: () => fetchRoutes(orderedAgencies),
  });

  const filteredRoutes = useMemo(() => {
    return routes?.filter(
      (route) =>
        route.shortName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        route.longName?.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [routes, searchQuery]);

  const routesByAgency = useMemo(() => {
    return filteredRoutes?.reduce(
      (acc, route) => {
        const agency = route.agencyName || t("routes.unknown_agency", "Otros");
        if (!acc[agency]) acc[agency] = [];
        acc[agency].push(route);
        return acc;
      },
      {} as Record<string, typeof routes>
    );
  }, [filteredRoutes, t]);

  const sortedAgencyEntries = useMemo(() => {
    if (!routesByAgency) return [];
    return Object.entries(routesByAgency).sort(([a], [b]) => {
      // First, sort by favorite status
      const isFavA = isFavoriteAgency(a);
      const isFavB = isFavoriteAgency(b);
      if (isFavA && !isFavB) return -1;
      if (!isFavA && isFavB) return 1;

      // Then by fixed order
      const indexA = orderedAgencies.indexOf(a.toLowerCase());
      const indexB = orderedAgencies.indexOf(b.toLowerCase());
      if (indexA === -1 && indexB === -1) {
        return a.localeCompare(b);
      }
      if (indexA === -1) return 1;
      if (indexB === -1) return -1;
      return indexA - indexB;
    });
  }, [routesByAgency, orderedAgencies, isFavoriteAgency]);

  const favoriteRoutes = useMemo(() => {
    return filteredRoutes?.filter((route) => isFavoriteRoute(route.id)) || [];
  }, [filteredRoutes, isFavoriteRoute]);

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="mb-6">
        <input
          type="text"
          placeholder={t("routes.search_placeholder", "Buscar rutas...")}
          className="w-full rounded-xl border border-border bg-surface px-4 py-3 text-text placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
      </div>

      {isLoading && (
        <div className="flex justify-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
        </div>
      )}

      <div className="space-y-3">
        {favoriteRoutes.length > 0 && !searchQuery && (
          <div className="mb-2">
            <h2 className="mb-3 flex items-center gap-2 border-b border-border pb-2 text-sm font-semibold uppercase tracking-wide text-muted">
              <Star size={16} className="fill-yellow-500 text-yellow-500" />
              {t("routes.favorites", "Favoritas")}
            </h2>
            <div className="space-y-2">
              {favoriteRoutes.map((route) => (
                <div
                  key={`fav-${route.id}`}
                  className="rounded-xl border border-border bg-surface"
                >
                  <Link
                    to={`/routes/${route.id}`}
                    className="flex items-center gap-3 px-4 py-3"
                  >
                    <RouteIcon
                      line={route.shortName ?? "?"}
                      mode="pill"
                      colour={route.color ?? undefined}
                      textColour={route.textColor ?? undefined}
                    />
                    <div className="flex-1 min-w-0">
                      <p className="truncate text-sm font-medium text-text">
                        {route.longName}
                      </p>
                    </div>
                  </Link>
                </div>
              ))}
            </div>
          </div>
        )}

        {sortedAgencyEntries.map(([agency, agencyRoutes]) => {
          const isFav = isFavoriteAgency(agency);
          const isExpanded = searchQuery
            ? true
            : (expandedAgencies[agency] ?? false);

          return (
            <div
              key={agency}
              className="overflow-hidden rounded-xl border border-border bg-surface"
            >
              <div
                className={`flex items-center justify-between px-4 py-3 select-none ${isExpanded ? "border-b border-border" : ""}`}
              >
                <button
                  type="button"
                  onClick={() => toggleAgencyExpanded(agency)}
                  className="flex flex-1 items-center gap-3 text-left"
                >
                  <div className="text-muted">
                    {isExpanded ? (
                      <ChevronDown size={18} />
                    ) : (
                      <ChevronRight size={18} />
                    )}
                  </div>
                  <h2 className="text-base font-semibold text-text">
                    {agency}
                  </h2>
                  <span className="rounded-full bg-background px-2 py-0.5 text-xs text-muted">
                    {agencyRoutes.length}
                  </span>
                </button>
                <button
                  type="button"
                  onClick={() => toggleFavoriteAgency(agency)}
                  className={`rounded-full p-2 transition-colors ${
                    isFav
                      ? "text-yellow-500"
                      : "text-muted hover:text-yellow-500"
                  }`}
                  aria-label={t(
                    "routes.toggle_favorite_agency",
                    "Alternar agencia favorita"
                  )}
                >
                  <Star size={16} className={isFav ? "fill-current" : ""} />
                </button>
              </div>

              {isExpanded && (
                <div className="space-y-1 px-3 py-2">
                  {agencyRoutes.map((route) => (
                    <div key={route.id} className="rounded-lg">
                      <Link
                        to={`/routes/${route.id}`}
                        className="flex items-center gap-3 rounded-lg px-3 py-2.5 hover:bg-background"
                      >
                        <RouteIcon
                          line={route.shortName ?? "?"}
                          mode="pill"
                          colour={route.color ?? undefined}
                          textColour={route.textColor ?? undefined}
                        />
                        <div className="flex-1 min-w-0">
                          <p className="truncate text-sm font-medium text-text">
                            {route.longName}
                          </p>
                        </div>
                      </Link>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}