File size: 57,050 Bytes
2d70903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
const app = document.querySelector("#app");
const toasts = document.querySelector("#toast-region");

const ui = {
  data: null,
  detail: null,
  menuOpen: false,
  locationOpen: false,
  filterOpen: false,
  modal: null,
  authTab: "signin",
  localCode: "",
  page: 0,
  limit: 30,
  busy: false,
  loadError: "",
};

const money = (cents) => new Intl.NumberFormat("en-US", {
  style: "currency", currency: "USD"
}).format((cents || 0) / 100);
const price = (value) => new Intl.NumberFormat("en-US", {
  style: "currency", currency: "USD"
}).format(value || 0);
const esc = (value = "") => String(value).replace(/[&<>"']/g, (char) => ({
  "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
}[char]));
const slugify = (value) => String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");

function icon(name, label = "") {
  const paths = {
    menu: '<path d="M3 6h18M3 12h18M3 18h18"/>',
    search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/>',
    user: '<circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 3.2-7 8-7s8 3 8 7"/>',
    cart: '<path d="M3 4h2l2 11h10l2-8H6"/><circle cx="9" cy="19" r="1.5"/><circle cx="17" cy="19" r="1.5"/>',
    location: '<path d="M20 10c0 5-8 12-8 12S4 15 4 10a8 8 0 1 1 16 0Z"/><circle cx="12" cy="10" r="2.5"/>',
    heart: '<path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8L12 21l8.9-8.6a5.5 5.5 0 0 0-.1-7.8Z"/>',
    list: '<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2m0 7h8m-8 4h4M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Z"/>',
    store: '<path d="M4 10v11h16V10M3 10l2-7h14l2 7"/><path d="M8 21v-7h8v7M3 10c1 2 4 2 5 0 1 2 4 2 5 0 1 2 4 2 5 0 1 2 4 2 5 0"/>',
    close: '<path d="m5 5 14 14M19 5 5 19"/>',
    filter: '<path d="M4 6h16M7 12h10M10 18h4"/>',
    arrow: '<path d="m9 18 6-6-6-6"/>',
    check: '<path d="m5 12 4 4L19 6"/>',
    minus: '<path d="M5 12h14"/>',
    plus: '<path d="M5 12h14M12 5v14"/>',
    info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7h.01"/>',
  };
  return `<svg aria-hidden="${label ? "false" : "true"}" ${label ? `aria-label="${esc(label)}"` : ""}
    viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor"
    stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${paths[name] || paths.info}</svg>`;
}

function toast(message, error = false) {
  const node = document.createElement("div");
  node.className = `toast${error ? " error" : ""}`;
  node.textContent = message;
  toasts.append(node);
  setTimeout(() => node.remove(), 3500);
}

async function api(path, options = {}) {
  const response = await fetch(path, {
    headers: {"Content-Type": "application/json", ...(options.headers || {})},
    ...options,
  });
  const body = await response.json().catch(() => ({}));
  if (!response.ok) {
    const error = new Error(body.detail || `Request failed (${response.status})`);
    error.status = response.status;
    throw error;
  }
  return body;
}


function route() {
  const path = location.pathname;
  const params = new URLSearchParams(location.search);
  if (path === "/") return {name: "home", params};
  if (path === "/search") return {name: "catalog", params};
  if (params.get("_q") && params.get("map") === "ft" && path.split("/").filter(Boolean).length === 1) {
    return {name: "catalog", params};
  }
  if (path.startsWith("/category/")) return {
    name: "catalog", category: decodeURIComponent(path.slice(10)), params
  };
  if (path.endsWith("/p")) return {name: "detail", slug: path.split("/").filter(Boolean)[0], params};
  if (path === "/cart") return {name: "cart", params};
  if (path === "/checkout") return {name: "checkout", params};
  if (path === "/favorites") return {name: "favorites", params};
  if (path === "/orders") return {name: "orders", params};
  if (path.startsWith("/orders/")) {
    const orderId = path.slice(8);
    if (orderId && !orderId.includes("/")) return {
      name: "order-details", orderId: decodeURIComponent(orderId), params
    };
  }
  if (path === "/support") return {name: "support", params};
  if (path === "/account/registration") return {name: "account", section: "registration", params};
  if (path === "/account/recovery") return {name: "account", section: "recovery", params};
  return {name: "not-found", params};
}

function sourceSearchUrl(value) {
  const query = String(value || "").trim();
  if (!query) return "/search";
  return `/${encodeURIComponent(slugify(query) || "search")}?_q=${encodeURIComponent(query)}&map=ft`;
}

function go(url) {
  history.pushState({}, "", url);
  ui.page = 0;
  ui.detail = null;
  ui.orderDetail = null;
  window.scrollTo({top: 0});
  load();
}

function logo() {
  return '<span class="logo-mark" aria-hidden="true"></span><span>H MART</span>';
}

