aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/components/StopSheet.tsx
blob: 0c19cb6f38e72f039c22bffdd55880aaf6373307 (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
import React, { useEffect, useState } from "react";
import { Sheet } from "react-modal-sheet";
import { Link } from "react-router";
import { useTranslation } from "react-i18next";
import { Clock, RefreshCw } from "lucide-react";
import LineIcon from "./LineIcon";
import { StopSheetSkeleton } from "./StopSheetSkeleton";
import { ErrorDisplay } from "./ErrorDisplay";
import { StopAlert } from "./StopAlert";
import { type Estimate } from "../routes/estimates-$id";
import { REGIONS, type RegionId, getRegionConfig } from "../data/RegionConfig";
import { useApp } from "../AppContext";
import "./StopSheet.css";
import type { Stop } from "~/data/StopDataProvider";

interface StopSheetProps {
  isOpen: boolean;
  onClose: () => void;
  stop: Stop;
}

interface ErrorInfo {
  type: "network" | "server" | "unknown";
  status?: number;
  message?: string;
}

const loadStopData = async (
  region: RegionId,
  stopId: number,
): Promise<Estimate[]> => {
  const regionConfig = getRegionConfig(region);
  const resp = await fetch(`${regionConfig.estimatesEndpoint}?id=${stopId}`, {
    headers: {
      Accept: "application/json",
    },
  });

  if (!resp.ok) {
    throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
  }

  return await resp.json();
};

export const StopSheet: React.FC<StopSheetProps> = ({
  isOpen,
  onClose,
  stop,
}) => {
  const { t } = useTranslation();
  const { region } = useApp();
  const regionConfig = getRegionConfig(region);
  const [data, setData] = useState<Estimate[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<ErrorInfo | null>(null);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);

  const parseError = (error: any): ErrorInfo => {
    if (!navigator.onLine) {
      return { type: "network", message: "No internet connection" };
    }

    if (
      error.message?.includes("Failed to fetch") ||
      error.message?.includes("NetworkError")
    ) {
      return { type: "network" };
    }

    if (error.message?.includes("HTTP")) {
      const statusMatch = error.message.match(/HTTP (\d+):/);
      const status = statusMatch ? parseInt(statusMatch[1]) : undefined;
      return { type: "server", status };
    }

    return { type: "unknown", message: error.message };
  };

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);
      setData(null);

      const stopData = await loadStopData(region, stop.stopId);
      setData(stopData);
      setLastUpdated(new Date());
    } catch (err) {
      console.error("Failed to load stop data:", err);
      setError(parseError(err));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (isOpen && stop.stopId) {
      loadData();
    }
  }, [isOpen, stop.stopId, region]);

  const formatTime = (minutes: number) => {
    if (minutes > 15) {
      const now = new Date();
      const arrival = new Date(now.getTime() + minutes * 60000);
      return Intl.DateTimeFormat(
        typeof navigator !== "undefined" ? navigator.language : "en",
        {
          hour: "2-digit",
          minute: "2-digit",
        },
      ).format(arrival);
    } else {
      return `${minutes} ${t("estimates.minutes", "min")}`;
    }
  };

  const formatDistance = (meters: number) => {
    if (meters > 1024) {
      return `${(meters / 1000).toFixed(1)} km`;
    } else {
      return `${meters} ${t("estimates.meters", "m")}`;
    }
  };

  // Show only the next 4 arrivals
  const limitedEstimates =
    data?.sort((a, b) => a.minutes - b.minutes).slice(0, 4) || [];

  return (
    <Sheet isOpen={isOpen} onClose={onClose} detent={"content-height" as any} >
      <Sheet.Container drag="y">
        <Sheet.Header />
        <Sheet.Content>
          <div className="stop-sheet-content">
            <div className="stop-sheet-header">
              <h2 className="stop-sheet-title">{stop.name.original}</h2>
              <span className="stop-sheet-id">({stop.stopId})</span>
            </div>

            <div
              className={`stop-sheet-lines-container ${stop.lines.length >= 6 ? "scrollable" : ""}`}
            >
              {stop.lines.map((line) => (
                <div key={line} className="stop-sheet-line-icon">
                  <LineIcon line={line} region={region} rounded />
                </div>
              ))}
            </div>

            <StopAlert stop={stop} compact />

            {loading ? (
              <StopSheetSkeleton />
            ) : error ? (
              <ErrorDisplay
                error={error}
                onRetry={loadData}
                title={t(
                  "errors.estimates_title",
                  "Error al cargar estimaciones",
                )}
                className="compact"
              />
            ) : data ? (
              <>
                <div className="stop-sheet-estimates">
                  <h3 className="stop-sheet-subtitle">
                    {t("estimates.next_arrivals", "Next arrivals")}
                  </h3>

                  {limitedEstimates.length === 0 ? (
                    <div className="stop-sheet-no-estimates">
                      {t("estimates.none", "No hay estimaciones disponibles")}
                    </div>
                  ) : (
                    <div className="stop-sheet-estimates-list">
                      {limitedEstimates.map((estimate, idx) => (
                        <div key={idx} className="stop-sheet-estimate-item">
                          <div className="stop-sheet-estimate-line">
                            <LineIcon line={estimate.line} region={region} />
                          </div>
                          <div className="stop-sheet-estimate-details">
                            <div className="stop-sheet-estimate-route">
                              {estimate.route}
                            </div>
                          </div>
                          <div className="stop-sheet-estimate-arrival">
                            <div
                              className={`stop-sheet-estimate-time ${estimate.minutes <= 15 ? "is-minutes" : ""}`}
                            >
                              <Clock />
                              {formatTime(estimate.minutes)}
                            </div>
                            {REGIONS[region].showMeters && estimate.meters >= 0 && (
                              <div className="stop-sheet-estimate-distance">
                                {formatDistance(estimate.meters)}
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                <div className="stop-sheet-footer">
                  {lastUpdated && (
                    <div className="stop-sheet-timestamp">
                      {t("estimates.last_updated", "Actualizado a las")}{" "}
                      {lastUpdated.toLocaleTimeString(undefined, {
                        hour: "2-digit",
                        minute: "2-digit",
                        second: "2-digit",
                      })}
                    </div>
                  )}

                  <div className="stop-sheet-actions">
                    <button
                      className="stop-sheet-reload"
                      onClick={loadData}
                      disabled={loading}
                      title={t("estimates.reload", "Recargar estimaciones")}
                    >
                      <RefreshCw
                        className={`reload-icon ${loading ? "spinning" : ""}`}
                      />
                      {t("estimates.reload", "Recargar")}
                    </button>

                    <Link
                      to={`/estimates/${stop.stopId}`}
                      className="stop-sheet-view-all"
                      onClick={onClose}
                    >
                      {t(
                        "map.view_all_estimates",
                        "Ver todas las estimaciones",
                      )}
                    </Link>
                  </div>
                </div>
              </>
            ) : null}
          </div>
        </Sheet.Content>
      </Sheet.Container>
      <Sheet.Backdrop onTap={onClose} />
    </Sheet>
  );
};