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:#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 </head>
183 <body class="<%= (typeof theme !== 'undefined' && theme === 'dark') ? 'dark-mode' : '' %>">
184 <header class="site-header">
185 <div class="brand">
186 <a href="/hinana/lounge"><img src="/image/lounge1.png" alt="비나래 라운지" class="header-logo"></a>
187 <span style="opacity:.4; font-weight:300; color:#fff;">|</span>
188 <span style="color:#fff;">열차 위치 조회</span>
189 </div>
190 <nav>
191 <a href="/hinana/lounge"><i class="bi bi-arrow-left me-1"></i>라운지로</a>
192 <form action="/toggle-theme" method="POST" style="margin:0; display:inline;">
193 <input type="hidden" name="redirect" value="/hinana/subway">
194 <button type="submit" style="background:none; border:none; color:var(--text-secondary); font-size:1rem; cursor:pointer; padding:4px 8px; margin-left:12px;" title="테마 변경">
195 <i class="bi <%= (typeof theme !== 'undefined' && theme === 'dark') ? 'bi-moon-stars-fill' : 'bi-sun-fill' %>"></i>
196 </button>
197 </form>
198 </nav>
199 </header>
200
201 <main class="page-body">
202 <section class="page-title">
203 <h1><i class="bi bi-train-front me-2" style="color:var(--accent);"></i>열차 열번 위치 조회</h1>
204 <p>서울시 지하철 실시간 열차 위치정보 API로 열차가 현재 어느 역에 있고, 진입·도착·출발 중인지 확인합니다.</p>
205 </section>
206
207 <section class="search-card">
208 <form id="searchForm" class="search-grid">
209 <div>
210 <div class="field-label">Train No.</div>
211 <input id="trainNo" class="field" name="trainNo" placeholder="예: 1006" autocomplete="off" required>
212 </div>
213 <div>
214 <div class="field-label">Line</div>
215 <select id="line" class="field" name="line">
216 <option value="">전체 주요 호선 검색</option>
217 <% subwayLines.forEach(function(line) { %>
218 <option value="<%= line %>"><%= line %></option>
219 <% }); %>
220 </select>
221 </div>
222 <div>
223 <div class="field-label">Target Station</div>
224 <select id="targetStation" class="field" name="targetStation" disabled>
225 <option value="">호선을 먼저 선택해 주세요</option>
226 </select>
227 </div>
228 <button id="submitBtn" class="submit-btn" type="submit"><i class="bi bi-search me-1"></i>조회</button>
229 </form>
230 <div class="tracker-bar">
231 <div class="tracker-status" id="trackerStatus">목표역 도착 알림을 쓰려면 호선과 역을 선택한 뒤 추적을 시작하세요.</div>
232 <div class="tracker-actions">
233 <button id="startTrackBtn" class="ghost-btn" type="button"><i class="bi bi-bell me-1"></i>도착 알림 시작</button>
234 <button id="stopTrackBtn" class="ghost-btn" type="button" disabled><i class="bi bi-bell-slash me-1"></i>중지</button>
235 </div>
236 <div class="push-guide">
237 Android Chrome/Edge는 알림 권한을 허용하면 백그라운드에서도 받을 수 있습니다. iPhone은 iOS 16.4 이상에서 홈 화면에 추가한 뒤 실행해야 백그라운드 알림이 동작합니다.
238 </div>
239 </div>
240 </section>
241
242 <section class="helper-card">
243 <div class="helper-title">어떤 열번의 열차를 탔는지/탈 예정인지 모르시나요?</div>
244 <div class="helper-desc">
245 호선을 선택한 뒤 탑승한 역 또는 탑승할 역을 고르면, 그 역에 도착했거나 곧 도착할 열차 후보를 불러옵니다.
246 후보를 선택하면 열번 입력칸에 자동으로 들어가고, 같은 방식으로 조회와 도착 알림을 사용할 수 있어요.
247 </div>
248 <div class="helper-grid">
249 <div>
250 <div class="field-label">Boarding Station</div>
251 <select id="boardingStation" class="field" disabled>
252 <option value="">호선을 먼저 선택해 주세요</option>
253 </select>
254 </div>
255 <button id="loadArrivalsBtn" class="ghost-btn" type="button"><i class="bi bi-search me-1"></i>탑승 열차 찾기</button>
256 </div>
257 <div id="arrivalList" class="arrival-list"></div>
258 </section>
259
260 <section id="resultCard" class="result-card">
261 <div class="result-head">
262 <div>
263 <div class="result-title" id="resultTitle">조회 결과</div>
264 <div class="source-label" id="resultSource">서울시 지하철 실시간 열차 위치정보</div>
265 </div>
266 <div class="source-label" id="searchedLines"></div>
267 </div>
268 <div id="resultBody"></div>
269 </section>
270
271 <section id="routeCard" class="route-card">
272 <div class="route-head">
273 <div>
274 <div class="route-title" id="routeTitle">노선 진행도</div>
275 <div class="route-sub" id="routeSub">현재 열차 위치를 기준으로 대략적인 지나간 역과 앞으로 갈 역을 표시합니다.</div>
276 </div>
277 </div>
278 <div class="route-legend">
279 <span><span class="legend-dot legend-past"></span>지나간 역</span>
280 <span><span class="legend-dot legend-current"></span>현재 위치</span>
281 <span><span class="legend-dot legend-future"></span>앞으로 갈 역</span>
282 <span><span class="legend-dot legend-target"></span>목표역</span>
283 </div>
284 <div id="stationStrip" class="station-strip"></div>
285 </section>
286
287 <section class="info-box">
288 <strong>참고:</strong> 호선을 고르면 API 호출 수를 줄일 수 있습니다. 전체 검색은 여러 호선을 순차 조회하므로 시간이 조금 더 걸릴 수 있어요.
289 서울시 API의 실시간 위치 데이터와 노선 진행도는 현장/관제 갱신 상황, 지선 운행, 회차 방식에 따라 실제 위치와 약간 차이가 날 수 있습니다.
290 이 페이지는 API 호출 제한 보호를 위해 로그인한 사용자만 사용할 수 있습니다. 도착 알림은 서버가 10초마다 추적하므로 브라우저를 백그라운드에 두거나 다른 앱을 사용해도 푸시 알림을 받을 수 있습니다.
291 </section>
292 </main>
293
294 <footer class="footer-area">
295 <div class="footer-brand">
296 <img src="/image/sign.png" alt="비나래" class="footer-logo">
297 <div>
298 <div class="footer-title">비나래 라운지</div>
299 <div class="footer-sub">Archive My Lounge</div>
300 </div>
301 </div>
302 <div>
303 <div class="footer-links">
304 <a href="/hinana/index">Archive</a>
305 <a href="/hinana/lounge">Lounge</a>
306 <a href="/hinana/gallery">Gallery</a>
307 <a href="/hinana/plaza">Plaza</a>
308 <a href="https://x.com/NoctchillHinana">X</a>
309 </div>
310 <div class="footer-copy"><span class="footer-version">Ver. 8.0.3.2-Utsumi Aoba</span>ⓒ 2024~2026. 비나래 | hinana.moe</div>
311 </div>
312 </footer>
313
314 <script>
315 const PUSH_KEY = '<%= typeof vapidPublicKey !== "undefined" ? vapidPublicKey : "" %>';
316 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
317 const form = document.getElementById('searchForm');
318 const submitBtn = document.getElementById('submitBtn');
319 const lineSelect = document.getElementById('line');
320 const trainNoInput = document.getElementById('trainNo');
321 const targetStationSelect = document.getElementById('targetStation');
322 const boardingStationSelect = document.getElementById('boardingStation');
323 const loadArrivalsBtn = document.getElementById('loadArrivalsBtn');
324 const arrivalList = document.getElementById('arrivalList');
325 const startTrackBtn = document.getElementById('startTrackBtn');
326 const stopTrackBtn = document.getElementById('stopTrackBtn');
327 const trackerStatus = document.getElementById('trackerStatus');
328 const resultCard = document.getElementById('resultCard');
329 const resultTitle = document.getElementById('resultTitle');
330 const resultSource = document.getElementById('resultSource');
331 const searchedLines = document.getElementById('searchedLines');
332 const resultBody = document.getElementById('resultBody');
333 const routeCard = document.getElementById('routeCard');
334 const routeTitle = document.getElementById('routeTitle');
335 const routeSub = document.getElementById('routeSub');
336 const stationStrip = document.getElementById('stationStrip');
337 let trackingTimer = null;
338 let trackingActive = false;
339 let lastNotifiedKey = '';
340 let currentAlertId = '';
341 let serviceWorkerRegistration = null;
342 let currentStations = [];
343 let selectedBoardingStation = '';
344 let selectedDirectionCode = '';
345 const LINE_COLORS = {
346 '1호선': '#0052A4',
347 '2호선': '#00A84D',
348 '3호선': '#EF7C1C',
349 '4호선': '#00A5DE',
350 '5호선': '#996CAC',
351 '6호선': '#CD7C2F',
352 '7호선': '#747F00',
353 '8호선': '#E6186C',
354 '9호선': '#BDB092',
355 '경의중앙선': '#77C4A3',
356 '경춘선': '#0C8E72',
357 '수인분당선': '#F5A200',
358 '신분당선': '#D4003B',
359 '공항철도': '#0090D2',
360 '경강선': '#003DA5',
361 '서해선': '#8FC31F',
362 '우이신설선': '#B0CE18',
363 '신림선': '#6789CA',
364 'GTX-A': '#9A6292',
365 '인천선': '#7CA8D5',
366 '인천2호선': '#ED8B00',
367 '김포도시철도': '#A17800'
368 };
369
370 function escapeHtml(value) {
371 return String(value ?? '').replace(/[&<>"']/g, function(ch) {
372 return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch];
373 });
374 }
375
376 function normalizeStationName(name) {
377 return String(name || '').trim().replace(/\s+/g, '').replace(/역$/, '');
378 }
379
380 function stationNamesMatch(a, b) {
381 return normalizeStationName(a) === normalizeStationName(b);
382 }
383
384 function renderEmpty(message) {
385 resultBody.innerHTML = `<p class="empty-message">${escapeHtml(message)}</p>`;
386 }
387
388 async function fetchJson(url, options) {
389 const response = await fetch(url, {
390 credentials: 'same-origin',
391 ...(options || {})
392 });
393 const text = await response.text();
394 let data = null;
395
396 try {
397 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
398 } catch (_) {
399 throw new Error(text.trim().startsWith('<')
400 ? '지하철 API 라우트가 아직 서버에 반영되지 않았습니다. 최신 배포 후 다시 시도해 주세요.'
401 : '서버 응답을 읽지 못했습니다.');
402 }
403
404 if (!response.ok) {
405 throw new Error(data.message || data.error || '요청에 실패했습니다.');
406 }
407 return data;
408 }
409
410 function renderMatches(matches) {
411 if (!matches.length) {
412 renderEmpty('해당 열번의 열차를 찾지 못했습니다. 호선 선택이 맞는지, 운행 중인 열차인지 확인해 주세요.');
413 return;
414 }
415
416 resultBody.innerHTML = `<div class="train-list">${matches.map(function(item) {
417 const flags = [
418 item.express ? '급행' : '',
419 item.lastTrain ? '막차' : '',
420 item.receivedAt ? '수신: ' + item.receivedAt : ''
421 ].filter(Boolean);
422 return `
423 <article class="train-item">
424 <div class="train-main">
425 <div>
426 <div class="train-no">${escapeHtml(item.trainNo)}</div>
427 <div class="source-label">${escapeHtml(item.line)} ${item.subwayId ? '· ' + escapeHtml(item.subwayId) : ''}</div>
428 </div>
429 <div class="status-badge"><i class="bi bi-broadcast-pin"></i>${escapeHtml(item.status)}</div>
430 </div>
431 <div class="train-meta">
432 <div><div class="meta-label">현재 위치</div><div class="meta-value">${escapeHtml(item.stationName || '확인 불가')}</div></div>
433 <div><div class="meta-label">행선지</div><div class="meta-value">${escapeHtml(item.destination || '확인 불가')}</div></div>
434 <div><div class="meta-label">방향</div><div class="meta-value">${escapeHtml(item.direction || '확인 불가')}</div></div>
435 <div><div class="meta-label">상태 코드</div><div class="meta-value">${escapeHtml(item.statusCode)}</div></div>
436 </div>
437 ${flags.length ? `<div class="pill-row">${flags.map(flag => `<span class="pill">${escapeHtml(flag)}</span>`).join('')}</div>` : ''}
438 </article>
439 `;
440 }).join('')}</div>`;
441 }
442
443 function renderArrivals(arrivals) {
444 if (!arrivals.length) {
445 arrivalList.innerHTML = '<p class="empty-message">지금 선택한 역에서 확인되는 열차 후보가 없습니다.</p>';
446 return;
447 }
448
449 arrivalList.innerHTML = arrivals.map(function(item) {
450 return `
451 <button class="arrival-item" type="button"
452 data-train-no="${escapeHtml(item.trainNo)}"
453 data-direction="${escapeHtml(item.direction || '')}"
454 data-direction-code="${escapeHtml(item.directionCode || '')}"
455 data-terminal="${escapeHtml(item.terminalStation || '')}"
456 data-station="${escapeHtml(item.stationName || '')}">
457 <div class="arrival-main">
458 <span class="arrival-train">${escapeHtml(item.trainNo)} 열차</span>
459 <span class="arrival-status">${escapeHtml(item.status)}</span>
460 </div>
461 <div class="arrival-meta">
462 ${escapeHtml(item.message || '도착 정보 없음')}
463 ${item.trainLineName ? ` · ${escapeHtml(item.trainLineName)}` : ''}
464 ${item.terminalStation ? ` · ${escapeHtml(item.terminalStation)}행` : ''}
465 </div>
466 </button>
467 `;
468 }).join('');
469 }
470
471 function renderTargetStationOptions(stations) {
472 targetStationSelect.innerHTML = '<option value="">목표역 선택</option>' + stations.map(function(station) {
473 const label = station.frCode ? `${station.name} (${station.frCode})` : station.name;
474 return `<option value="${escapeHtml(station.name)}">${escapeHtml(label)}</option>`;
475 }).join('');
476 targetStationSelect.disabled = stations.length === 0;
477 }
478
479 function filterStationsByDirection(boardingStation, directionCode, terminalStation) {
480 if (!boardingStation || !currentStations.length) return currentStations;
481 const boardingIndex = currentStations.findIndex(function(station) {
482 return station.name === boardingStation;
483 });
484 if (boardingIndex === -1) return currentStations;
485
486 if (terminalStation) {
487 const terminalIndex = currentStations.findIndex(function(station) {
488 return stationNamesMatch(station.name, terminalStation);
489 });
490 if (terminalIndex !== -1 && terminalIndex !== boardingIndex) {
491 const start = Math.min(boardingIndex, terminalIndex);
492 const end = Math.max(boardingIndex, terminalIndex);
493 const segment = currentStations.slice(start, end + 1);
494 return terminalIndex > boardingIndex ? segment.slice(1) : segment.slice(0, -1).reverse();
495 }
496 }
497
498 if (directionCode === '0') return currentStations.slice(0, boardingIndex).reverse();
499 if (directionCode === '1') return currentStations.slice(boardingIndex + 1);
500 return currentStations;
501 }
502
503 function applySelectedTrainTargetFilter() {
504 const selectedTerminal = arrivalList.querySelector('.arrival-item.selected')?.dataset.terminal || '';
505 const filtered = filterStationsByDirection(selectedBoardingStation, selectedDirectionCode, selectedTerminal);
506 renderTargetStationOptions(filtered);
507 if (filtered.length === 0) {
508 trackerStatus.textContent = '선택한 열차의 진행 방향에서 고를 수 있는 목표역이 없습니다.';
509 } else if (selectedBoardingStation && selectedDirectionCode) {
510 trackerStatus.textContent = `${trainNoInput.value} 열차의 진행 방향에 있는 역만 목표역으로 표시했습니다.`;
511 }
512 }
513
514 async function loadStationArrivals() {
515 const line = lineSelect.value;
516 const station = boardingStationSelect.value;
517 if (!line || !station) {
518 if (typeof showAlert === 'function') await showAlert('호선과 탑승역을 선택해 주세요.');
519 return;
520 }
521
522 loadArrivalsBtn.disabled = true;
523 arrivalList.innerHTML = '<p class="empty-message">탑승 가능한 열차 후보를 불러오는 중입니다.</p>';
524 try {
525 const params = new URLSearchParams({ line, station });
526 const data = await fetchJson(`/api/subway/station-arrivals?${params.toString()}`);
527 if (!data.success) throw new Error(data.message || '도착 정보를 불러오지 못했습니다.');
528 renderArrivals(data.arrivals || []);
529 } catch (error) {
530 arrivalList.innerHTML = `<p class="empty-message">${escapeHtml(error.message || '도착 정보를 불러오지 못했습니다.')}</p>`;
531 } finally {
532 loadArrivalsBtn.disabled = false;
533 }
534 }
535
536 function renderTrainBadgesForStation(station, lineTrains, selectedTrainNo, displayDirectionCode) {
537 const trains = (lineTrains || []).filter(function(train) {
538 return stationNamesMatch(train.stationName, station.name);
539 }).slice(0, 4);
540
541 if (!trains.length) return '';
542
543 return trains.map(function(train) {
544 const directionCode = String(train.directionCode ?? '');
545 const sideClass = directionCode === '0' ? 'up' : 'down';
546 const movementClass = directionCode && directionCode === displayDirectionCode ? ' moving-down' : ' moving-up';
547 const statusClass = train.status === '진입' ? ' status-enter' : (train.status === '출발' ? ' status-depart' : ' status-arrive');
548 const selectedClass = String(train.trainNo) === String(selectedTrainNo) ? ' selected' : '';
549 const terminal = train.destination || '';
550 const title = `${terminal ? terminal + '행 ' : ''}${train.trainNo} · ${train.status || '상태 미확인'}`;
551 return `
552 <div class="train-badge ${sideClass}${movementClass}${statusClass}${selectedClass}" title="${escapeHtml(title)}">
553 <span class="train-icon"></span>
554 <span>
555 <span class="train-label">${escapeHtml(train.trainNo)}</span>
556 </span>
557 </div>
558 `;
559 }).join('');
560 }
561
562 function renderTrainChipsForStation(station, lineTrains, selectedTrainNo) {
563 const trains = (lineTrains || []).filter(function(train) {
564 return stationNamesMatch(train.stationName, station.name);
565 }).slice(0, 4);
566
567 if (!trains.length) return '';
568
569 return `<div class="station-train-list">${trains.map(function(train) {
570 const terminal = train.destination || '';
571 const selectedClass = String(train.trainNo) === String(selectedTrainNo) ? ' selected' : '';
572 const label = `${train.trainNo}${terminal ? ' · ' + terminal + '행' : ''}${train.express ? ' · 급행' : ''}${train.lastTrain ? ' · 막차' : ''}`;
573 return `<span class="station-train-chip${selectedClass}" title="${escapeHtml(label)}">${escapeHtml(label)}</span>`;
574 }).join('')}</div>`;
575 }
576
577 function renderRouteMap(match, lineTrains) {
578 const line = lineSelect.value;
579 const targetStation = targetStationSelect.value;
580 if (!line || !currentStations.length || !match) {
581 routeCard.classList.remove('show');
582 stationStrip.innerHTML = '';
583 return;
584 }
585
586 const currentIndex = currentStations.findIndex(function(station) {
587 return stationNamesMatch(station.name, match.stationName);
588 });
589 if (currentIndex === -1) {
590 routeCard.classList.add('show');
591 routeTitle.textContent = `${line} 노선 진행도`;
592 routeSub.textContent = `${match.stationName || '현재역'} 위치가 역 목록과 정확히 매칭되지 않았습니다.`;
593 stationStrip.innerHTML = '';
594 return;
595 }
596
597 const directionCode = String(match.directionCode ?? '');
598 const displayStations = directionCode === '0' ? currentStations.slice().reverse() : currentStations.slice();
599 const displayCurrentIndex = displayStations.findIndex(function(station) {
600 return stationNamesMatch(station.name, match.stationName);
601 });
602
603 routeCard.classList.add('show');
604 routeTitle.textContent = `${line} ${match.trainNo} 진행도`;
605 routeSub.textContent = `${match.stationName}역 ${match.status} · ${match.direction || '방향 미확인'} · 목표역 ${targetStation || '미선택'}`;
606 stationStrip.style.setProperty('--line-color', LINE_COLORS[line] || 'var(--accent)');
607 stationStrip.innerHTML = displayStations.map(function(station, index) {
608 const isCurrent = stationNamesMatch(station.name, match.stationName);
609 const isTarget = targetStation && stationNamesMatch(station.name, targetStation);
610 const state = index < displayCurrentIndex ? 'past' : (isCurrent ? 'current' : 'future');
611 const title = `${station.name}${station.frCode ? ' (' + station.frCode + ')' : ''}`;
612 return `
613 <div class="station-node ${state}${isTarget ? ' target' : ''}" data-current="${isCurrent ? 'true' : 'false'}" title="${escapeHtml(title)}">
614 <div class="station-rail">
615 <div class="station-dot"></div>
616 <div class="train-badges">${renderTrainBadgesForStation(station, lineTrains || [], match.trainNo, directionCode)}</div>
617 </div>
618 <div class="station-info">
619 <div class="station-name">${escapeHtml(station.name)}${station.frCode ? `<span class="station-code">${escapeHtml(station.frCode)}</span>` : ''}</div>
620 ${renderTrainChipsForStation(station, lineTrains || [], match.trainNo)}
621 </div>
622 </div>
623 `;
624 }).join('');
625
626 const currentEl = stationStrip.querySelector('[data-current="true"]');
627 if (currentEl) {
628 requestAnimationFrame(function() {
629 currentEl.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
630 });
631 }
632 }
633
634 function getArrivalMessage(status) {
635 if (status === '진입') return '열차가 도착역에 진입했어요. 하차하세요.';
636 return '열차가 도착역에 도착했어요. 하차하세요.';
637 }
638
639 async function showBrowserNotification(title, body) {
640 if (!('Notification' in window) || Notification.permission !== 'granted') return;
641 if (!('serviceWorker' in navigator)) return;
642
643 const reg = serviceWorkerRegistration || await navigator.serviceWorker.register('/sw.js');
644 serviceWorkerRegistration = reg;
645 const readyRegistration = await navigator.serviceWorker.ready;
646 await readyRegistration.showNotification(title, {
647 body,
648 icon: '/image/title.png',
649 badge: '/image/title.png',
650 data: { url: '/hinana/subway' }
651 });
652 }
653
654 function notifyArrival(trainNo, status) {
655 const title = `${trainNo} 열차 ${status}`;
656 const body = getArrivalMessage(status);
657 showBrowserNotification(title, body).catch(function(error) {
658 console.warn('브라우저 알림 표시 실패:', error);
659 });
660 if (typeof showAlert === 'function') {
661 showAlert(body);
662 } else {
663 alert(body);
664 }
665 }
666
667 function urlBase64ToUint8Array(b64) {
668 const pad = '='.repeat((4 - b64.length % 4) % 4);
669 const base64 = (b64 + pad).replace(/-/g, '+').replace(/_/g, '/');
670 const raw = atob(base64);
671 return Uint8Array.from(raw, c => c.charCodeAt(0));
672 }
673
674 function arrayBufferToBase64Url(buffer) {
675 const bytes = new Uint8Array(buffer);
676 let binary = '';
677 bytes.forEach(function(byte) { binary += String.fromCharCode(byte); });
678 return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
679 }
680
681 function subscriptionUsesCurrentKey(subscription) {
682 if (!subscription || !subscription.options || !subscription.options.applicationServerKey) return true;
683 return arrayBufferToBase64Url(subscription.options.applicationServerKey) === PUSH_KEY;
684 }
685
686 async function ensurePushSubscription() {
687 if (!PUSH_USER) throw new Error('서버 도착 알림은 로그인이 필요합니다.');
688 if (!PUSH_KEY) throw new Error('푸시 알림 키가 설정되어 있지 않습니다.');
689 if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
690 throw new Error('이 브라우저는 푸시 알림을 지원하지 않습니다.');
691 }
692
693 const reg = serviceWorkerRegistration || await navigator.serviceWorker.register('/sw.js');
694 serviceWorkerRegistration = reg;
695 await navigator.serviceWorker.ready;
696
697 if ('Notification' in window && Notification.permission === 'default') {
698 const permission = await Notification.requestPermission();
699 if (permission !== 'granted') throw new Error('알림 권한이 허용되지 않았습니다.');
700 }
701 if ('Notification' in window && Notification.permission === 'denied') {
702 throw new Error('브라우저 알림 권한이 차단되어 있습니다.');
703 }
704
705 let subscription = await reg.pushManager.getSubscription();
706 if (subscription && !subscriptionUsesCurrentKey(subscription)) {
707 await subscription.unsubscribe();
708 subscription = null;
709 }
710 if (!subscription) {
711 subscription = await reg.pushManager.subscribe({
712 userVisibleOnly: true,
713 applicationServerKey: urlBase64ToUint8Array(PUSH_KEY)
714 });
715 }
716
717 await fetchJson('/api/push/subscribe', {
718 method: 'POST',
719 headers: { 'Content-Type': 'application/json' },
720 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
721 });
722 }
723
724 async function createServerAlert(trainNo, line, targetStation) {
725 const data = await fetchJson('/api/subway/alerts', {
726 method: 'POST',
727 headers: { 'Content-Type': 'application/json' },
728 [SECURITY REDACTED] 민감한 설정/인증/토큰 관련 코드입니다.
729 });
730 if (!data.success) throw new Error(data.message || '도착 알림을 등록하지 못했습니다.');
731 return data.alert;
732 }
733
734 async function cancelServerAlert() {
735 if (!currentAlertId) return;
736 await fetchJson(`/api/subway/alerts/${encodeURIComponent(currentAlertId)}`, { method: 'DELETE' }).catch(function() {});
737 currentAlertId = '';
738 }
739
740 async function loadStationsForLine(line) {
741 targetStationSelect.disabled = true;
742 boardingStationSelect.disabled = true;
743 selectedBoardingStation = '';
744 selectedDirectionCode = '';
745 targetStationSelect.innerHTML = '<option value="">역 목록을 불러오는 중...</option>';
746 boardingStationSelect.innerHTML = '<option value="">역 목록을 불러오는 중...</option>';
747 arrivalList.innerHTML = '';
748 if (!line) {
749 currentStations = [];
750 routeCard.classList.remove('show');
751 targetStationSelect.innerHTML = '<option value="">호선을 먼저 선택해 주세요</option>';
752 boardingStationSelect.innerHTML = '<option value="">호선을 먼저 선택해 주세요</option>';
753 return;
754 }
755 try {
756 const data = await fetchJson(`/api/subway/stations?line=${encodeURIComponent(line)}`);
757 if (!data.success) throw new Error(data.message || '역 목록을 불러오지 못했습니다.');
758 currentStations = data.stations || [];
759 const stationOptions = (data.stations || []).map(function(station) {
760 const label = station.frCode ? `${station.name} (${station.frCode})` : station.name;
761 return `<option value="${escapeHtml(station.name)}">${escapeHtml(label)}</option>`;
762 }).join('');
763 renderTargetStationOptions(data.stations || []);
764 boardingStationSelect.innerHTML = '<option value="">탑승역 선택</option>' + stationOptions;
765 boardingStationSelect.disabled = false;
766 trackerStatus.textContent = `${line} 역 목록을 불러왔습니다. 목표역을 선택하면 도착 알림을 시작할 수 있어요.`;
767 } catch (error) {
768 currentStations = [];
769 routeCard.classList.remove('show');
770 targetStationSelect.innerHTML = '<option value="">역 목록 로드 실패</option>';
771 boardingStationSelect.innerHTML = '<option value="">역 목록 로드 실패</option>';
772 trackerStatus.textContent = error.message || '역 목록을 불러오지 못했습니다.';
773 }
774 }
775
776 async function queryTrainPosition(options = {}) {
777 const trainNo = trainNoInput.value.trim();
778 const line = lineSelect.value;
779 if (!trainNo) return;
780
781 if (!options.silent) {
782 resultCard.classList.add('show');
783 resultTitle.textContent = `${trainNo} 조회 중...`;
784 resultSource.textContent = '서울시 지하철 실시간 열차 위치정보';
785 searchedLines.textContent = '';
786 renderEmpty('실시간 위치를 확인하고 있습니다.');
787 submitBtn.disabled = true;
788 }
789
790 try {
791 const params = new URLSearchParams({ trainNo });
792 if (line) params.set('line', line);
793 const data = await fetchJson(`/api/subway/train-position?${params.toString()}`);
794 if (!data.success) throw new Error(data.message || '조회에 실패했습니다.');
795
796 resultTitle.textContent = `${data.trainNo} 조회 결과`;
797 resultSource.textContent = data.source || '서울시 지하철 실시간 열차 위치정보';
798 searchedLines.textContent = `${data.searchedLines.length}개 호선 조회`;
799 renderMatches(data.matches || []);
800 renderRouteMap((data.matches || [])[0], data.lineTrains || []);
801 return data;
802 } catch (error) {
803 if (!options.silent) {
804 resultTitle.textContent = '조회 실패';
805 searchedLines.textContent = '';
806 renderEmpty(error.message || '잠시 후 다시 시도해 주세요.');
807 routeCard.classList.remove('show');
808 }
809 throw error;
810 } finally {
811 if (!options.silent) submitBtn.disabled = false;
812 }
813 }
814
815 async function pollTracking() {
816 if (!trackingActive) return;
817 const targetStation = targetStationSelect.value;
818 const line = lineSelect.value;
819 const trainNo = trainNoInput.value.trim();
820
821 try {
822 const data = await queryTrainPosition({ silent: true });
823 const match = (data.matches || []).find(function(item) {
824 return stationNamesMatch(item.stationName, targetStation) && (item.status === '진입' || item.status === '도착');
825 });
826 const current = (data.matches || [])[0];
827 renderRouteMap(current, data.lineTrains || []);
828 if (current) {
829 trackerStatus.textContent = `${trainNo} 추적 중 · 현재 ${current.line} ${current.stationName || '위치 미확인'} · ${current.status}`;
830 } else {
831 trackerStatus.textContent = `${trainNo} 추적 중 · 현재 운행 위치를 찾지 못했습니다.`;
832 }
833 if (match) {
834 const notifyKey = `${trainNo}:${line}:${targetStation}:${match.receivedAt || Date.now()}`;
835 if (notifyKey !== lastNotifiedKey) {
836 lastNotifiedKey = notifyKey;
837 trackerStatus.textContent = `${getArrivalMessage(match.status)} 서버 푸시 알림이 곧 전송됩니다.`;
838 }
839 }
840 } catch (error) {
841 trackerStatus.textContent = '화면 갱신에 실패했지만 서버 도착 알림은 계속 추적 중입니다.';
842 }
843 }
844
845 async function startTracking() {
846 const trainNo = trainNoInput.value.trim();
847 const line = lineSelect.value;
848 const targetStation = targetStationSelect.value;
849 if (!PUSH_USER) {
850 if (typeof showAlert === 'function') await showAlert('도착 알림 기능은 로그인 후 사용할 수 있습니다.');
851 return;
852 }
853 if (!trainNo || !line || !targetStation) {
854 if (typeof showAlert === 'function') await showAlert('열번, 호선, 목표역을 모두 선택해 주세요.');
855 return;
856 }
857
858 try {
859 await ensurePushSubscription();
860 const serverAlert = await createServerAlert(trainNo, line, targetStation);
861 currentAlertId = serverAlert.id;
862 } catch (error) {
863 if (typeof showAlert === 'function') await showAlert(error.message || '도착 알림을 등록하지 못했습니다.');
864 return;
865 }
866
867 trackingActive = true;
868 lastNotifiedKey = '';
869 startTrackBtn.disabled = true;
870 stopTrackBtn.disabled = false;
871 trackerStatus.textContent = `${trainNo} 열차가 ${targetStation}역에 도착하는지 서버에서 10초마다 확인 중입니다. 브라우저를 백그라운드에 둬도 푸시 알림이 전송됩니다.`;
872 await pollTracking();
873 if (trackingActive) trackingTimer = setInterval(pollTracking, 10 * 1000);
874 }
875
876 async function resumeTracking(alert) {
877 if (!alert || !alert.active) return;
878 currentAlertId = alert.id;
879 trainNoInput.value = alert.trainNo;
880 lineSelect.value = alert.line;
881 await loadStationsForLine(alert.line);
882 targetStationSelect.value = alert.targetStation;
883
884 trackingActive = true;
885 startTrackBtn.disabled = true;
886 stopTrackBtn.disabled = false;
887 trackerStatus.textContent = `${alert.trainNo} 열차가 ${alert.targetStation}역에 도착하는지 서버에서 추적 중입니다. 브라우저를 백그라운드에 둬도 푸시 알림이 전송됩니다.`;
888 await pollTracking();
889 if (trackingActive) trackingTimer = setInterval(pollTracking, 10 * 1000);
890 }
891
892 async function loadExistingAlert() {
893 if (!PUSH_USER) return;
894 try {
895 const data = await fetchJson('/api/subway/alerts');
896 if (!data.success) return;
897 const activeAlert = (data.alerts || []).find(function(alert) { return alert.active; });
898 if (activeAlert) await resumeTracking(activeAlert);
899 } catch (_) {}
900 }
901
902 async function stopTracking(showMessage = true) {
903 trackingActive = false;
904 if (trackingTimer) clearInterval(trackingTimer);
905 trackingTimer = null;
906 await cancelServerAlert();
907 startTrackBtn.disabled = false;
908 stopTrackBtn.disabled = true;
909 if (showMessage) trackerStatus.textContent = '도착 알림 추적을 중지했습니다.';
910 }
911
912 form.addEventListener('submit', async function(event) {
913 event.preventDefault();
914 queryTrainPosition().catch(function() {});
915 });
916
917 lineSelect.addEventListener('change', function() {
918 stopTracking(false);
919 loadStationsForLine(this.value);
920 });
921 loadArrivalsBtn.addEventListener('click', loadStationArrivals);
922 arrivalList.addEventListener('click', function(event) {
923 const item = event.target.closest('.arrival-item');
924 if (!item) return;
925 arrivalList.querySelectorAll('.arrival-item').forEach(function(el) { el.classList.remove('selected'); });
926 item.classList.add('selected');
927 trainNoInput.value = item.dataset.trainNo || '';
928 selectedBoardingStation = item.dataset.station || boardingStationSelect.value;
929 selectedDirectionCode = item.dataset.directionCode || '';
930 applySelectedTrainTargetFilter();
931 });
932 if (startTrackBtn) startTrackBtn.addEventListener('click', startTracking);
933 if (stopTrackBtn) stopTrackBtn.addEventListener('click', function() { stopTracking(true); });
934
935 (async function initServiceWorker() {
936 if (!('serviceWorker' in navigator)) return;
937 serviceWorkerRegistration = await navigator.serviceWorker.register('/sw.js').catch(function() { return null; });
938 })();
939 loadExistingAlert();
940 </script>
941 </body>
942 </html>
943