function header() {
  const count = ui.data?.cart?.item_count || 0;
  const account = ui.data?.session?.account;
  const query = route().params.get("_q") || route().params.get("q") || "";
  const categoryLinks = (ui.data?.categories || []).slice(0, 15).map((row) =>
    `<a href="/category/${encodeURIComponent(row.category)}" data-nav>
      ${esc(row.category)} <small>(${row.count})</small></a>`
  ).join("");
  return `
    <header>
      <div class="campaign-strip">Feel At Home Wherever You Are From</div>
      <div class="utility-bar">
        <div class="utility-inner">
          <div class="binding-tabs"><span class="binding-tab">H MART</span><span class="binding-tab">한국으로 선물</span></div>
          <div class="utility-links">
            <button class="nav-button" data-info="Contact support is not available in this preview.">Contact Us</button>
            <button class="nav-button" data-info="English is currently selected.">English</button>
          </div>
        </div>
      </div>
      <div class="main-header">
        <div class="header-main">
          <a href="/" data-nav class="logo" aria-label="H Mart home">${logo()}</a>
          <form class="search-form" data-search-form>
            <label class="sr-only" for="desktop-search">Search products</label>
            <input id="desktop-search" class="search-input" name="q" value="${esc(query)}" placeholder="Search products..." autocomplete="off">
            <button class="search-submit" aria-label="Search Products">Search</button>
          </form>
          <div class="header-actions">
            <button class="header-action" data-account>
              <span class="icon">${icon("user")}</span>
              <span>${account ? `Hi, ${esc(account.display_name)}` : "Log in/Sign up"}<strong>My Account</strong></span>
            </button>
            <button class="header-action cart-action" data-nav-url="/cart" aria-label="Cart with ${count} items">
              <span class="icon">${icon("cart")}</span><span class="cart-badge">${count}</span>
            </button>
          </div>
        </div>
      </div>
      <nav class="nav-bar" aria-label="Primary navigation">
        <div class="nav-inner">
          <button class="nav-button" data-menu aria-expanded="${ui.menuOpen}">Categories</button>
          <a class="nav-link" href="/category/Rice & Grain" data-nav>CJ</a>
          <a class="nav-link" href="/search?sale=1" data-nav>Sale</a>
          <a class="nav-link" href="/beauty?_q=beauty&map=ft" data-nav>Beauty</a>
          <a class="nav-link" href="/search?sort=newest" data-nav>New Arrivals</a>
          <a class="nav-link" href="/category/Korea Direct" data-nav>Korea Direct</a>
          <button class="nav-link nav-button" data-info="Market+ is represented by local catalog results.">Market+</button>
          <button class="nav-link nav-button" data-info="Browse brands with the catalog filters.">Brands</button>
          <button class="nav-link nav-button" data-info="Weekly Ads are not available in this preview.">Weekly Ads</button>
          <button class="nav-link nav-button" data-info="H Mart: The Best of Asia in America. Since 1982.">Our Story</button>
          <button class="nav-link nav-button" data-info="Smart Rewards is not connected to a real loyalty account.">Smart Rewards</button>
          <span class="nav-spacer"></span>
          <button class="nav-button" data-location>${icon("location")} Enter a location</button>
          <button class="nav-button" data-info="Store availability is shown for your selected location.">${icon("store")} Store Finder</button>
        </div>
      </nav>
      <div class="mobile-head">
        <div class="mobile-top">
          <button class="mobile-icon-button" data-menu aria-label="Open navigation">${icon("menu")}</button>
          <a href="/" data-nav class="logo" aria-label="H Mart home">${logo()}</a>
          <div class="mobile-icons">
            <button class="mobile-icon-button" data-account aria-label="My Account">${icon("user")}</button>
            <button class="mobile-icon-button cart-action" data-nav-url="/cart" aria-label="Cart with ${count} items">
              ${icon("cart")}<span class="cart-badge">${count}</span>
            </button>
          </div>
        </div>
        <form class="search-form mobile-search" data-search-form>
          <label class="sr-only" for="mobile-search">Search products</label>
          <input id="mobile-search" class="search-input" name="q" value="${esc(query)}" placeholder="Search products..." autocomplete="off">
          <button class="search-submit" aria-label="Search Products">Search</button>
        </form>
      </div>
      ${ui.menuOpen ? `<nav class="category-menu" aria-label="Categories">
        <button class="menu-close" data-menu aria-label="Close navigation">${icon("close")}</button>${categoryLinks}
        <button class="category-menu-action" data-location>${icon("location")} Set shopping location</button>
        <a href="/favorites" data-nav>Favorites</a><a href="/orders" data-nav>Order history</a>
        <a href="/support" data-nav>Help & support</a></nav>` : ""}
    </header>`;
}

function locationPanel() {
  const compact = window.matchMedia("(max-width: 720px)").matches;
  const compactHome = compact && route().name === "home";
  if (!ui.data || (!ui.locationOpen && (ui.data.state.postal_code || compactHome))) return "";
  return `<section class="location-panel ${route().name === "detail" ? "location-panel-detail" : ""}" aria-label="Set shopping location">
    <h2>Offers and delivery options vary based on region.</h2>
    <form class="location-row" data-location-form novalidate>
      <label class="sr-only" for="postal-code">Postal Code</label>
      <input id="postal-code" name="postal_code" value="${esc(ui.data.state.postal_code || "")}"
        placeholder="Postal Code" inputmode="numeric" pattern="[0-9]{5}(-[0-9]{4})?" aria-describedby="location-error">
      <button class="red-button">Continue</button>
      <span id="location-error" class="form-error" data-location-error role="alert"></span>
    </form>
    <button class="text-button" data-info="Local demo areas include ZIP codes such as 10001, 07001, 75001, and 90001. No address leaves this computer.">I don't know my postal code</button>
  </section>`;
}

const infoLinks = {
  "GET TO KNOW US": ["About Us", "Founder's Greeting", "Mission", "History", "Community", "Our Story"],
  "H MART STORES": ["Weekly Sales & Events", "Locations & Hours", "Smart Rewards Card", "Store FAQ", "Store Tenant", "Careers", "Health Benefit Card"],
  "H MART.COM": ["Online Order Delivery", "Online FAQ", "Privacy Notice", "Privacy Notice for California Employees Only", "Conditions of Use", "Do Not Sell My Personal Information"],
};

function footer() {
  return `<footer class="footer"><div class="footer-grid">
    ${Object.entries(infoLinks).map(([title, links]) => `<section><h3>${title}</h3>
      ${links.map((label) => `<button class="nav-button" data-info="${esc(label)} information is not available in this preview.">${esc(label)}</button>`).join("")}
    </section>`).join("")}
    <section><h3>STAY IN TOUCH</h3><div class="socials">
      ${[["FB", "Facebook"], ["YT", "YouTube"], ["TT", "TikTok"], ["IG", "Instagram"],
        ["PT", "Pinterest"], ["WB", "Weibo"], ["WC", "WeChat"], ["KT", "KakaoTalk"]].map(([label, name]) =>
        `<button class="social" data-info="This social link is not available in this preview." aria-label="${name} unavailable">${label}</button>`
      ).join("")}</div>
      <p><button class="ghost-button" data-info="App downloads are not available in this preview.">App Store</button>
      <button class="ghost-button" data-info="App downloads are not available in this preview.">Google Play</button></p>
    </section>
  </div><div class="footer-bottom">© 2026 H Mart. All Rights Reserved.<br>
    The Best of Asia in America. Since 1982. H MART</div></footer>`;
}

function image(product, className = "") {
  return product.image
    ? `<img class="${className}" src="${esc(product.image)}" alt="${esc(product.name)}" loading="lazy">`
    : `<div class="image-missing">Product image coming soon<br>${esc(product.brand)}</div>`;
}

function productCard(product) {
  const discount = product.list_price > product.price && product.list_price
    ? Math.round((1 - product.price / product.list_price) * 100) : 0;
  const favorite = ui.data.favorite_product_ids.includes(product.product_id);
  return `<article class="product-card" data-product-id="${esc(product.product_id)}">
    ${discount ? `<span class="discount-tag">-${discount}%</span>` : ""}
    <button class="favorite-button ${favorite ? "active" : ""}" data-favorite="${esc(product.product_id)}"
      aria-label="${favorite ? "Remove from" : "Add to"} favorites">${icon("list")}</button>
    <a class="product-card-media" href="/${encodeURIComponent(product.slug)}/p" data-nav>
      ${image(product)}
    </a>
    <div class="price-row"><span class="price">${price(product.price)}</span>
      ${discount ? `<span class="list-price">${price(product.list_price)}</span>` : ""}</div>
    <span class="brand">${esc(product.brand)}</span>
    <a class="product-name" href="/${encodeURIComponent(product.slug)}/p" data-nav>${esc(product.name)}</a>
    ${ui.data.state.postal_code ? `<div class="availability ${product.available ? "" : "unavailable"}">
      ${product.available ? "Available for selected region" : "Unavailable"}</div>
      <button class="add-button" data-add="${esc(product.product_id)}" ${product.available ? "" : "disabled"}>
        ${product.available ? "Add to Cart" : "Unavailable"}</button>` : `<button class="availability-prompt" data-location
        aria-label="Set a location to check availability for ${esc(product.name)}">Set location to check availability</button>`}
  </article>`;
}

