본문으로 건너뛰기
Public Source Viewer

비나래아카이브 개발자 포털

실제 서비스 구조를 살펴볼 수 있는 공개용 코드 뷰어입니다. 인증, 세션, 외부 연동, 토큰, 관리자 식별 등 보안상 민감한 구현은 파일 단위 또는 줄 단위로 검열됩니다.

Redacted View
view/hinana/subway.ejs
공개 가능
1 <!DOCTYPE html>
2 <html lang="ko">
3 <head>
4 <meta charset="utf-8" />
5 <meta name="color-scheme" content="light dark">
6 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, maximum-scale=1.0">
7 <meta name="theme-color" content="<%= (typeof theme !== 'undefined' && theme === 'dark') ? '#0f141e' : '#f8f7f5' %>">
8 <meta property="og:image" content="/image/lounge1.png" />
9 <meta property="og:title" content="열차 위치 조회 — 비나래 라운지" />
10 <meta property="og:description" content="서울시 지하철 실시간 위치정보 API로 열차 열번의 현재 위치를 확인합니다." />
11 <title>열차 위치 조회 — 비나래 라운지</title>
12 <link rel='stylesheet' href='/vendors/bootstrap/css/bootstrap.min.css' />
13 <script src="/vendors/bootstrap/js/bootstrap.min.js"></script>
14 <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;700&family=Montserrat:wght@300;400;700&display=swap" rel="stylesheet">
15 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
16 <script src="/js/popup.js"></script>
17 <style>
18 *, *::before, *::after { box-sizing: border-box; }
19 :root {
20 --bg-main: #f8f7f5; --bg-secondary: #ffffff;
21 --bg-tertiary: #1a2238; --bg-card: #ffffff; --bg-input: #f1f0ed;
22 --text-primary: #1a2238; --text-secondary: #5e6676;
23 --accent: #c5a059; --accent-dim: rgba(197,160,89,0.12);
24 --border: #e5e1da; --success: #16a34a; --danger: #dc2626;
25 --font: 'Noto Sans KR', sans-serif;
26 }
27 body.dark-mode {
28 --bg-main: #0f141e; --bg-secondary: #1a2238; --bg-tertiary: #111827;
29 --bg-card: #1e2a42; --bg-input: #243050;
30 --text-primary: #e7e5e4; --text-secondary: #94a3b8;
31 --border: #2e3a59;
32 }
33 html, body { margin:0; padding:0; background:var(--bg-main); color:var(--text-primary); font-family:var(--font); min-height:100vh; display:flex; flex-direction:column; }
34 a { text-decoration:none; color:inherit; }
35 .site-header { background:var(--bg-tertiary); height:60px; padding:0 24px; display:flex; align-items:center; justify-content:space-between; gap:14px; border-bottom:1px solid var(--border); position:sticky; top:0; z-index:100; }
36 .brand { display:flex; align-items:center; gap:12px; min-width:0; flex:1; font-size:.9rem; font-weight:700; color:#fff; }
37 .brand > span:last-child { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
38 .header-logo { height:26px; max-width:170px; object-fit:contain; }
39 .site-header nav { display:flex; align-items:center; gap:6px; flex:0 0 auto; }
40 .site-header nav a { font-size:.82rem; color:var(--text-secondary); margin-left:20px; transition:color .2s; }
41 .site-header nav a:hover { color:var(--accent); }
42 .page-body { flex:1; max-width:920px; width:100%; margin:0 auto; padding:40px 24px 0; }
43 .page-title { margin-bottom:28px; }
44 .page-title h1 { font-size:1.5rem; font-weight:700; margin:0 0 6px; }
45 .page-title p { font-size:.82rem; color:var(--text-secondary); margin:0; line-height:1.7; }
46 .search-card, .result-card, .info-box, .helper-card { background:var(--bg-card); border:1px solid var(--border); border-radius:12px; padding:20px; margin-bottom:20px; }
47 .search-grid { display:grid; grid-template-columns: 1.05fr .85fr 1.1fr auto; gap:10px; align-items:end; }
48 .field-label { font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.1em; color:var(--text-secondary); margin-bottom:8px; }
49 .field { width:100%; border:1px solid var(--border); border-radius:8px; background:var(--bg-input); color:var(--text-primary); font-family:var(--font); font-size:.95rem; padding:11px 13px; outline:none; }
50 .field:focus { border-color:var(--accent); }
51 .submit-btn { border:1px solid rgba(197,160,89,.55); background:var(--accent); color:var(--ui-on-accent, #fff); border-radius:8px; padding:11px 18px; font-weight:700; font-family:var(--font); white-space:nowrap; }
52 .submit-btn:disabled { opacity:.65; cursor:not-allowed; }
53 .tracker-bar { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-top:14px; padding-top:14px; border-top:1px solid var(--border); flex-wrap:wrap; }
54 .tracker-status { font-size:.78rem; color:var(--text-secondary); line-height:1.6; }
55 .tracker-actions { display:flex; gap:8px; flex-wrap:wrap; }
56 .push-guide { width:100%; margin-top:2px; font-size:.72rem; color:var(--text-secondary); line-height:1.6; }
57 .ghost-btn { border:1px solid var(--border); background:transparent; color:var(--text-secondary); border-radius:8px; padding:9px 12px; font-size:.82rem; font-weight:700; font-family:var(--font); }
58 .ghost-btn:hover { border-color:var(--accent); color:var(--accent); }
59 .ghost-btn:disabled { opacity:.5; cursor:not-allowed; }
60 .helper-title { font-weight:800; margin-bottom:6px; }
61 .helper-desc { font-size:.82rem; color:var(--text-secondary); line-height:1.7; margin-bottom:14px; }
62 .helper-grid { display:grid; grid-template-columns:1fr auto; gap:10px; align-items:end; }
63 .arrival-list { display:grid; gap:10px; margin-top:14px; }
64 .arrival-item { width:100%; text-align:left; border:1px solid var(--border); background:var(--bg-main); color:var(--text-primary); border-radius:10px; padding:12px 14px; font-family:var(--font); cursor:pointer; transition:border-color .15s, transform .15s; }
65 .arrival-item:hover { border-color:var(--accent); transform:translateY(-1px); }
66 .arrival-item.selected { border-color:var(--accent); background:var(--accent-dim); }
67 .arrival-main { display:flex; justify-content:space-between; gap:10px; align-items:center; margin-bottom:6px; }
68 .arrival-train { font-weight:800; color:var(--accent); font-size:1.05rem; }
69 .arrival-status { font-size:.75rem; border:1px solid rgba(197,160,89,.35); border-radius:999px; padding:3px 8px; color:var(--accent); white-space:nowrap; }
70 .arrival-meta { font-size:.78rem; color:var(--text-secondary); line-height:1.6; }
71 .result-card { display:none; }
72 .result-card.show { display:block; }
73 .result-head { display:flex; align-items:center; justify-content:space-between; gap:14px; padding-bottom:14px; margin-bottom:14px; border-bottom:1px solid var(--border); }
74 .result-title { font-weight:800; font-size:1.05rem; }
75 .source-label { font-size:.7rem; color:var(--text-secondary); }
76 .train-list { display:grid; gap:12px; }
77 .train-item { border:1px solid var(--border); background:var(--bg-main); border-radius:10px; padding:16px; }
78 .train-main { display:flex; justify-content:space-between; gap:12px; margin-bottom:12px; flex-wrap:wrap; }
79 .train-no { font-size:1.4rem; font-weight:800; color:var(--accent); font-feature-settings:'tnum'; }
80 .status-badge { display:inline-flex; align-items:center; gap:6px; border-radius:999px; padding:5px 10px; background:var(--accent-dim); color:var(--accent); font-size:.78rem; font-weight:800; }
81 .train-meta { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:10px; }
82 .meta-label { font-size:.68rem; color:var(--text-secondary); margin-bottom:3px; }
83 .meta-value { font-size:.95rem; font-weight:700; overflow-wrap:anywhere; }
84 .pill-row { display:flex; gap:6px; flex-wrap:wrap; margin-top:10px; }
85 .pill { border:1px solid var(--border); border-radius:999px; padding:3px 8px; font-size:.72rem; color:var(--text-secondary); }
86 .route-card { display:none; background:var(--bg-card); border:1px solid var(--border); border-radius:12px; padding:20px; margin-bottom:20px; }
87 .route-card.show { display:block; }
88 .route-head { display:flex; justify-content:space-between; gap:12px; align-items:flex-start; margin-bottom:14px; }
89 .route-title { font-weight:800; }
90 .route-sub { font-size:.78rem; color:var(--text-secondary); line-height:1.6; }
91 .station-strip { --line-color: var(--accent); display:flex; flex-direction:column; gap:0; max-height:620px; overflow-y:auto; overflow-x:hidden; padding:8px 0; scroll-behavior:smooth; }
92 .station-node { position:relative; display:grid; grid-template-columns:260px minmax(0, 1fr); gap:22px; min-height:78px; color:var(--text-secondary); border-bottom:1px solid rgba(148,163,184,.16); }
93 .station-node::before, .station-node::after { content:''; position:absolute; top:0; bottom:0; width:4px; background:var(--line-color); opacity:.95; transform:translateX(-50%); }
94 .station-node::before { left:108px; }
95 .station-node::after { left:156px; }
96 .station-node:first-child::before { top:22px; }
97 .station-node:last-child::before { bottom:22px; }
98 .station-node:first-child::after { top:22px; }
99 .station-node:last-child::after { bottom:22px; }
100 .station-node.past::before, .station-node.past::after { background:#aeb4bd; opacity:.65; }
101 .station-rail { position:relative; min-height:56px; }
102 .station-dot { position:absolute; z-index:1; left:132px; top:28px; transform:translateX(-50%); width:18px; height:18px; border-radius:50%; background:var(--line-color); border:3px solid var(--bg-card); box-shadow:0 0 0 1px rgba(0,0,0,.12); }
103 .station-node.past .station-dot { background:#aeb4bd; box-shadow:0 0 0 1px rgba(148,163,184,.5); }
104 .station-node.current .station-dot { width:28px; height:28px; top:23px; background:var(--success); box-shadow:0 0 0 4px rgba(22,163,74,.16); }
105 .station-node.target .station-dot { background:#f59e0b; box-shadow:0 0 0 4px rgba(245,158,11,.16); }
106 .station-node.current.target .station-dot { background:var(--success); }
107 .train-badges { position:absolute; inset:0; z-index:3; pointer-events:none; }
108 .train-badge { position:absolute; top:11px; width:102px; min-height:38px; border:1px solid var(--border); border-radius:8px; background:var(--bg-card); color:var(--text-primary); box-shadow:0 3px 10px rgba(0,0,0,.08); display:flex; align-items:center; gap:6px; padding:5px 7px; font-size:.7rem; line-height:1.15; overflow:hidden; }
109 .train-badge.up { left:0; justify-content:flex-end; text-align:right; }
110 .train-badge.down { left:166px; }
111 .train-badge.status-enter.moving-down { transform:translateY(-12px); }
112 .train-badge.status-enter.moving-up { transform:translateY(12px); }
113 .train-badge.status-depart.moving-down { transform:translateY(12px); }
114 .train-badge.status-depart.moving-up { transform:translateY(-12px); }
115 .train-icon { position:relative; flex:0 0 auto; width:18px; height:30px; border:2px solid rgba(0,0,0,.45); background:#22c55e; overflow:hidden; box-shadow:inset 0 -4px 0 rgba(255,255,255,.28); }
116 .train-icon::before { content:''; position:absolute; left:4px; right:4px; height:6px; border-radius:4px; background:rgba(255,255,255,.82); box-shadow:0 0 0 1px rgba(255,255,255,.2); }
117 .train-icon::after { content:''; position:absolute; left:5px; right:5px; height:3px; border-radius:999px; background:rgba(0,0,0,.28); }
118 .train-badge.up .train-icon { order:2; background:#ea580c; }
119 .train-badge.moving-down .train-icon { border-radius:6px 6px 9px 9px; }
120 .train-badge.moving-down .train-icon::before { bottom:3px; }
121 .train-badge.moving-down .train-icon::after { top:3px; }
122 .train-badge.moving-up .train-icon { border-radius:9px 9px 6px 6px; box-shadow:inset 0 4px 0 rgba(255,255,255,.28); }
123 .train-badge.moving-up .train-icon::before { top:3px; }
124 .train-badge.moving-up .train-icon::after { bottom:3px; }
125 .train-badge.selected { border-color:var(--success); box-shadow:0 0 0 3px rgba(22,163,74,.16); }
126 .train-label { display:block; font-weight:800; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
127 .train-sub { display:none; }
128 .station-info { align-self:center; min-width:0; padding:12px 0; }
129 .station-name { font-size:.9rem; font-weight:800; line-height:1.35; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
130 .station-node.current .station-name { color:var(--success); }
131 .station-node.future .station-name, .station-node.target .station-name { color:var(--text-primary); }
132 .station-node.past .station-name { color:#8a94a3; }
133 .station-code { font-size:.7rem; color:var(--text-secondary); margin-left:6px; font-weight:500; }
134 .station-train-list { display:flex; gap:6px; flex-wrap:wrap; margin-top:6px; }
135 .station-train-chip { max-width:180px; border:1px solid var(--border); border-radius:999px; background:var(--bg-main); color:var(--text-secondary); padding:3px 8px; font-size:.68rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
136 .station-train-chip.selected { border-color:var(--success); color:var(--success); background:rgba(22,163,74,.08); }
137 .route-legend { display:flex; gap:10px; flex-wrap:wrap; font-size:.72rem; color:var(--text-secondary); }
138 .legend-dot { display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:4px; vertical-align:-1px; }
139 .legend-past { background:#aeb4bd; }
140 .legend-current { background:var(--success); }
141 .legend-future { background:var(--accent); }
142 .legend-target { background:#f59e0b; }
143 .empty-message { color:var(--text-secondary); font-size:.9rem; line-height:1.8; margin:0; }
144 .info-box { font-size:.78rem; color:var(--text-secondary); line-height:1.8; margin-bottom:40px; }
145 .info-box strong { color:var(--text-primary); }
146 .footer-area { max-width:920px; width:100%; margin:48px auto 0; padding:28px 24px 40px; color:var(--text-secondary); font-size:.78rem; border-top:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; gap:20px; }
147 .footer-brand { display:flex; align-items:center; gap:12px; min-width:0; }
148 .footer-logo { width:44px; height:44px; object-fit:contain; opacity:.72; mix-blend-mode:multiply; flex:0 0 auto; }
149 body.dark-mode .footer-logo { mix-blend-mode:screen; opacity:.86; }
150 .footer-title { font-weight:800; color:var(--text-primary); font-size:.9rem; }
151 .footer-sub { margin-top:2px; }
152 .footer-links { display:flex; align-items:center; gap:12px; flex-wrap:wrap; justify-content:flex-end; }
153 .footer-links a { color:var(--text-secondary); font-weight:700; }
154 .footer-links a:hover { color:var(--accent); }
155 .footer-copy { width:100%; text-align:right; font-size:.72rem; }
156 .footer-version { display:inline-flex; align-items:center; min-height:20px; padding:0 8px; margin-right:8px; border:1px solid var(--border); border-radius:999px; color:var(--accent); font-weight:800; background:var(--bg-secondary); }
157 @media (max-width: 720px) {
158 .page-body { padding:24px 16px 0; }
159 .site-header { padding:0 12px; gap:8px; }
160 .brand { gap:8px; font-size:.82rem; }
161 .header-logo { max-width:132px; height:24px; }
162 .site-header nav a { margin-left:0; width:32px; height:32px; display:inline-flex; align-items:center; justify-content:center; font-size:0; }
163 .site-header nav a i { font-size:1rem; margin:0 !important; }
164 .search-grid { grid-template-columns:1fr; }
165 .helper-grid { grid-template-columns:1fr; }
166 .train-meta { grid-template-columns:1fr; }
167 .result-head { align-items:flex-start; flex-direction:column; }
168 .station-strip { max-height:540px; }
169 .station-node { grid-template-columns:206px minmax(0, 1fr); gap:12px; min-height:72px; }
170 .station-node::before { left:82px; }
171 .station-node::after { left:124px; }
172 .station-dot { left:103px; top:27px; }
173 .station-node.current .station-dot { top:22px; }
174 .train-badge { width:82px; padding:4px 5px; font-size:.66rem; }
175 .train-badge.up { left:0; }
176 .train-badge.down { left:134px; }
177 .footer-area { flex-direction:column; align-items:flex-start; margin-top:36px; }
178 .footer-links { justify-content:flex-start; }
179 .footer-copy { text-align:left; }
180 }
181 </style>
182 <link rel="stylesheet" href="/css/site-ui.css?v=3">
183 <link rel="stylesheet" href="/css/site-app.css?v=1">
184 </head>
185 <body data-ui-page="subway" class="ui-shell <%= (typeof theme !== 'undefined' && theme === 'dark') ? 'dark-mode' : '' %>">
186 <%- include('partials/site-header', { uiPage: 'subway' }) %>
187
188 <main id="ui-content" tabindex="-1" class="page-body">
189 <section class="page-title">
190 <h1><i class="bi bi-train-front me-2" style="color:var(--accent);"></i>열차 열번 위치 조회</h1>
191 <p>서울시 지하철 실시간 열차 위치정보 API로 열차가 현재 어느 역에 있고, 진입·도착·출발 중인지 확인합니다.</p>
192 </section>
193
194 <section class="search-card">
195 <form id="searchForm" class="search-grid">
196 <div>
197 <div class="field-label">Train No.</div>
198 <input id="trainNo" class="field" name="trainNo" placeholder="예: 1006" autocomplete="off" required>
199 </div>
200 <div>
201 <div class="field-label">Line</div>
202 <select id="line" class="field" name="line">
203 <option value="">전체 주요 호선 검색</option>
204 <% subwayLines.forEach(function(line) { %>
205 <option value="<%= line %>"><%= line %></option>
206 <% }); %>
207 </select>
208 </div>
209 <div>
210 <div class="field-label">Target Station</div>
211 <select id="targetStation" class="field" name="targetStation" disabled>
212 <option value="">호선을 먼저 선택해 주세요</option>
213 </select>
214 </div>
215 <button id="submitBtn" class="submit-btn" type="submit"><i class="bi bi-search me-1"></i>조회</button>
216 </form>
217 <div class="tracker-bar">
218 <div class="tracker-status" id="trackerStatus">목표역 도착 알림을 쓰려면 호선과 역을 선택한 뒤 추적을 시작하세요.</div>
219 <div class="tracker-actions">
220 <button id="startTrackBtn" class="ghost-btn" type="button"><i class="bi bi-bell me-1"></i>도착 알림 시작</button>
221 <button id="stopTrackBtn" class="ghost-btn" type="button" disabled><i class="bi bi-bell-slash me-1"></i>중지</button>
222 </div>
223 <div class="push-guide">
224 Android Chrome/Edge는 알림 권한을 허용하면 백그라운드에서도 받을 수 있습니다. iPhone은 iOS 16.4 이상에서 홈 화면에 추가한 뒤 실행해야 백그라운드 알림이 동작합니다.
225 </div>
226 </div>
227 </section>
228
229 <section class="helper-card">
230 <div class="helper-title">어떤 열번의 열차를 탔는지/탈 예정인지 모르시나요?</div>
231 <div class="helper-desc">
232 호선을 선택한 뒤 탑승한 역 또는 탑승할 역을 고르면, 그 역에 도착했거나 곧 도착할 열차 후보를 불러옵니다.
233 후보를 선택하면 열번 입력칸에 자동으로 들어가고, 같은 방식으로 조회와 도착 알림을 사용할 수 있어요.
234 </div>
235 <div class="helper-grid">
236 <div>
237 <div class="field-label">Boarding Station</div>
238 <select id="boardingStation" class="field" disabled>
239 <option value="">호선을 먼저 선택해 주세요</option>
240 </select>
241 </div>
242 <button id="loadArrivalsBtn" class="ghost-btn" type="button"><i class="bi bi-search me-1"></i>탑승 열차 찾기</button>
243 </div>
244 <div id="arrivalList" class="arrival-list"></div>
245 </section>
246
247 <section id="resultCard" class="result-card">
248 <div class="result-head">
249 <div>
250 <div class="result-title" id="resultTitle">조회 결과</div>
251 <div class="source-label" id="resultSource">서울시 지하철 실시간 열차 위치정보</div>
252 </div>
253 <div class="source-label" id="searchedLines"></div>
254 </div>
255 <div id="resultBody"></div>
256 </section>
257
258 <section id="routeCard" class="route-card">
259 <div class="route-head">
260 <div>
261 <div class="route-title" id="routeTitle">노선 진행도</div>
262 <div class="route-sub" id="routeSub">현재 열차 위치를 기준으로 대략적인 지나간 역과 앞으로 갈 역을 표시합니다.</div>
263 </div>
264 </div>
265 <div class="route-legend">
266 <span><span class="legend-dot legend-past"></span>지나간 역</span>
267 <span><span class="legend-dot legend-current"></span>현재 위치</span>
268 <span><span class="legend-dot legend-future"></span>앞으로 갈 역</span>
269 <span><span class="legend-dot legend-target"></span>목표역</span>
270 </div>
271 <div id="stationStrip" class="station-strip"></div>
272 </section>
273
274 <section class="info-box">
275 <strong>참고:</strong> 호선을 고르면 API 호출 수를 줄일 수 있습니다. 전체 검색은 여러 호선을 순차 조회하므로 시간이 조금 더 걸릴 수 있어요.
276 서울시 API의 실시간 위치 데이터와 노선 진행도는 현장/관제 갱신 상황, 지선 운행, 회차 방식에 따라 실제 위치와 약간 차이가 날 수 있습니다.
277 열차 위치 조회는 누구나 이용할 수 있습니다. 도착 알림(푸시 전송)은 로그인 후 등록할 수 있고, 서버가 5초마다 추적하므로 브라우저를 백그라운드에 두거나 다른 앱을 사용해도 알림을 받을 수 있습니다.
278 </section>
279 </main>
280
281 <footer class="footer-area">
282 <div class="footer-brand">
283 <img src="/image/sign.png" alt="비나래" class="footer-logo">
284 <div>
285 <div class="footer-title">비나래 라운지</div>
286 <div class="footer-sub">Archive My Lounge</div>
287 </div>
288 </div>
289 <div>
290 <div class="footer-links">
291 <a href="/hinana/index">Archive</a>
292 <a href="/hinana/lounge">Lounge</a>
293 <a href="/hinana/gallery">Gallery</a>
294 <a href="/hinana/plaza">Plaza</a>
295 <a href="https://x.com/NoctchillHinana">X</a>
296 </div>
297 <div class="footer-copy"><span class="footer-version">Ver. 9.2.1.0 - Iochi Mari</span>ⓒ 2024~2026. 비나래 | hinana.moe</div>
298 </div>
299 </footer>
300
301 <script>
302 const PUSH_KEY = '<%= typeof vapidPublicKey !== "undefined" ? vapidPublicKey : "" %>';
303 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
304 const form = document.getElementById('searchForm');
305 const submitBtn = document.getElementById('submitBtn');
306 const lineSelect = document.getElementById('line');
307 const trainNoInput = document.getElementById('trainNo');
308 const targetStationSelect = document.getElementById('targetStation');
309 const boardingStationSelect = document.getElementById('boardingStation');
310 const loadArrivalsBtn = document.getElementById('loadArrivalsBtn');
311 const arrivalList = document.getElementById('arrivalList');
312 const startTrackBtn = document.getElementById('startTrackBtn');
313 const stopTrackBtn = document.getElementById('stopTrackBtn');
314 const trackerStatus = document.getElementById('trackerStatus');
315 const resultCard = document.getElementById('resultCard');
316 const resultTitle = document.getElementById('resultTitle');
317 const resultSource = document.getElementById('resultSource');
318 const searchedLines = document.getElementById('searchedLines');
319 const resultBody = document.getElementById('resultBody');
320 const routeCard = document.getElementById('routeCard');
321 const routeTitle = document.getElementById('routeTitle');
322 const routeSub = document.getElementById('routeSub');
323 const stationStrip = document.getElementById('stationStrip');
324 let trackingTimer = null;
325 let trackingActive = false;
326 let lastNotifiedKey = '';
327 let currentAlertId = '';
328 let serviceWorkerRegistration = null;
329 let currentStations = [];
330 let selectedBoardingStation = '';
331 let selectedDirectionCode = '';
332 const LINE_COLORS = {
333 '1호선': '#0052A4',
334 '2호선': '#00A84D',
335 '3호선': '#EF7C1C',
336 '4호선': '#00A5DE',
337 '5호선': '#996CAC',
338 '6호선': '#CD7C2F',
339 '7호선': '#747F00',
340 '8호선': '#E6186C',
341 '9호선': '#BDB092',
342 '경의중앙선': '#77C4A3',
343 '경춘선': '#0C8E72',
344 '수인분당선': '#F5A200',
345 '신분당선': '#D4003B',
346 '공항철도': '#0090D2',
347 '경강선': '#003DA5',
348 '서해선': '#8FC31F',
349 '우이신설선': '#B0CE18',
350 '신림선': '#6789CA',
351 'GTX-A': '#9A6292',
352 '인천선': '#7CA8D5',
353 '인천2호선': '#ED8B00',
354 '김포도시철도': '#A17800'
355 };
356
357 function escapeHtml(value) {
358 return String(value ?? '').replace(/[&<>"']/g, function(ch) {
359 return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch];
360 });
361 }
362
363 function normalizeStationName(name) {
364 return String(name || '').trim().replace(/\s+/g, '').replace(/역$/, '');
365 }
366
367 function stationNamesMatch(a, b) {
368 return normalizeStationName(a) === normalizeStationName(b);
369 }
370
371 function renderEmpty(message) {
372 resultBody.innerHTML = `<p class="empty-message">${escapeHtml(message)}</p>`;
373 }
374
375 async function fetchJson(url, options) {
376 const response = await fetch(url, {
377 credentials: 'same-origin',
378 ...(options || {})
379 });
380 const text = await response.text();
381 let data = null;
382
383 try {
384 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
385 } catch (_) {
386 throw new Error(text.trim().startsWith('<')
387 ? '지하철 API 라우트가 아직 서버에 반영되지 않았습니다. 최신 배포 후 다시 시도해 주세요.'
388 : '서버 응답을 읽지 못했습니다.');
389 }
390
391 if (!response.ok) {
392 throw new Error(data.message || data.error || '요청에 실패했습니다.');
393 }
394 return data;
395 }
396
397 function renderMatches(matches) {
398 if (!matches.length) {
399 renderEmpty('해당 열번의 열차를 찾지 못했습니다. 호선 선택이 맞는지, 운행 중인 열차인지 확인해 주세요.');
400 return;
401 }
402
403 resultBody.innerHTML = `<div class="train-list">${matches.map(function(item) {
404 const flags = [
405 item.express ? '급행' : '',
406 item.lastTrain ? '막차' : '',
407 item.receivedAt ? '수신: ' + item.receivedAt : ''
408 ].filter(Boolean);
409 return `
410 <article class="train-item">
411 <div class="train-main">
412 <div>
413 <div class="train-no">${escapeHtml(item.trainNo)}</div>
414 <div class="source-label">${escapeHtml(item.line)} ${item.subwayId ? '· ' + escapeHtml(item.subwayId) : ''}</div>
415 </div>
416 <div class="status-badge"><i class="bi bi-broadcast-pin"></i>${escapeHtml(item.status)}</div>
417 </div>
418 <div class="train-meta">
419 <div><div class="meta-label">현재 위치</div><div class="meta-value">${escapeHtml(item.stationName || '확인 불가')}</div></div>
420 <div><div class="meta-label">행선지</div><div class="meta-value">${escapeHtml(item.destination || '확인 불가')}</div></div>
421 <div><div class="meta-label">방향</div><div class="meta-value">${escapeHtml(item.direction || '확인 불가')}</div></div>
422 <div><div class="meta-label">상태 코드</div><div class="meta-value">${escapeHtml(item.statusCode)}</div></div>
423 </div>
424 ${flags.length ? `<div class="pill-row">${flags.map(flag => `<span class="pill">${escapeHtml(flag)}</span>`).join('')}</div>` : ''}
425 </article>
426 `;
427 }).join('')}</div>`;
428 }
429
430 function renderArrivals(arrivals) {
431 if (!arrivals.length) {
432 arrivalList.innerHTML = '<p class="empty-message">지금 선택한 역에서 확인되는 열차 후보가 없습니다.</p>';
433 return;
434 }
435
436 arrivalList.innerHTML = arrivals.map(function(item) {
437 return `
438 <button class="arrival-item" type="button"
439 data-train-no="${escapeHtml(item.trainNo)}"
440 data-direction="${escapeHtml(item.direction || '')}"
441 data-direction-code="${escapeHtml(item.directionCode || '')}"
442 data-terminal="${escapeHtml(item.terminalStation || '')}"
443 data-station="${escapeHtml(item.stationName || '')}">
444 <div class="arrival-main">
445 <span class="arrival-train">${escapeHtml(item.trainNo)} 열차</span>
446 <span class="arrival-status">${escapeHtml(item.status)}</span>
447 </div>
448 <div class="arrival-meta">
449 ${escapeHtml(item.message || '도착 정보 없음')}
450 ${item.trainLineName ? ` · ${escapeHtml(item.trainLineName)}` : ''}
451 ${item.terminalStation ? ` · ${escapeHtml(item.terminalStation)}행` : ''}
452 </div>
453 </button>
454 `;
455 }).join('');
456 }
457
458 function renderTargetStationOptions(stations) {
459 targetStationSelect.innerHTML = '<option value="">목표역 선택</option>' + stations.map(function(station) {
460 const label = station.frCode ? `${station.name} (${station.frCode})` : station.name;
461 return `<option value="${escapeHtml(station.name)}">${escapeHtml(label)}</option>`;
462 }).join('');
463 targetStationSelect.disabled = stations.length === 0;
464 }
465
466 function filterStationsByDirection(boardingStation, directionCode, terminalStation) {
467 if (!boardingStation || !currentStations.length) return currentStations;
468 const boardingIndex = currentStations.findIndex(function(station) {
469 return station.name === boardingStation;
470 });
471 if (boardingIndex === -1) return currentStations;
472
473 if (terminalStation) {
474 const terminalIndex = currentStations.findIndex(function(station) {
475 return stationNamesMatch(station.name, terminalStation);
476 });
477 if (terminalIndex !== -1 && terminalIndex !== boardingIndex) {
478 const start = Math.min(boardingIndex, terminalIndex);
479 const end = Math.max(boardingIndex, terminalIndex);
480 const segment = currentStations.slice(start, end + 1);
481 return terminalIndex > boardingIndex ? segment.slice(1) : segment.slice(0, -1).reverse();
482 }
483 }
484
485 if (directionCode === '0') return currentStations.slice(0, boardingIndex).reverse();
486 if (directionCode === '1') return currentStations.slice(boardingIndex + 1);
487 return currentStations;
488 }
489
490 function applySelectedTrainTargetFilter() {
491 const selectedTerminal = arrivalList.querySelector('.arrival-item.selected')?.dataset.terminal || '';
492 const filtered = filterStationsByDirection(selectedBoardingStation, selectedDirectionCode, selectedTerminal);
493 renderTargetStationOptions(filtered);
494 if (filtered.length === 0) {
495 trackerStatus.textContent = '선택한 열차의 진행 방향에서 고를 수 있는 목표역이 없습니다.';
496 } else if (selectedBoardingStation && selectedDirectionCode) {
497 trackerStatus.textContent = `${trainNoInput.value} 열차의 진행 방향에 있는 역만 목표역으로 표시했습니다.`;
498 }
499 }
500
501 async function loadStationArrivals() {
502 const line = lineSelect.value;
503 const station = boardingStationSelect.value;
504 if (!line || !station) {
505 if (typeof showAlert === 'function') await showAlert('호선과 탑승역을 선택해 주세요.');
506 return;
507 }
508
509 loadArrivalsBtn.disabled = true;
510 arrivalList.innerHTML = '<p class="empty-message">탑승 가능한 열차 후보를 불러오는 중입니다.</p>';
511 try {
512 const params = new URLSearchParams({ line, station });
513 const data = await fetchJson(`/api/subway/station-arrivals?${params.toString()}`);
514 if (!data.success) throw new Error(data.message || '도착 정보를 불러오지 못했습니다.');
515 renderArrivals(data.arrivals || []);
516 } catch (error) {
517 arrivalList.innerHTML = `<p class="empty-message">${escapeHtml(error.message || '도착 정보를 불러오지 못했습니다.')}</p>`;
518 } finally {
519 loadArrivalsBtn.disabled = false;
520 }
521 }
522
523 function renderTrainBadgesForStation(station, lineTrains, selectedTrainNo, displayDirectionCode) {
524 const trains = (lineTrains || []).filter(function(train) {
525 return stationNamesMatch(train.stationName, station.name);
526 }).slice(0, 4);
527
528 if (!trains.length) return '';
529
530 return trains.map(function(train) {
531 const directionCode = String(train.directionCode ?? '');
532 const sideClass = directionCode === '0' ? 'up' : 'down';
533 const movementClass = directionCode && directionCode === displayDirectionCode ? ' moving-down' : ' moving-up';
534 const statusClass = train.status === '진입' ? ' status-enter' : (train.status === '출발' ? ' status-depart' : ' status-arrive');
535 const selectedClass = String(train.trainNo) === String(selectedTrainNo) ? ' selected' : '';
536 const terminal = train.destination || '';
537 const title = `${terminal ? terminal + '행 ' : ''}${train.trainNo} · ${train.status || '상태 미확인'}`;
538 return `
539 <div class="train-badge ${sideClass}${movementClass}${statusClass}${selectedClass}" title="${escapeHtml(title)}">
540 <span class="train-icon"></span>
541 <span>
542 <span class="train-label">${escapeHtml(train.trainNo)}</span>
543 </span>
544 </div>
545 `;
546 }).join('');
547 }
548
549 function renderTrainChipsForStation(station, lineTrains, selectedTrainNo) {
550 const trains = (lineTrains || []).filter(function(train) {
551 return stationNamesMatch(train.stationName, station.name);
552 }).slice(0, 4);
553
554 if (!trains.length) return '';
555
556 return `<div class="station-train-list">${trains.map(function(train) {
557 const terminal = train.destination || '';
558 const selectedClass = String(train.trainNo) === String(selectedTrainNo) ? ' selected' : '';
559 const label = `${train.trainNo}${terminal ? ' · ' + terminal + '행' : ''}${train.express ? ' · 급행' : ''}${train.lastTrain ? ' · 막차' : ''}`;
560 return `<span class="station-train-chip${selectedClass}" title="${escapeHtml(label)}">${escapeHtml(label)}</span>`;
561 }).join('')}</div>`;
562 }
563
564 function renderRouteMap(match, lineTrains) {
565 const line = lineSelect.value;
566 const targetStation = targetStationSelect.value;
567 if (!line || !currentStations.length || !match) {
568 routeCard.classList.remove('show');
569 stationStrip.innerHTML = '';
570 return;
571 }
572
573 const currentIndex = currentStations.findIndex(function(station) {
574 return stationNamesMatch(station.name, match.stationName);
575 });
576 if (currentIndex === -1) {
577 routeCard.classList.add('show');
578 routeTitle.textContent = `${line} 노선 진행도`;
579 routeSub.textContent = `${match.stationName || '현재역'} 위치가 역 목록과 정확히 매칭되지 않았습니다.`;
580 stationStrip.innerHTML = '';
581 return;
582 }
583
584 const directionCode = String(match.directionCode ?? '');
585 const displayStations = directionCode === '0' ? currentStations.slice().reverse() : currentStations.slice();
586 const displayCurrentIndex = displayStations.findIndex(function(station) {
587 return stationNamesMatch(station.name, match.stationName);
588 });
589
590 routeCard.classList.add('show');
591 routeTitle.textContent = `${line} ${match.trainNo} 진행도`;
592 routeSub.textContent = `${match.stationName}역 ${match.status} · ${match.direction || '방향 미확인'} · 목표역 ${targetStation || '미선택'}`;
593 stationStrip.style.setProperty('--line-color', LINE_COLORS[line] || 'var(--accent)');
594 stationStrip.innerHTML = displayStations.map(function(station, index) {
595 const isCurrent = stationNamesMatch(station.name, match.stationName);
596 const isTarget = targetStation && stationNamesMatch(station.name, targetStation);
597 const state = index < displayCurrentIndex ? 'past' : (isCurrent ? 'current' : 'future');
598 const title = `${station.name}${station.frCode ? ' (' + station.frCode + ')' : ''}`;
599 return `
600 <div class="station-node ${state}${isTarget ? ' target' : ''}" data-current="${isCurrent ? 'true' : 'false'}" title="${escapeHtml(title)}">
601 <div class="station-rail">
602 <div class="station-dot"></div>
603 <div class="train-badges">${renderTrainBadgesForStation(station, lineTrains || [], match.trainNo, directionCode)}</div>
604 </div>
605 <div class="station-info">
606 <div class="station-name">${escapeHtml(station.name)}${station.frCode ? `<span class="station-code">${escapeHtml(station.frCode)}</span>` : ''}</div>
607 ${renderTrainChipsForStation(station, lineTrains || [], match.trainNo)}
608 </div>
609 </div>
610 `;
611 }).join('');
612
613 const currentEl = stationStrip.querySelector('[data-current="true"]');
614 if (currentEl) {
615 requestAnimationFrame(function() {
616 currentEl.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
617 });
618 }
619 }
620
621 function getArrivalMessage(status) {
622 if (status === '진입') return '열차가 도착역에 진입했어요. 하차하세요.';
623 return '열차가 도착역에 도착했어요. 하차하세요.';
624 }
625
626 async function showBrowserNotification(title, body) {
627 if (!('Notification' in window) || Notification.permission !== 'granted') return;
628 if (!('serviceWorker' in navigator)) return;
629
630 const reg = serviceWorkerRegistration || await navigator.serviceWorker.register('/sw.js');
631 serviceWorkerRegistration = reg;
632 const readyRegistration = await navigator.serviceWorker.ready;
633 await readyRegistration.showNotification(title, {
634 body,
635 icon: '/image/title.png',
636 badge: '/image/title.png',
637 data: { url: '/hinana/subway' }
638 });
639 }
640
641 function notifyArrival(trainNo, status) {
642 const title = `${trainNo} 열차 ${status}`;
643 const body = getArrivalMessage(status);
644 showBrowserNotification(title, body).catch(function(error) {
645 console.warn('브라우저 알림 표시 실패:', error);
646 });
647 if (typeof showAlert === 'function') {
648 showAlert(body);
649 } else {
650 alert(body);
651 }
652 }
653
654 function urlBase64ToUint8Array(b64) {
655 const pad = '='.repeat((4 - b64.length % 4) % 4);
656 const base64 = (b64 + pad).replace(/-/g, '+').replace(/_/g, '/');
657 const raw = atob(base64);
658 return Uint8Array.from(raw, c => c.charCodeAt(0));
659 }
660
661 function arrayBufferToBase64Url(buffer) {
662 const bytes = new Uint8Array(buffer);
663 let binary = '';
664 bytes.forEach(function(byte) { binary += String.fromCharCode(byte); });
665 return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
666 }
667
668 function subscriptionUsesCurrentKey(subscription) {
669 if (!subscription || !subscription.options || !subscription.options.applicationServerKey) return true;
670 return arrayBufferToBase64Url(subscription.options.applicationServerKey) === PUSH_KEY;
671 }
672
673 async function ensurePushSubscription() {
674 if (!PUSH_USER) throw new Error('서버 도착 알림은 로그인이 필요합니다.');
675 if (!PUSH_KEY) throw new Error('푸시 알림 키가 설정되어 있지 않습니다.');
676 if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
677 throw new Error('이 브라우저는 푸시 알림을 지원하지 않습니다.');
678 }
679
680 const reg = serviceWorkerRegistration || await navigator.serviceWorker.register('/sw.js');
681 serviceWorkerRegistration = reg;
682 await navigator.serviceWorker.ready;
683
684 if ('Notification' in window && Notification.permission === 'default') {
685 const permission = await Notification.requestPermission();
686 if (permission !== 'granted') throw new Error('알림 권한이 허용되지 않았습니다.');
687 }
688 if ('Notification' in window && Notification.permission === 'denied') {
689 throw new Error('브라우저 알림 권한이 차단되어 있습니다.');
690 }
691
692 let subscription = await reg.pushManager.getSubscription();
693 if (subscription && !subscriptionUsesCurrentKey(subscription)) {
694 await subscription.unsubscribe();
695 subscription = null;
696 }
697 if (!subscription) {
698 subscription = await reg.pushManager.subscribe({
699 userVisibleOnly: true,
700 applicationServerKey: urlBase64ToUint8Array(PUSH_KEY)
701 });
702 }
703
704 await fetchJson('/api/push/subscribe', {
705 method: 'POST',
706 headers: { 'Content-Type': 'application/json' },
707 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
708 });
709 }
710
711 async function createServerAlert(trainNo, line, targetStation) {
712 const data = await fetchJson('/api/subway/alerts', {
713 method: 'POST',
714 headers: { 'Content-Type': 'application/json' },
715 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
716 });
717 if (!data.success) throw new Error(data.message || '도착 알림을 등록하지 못했습니다.');
718 return data.alert;
719 }
720
721 async function cancelServerAlert() {
722 if (!currentAlertId) return;
723 await fetchJson(`/api/subway/alerts/${encodeURIComponent(currentAlertId)}`, { method: 'DELETE' }).catch(function() {});
724 currentAlertId = '';
725 }
726
727 async function loadStationsForLine(line) {
728 targetStationSelect.disabled = true;
729 boardingStationSelect.disabled = true;
730 selectedBoardingStation = '';
731 selectedDirectionCode = '';
732 targetStationSelect.innerHTML = '<option value="">역 목록을 불러오는 중...</option>';
733 boardingStationSelect.innerHTML = '<option value="">역 목록을 불러오는 중...</option>';
734 arrivalList.innerHTML = '';
735 if (!line) {
736 currentStations = [];
737 routeCard.classList.remove('show');
738 targetStationSelect.innerHTML = '<option value="">호선을 먼저 선택해 주세요</option>';
739 boardingStationSelect.innerHTML = '<option value="">호선을 먼저 선택해 주세요</option>';
740 return;
741 }
742 try {
743 const data = await fetchJson(`/api/subway/stations?line=${encodeURIComponent(line)}`);
744 if (!data.success) throw new Error(data.message || '역 목록을 불러오지 못했습니다.');
745 currentStations = data.stations || [];
746 const stationOptions = (data.stations || []).map(function(station) {
747 const label = station.frCode ? `${station.name} (${station.frCode})` : station.name;
748 return `<option value="${escapeHtml(station.name)}">${escapeHtml(label)}</option>`;
749 }).join('');
750 renderTargetStationOptions(data.stations || []);
751 boardingStationSelect.innerHTML = '<option value="">탑승역 선택</option>' + stationOptions;
752 boardingStationSelect.disabled = false;
753 trackerStatus.textContent = `${line} 역 목록을 불러왔습니다. 목표역을 선택하면 도착 알림을 시작할 수 있어요.`;
754 } catch (error) {
755 currentStations = [];
756 routeCard.classList.remove('show');
757 targetStationSelect.innerHTML = '<option value="">역 목록 로드 실패</option>';
758 boardingStationSelect.innerHTML = '<option value="">역 목록 로드 실패</option>';
759 trackerStatus.textContent = error.message || '역 목록을 불러오지 못했습니다.';
760 }
761 }
762
763 async function queryTrainPosition(options = {}) {
764 const trainNo = trainNoInput.value.trim();
765 const line = lineSelect.value;
766 if (!trainNo) return;
767
768 if (!options.silent) {
769 resultCard.classList.add('show');
770 resultTitle.textContent = `${trainNo} 조회 중...`;
771 resultSource.textContent = '서울시 지하철 실시간 열차 위치정보';
772 searchedLines.textContent = '';
773 renderEmpty('실시간 위치를 확인하고 있습니다.');
774 submitBtn.disabled = true;
775 }
776
777 try {
778 const params = new URLSearchParams({ trainNo });
779 if (line) params.set('line', line);
780 const data = await fetchJson(`/api/subway/train-position?${params.toString()}`);
781 if (!data.success) throw new Error(data.message || '조회에 실패했습니다.');
782
783 resultTitle.textContent = `${data.trainNo} 조회 결과`;
784 resultSource.textContent = data.source || '서울시 지하철 실시간 열차 위치정보';
785 searchedLines.textContent = `${data.searchedLines.length}개 호선 조회`;
786 renderMatches(data.matches || []);
787 renderRouteMap((data.matches || [])[0], data.lineTrains || []);
788 return data;
789 } catch (error) {
790 if (!options.silent) {
791 resultTitle.textContent = '조회 실패';
792 searchedLines.textContent = '';
793 renderEmpty(error.message || '잠시 후 다시 시도해 주세요.');
794 routeCard.classList.remove('show');
795 }
796 throw error;
797 } finally {
798 if (!options.silent) submitBtn.disabled = false;
799 }
800 }
801
802 async function pollTracking() {
803 if (!trackingActive) return;
804 const targetStation = targetStationSelect.value;
805 const line = lineSelect.value;
806 const trainNo = trainNoInput.value.trim();
807
808 try {
809 const data = await queryTrainPosition({ silent: true });
810 const match = (data.matches || []).find(function(item) {
811 return stationNamesMatch(item.stationName, targetStation) && (item.status === '진입' || item.status === '도착');
812 });
813 const current = (data.matches || [])[0];
814 renderRouteMap(current, data.lineTrains || []);
815 if (current) {
816 trackerStatus.textContent = `${trainNo} 추적 중 · 현재 ${current.line} ${current.stationName || '위치 미확인'} · ${current.status}`;
817 } else {
818 trackerStatus.textContent = `${trainNo} 추적 중 · 현재 운행 위치를 찾지 못했습니다.`;
819 }
820 if (match) {
821 const notifyKey = `${trainNo}:${line}:${targetStation}:${match.receivedAt || Date.now()}`;
822 if (notifyKey !== lastNotifiedKey) {
823 lastNotifiedKey = notifyKey;
824 trackerStatus.textContent = `${getArrivalMessage(match.status)} 서버 푸시 알림이 곧 전송됩니다.`;
825 }
826 }
827 } catch (error) {
828 trackerStatus.textContent = '화면 갱신에 실패했지만 서버 도착 알림은 계속 추적 중입니다.';
829 }
830 }
831
832 async function startTracking() {
833 const trainNo = trainNoInput.value.trim();
834 const line = lineSelect.value;
835 const targetStation = targetStationSelect.value;
836 if (!PUSH_USER) {
837 if (typeof showAlert === 'function') await showAlert('도착 알림 기능은 로그인 후 사용할 수 있습니다.');
838 return;
839 }
840 if (!trainNo || !line || !targetStation) {
841 if (typeof showAlert === 'function') await showAlert('열번, 호선, 목표역을 모두 선택해 주세요.');
842 return;
843 }
844
845 try {
846 await ensurePushSubscription();
847 const serverAlert = await createServerAlert(trainNo, line, targetStation);
848 currentAlertId = serverAlert.id;
849 } catch (error) {
850 if (typeof showAlert === 'function') await showAlert(error.message || '도착 알림을 등록하지 못했습니다.');
851 return;
852 }
853
854 trackingActive = true;
855 lastNotifiedKey = '';
856 startTrackBtn.disabled = true;
857 stopTrackBtn.disabled = false;
858 trackerStatus.textContent = `${trainNo} 열차가 ${targetStation}역에 도착하는지 서버에서 5초마다 확인 중입니다. 브라우저를 백그라운드에 둬도 푸시 알림이 전송됩니다.`;
859 await pollTracking();
860 if (trackingActive) trackingTimer = setInterval(pollTracking, 5 * 1000);
861 }
862
863 async function resumeTracking(alert) {
864 if (!alert || !alert.active) return;
865 currentAlertId = alert.id;
866 trainNoInput.value = alert.trainNo;
867 lineSelect.value = alert.line;
868 await loadStationsForLine(alert.line);
869 targetStationSelect.value = alert.targetStation;
870
871 trackingActive = true;
872 startTrackBtn.disabled = true;
873 stopTrackBtn.disabled = false;
874 trackerStatus.textContent = `${alert.trainNo} 열차가 ${alert.targetStation}역에 도착하는지 서버에서 추적 중입니다. 브라우저를 백그라운드에 둬도 푸시 알림이 전송됩니다.`;
875 await pollTracking();
876 if (trackingActive) trackingTimer = setInterval(pollTracking, 5 * 1000);
877 }
878
879 async function loadExistingAlert() {
880 if (!PUSH_USER) return;
881 try {
882 const data = await fetchJson('/api/subway/alerts');
883 if (!data.success) return;
884 const activeAlert = (data.alerts || []).find(function(alert) { return alert.active; });
885 if (activeAlert) await resumeTracking(activeAlert);
886 } catch (_) {}
887 }
888
889 async function stopTracking(showMessage = true) {
890 trackingActive = false;
891 if (trackingTimer) clearInterval(trackingTimer);
892 trackingTimer = null;
893 await cancelServerAlert();
894 startTrackBtn.disabled = false;
895 stopTrackBtn.disabled = true;
896 if (showMessage) trackerStatus.textContent = '도착 알림 추적을 중지했습니다.';
897 }
898
899 form.addEventListener('submit', async function(event) {
900 event.preventDefault();
901 queryTrainPosition().catch(function() {});
902 });
903
904 lineSelect.addEventListener('change', function() {
905 stopTracking(false);
906 loadStationsForLine(this.value);
907 });
908 loadArrivalsBtn.addEventListener('click', loadStationArrivals);
909 arrivalList.addEventListener('click', function(event) {
910 const item = event.target.closest('.arrival-item');
911 if (!item) return;
912 arrivalList.querySelectorAll('.arrival-item').forEach(function(el) { el.classList.remove('selected'); });
913 item.classList.add('selected');
914 trainNoInput.value = item.dataset.trainNo || '';
915 selectedBoardingStation = item.dataset.station || boardingStationSelect.value;
916 selectedDirectionCode = item.dataset.directionCode || '';
917 applySelectedTrainTargetFilter();
918 });
919 if (startTrackBtn) startTrackBtn.addEventListener('click', startTracking);
920 if (stopTrackBtn) stopTrackBtn.addEventListener('click', function() { stopTracking(true); });
921
922 (async function initServiceWorker() {
923 if (!('serviceWorker' in navigator)) return;
924 serviceWorkerRegistration = await navigator.serviceWorker.register('/sw.js').catch(function() { return null; });
925 })();
926 loadExistingAlert();
927 </script>
928 </body>
929 </html>
930