function productGrid(products, extraClass = "") {
  return `<div class="product-grid ${extraClass}">${products.map(productCard).join("")}</div>`;
}

function home() {
  const products = ui.data.products;
  const quick = ["Best Sellers", "Stationery", "Toys", "Meat & Poultry", "Wellness", "Ramen & Noodles", "Side Dishes", "Produce"];
  const sections = [
    ["Recommended For You", products.slice(0, 5)],
    ["New Arrivals", products.slice(5, 10)],
    ["Hot Picks & Best Sellers", products.slice(10, 15)],
    ["Home & Lifestyle", products.slice(15, 20)],
    ["Side Dishes(Banchan)", products.slice(20, 25)],
    ["Japanese", products.slice(25, 30)],
  ];
  return `<main id="main" class="page-shell"><h1 class="sr-only">H Mart online grocery</h1>
    <section class="hero" aria-label="Featured promotions">
      <div class="promo-carousel"><div class="promo-track">
        ${[1, 2, 3, 4].map((number) => `<button class="promo-card" data-info="Promotion details are not available in this preview.">
          <img src="/static/promos/home-${number}.webp" alt="Captured H Mart weekly promotion ${number}"></button>`).join("")}
      </div></div>
      <div class="promo-controls" aria-label="Promotion controls"><span class="promo-progress"></span>
        <button class="promo-control" data-info="Promotion rotation is paused." aria-label="Pause promotions">${icon("minus")}</button>
        <strong>01 / 06</strong><button class="promo-control" data-info="More promotions are not available in this preview." aria-label="Next promotion">${icon("arrow")}</button>
      </div>
    </section>
    <nav class="quick-categories" aria-label="Popular categories">
      ${quick.map((label, index) => `<button class="quick-category" data-search="${esc(label)}">
        <span class="quick-icon" aria-hidden="true">${icon(index % 2 ? "store" : "cart")}</span>${esc(label)}</button>`).join("")}
    </nav>
    <section class="content-section"><div class="section-heading"><div>
      <h2>Recommended For You</h2><p>Explore 240 grocery and pantry essentials</p></div></div>
      <div class="tabs">${["Weekly Sale","Korea Direct","Fresh Produce","Flash Sale","Kitchenware","Characters"].map((label, index) =>
        `<button class="pill ${index === 0 ? "active" : ""}" data-home-tab="${index}">${label}</button>`
      ).join("")}</div>
      ${productGrid(products.slice(0, 5), "home-grid")}
    </section>
    ${sections.slice(1).map(([title, items]) => `<section class="content-section">
      <div class="section-heading"><h2>${title}</h2><button class="text-button" data-search="${esc(title)}">See all</button></div>
      ${productGrid(items, "home-grid")}</section>`).join("")}
    <section class="content-section"><div class="section-heading"><h2>Recipes We Love</h2></div>
      <div class="hero-side" style="display:flex;min-height:220px"><h2>Weeknight rice bowls</h2>
      <p>Browse rice, sauces, seaweed, and quick side dishes.</p>
      <button class="outline-button" data-search="rice">Explore ingredients</button></div></section>
  </main>`;
}

function filterPanel() {
  const activeCategory = route().category || route().params.get("category") || "";
  const activeBrand = route().params.get("brand") || "";
  const activeCountry = route().params.get("country") || "";
  const activeStorage = route().params.get("storage") || "";
  return `<aside class="filter-panel ${ui.filterOpen ? "open" : ""}" aria-label="Filters">
    <button class="modal-close mobile-filter-button" data-filter-close aria-label="Close filters">${icon("close")}</button>
    <h2>Filters</h2>
    <details class="filter-group" open><summary>Department</summary><div class="filter-options">
      ${ui.data.categories.map((row) => `<label class="filter-option">
        <input type="radio" name="category" value="${esc(row.category)}" ${row.category === activeCategory ? "checked" : ""}>
        <span>${esc(row.category)} (${row.count})</span></label>`).join("")}
    </div></details>
    <details class="filter-group"><summary>Brand</summary><div class="filter-options">
      ${ui.data.brands.map((row) => `<label class="filter-option">
        <input type="radio" name="brand" value="${esc(row.brand)}" ${row.brand === activeBrand ? "checked" : ""}>
        <span>${esc(row.brand)} (${row.count})</span></label>`).join("")}
    </div></details>
    <details class="filter-group"><summary>Country</summary><div class="filter-options">
      ${ui.data.countries.map((row) => `<label class="filter-option">
        <input type="radio" name="country" value="${esc(row.country)}" ${row.country === activeCountry ? "checked" : ""}>
        <span>${esc(row.country)} (${row.count})</span></label>`).join("")}
    </div></details>
    <details class="filter-group"><summary>Refrigerated</summary><div class="filter-options">
      ${ui.data.storage_options.map((row) => `<label class="filter-option">
        <input type="radio" name="storage" value="${esc(row.storage)}" ${row.storage === activeStorage ? "checked" : ""}>
        <span>${esc(row.storage)} (${row.count})</span></label>`).join("")}
    </div></details>
    <div class="filter-group"><strong>Price Ranges</strong><p>$0.00 — $550.00</p>
      <input type="range" min="0" max="550" value="550" disabled aria-label="Maximum price"></div>
    <label class="filter-option"><input id="sale-filter" type="checkbox" ${route().params.get("sale") === "1" ? "checked" : ""}> On Sale</label>
    <button class="ghost-button button-wide" data-clear-filters>Clear</button>
  </aside>`;
}

function catalog() {
  const r = route();
  const query = r.params.get("_q") || r.params.get("q") || "";
  const rawTitle = r.category || query || (r.params.get("sale") === "1" ? "Sale" : "All Products");
  const title = rawTitle ? rawTitle.charAt(0).toUpperCase() + rawTitle.slice(1) : rawTitle;
  const displayTotal = ui.data.product_total;
  const start = ui.page * ui.limit + 1;
  const end = Math.min(displayTotal, start + ui.data.products.length - 1);
  const pages = Math.max(1, Math.ceil(displayTotal / ui.limit));
  return `<main id="main" class="page-shell catalog-page">
    <section class="catalog-banner"><div class="crumbs"><a href="/" data-nav>Home</a> › ${esc(title)}</div><h1>${esc(title)}</h1></section>
    <div class="catalog-layout">${filterPanel()}<section>
      <div class="catalog-toolbar">
        <button class="ghost-button mobile-filter-button" data-filter-open>${icon("filter")} Filter</button>
        <span>Items ${ui.data.product_total ? start : 0}-${end} of ${displayTotal}</span>
        <label>Sort by: <select id="sort-select" aria-label="Sort products">
          ${[
            ["best-sellers","Best Sellers"],["newest","New"],["price-high","Price: high to low"],
            ["price-low","Price: low to high"],["name","Product name"]
          ].map(([value, label]) => `<option value="${value}" ${r.params.get("sort") === value ? "selected" : ""}>${label}</option>`).join("")}
        </select></label>
      </div>
      ${ui.data.products.length ? productGrid(ui.data.products) : `<div class="empty-state">
        <h2>We couldn't find a match for “${esc(query || r.category || "this selection")}”</h2>
        <p>Try another search or browse all available products.</p>
        <div class="empty-actions"><button class="red-button" data-nav-url="/search">Browse all products</button>
        <button class="ghost-button" data-nav-url="/">Return home</button></div></div>`}
      <nav class="pagination" aria-label="Pagination">
        <button class="ghost-button" data-page="${Math.max(0, ui.page - 1)}" ${ui.page === 0 ? "disabled" : ""}>Previous</button>
        <span class="pill active">Page ${ui.page + 1} of ${pages}</span>
        <button class="ghost-button" data-page="${Math.min(pages - 1, ui.page + 1)}" ${ui.page >= pages - 1 ? "disabled" : ""}>Next</button>
      </nav>
    </section></div>
  </main>`;
}

function detail() {
  const product = ui.detail;
  if (!product) return '<main id="main"><div class="loading" role="status"><span class="sr-only">Loading product details</span></div></main>';
  if (product.missing) return notFound();
  const selected = product.variants.find((variant) => variant.variant_id === product.selected_variant_id)
    || product.variants.find((variant) => variant.is_default) || product.variants[0];
  const discount = selected.list_price > selected.price;
  return `<main id="main" class="product-detail">
    <nav class="breadcrumbs"><a href="/" data-nav>Home</a> › <a href="/category/${encodeURIComponent(product.category)}" data-nav>${esc(product.category)}</a> › ${esc(product.name)}</nav>
    <div class="detail-grid">
      <section class="detail-gallery" aria-label="Product gallery">${image(product)}</section>
      <section class="detail-info">
        <span class="brand">${esc(product.brand)}</span><h1>${esc(product.name)}</h1>
        <div class="price-row"><span class="price">${price(selected.price)}</span>
          ${discount ? `<span class="list-price">${price(selected.list_price)}</span>` : ""}</div>
        <label class="form-field full" for="detail-variant">Pack option
          <select id="detail-variant" data-detail-variant>
            ${product.variants.map((variant) => `<option value="${esc(variant.variant_id)}"
              ${variant.variant_id === selected.variant_id ? "selected" : ""} ${variant.available ? "" : "disabled"}>
              ${esc(variant.label)} — ${price(variant.price)}${variant.available ? "" : " (unavailable)"}</option>`).join("")}
          </select></label>
        ${ui.data.state.postal_code ? `<p class="availability ${selected.available ? "" : "unavailable"}">
          ${selected.available ? `In stock for ${esc(ui.data.location.name)}` : "Unavailable for selected region"}</p>
          <p class="detail-description">${esc(product.description || "Product details are available in the local catalog.")}</p>
          <label for="detail-quantity">Quantity</label>
          <div class="detail-actions"><select id="detail-quantity" class="quantity-select">
            ${Array.from({length: Math.min(12, product.max_per_order)}, (_, index) => `<option>${index + 1}</option>`).join("")}
          </select><button class="red-button" data-add="${esc(product.product_id)}" data-detail-add
            data-variant-id="${esc(selected.variant_id)}" ${selected.available ? "" : "disabled"}>Add to Cart</button></div>
          <button class="outline-button button-wide" style="margin-top:12px" data-favorite="${esc(product.product_id)}">
            ${icon("list")} ${product.in_favorites ? "Remove from favorites" : "Save to favorites"}</button>` : `<button class="availability-prompt" data-location
            aria-label="Set a location to check availability for ${esc(product.name)}">Set location to check availability</button>`}
      </section>
    </div>
    <table class="detail-table"><caption class="section-heading"><h2>More Details</h2></caption>
      <tbody><tr><th>Brand</th><td>${esc(product.brand)}</td></tr>
      <tr><th>Product Name</th><td>${esc(product.name)}</td></tr>
      <tr><th>SKU</th><td>${esc(product.product_id)}</td></tr>
      <tr><th>Storage</th><td>${esc(product.storage || "Dry")}</td></tr>
      <tr><th>Country</th><td>${esc(product.country || "Not specified")}</td></tr></tbody></table>
    <section class="content-section"><div class="section-heading"><h2>Reviews</h2></div>
      <p>No customer reviews are available for this item.</p>
      <button class="outline-button" data-account>Please log in to write a review.</button>
    </section>
  </main>`;
}

function cartSummary(cart) {
  return `<div class="summary-row"><span>Subtotal</span><strong>${money(cart.subtotal_cents)}</strong></div>
    <div class="summary-row"><span>Discounts</span><strong>-${money(cart.discount_cents)}</strong></div>
    <div class="summary-row"><span>Fulfillment fee</span><strong>${money(cart.fulfillment_fee_cents)}</strong></div>
    <div class="summary-row total"><span>Estimated total</span><strong>${money(cart.total_cents)}</strong></div>`;
}

const slotLabels = {
  "standard-3-5": "Standard shipping · 3–5 days",
  "today-6-8": "Today · 6–8 PM",
  "tomorrow-10-12": "Tomorrow · 10 AM–12 PM",
  "today-5-6": "Today · 5–6 PM",
  "tomorrow-9-10": "Tomorrow · 9–10 AM",
};

function fulfillmentControls() {
  if (!ui.data.state.postal_code) return `<button class="availability-prompt" data-location>Set a location to choose fulfillment</button>`;
  const method = ui.data.state.fulfillment;
  const slots = ui.data.location.slots[method] || [];
  return `<fieldset class="fulfillment-controls"><legend>Fulfillment</legend>
    <div class="fulfillment-methods">${ui.data.location.fulfillment.map((value) => `<label>
      <input type="radio" name="fulfillment" value="${esc(value)}" ${value === method ? "checked" : ""}>
      ${esc(value.charAt(0).toUpperCase() + value.slice(1))}</label>`).join("")}</div>
    <label class="form-field full">Time slot<select id="fulfillment-slot">
      ${slots.map((value) => `<option value="${esc(value)}" ${value === ui.data.state.fulfillment_slot ? "selected" : ""}>
        ${esc(slotLabels[value] || value)}</option>`).join("")}</select></label>
    <small>Availability and fees are local demo estimates for ${esc(ui.data.location.name)}.</small>
  </fieldset>`;
}

function cartPage() {
  const cart = ui.data.cart;
  if (!cart.items.length) return `<main id="main" class="cart-page"><h1 class="page-title">Your Cart</h1>
    <div class="empty-state"><h2>Your cart is empty.</h2><p>Search the local H Mart catalog to begin.</p>
    <button class="red-button" data-nav-url="/search">Shop groceries</button></div></main>`;
  const hasUnavailable = cart.items.some((item) => !item.available);
  return `<main id="main" class="cart-page"><h1 class="page-title">Your Cart</h1><div class="two-column">
    <section class="panel">${cart.items.map((item) => `<article class="cart-item">
      ${image(item)}<div><h3><a href="/${encodeURIComponent(item.slug)}/p" data-nav>${esc(item.name)}</a></h3>
      <span class="brand">${esc(item.brand)} · ${esc(item.variant_label)}</span>
      ${item.available ? "" : '<p class="availability unavailable">Unavailable at the selected location</p>'}
      <div class="cart-controls"><label>Qty <select data-cart-qty="${esc(item.product_id)}">
        ${Array.from({length: Math.min(12, item.max_per_order)}, (_, i) => `<option value="${i + 1}" ${item.quantity === i + 1 ? "selected" : ""}>${i + 1}</option>`).join("")}
      </select></label>
      <label class="substitution-control">Local preference simulation (demo only)
        <select data-substitution="${esc(item.product_id)}" aria-label="Local preference simulation (demo only) for ${esc(item.name)}">
          <option value="best-match" ${item.substitution === "best-match" ? "selected" : ""}>Choose the closest available item</option>
          <option value="refund" ${item.substitution === "refund" ? "selected" : ""}>Refund this item</option>
          <option value="specific" ${item.substitution === "specific" ? "selected" : ""}>Use my specific choice</option>
        </select>
        <small>This is a local simulation saved on this device. The live H Mart replacement options could not be verified, and nothing is sent to H Mart.</small>
      </label>
      <button class="text-button" data-remove="${esc(item.product_id)}">Remove</button></div></div>
      <strong>${money(item.line_total_cents)}</strong></article>`).join("")}</section>
    <aside class="panel">${fulfillmentControls()}<h2>Order summary</h2>${cartSummary(cart)}
      <form class="coupon-form" data-coupon-form><input name="code" placeholder="Coupon code" aria-label="Coupon code">
      <button class="ghost-button">Apply</button></form>
      <button class="red-button button-wide" data-nav-url="/checkout" ${hasUnavailable ? "disabled" : ""}>
        ${hasUnavailable ? "Remove unavailable items to continue" : "Go to checkout"}</button>
      <p class="safe-stop">Review only. No order will be submitted.</p>
    </aside></div></main>`;
}

function checkoutPage() {
  const cart = ui.data.cart;
  if (!cart.items.length) return `<main id="main" class="checkout-page"><div class="empty-state">
    <h2>Add an item before checkout</h2><button class="red-button" data-nav-url="/search">Browse products</button>
  </div></main>`;
  const address = ui.data.state.address || {};
  const review = ui.data.state.checkout_step === "review";
  return `<main id="main" class="checkout-page"><h1 class="page-title">Checkout Review</h1>
    <div class="checkout-steps"><span class="checkout-step active">1 Address</span>
      <span class="checkout-step ${review ? "active" : ""}">2 Review</span>
      <span class="checkout-step">3 Place order</span></div>
    <div class="two-column"><section class="panel">${fulfillmentControls()}
      <h2>Service address</h2><form class="form-grid" data-checkout-form novalidate>
        <label class="form-field full">Full name<input name="name" required value="${esc(address.name || "")}"><span class="validation"></span></label>
        <label class="form-field full">Street address<input name="street" required value="${esc(address.street || "")}"><span class="validation"></span></label>
        <label class="form-field">City<input name="city" required value="${esc(address.city || "")}"><span class="validation"></span></label>
        <label class="form-field">State<input name="region" required maxlength="2" value="${esc(address.region || ui.data.location.region)}"><span class="validation"></span></label>
        <label class="form-field">ZIP code<input name="postal_code" required pattern="[0-9]{5}(-[0-9]{4})?" value="${esc(address.postal_code || ui.data.state.postal_code || "")}"><span class="validation"></span></label>
        <div class="form-field"><span>&nbsp;</span><button class="red-button">Review order</button></div>
      </form>
      ${review ? `<section class="checkout-review" aria-label="Complete order review">
        <h2>Review ready.</h2>
        <p><strong>${esc(address.name)}</strong><br>${esc(address.street)}<br>${esc(address.city)}, ${esc(address.region)} ${esc(address.postal_code)}</p>
        <h3>${esc(ui.data.state.fulfillment)} · ${esc(slotLabels[ui.data.state.fulfillment_slot] || ui.data.state.fulfillment_slot || "Select a slot")}</h3>
        ${cart.items.map((item) => `<article class="review-item"><strong>${esc(item.name)}</strong>
          <span>${esc(item.variant_label)} · Qty ${item.quantity} · ${money(item.line_total_cents)}</span>
          <small>Substitution: ${esc({"best-match":"closest available item","refund":"refund this item","specific":"specific local choice"}[item.substitution] || item.substitution)} (local simulation only)</small></article>`).join("")}
        <div class="safe-stop">No order was submitted and no payment was attempted.</div>
        <button class="ghost-button button-wide" data-prohibited-submit style="margin-top:12px">Place order (not available)</button>
      </section>` : ""}
    </section><aside class="panel"><h2>Order summary</h2>${cartSummary(cart)}
      <p>${cart.item_count} item${cart.item_count === 1 ? "" : "s"} · ${esc(ui.data.state.fulfillment)}</p>
    </aside></div></main>`;
}

function favoritesPage() {
  if (!ui.data.session.account) return accountRequired("favorites");
  const items = ui.data.products.filter((product) => ui.data.favorite_product_ids.includes(product.product_id));
  return `<main id="main" class="account-page"><h1 class="page-title">Favorites</h1>
    ${items.length ? productGrid(items) : '<div class="empty-state"><h2>No favorites yet</h2><p>Save products to find them here.</p></div>'}</main>`;
}

function accountRequired(feature) {
  return `<main id="main" class="account-page"><div class="empty-state"><h2>Sign in to view ${esc(feature)}</h2>
    <p>Your local demo account is available without any external service.</p>
    <button class="red-button" data-account>Log in / Sign up</button></div></main>`;
}

function authForms() {
  return {
    signin: `<form class="stack-form" data-auth-form="signin"><input name="email" type="email" required value="demo@hmart.local" placeholder="Email">
      <input name="password" type="password" required value="Hmart123!" placeholder="Password"><button class="red-button">Log in</button>
      <p class="demo-note">Local test account: demo@hmart.local / Hmart123!</p></form>`,
    register: `<form class="stack-form" data-auth-form="register"><input name="display_name" required placeholder="Display name">
      <input name="email" type="email" required placeholder="Email"><input name="password" type="password" minlength="8" required placeholder="Password">
      <button class="red-button">Create local account</button><p class="demo-note">Verification is delivered only to the trial browser inbox.</p></form>`,
    "register-verify": `<form class="stack-form" data-auth-form="register-verify">
      <input name="code" inputmode="numeric" minlength="6" maxlength="6" required placeholder="6-digit local verification code">
      <button class="red-button">Verify and finish registration</button>
      ${ui.localCode ? `<p class="demo-note">Local-only code: <strong data-local-code>${esc(ui.localCode)}</strong></p>` : ""}
      <p class="demo-note">Read the code from the trial browser inbox and return to this same browser session.</p></form>`,
    recovery: `<form class="stack-form" data-auth-form="recovery"><input name="email" type="email" required value="demo@hmart.local" placeholder="Email">
      <button class="red-button">Send local reset code</button><p class="demo-note">Read the verification message in your trial browser inbox.</p></form>`,
    "recovery-code": `<form class="stack-form" data-auth-form="recovery-code">
      <input name="code" inputmode="numeric" minlength="6" maxlength="6" required placeholder="6-digit local reset code">
      <button class="red-button">Verify reset code</button>
      ${ui.localCode ? `<p class="demo-note">Local-only code: <strong data-local-code>${esc(ui.localCode)}</strong></p>` : ""}
      <p class="demo-note">Invalid or expired codes fail closed and may be restarted locally.</p></form>`,
    "recovery-password": `<form class="stack-form" data-auth-form="recovery-password">
      <input name="new_password" type="password" minlength="8" required placeholder="New password">
      <button class="red-button">Replace password</button>
      <p class="demo-note">Completing recovery revokes older sessions for this local account.</p></form>`,
  };
}

function accountPage() {
  const account = ui.data.session.account;
  if (account) return `<main id="main" class="account-page"><div class="panel">
    <h1 class="page-title">My Account</h1><p>Signed in as <strong>${esc(account.display_name)}</strong><br>${esc(account.email_normalized)}</p>
    <div class="stack-form"><button class="ghost-button" data-nav-url="/favorites">Favorites</button>
    <button class="ghost-button" data-nav-url="/orders">Order History</button>
    <button class="ghost-button" data-nav-url="/support">Help & Support</button>
    <button class="red-button" data-sign-out>Sign out</button></div></div></main>`;
  const title = route().section === "registration" ? "Create a local account" : "Recover a local account";
  return `<main id="main" class="account-page"><div class="panel"><h1 class="page-title">${title}</h1>
    <p>Registration and recovery deliver verification mail only to your injected trial inbox.</p>
    ${authForms()[ui.authTab]}</div></main>`;
}

function ordersPage() {
  if (!ui.data.session.account) return accountRequired("order history");
  if (!ui.orders) return '<main id="main"><div class="loading"></div></main>';
  return `<main id="main" class="account-page"><h1 class="page-title">Order History</h1>
    ${ui.orders.map((order) => `<article class="order-card"><div class="order-head">
      <div><strong>${esc(order.order_id)}</strong><p>${esc(order.placed_at.slice(0, 10))} · ${esc(order.fulfillment)}</p></div>
      <div><strong>${esc(order.status)}</strong><p>${money(order.total_cents)}</p></div></div>
      <p>${order.items.map((item) => esc(item.name)).join(" · ")}</p>
      <button class="ghost-button" data-nav-url="/orders/${encodeURIComponent(order.order_id)}">View order details</button>
      <button class="outline-button" data-reorder="${esc(order.order_id)}">Reorder in local cart</button></article>`).join("")}
  </main>`;
}

function orderDetailsPage() {
  if (!ui.data.session.account) return accountRequired("order details");
  const order = ui.orderDetail;
  if (!order) return '<main id="main"><div class="loading"></div></main>';
  if (order.missing) return notFound();
  return `<main id="main" class="account-page"><button class="text-button" data-nav-url="/orders">← Order history</button>
    <h1 class="page-title">Order ${esc(order.order_id)}</h1><article class="panel">
      <div class="order-head"><div><strong>${esc(order.status)}</strong><p>${esc(order.placed_at.slice(0, 10))}</p></div>
      <div><strong>${money(order.total_cents)}</strong><p>${esc(order.fulfillment)}</p></div></div>
      ${order.items.map((item) => `<div class="review-item"><strong>${esc(item.name)}</strong>
        <span>Qty ${item.quantity} · ${money(item.price_cents * item.quantity)}</span></div>`).join("")}
      <p class="safe-stop">Seeded local order details. No live H Mart order is represented.</p>
      <button class="outline-button" data-reorder="${esc(order.order_id)}">Reorder available items</button>
    </article></main>`;
}

function supportPage() {
  if (!ui.data.session.account) return accountRequired("support history");
  if (!ui.cases) return '<main id="main"><div class="loading"></div></main>';
  return `<main id="main" class="account-page"><h1 class="page-title">Help & Support</h1><div class="two-column">
    <section class="panel"><h2>Local support cases</h2>${ui.cases.map((item) => `<article class="order-card">
      <strong>${esc(item.subject)}</strong><p>${esc(item.detail)}</p><span class="pill">${esc(item.status)}</span></article>`).join("")}</section>
    <section class="panel"><h2>Start a local case</h2><form class="stack-form" data-support-form>
      <input name="subject" required placeholder="Subject"><textarea name="detail" required rows="6" placeholder="How can we help?"></textarea>
      <button class="red-button">Create case</button></form><p class="safe-stop">No email or external message will be sent.</p></section>
  </div></main>`;
}

function notFound() {
  return `<main id="main" class="account-page"><div class="empty-state not-found-state"><span class="error-code">404</span>
    <h1>We couldn't find that page</h1><p>The address may have changed, but the H Mart catalog is still available.</p>
    <div class="empty-actions"><button class="red-button" data-nav-url="/">Return to H Mart home</button>
    <button class="ghost-button" data-nav-url="/search">Browse all products</button></div></div></main>`;
}

function modal() {
  if (!ui.modal) return "";
  if (ui.modal.type === "info") return `<div class="modal-backdrop" data-modal-backdrop>
    <section class="modal" role="dialog" aria-modal="true" aria-labelledby="info-title">
      <button class="modal-close" data-modal-close aria-label="Close">${icon("close")}</button>
      <h2 id="info-title">H Mart</h2><p>${esc(ui.modal.message)}</p>
      <button class="red-button" data-modal-close>Close</button>
    </section></div>`;
  const account = ui.data?.session?.account;
  if (account) return `<div class="modal-backdrop" data-modal-backdrop><section class="modal" role="dialog" aria-modal="true" aria-labelledby="account-title">
    <button class="modal-close" data-modal-close aria-label="Close">${icon("close")}</button>
    <h2 id="account-title">My Account</h2><p>Signed in as <strong>${esc(account.display_name)}</strong><br>${esc(account.email_normalized)}</p>
    <div class="stack-form"><button class="ghost-button" data-nav-url="/favorites">Favorites</button>
    <button class="ghost-button" data-nav-url="/orders">Order History</button>
    <button class="ghost-button" data-nav-url="/support">Help & Support</button>
    <button class="red-button" data-sign-out>Sign out</button></div></section></div>`;
  const forms = authForms();
  const activeTab = ui.authTab.startsWith("register") ? "register"
    : ui.authTab.startsWith("recovery") ? "recovery" : "signin";
  return `<div class="modal-backdrop" data-modal-backdrop><section class="modal" role="dialog" aria-modal="true" aria-labelledby="auth-title">
    <button class="modal-close" data-modal-close aria-label="Close">${icon("close")}</button><h2 id="auth-title">Log in / Sign up</h2>
    <div class="modal-tabs">${[["signin","Log in"],["register","Sign up"],["recovery","Recover"]].map(([id, label]) =>
      `<button class="modal-tab ${activeTab === id ? "active" : ""}" data-auth-tab="${id}">${label}</button>`).join("")}</div>
    ${forms[ui.authTab]}</section></div>`;
}

function render() {
  const r = route();
  document.body.dataset.route = r.name;
  const body = ui.loadError
    ? `<main id="main" class="empty-state load-error" role="alert"><h1>H Mart is temporarily unavailable</h1>
      <p>${esc(ui.loadError)}</p><button class="red-button" data-retry>Try again</button></main>`
    : !ui.data ? '<main id="main"><div class="loading" role="status"><span class="sr-only">Loading H Mart</span></div></main>' : ({
    home, catalog, detail, cart: cartPage, checkout: checkoutPage, account: accountPage,
    favorites: favoritesPage, orders: ordersPage, support: supportPage,
    "order-details": orderDetailsPage,
    "not-found": notFound,
  }[r.name] || notFound)();
  app.innerHTML = `${header()}${locationPanel()}${body}${footer()}${modal()}`;
  document.body.classList.toggle("modal-open", Boolean(ui.modal));
}

function paramsForBootstrap() {
  const r = route();
  const params = new URLSearchParams();
  if (r.name === "catalog") {
    if (r.params.get("_q") || r.params.get("q")) params.set("query", r.params.get("_q") || r.params.get("q"));
    if (r.category) params.set("category", r.category);
    if (r.params.get("brand")) params.set("brand", r.params.get("brand"));
    if (r.params.get("country")) params.set("country", r.params.get("country"));
    if (r.params.get("storage")) params.set("storage", r.params.get("storage"));
    if (r.params.get("sale") === "1") params.set("on_sale", "true");
    params.set("sort", r.params.get("sort") || "best-sellers");
    params.set("offset", String(ui.page * ui.limit));
  }
  params.set("limit", r.name === "home" ? "30" : String(ui.limit));
  return params;
}

async function load() {
  ui.busy = true;
  ui.loadError = "";
  render();
  try {
    ui.data = await api(`/api/bootstrap?${paramsForBootstrap()}`);
    const r = route();
    if (r.name === "account" && !ui.data.session.account) {
      const prefix = r.section === "registration" ? "register" : "recovery";
      if (!ui.authTab.startsWith(prefix)) ui.authTab = prefix;
      ui.modal = null;
    }
    if (r.name === "catalog" && (r.params.get("_q") || r.params.get("q") || "").toLowerCase() === "rice") {
      const sourceOrder = ["4474", "72", "4473", "4494", "3410"];
      const rank = new Map(sourceOrder.map((id, index) => [id, index]));
      ui.data.products.sort((left, right) =>
        (rank.get(left.product_id) ?? sourceOrder.length) - (rank.get(right.product_id) ?? sourceOrder.length)
      );
    }
    if (r.name === "detail") {
      try {
        ui.detail = await api(`/api/products/${encodeURIComponent(r.slug)}`);
      } catch (error) {
        if (error.status === 404) ui.detail = {missing: true};
        else throw error;
      }
    }
    if (r.name === "orders" && ui.data.session.account) ui.orders = (await api("/api/orders")).orders;
    if (r.name === "order-details" && ui.data.session.account) {
      try {
        ui.orderDetail = (await api(`/api/orders/${encodeURIComponent(r.orderId)}`)).order;
      } catch (error) {
        if (error.status === 404) ui.orderDetail = {missing: true};
        else throw error;
      }
    }
    if (r.name === "support" && ui.data.session.account) ui.cases = (await api("/api/support")).cases;
    if (r.name === "favorites") {
      const all = await api("/api/bootstrap?limit=240");
      ui.data.products = all.products;
    }
  } catch (error) {
    ui.loadError = error.message || "The local preview could not load this page.";
    toast(error.message, true);
  } finally {
    ui.busy = false;
    render();
  }
}

document.addEventListener("click", async (event) => {
  if (event.target instanceof Element && event.target.matches("[data-modal-backdrop]")) {
    ui.modal = null;
    render();
    return;
  }
  const target = event.target.closest("a,button");
  if (!target) return;
  if (target.matches("[data-nav]")) { event.preventDefault(); go(target.getAttribute("href")); return; }
  if (target.dataset.navUrl) { ui.modal = null; go(target.dataset.navUrl); return; }
  if (target.dataset.retry !== undefined) { await load(); return; }
  if (target.matches("[data-menu]")) {
    ui.menuOpen = !ui.menuOpen;
    render();
    if (ui.menuOpen) document.querySelector(".category-menu a")?.focus();
    return;
  }
  if (target.matches("[data-location]")) { ui.locationOpen = !ui.locationOpen; render(); return; }
  if (target.matches("[data-account]")) { ui.modal = {type: "account"}; render(); return; }
  if (target.matches("[data-modal-close]") || target.matches("[data-modal-backdrop]")) { ui.modal = null; render(); return; }
  if (target.dataset.info) { ui.modal = {type: "info", message: target.dataset.info}; render(); return; }
  if (target.dataset.search) { go(sourceSearchUrl(target.dataset.search)); return; }
  if (target.dataset.filterOpen !== undefined) { ui.filterOpen = true; render(); return; }
  if (target.dataset.filterClose !== undefined) { ui.filterOpen = false; render(); return; }
  if (target.dataset.clearFilters !== undefined) { go("/search"); return; }
  if (target.dataset.page) { ui.page = Number(target.dataset.page); await load(); return; }
  if (target.dataset.authTab) { ui.authTab = target.dataset.authTab; render(); return; }
  if (target.dataset.prohibitedSubmit !== undefined) { toast("Stopped before order submission. No external effect occurred."); return; }
  try {
    if (target.dataset.add) {
      const quantity = target.dataset.detailAdd !== undefined
        ? Number(document.querySelector("#detail-quantity")?.value || 1) : 1;
      const variantId = target.dataset.detailAdd !== undefined
        ? document.querySelector("#detail-variant")?.value : undefined;
      const cart = await api(`/api/cart/${target.dataset.add}`, {
        method: "POST", body: JSON.stringify({quantity, variant_id: variantId})
      });
      ui.data.cart = cart;
      toast("Item added to your cart");
      render();
      return;
    }
    if (target.dataset.favorite) {
      try {
        await api(`/api/favorites/${target.dataset.favorite}`, {method: "POST"});
        await load();
      } catch (error) {
        if (error.status === 401) { ui.modal = {type: "account"}; render(); }
        else throw error;
      }
      return;
    }
    if (target.dataset.remove) {
      ui.data.cart = await api(`/api/cart/${target.dataset.remove}`, {method: "DELETE"});
      render(); return;
    }
    if (target.dataset.reorder) {
      const result = await api(`/api/orders/${target.dataset.reorder}/reorder`, {method: "POST"});
      ui.data.cart = result;
      const skipped = result.skipped_items.length;
      toast(skipped ? `Available items added; ${skipped} unavailable item${skipped === 1 ? " was" : "s were"} skipped` : "Order items added to your local cart");
      go("/cart"); return;
    }
    if (target.dataset.signOut !== undefined) {
      await api("/api/auth/sign-out", {method: "POST"});
      ui.authTab = "signin"; ui.localCode = ""; ui.modal = null;
      ui.orders = null; ui.cases = null; await load(); return;
    }
  } catch (error) { toast(error.message, true); }
});

document.addEventListener("submit", async (event) => {
  const form = event.target;
  event.preventDefault();
  const values = Object.fromEntries(new FormData(form));
  try {
    if (form.matches("[data-search-form]")) {
      const query = String(values.q || "").trim();
      go(sourceSearchUrl(query));
    } else if (form.matches("[data-location-form]")) {
      const postalCode = String(values.postal_code || "").trim();
      const postalInput = form.querySelector('[name="postal_code"]');
      const error = form.querySelector("[data-location-error]");
      if (!/^[0-9]{5}(?:-[0-9]{4})?$/.test(postalCode)) {
        postalInput.setAttribute("aria-invalid", "true");
        error.textContent = "Enter a valid US postal code, such as 10001.";
        postalInput.focus();
        return;
      }
      postalInput.removeAttribute("aria-invalid");
      error.textContent = "";
      await api("/api/location", {method: "PUT", body: JSON.stringify({postal_code: postalCode, fulfillment: "shipping"})});
      ui.locationOpen = false; toast("Location set for local availability"); await load();
    } else if (form.matches("[data-coupon-form]")) {
      ui.data.cart = await api("/api/coupon", {method: "POST", body: JSON.stringify(values)});
      toast("Coupon applied"); render();
    } else if (form.matches("[data-checkout-form]")) {
      if (!form.checkValidity()) {
        form.reportValidity();
        form.querySelectorAll(":invalid").forEach((field) => {
          const validation = field.parentElement.querySelector(".validation");
          if (validation) validation.textContent = field.validationMessage;
        });
        return;
      }
      const result = await api("/api/checkout/review", {method: "POST", body: JSON.stringify(values)});
      ui.data.state.address = result.address; ui.data.state.checkout_step = "review";
      toast(result.safe_stop); render();
    } else if (form.dataset.authForm) {
      const kind = form.dataset.authForm;
      const endpoint = {
        signin: "sign-in", register: "register", "register-verify": "register/verify",
        recovery: "recovery", "recovery-code": "recovery/verify",
        "recovery-password": "recovery/complete",
      }[kind];
      const result = await api(`/api/auth/${endpoint}`, {
        method: "POST", body: JSON.stringify(values)
      });
      if (kind === "signin") {
        ui.modal = null; toast("Signed in to the local H Mart account"); await load();
      } else if (kind === "register") {
        ui.localCode = "";
        ui.authTab = "register-verify"; toast("Read the code from the trial browser inbox"); render();
      } else if (kind === "register-verify") {
        ui.localCode = ""; ui.modal = null; toast("Local account registration completed"); await load();
      } else if (kind === "recovery") {
        ui.localCode = "";
        ui.authTab = "recovery-code"; toast(result.message || "Read the local reset code"); render();
      } else if (kind === "recovery-code") {
        ui.localCode = ""; ui.authTab = "recovery-password"; toast("Reset code verified"); render();
      } else if (kind === "recovery-password") {
        ui.modal = null; toast("Password replaced; older sessions were revoked"); await load();
      } else {
        toast(result.message || "Local-only request accepted");
      }
    } else if (form.matches("[data-support-form]")) {
      await api("/api/support", {method: "POST", body: JSON.stringify(values)});
      toast("Local support case created; no message was sent");
      ui.cases = (await api("/api/support")).cases; render();
    }
  } catch (error) { toast(error.message, true); }
});

document.addEventListener("change", async (event) => {
  const target = event.target;
  const r = route();
  try {
    if (target.id === "sort-select") {
      const params = new URLSearchParams(location.search); params.set("sort", target.value);
      go(`${location.pathname}?${params}`);
    } else if (["category", "brand", "country", "storage"].includes(target.name)) {
      const params = new URLSearchParams(location.search);
      if (target.name === "category") {
        params.delete("category"); go(`/category/${encodeURIComponent(target.value)}?${params}`);
      } else {
        params.set(target.name, target.value); go(`${location.pathname}?${params}`);
      }
    } else if (target.id === "sale-filter") {
      const params = new URLSearchParams(location.search);
      target.checked ? params.set("sale", "1") : params.delete("sale");
      go(`${location.pathname}?${params}`);
    } else if (target.dataset.substitution) {
      ui.data.cart = await api(`/api/cart/${target.dataset.substitution}`, {
        method: "PATCH", body: JSON.stringify({substitution: target.value})
      });
      toast("Local preference simulation saved on this device"); render();
    } else if (target.dataset.detailVariant !== undefined) {
      ui.detail.selected_variant_id = target.value;
      render();
    } else if (target.name === "fulfillment") {
      await api("/api/location", {method: "PUT", body: JSON.stringify({
        postal_code: ui.data.state.postal_code, fulfillment: target.value
      })});
      toast("Fulfillment method updated"); await load();
    } else if (target.id === "fulfillment-slot") {
      await api("/api/location", {method: "PUT", body: JSON.stringify({
        postal_code: ui.data.state.postal_code,
        fulfillment: ui.data.state.fulfillment,
        slot: target.value,
      })});
      toast("Fulfillment time updated"); await load();
    } else if (target.dataset.cartQty) {
      ui.data.cart = await api(`/api/cart/${target.dataset.cartQty}`, {
        method: "PATCH", body: JSON.stringify({quantity: Number(target.value)})
      }); render();
    }
  } catch (error) { toast(error.message, true); }
});

window.addEventListener("popstate", () => { ui.detail = null; ui.page = 0; load(); });
document.addEventListener("keydown", (event) => {
  if (event.key !== "Escape") return;
  if (ui.menuOpen) {
    ui.menuOpen = false;
    render();
    document.querySelector('[data-menu][aria-label="Open navigation"]')?.focus();
  } else if (ui.modal) {
    ui.modal = null;
    render();
  }
});
load();