File size: 44,776 Bytes
489b6e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
"""Page bodies for the Lowe's offline clone.

Home-page structure follows the captured desktop screenshot top to bottom:
promotion strip, masthead, category nav, "Recommended Searches for You" chips,
the dark promotional hero with its brand row and savings table, the
"Members Get More" strip, then the deal cards. Everything below that fold, and
every route other than ``/`` and the account drawer, is clone-authored around
the synthetic catalog; ``scope/claims.jsonl`` records which is which.
"""

from __future__ import annotations

from typing import Any, Mapping, Sequence
from urllib.parse import urlencode

from backend import store as site_store
from ui.icons import icon
from ui.layout import Chrome, attr, esc

STAR_FULL = "★"
STAR_EMPTY = "☆"


# ---------------------------------------------------------------------------
# small components
# ---------------------------------------------------------------------------


def image_url(product: Mapping[str, Any], view: str = "front") -> str:
    return f"/img/p/{product['id']}/{view}.svg"


def price_block(product: Mapping[str, Any]) -> str:
    dollars, cents = site_store.money_parts(int(product["price_cents"]))
    was = product.get("was_cents")
    extra = ""
    if was:
        saved = int(was) - int(product["price_cents"])
        extra = (
            f'<span class="price__was">was ${esc(site_store.money(int(was)))}</span>'
            f'<span class="price__save">Save ${esc(site_store.money(saved))}</span>'
        )
    return (
        '<div class="price">'
        f'<span class="price__amount">${esc(dollars)}<sup>{esc(cents)}</sup></span>'
        f"{extra}</div>"
    )


def rating_block(product: Mapping[str, Any]) -> str:
    rating = float(product["rating"])
    filled = int(rating + 0.5)
    stars = STAR_FULL * filled + STAR_EMPTY * (5 - filled)
    average = "{:.1f}".format(rating)
    reviews = "{:,}".format(int(product["review_count"]))
    return (
        '<span class="rating">'
        f'<span class="rating__stars" aria-hidden="true">{esc(stars)}</span>'
        f"<span>{esc(average)} ({esc(reviews)} reviews)</span>"
        "</span>"
    )


def fulfillment_block(product: Mapping[str, Any], store_name: str) -> str:
    pickup = (
        f"<span><strong>Free pickup</strong> today at {esc(store_name)}</span>"
        if product["pickup_today"]
        else "<span>Not available for store pickup</span>"
    )
    delivery = (
        f"<span><strong>Free delivery</strong> in {esc(product['delivery_days'])} days</span>"
        if product["free_delivery"]
        else f"<span>Delivery in {esc(product['delivery_days'])} days</span>"
    )
    return f'<div class="fulfillment">{pickup}{delivery}</div>'


def product_card(product: Mapping[str, Any], store_name: str) -> str:
    flag = ""
    if product.get("badge"):
        flag = (
            '<span class="product-card__flag" aria-hidden="true"></span>'
            f'<span class="product-card__flag-text">{esc(product["badge"])}</span>'
        )
    return (
        '<article class="product-card">'
        f"{flag}"
        f'<a class="product-card__media" href="{attr(product["url"])}">'
        f'<img src="{attr(image_url(product))}" width="320" height="320" loading="lazy"'
        f' alt="{attr(product["title"])}"></a>'
        '<div class="product-card__body">'
        f'<span class="product-card__brand">{esc(product["brand"])}</span>'
        f'<a class="product-card__title" href="{attr(product["url"])}">'
        f'{esc(product["title"])}</a>'
        + price_block(product)
        + rating_block(product)
        + fulfillment_block(product, store_name)
        + "</div></article>"
    )


def card_grid(products: Sequence[Mapping[str, Any]], store_name: str) -> str:
    return (
        '<div class="card-grid">'
        + "".join(product_card(product, store_name) for product in products)
        + "</div>"
    )


def breadcrumbs(trail: Sequence[tuple[str, str | None]]) -> str:
    parts: list[str] = []
    for label, href in trail:
        if href:
            parts.append(f'<a href="{attr(href)}">{esc(label)}</a>')
        else:
            parts.append(f"<span>{esc(label)}</span>")
    return '<nav class="breadcrumbs shell" aria-label="Breadcrumb">' + " / ".join(parts) + "</nav>"


def _query_string(base: Mapping[str, Any], **overrides: Any) -> str:
    merged: list[tuple[str, str]] = []
    for key, value in base.items():
        if key in overrides:
            continue
        if isinstance(value, (list, tuple)):
            merged.extend((key, str(item)) for item in value)
        elif value not in (None, "", False):
            merged.append((key, str(value)))
    for key, value in overrides.items():
        if isinstance(value, (list, tuple)):
            merged.extend((key, str(item)) for item in value)
        elif value not in (None, "", False):
            merged.append((key, str(value)))
    return urlencode(merged)


# ---------------------------------------------------------------------------
# home
# ---------------------------------------------------------------------------


def home(
    chrome: Chrome,
    *,
    recommended: Sequence[str],
    deals: Sequence[Mapping[str, Any]],
    top_sellers: Sequence[Mapping[str, Any]],
) -> str:
    store_name = (chrome.store or {}).get("name", "your store")
    chips = "".join(
        f'<a class="chip" href="/search?q={attr(term.replace(" ", "+"))}">{esc(term)}</a>'
        for term in recommended
    )
    return (
        '<section class="section shell">'
        '<div class="section__head">'
        '<h2 class="section__title">Recommended Searches for You</h2>'
        '<a class="section__more" href="/departments">More Suggestions for You '
        + icon("chevron", 14)
        + "</a>"
        "</div>"
        f'<div class="chip-row">{chips}</div>'
        "</section>"
        + hero_section()
        + '<section class="section shell">'
        '<div class="section__head">'
        '<h2 class="section__title">Appliance Special Values</h2>'
        '<a class="section__more" href="/search?sort=savings">Shop all deals '
        + icon("chevron", 14)
        + "</a></div>"
        + card_grid(deals, store_name)
        + "</section>"
        '<section class="section shell">'
        '<div class="section__head">'
        '<h2 class="section__title">Top Sellers in Your Area</h2>'
        '<a class="section__more" href="/search?sort=top-sellers">Shop top sellers '
        + icon("chevron", 14)
        + "</a></div>"
        + card_grid(top_sellers, store_name)
        + "</section>"
        + services_section()
    )


def hero_section() -> str:
    brands = "".join(
        f"<span>{esc(name)}</span>"
        for name in (
            "Electrolux",
            "Frigidaire",
            "Frigidaire Gallery",
            "Frigidaire Professional",
        )
    )
    return (
        '<section class="section shell"><div class="hero">'
        '<h2 class="hero__title">Electrolux End-of-Summer Sale</h2>'
        f'<div class="hero__brands">{brands}</div>'
        '<div class="hero__panel">'
        "<div>"
        '<p class="hero__eyebrow">Frigidaire</p>'
        '<p class="hero__save">Save up to</p>'
        '<p class="hero__amount"><sup>$</sup>300</p>'
        '<p class="hero__copy">When you bundle select Frigidaire major appliances.</p>'
        '<table class="hero__table">'
        "<thead><tr><th>Save</th><th>When You Buy</th></tr></thead>"
        "<tbody>"
        "<tr><td>$100</td><td>2</td></tr>"
        "<tr><td>$200</td><td>3</td></tr>"
        "<tr><td>$300</td><td>4 or More</td></tr>"
        "</tbody></table>"
        '<a class="button button--light" href="/search?category=appliances">Shop Now</a>'
        "</div>"
        '<div class="hero__art">'
        '<img src="/static/site/img/hero-appliances.svg" width="720" height="340"'
        ' alt="Illustrated kitchen with a range, refrigerator and island">'
        "</div>"
        "</div>"
        '<div class="members">'
        "<strong>myLowe&#8217;s Rewards</strong>"
        "<span><strong>Members Get More</strong> when you spend $1,799 or more on "
        "select Frigidaire and Electrolux major appliances.</span>"
        "<span><strong>FREE</strong> Delivery and Haul Away</span>"
        "<span><strong>FREE</strong> Basic Installation and Installation Parts</span>"
        "<span>2-Year Lowe&#8217;s Protection Plan</span>"
        "</div>"
        "</div></section>"
    )


SERVICES: tuple[tuple[str, str, str, str], ...] = (
    (
        "tools",
        "Installation Services",
        "Book a local installer for appliances, flooring, windows and more.",
        "/services/installation",
    ),
    (
        "truck",
        "Delivery & Haul Away",
        "Schedule delivery to your ZIP code and have the old unit taken away.",
        "/help/delivery",
    ),
    (
        "store",
        "Store Pickup",
        "Buy online and pick up at the store you selected in the header.",
        "/help/pickup",
    ),
    (
        "points",
        "myLowe's Rewards",
        "Earn points on eligible purchases and get member-only offers.",
        "/rewards",
    ),
)


def services_section() -> str:
    cards = "".join(
        '<article class="service-card">'
        + icon(glyph, 26)
        + f"<h3>{esc(title)}</h3><p>{esc(copy)}</p>"
        f'<a class="button button--outline" href="{attr(href)}">Learn more</a>'
        "</article>"
        for glyph, title, copy, href in SERVICES
    )
    return (
        '<section class="section shell">'
        '<div class="section__head"><h2 class="section__title">How We Can Help</h2></div>'
        f'<div class="service-grid">{cards}</div>'
        "</section>"
    )


# ---------------------------------------------------------------------------
# search results
# ---------------------------------------------------------------------------


def search_results(
    chrome: Chrome,
    *,
    result: Mapping[str, Any],
    params: Mapping[str, Any],
    categories: Sequence[Mapping[str, Any]],
    brands: Sequence[str],
) -> str:
    store_name = (chrome.store or {}).get("name", "your store")
    heading = (
        f'Results for "{result["query"]}"' if result["query"] else "Shop all products"
    )
    label_by_id = {str(row["id"]): str(row["label"]) for row in categories}

    applied: list[str] = []
    for category_id in params.get("category", []):
        applied.append(
            '<a class="applied-filters__chip" href="/search?'
            f'{attr(_query_string(params, category=[c for c in params.get("category", []) if c != category_id], page=1))}">'
            f'{esc(label_by_id.get(category_id, category_id))} {icon("close", 12)}</a>'
        )
    for brand in params.get("brand", []):
        applied.append(
            '<a class="applied-filters__chip" href="/search?'
            f'{attr(_query_string(params, brand=[b for b in params.get("brand", []) if b != brand], page=1))}">'
            f'{esc(brand)} {icon("close", 12)}</a>'
        )
    if params.get("min_price") or params.get("max_price"):
        applied.append(
            '<a class="applied-filters__chip" href="/search?'
            f'{attr(_query_string(params, min_price="", max_price="", page=1))}">'
            f'${esc(params.get("min_price") or "0")}&ndash;${esc(params.get("max_price") or "any")} '
            f'{icon("close", 12)}</a>'
        )
    if params.get("rating"):
        applied.append(
            '<a class="applied-filters__chip" href="/search?'
            f'{attr(_query_string(params, rating="", page=1))}">'
            f'{esc(params["rating"])}+ stars {icon("close", 12)}</a>'
        )
    for flag, label in (("pickup", "Pickup today"), ("free_delivery", "Free delivery")):
        if params.get(flag):
            applied.append(
                '<a class="applied-filters__chip" href="/search?'
                f'{attr(_query_string(params, **{flag: "", "page": 1}))}">'
                f'{esc(label)} {icon("close", 12)}</a>'
            )
    applied_html = (
        f'<div class="applied-filters">{"".join(applied)}'
        '<a class="applied-filters__chip" href="/search?'
        f'{attr(_query_string({"q": params.get("q", ""), "sort": params.get("sort", "relevance")}))}">'
        "Clear all</a></div>"
        if applied
        else ""
    )

    sort_options = "".join(
        f'<option value="{attr(key)}"'
        + (" selected" if params.get("sort", "relevance") == key else "")
        + f">{esc(label)}</option>"
        for key, label in site_store.SORT_OPTIONS
    )

    body = (
        card_grid(result["products"], store_name)
        if result["products"]
        else (
            '<div class="empty-state"><p><strong>No results.</strong></p>'
            "<p>Try fewer filters or a different search term. This offline clone "
            "carries a fixed synthetic catalog, so it will not match every real "
            "Lowe&#8217;s product.</p>"
            '<p><a class="button button--outline" href="/search">Browse everything</a></p>'
            "</div>"
        )
    )

    return (
        breadcrumbs([("Home", "/"), ("Search results", None)])
        + '<div class="shell">'
        f'<h1 class="page-title">{esc(heading)}</h1>'
        '<div class="results-layout">'
        + _filters_form(params, categories, brands, result)
        + "<section>"
        + applied_html
        + '<div class="results-head">'
        '<p class="results-head__count">'
        + (
            f'Showing {esc(result["first_index"])}&ndash;{esc(result["last_index"])} of '
            f'{esc(result["total"])} results'
            if result["total"]
            else "0 results"
        )
        + "</p>"
        '<form method="get" action="/search">'
        + _hidden_params(params, drop={"sort", "page"})
        + '<label class="visually-hidden" for="sort-select">Sort by</label>'
        '<select class="field__control" id="sort-select" name="sort" data-autosubmit>'
        + sort_options
        + "</select>"
        '<button class="visually-hidden" type="submit">Sort</button>'
        "</form>"
        "</div>"
        + body
        + _pagination(result, params)
        + "</section></div></div>"
    )


def _hidden_params(params: Mapping[str, Any], *, drop: set[str]) -> str:
    fields: list[str] = []
    for key, value in params.items():
        if key in drop:
            continue
        values = value if isinstance(value, (list, tuple)) else [value]
        for item in values:
            if item in (None, "", False):
                continue
            fields.append(
                f'<input type="hidden" name="{attr(key)}" value="{attr(item)}">'
            )
    return "".join(fields)


def _filters_form(
    params: Mapping[str, Any],
    categories: Sequence[Mapping[str, Any]],
    brands: Sequence[str],
    result: Mapping[str, Any],
) -> str:
    selected_categories = set(params.get("category", []))
    selected_brands = set(params.get("brand", []))
    facet_categories = result["facet_categories"]
    facet_brands = result["facet_brands"]

    category_options = "".join(
        '<label class="filters__option"><input type="checkbox" name="category"'
        f' value="{attr(row["id"])}"'
        + (" checked" if str(row["id"]) in selected_categories else "")
        + f'><span>{esc(row["label"])}</span>'
        + (
            f'<span class="results-head__count">({esc(facet_categories.get(str(row["id"]), 0))})</span>'
            if facet_categories.get(str(row["id"]))
            else ""
        )
        + "</label>"
        for row in categories
    )
    brand_options = "".join(
        '<label class="filters__option"><input type="checkbox" name="brand"'
        f' value="{attr(name)}"'
        + (" checked" if name in selected_brands else "")
        + f'><span>{esc(name)}</span>'
        + (
            f'<span class="results-head__count">({esc(facet_brands.get(name, 0))})</span>'
            if facet_brands.get(name)
            else ""
        )
        + "</label>"
        for name in brands
    )
    rating_options = "".join(
        '<label class="filters__option"><input type="radio" name="rating"'
        f' value="{attr(value)}"'
        + (" checked" if str(params.get("rating", "")) == value else "")
        + f'><span>{esc(value)} stars &amp; up</span></label>'
        for value in ("4.5", "4", "3")
    )

    return (
        '<form class="filters" method="get" action="/search">'
        f'<input type="hidden" name="q" value="{attr(params.get("q", ""))}">'
        f'<input type="hidden" name="sort" value="{attr(params.get("sort", "relevance"))}">'
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Department</legend>'
        + category_options
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Brand</legend>'
        + brand_options
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Price</legend>'
        '<div class="filters__price">'
        '<label class="visually-hidden" for="min-price">Minimum price</label>'
        '<input class="field__control" id="min-price" type="number" min="0" step="1"'
        f' name="min_price" value="{attr(params.get("min_price", ""))}" placeholder="Min">'
        '<label class="visually-hidden" for="max-price">Maximum price</label>'
        '<input class="field__control" id="max-price" type="number" min="0" step="1"'
        f' name="max_price" value="{attr(params.get("max_price", ""))}" placeholder="Max">'
        "</div></fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Customer Rating</legend>'
        + rating_options
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Availability</legend>'
        '<label class="filters__option"><input type="checkbox" name="pickup" value="1"'
        + (" checked" if params.get("pickup") else "")
        + "><span>Pickup today</span></label>"
        '<label class="filters__option"><input type="checkbox" name="free_delivery"'
        ' value="1"'
        + (" checked" if params.get("free_delivery") else "")
        + "><span>Free delivery</span></label>"
        "</fieldset>"
        '<button class="button button--primary button--block" type="submit">'
        "Apply filters</button>"
        "</form>"
    )


def _pagination(result: Mapping[str, Any], params: Mapping[str, Any]) -> str:
    if result["page_count"] <= 1:
        return ""
    links: list[str] = []
    if result["page"] > 1:
        links.append(
            '<a class="pagination__link" rel="prev" href="/search?'
            f'{attr(_query_string(params, page=result["page"] - 1))}">Previous</a>'
        )
    for number in range(1, int(result["page_count"]) + 1):
        current = ' aria-current="page"' if number == result["page"] else ""
        links.append(
            f'<a class="pagination__link"{current} href="/search?'
            f'{attr(_query_string(params, page=number))}">{esc(number)}</a>'
        )
    if result["page"] < result["page_count"]:
        links.append(
            '<a class="pagination__link" rel="next" href="/search?'
            f'{attr(_query_string(params, page=result["page"] + 1))}">Next</a>'
        )
    return (
        '<nav class="pagination" aria-label="Search result pages">'
        + "".join(links)
        + "</nav>"
    )


# ---------------------------------------------------------------------------
# product detail
# ---------------------------------------------------------------------------


def product_detail(
    chrome: Chrome,
    *,
    product: Mapping[str, Any],
    category_label: str,
    related: Sequence[Mapping[str, Any]],
    message: str = "",
    error: str = "",
) -> str:
    store_name = (chrome.store or {}).get("name", "your store")
    thumbs = "".join(
        f'<button class="pdp__thumb" type="button" aria-current="{"true" if index == 0 else "false"}"'
        f' data-gallery-thumb="{attr(image_url(product, view))}"'
        f' data-gallery-alt="{attr(product["title"])} ({esc(view)} view)">'
        f'<img src="{attr(image_url(product, view))}" width="80" height="80"'
        f' alt="{attr(product["title"])} {esc(view)} view"></button>'
        for index, view in enumerate(("front", "angle", "detail"))
    )
    specs = "".join(
        f"<tr><th scope=\"row\">{esc(name)}</th><td>{esc(value)}</td></tr>"
        for name, value in product["specs"]
    )
    notices = ""
    if message:
        notices += f'<p class="notice">{esc(message)}</p>'
    if error:
        notices += f'<p class="notice notice--error">{esc(error)}</p>'

    pickup_disabled = "" if product["pickup_today"] else " disabled"
    pickup_note = (
        f"Free pickup today at {store_name}"
        if product["pickup_today"]
        else "Not available for pickup"
    )
    return (
        breadcrumbs(
            [
                ("Home", "/"),
                (category_label, f"/search?category={product['category_id']}"),
                (product["title"], None),
            ]
        )
        + '<div class="shell section">'
        + notices
        + '<div class="pdp">'
        f'<div class="pdp__thumbs">{thumbs}</div>'
        '<div class="pdp__stage">'
        f'<img src="{attr(image_url(product))}" width="320" height="320"'
        f' alt="{attr(product["title"])}" data-gallery-stage>'
        "</div>"
        '<div class="pdp__buybox">'
        f'<p class="product-card__brand">{esc(product["brand"])}</p>'
        f'<h1 class="pdp__title">{esc(product["title"])}</h1>'
        + rating_block(product)
        + price_block(product)
        + f"<p>{esc(product['summary'])}</p>"
        f'<p class="results-head__count">Model # {esc(product["model_number"])} '
        f'&middot; Item # {esc(product["id"])}</p>'
        '<form method="post" action="/cart/add">'
        f'<input type="hidden" name="product_id" value="{attr(product["id"])}">'
        f'<input type="hidden" name="next" value="{attr(product["url"])}">'
        '<div class="fulfillment-choice">'
        '<label><span><input type="radio" name="fulfillment" value="pickup"'
        + (" checked" if product["pickup_today"] else "")
        + pickup_disabled
        + ">Pickup</span>"
        f"<span>{esc(pickup_note)}</span></label>"
        '<label><span><input type="radio" name="fulfillment" value="delivery"'
        + ("" if product["pickup_today"] else " checked")
        + ">Delivery</span>"
        f'<span>{esc("Free" if product["free_delivery"] else "Fee applies")} in '
        f'{esc(product["delivery_days"])} days to {esc(chrome.postal_code)}</span></label>'
        "</div>"
        '<div class="cart-line__actions">'
        '<div class="quantity" data-quantity>'
        '<button type="button" data-quantity-step="-1" aria-label="Decrease quantity">'
        "&minus;</button>"
        '<label class="visually-hidden" for="pdp-quantity">Quantity</label>'
        '<input id="pdp-quantity" type="number" name="quantity" value="1" min="1"'
        ' max="99" step="1">'
        '<button type="button" data-quantity-step="1" aria-label="Increase quantity">'
        "+</button></div>"
        '<button class="button button--primary" type="submit">Add to Cart</button>'
        "</div></form>"
        + fulfillment_block(product, store_name)
        + f'<p class="results-head__count">{esc(product["stock"])} in stock at this '
        "location in the clone&#8217;s synthetic inventory.</p>"
        "</div></div>"
        '<section class="section">'
        "<h2 class=\"section__title\">Specifications</h2>"
        f'<table class="spec-table"><tbody>{specs}</tbody></table>'
        "</section>"
        + (
            '<section class="section">'
            '<div class="section__head"><h2 class="section__title">'
            "Customers also viewed</h2></div>" + card_grid(related, store_name) + "</section>"
            if related
            else ""
        )
        + "</div>"
    )


# ---------------------------------------------------------------------------
# cart
# ---------------------------------------------------------------------------


def cart_page(
    chrome: Chrome,
    *,
    cart: Mapping[str, Any],
    totals: Mapping[str, Any],
    message: str = "",
    error: str = "",
) -> str:
    if not cart["items"]:
        return (
            breadcrumbs([("Home", "/"), ("Cart", None)])
            + '<div class="shell section">'
            '<h1 class="page-title">Your cart is empty</h1>'
            '<div class="empty-state"><p>Nothing has been added yet.</p>'
            '<p><a class="button button--primary" href="/search?sort=top-sellers">'
            "Shop top sellers</a></p></div></div>"
        )

    lines = "".join(_cart_line(item) for item in cart["items"])
    notices = ""
    if message:
        notices += f'<p class="notice">{esc(message)}</p>'
    if error:
        notices += f'<p class="notice notice--error">{esc(error)}</p>'
    return (
        breadcrumbs([("Home", "/"), ("Cart", None)])
        + '<div class="shell section">'
        f'<h1 class="page-title">Cart ({esc(cart["units"])} '
        f'{esc("item" if cart["units"] == 1 else "items")})</h1>'
        + notices
        + '<div class="cart-layout"><section>'
        + lines
        + "</section>"
        + summary_panel(totals, cart, action="/checkout", action_label="Proceed to Checkout")
        + "</div></div>"
    )


def _cart_line(item: Mapping[str, Any]) -> str:
    art = "/img/p/{}/front.svg".format(int(item["product_id"]))
    return (
        '<article class="cart-line">'
        '<div class="cart-line__media">'
        f'<img src="{attr(art)}" width="320"'
        f' height="320" alt="{attr(item["title"])}"></div>'
        "<div>"
        f'<p class="product-card__brand">{esc(item["brand"])}</p>'
        f'<a class="product-card__title" href="{attr(item["url"])}">{esc(item["title"])}</a>'
        '<div class="cart-line__actions">'
        '<form method="post" action="/cart/update">'
        f'<input type="hidden" name="item_id" value="{attr(item["item_id"])}">'
        '<div class="quantity" data-quantity>'
        '<button type="button" data-quantity-step="-1" aria-label="Decrease quantity">'
        "&minus;</button>"
        f'<label class="visually-hidden" for="qty-{attr(item["item_id"])}">Quantity for '
        f'{esc(item["title"])}</label>'
        f'<input id="qty-{attr(item["item_id"])}" type="number" name="quantity"'
        f' value="{attr(item["quantity"])}" min="0" max="99" step="1">'
        '<button type="button" data-quantity-step="1" aria-label="Increase quantity">'
        "+</button></div>"
        '<button class="button button--outline" type="submit">Update</button>'
        "</form>"
        '<form method="post" action="/cart/remove">'
        f'<input type="hidden" name="item_id" value="{attr(item["item_id"])}">'
        '<button class="link-button" type="submit">Remove</button>'
        "</form>"
        '<form method="post" action="/cart/fulfillment">'
        f'<input type="hidden" name="item_id" value="{attr(item["item_id"])}">'
        '<input type="hidden" name="fulfillment" value="'
        + ("delivery" if item["fulfillment"] == "pickup" else "pickup")
        + '">'
        '<button class="link-button" type="submit">Switch to '
        + esc("delivery" if item["fulfillment"] == "pickup" else "pickup")
        + "</button></form>"
        "</div>"
        '<p class="fulfillment"><span><strong>'
        + esc("Store pickup" if item["fulfillment"] == "pickup" else "Delivery")
        + "</strong></span></p>"
        "</div>"
        '<div class="cart-line__price">'
        f'<span class="price__amount">${esc(site_store.money(int(item["line_total_cents"])))}</span>'
        "</div>"
        "</article>"
    )


def summary_panel(
    totals: Mapping[str, Any],
    cart: Mapping[str, Any],
    *,
    action: str | None = None,
    action_label: str = "",
    submit: bool = False,
) -> str:
    rows = [
        ("Subtotal", f"${site_store.money(int(totals['subtotal_cents']))}"),
        (
            "Savings",
            f"-${site_store.money(int(totals['savings_cents']))}"
            if totals["savings_cents"]
            else "$0.00",
        ),
        (
            "Delivery",
            "FREE"
            if totals["delivery_cents"] == 0
            else f"${site_store.money(int(totals['delivery_cents']))}",
        ),
        ("Estimated tax", f"${site_store.money(int(totals['tax_cents']))}"),
    ]
    row_html = "".join(
        f'<div class="summary__row"><span>{esc(label)}</span><span>{esc(value)}</span></div>'
        for label, value in rows
    )
    cta = ""
    if action and not submit:
        cta = (
            f'<a class="button button--primary button--block" href="{attr(action)}">'
            f"{esc(action_label)}</a>"
        )
    elif submit:
        cta = (
            '<button class="button button--primary button--block" type="submit">'
            f"{esc(action_label)}</button>"
        )
    return (
        '<aside class="summary">'
        '<h2 class="section__title">Order Summary</h2>'
        f'<div class="summary__row"><span>{esc(cart["units"])} items</span>'
        f'<span>{esc(cart["count"])} lines</span></div>'
        + row_html
        + '<div class="summary__row summary__row--total"><span>Total</span>'
        f'<span>${esc(site_store.money(int(totals["total_cents"])))}</span></div>'
        + cta
        + "</aside>"
    )


# ---------------------------------------------------------------------------
# checkout
# ---------------------------------------------------------------------------


def checkout_page(
    chrome: Chrome,
    *,
    cart: Mapping[str, Any],
    totals: Mapping[str, Any],
    form: Mapping[str, Any],
    errors: Mapping[str, str],
    scenarios: Sequence[Mapping[str, str]],
    payment: Mapping[str, Any] | None = None,
) -> str:
    fulfillment = str(form.get("fulfillment", "pickup"))
    store_options = "".join(
        f'<option value="{attr(item["id"])}"'
        + (" selected" if form.get("store_id") == item["id"] else "")
        + f'>{esc(item["name"])} &middot; {esc(item["city"])}, {esc(item["state"])}</option>'
        for item in chrome.stores
    )
    scenario_inputs = "".join(
        '<label class="filters__option">'
        f'<input type="radio" name="scenario_id" value="{attr(item["id"])}"'
        + (" checked" if form.get("scenario_id") == item["id"] else "")
        + f'><span>{esc(item["display_label"])}</span>'
        f'<span class="tag tag--{attr(item["outcome"])}">{esc(item["outcome"])}</span>'
        "</label>"
        for item in scenarios
    )

    payment_notice = ""
    if payment:
        status = str(payment["status"])
        wording = {
            "DECLINED": "The local sandbox declined this simulated payment. Nothing "
            "was charged and your cart is unchanged. Pick another scenario to retry.",
            "RETRYABLE": "The local sandbox returned a retryable result. Nothing was "
            "charged and your cart is unchanged. Submit again to retry.",
        }.get(status, "The local sandbox returned an unexpected result.")
        payment_notice = (
            '<p class="notice notice--error"><span class="tag tag--'
            + attr(status.casefold())
            + f'">{esc(status)}</span> {esc(wording)}</p>'
        )

    error_summary = ""
    if errors:
        error_summary = (
            '<p class="notice notice--error">Check the highlighted fields below.</p>'
        )

    def field_error(name: str) -> str:
        return (
            f'<span class="field__error">{esc(errors[name])}</span>'
            if name in errors
            else ""
        )

    return (
        breadcrumbs([("Home", "/"), ("Cart", "/cart"), ("Checkout", None)])
        + '<div class="shell section">'
        '<h1 class="page-title">Checkout</h1>'
        '<ol class="steps">'
        '<li>Cart</li>'
        '<li aria-current="step">Fulfillment &amp; payment</li>'
        "<li>Confirmation</li></ol>"
        + error_summary
        + payment_notice
        + '<form method="post" action="/checkout">'
        '<div class="checkout-layout"><section>'
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">How do you want it?</legend>'
        '<label class="filters__option"><input type="radio" name="fulfillment"'
        ' value="pickup"'
        + (" checked" if fulfillment == "pickup" else "")
        + "><span>Store pickup (free)</span></label>"
        '<label class="filters__option"><input type="radio" name="fulfillment"'
        ' value="delivery"'
        + (" checked" if fulfillment == "delivery" else "")
        + "><span>Delivery to an address</span></label>"
        + field_error("fulfillment")
        + '<label class="field" for="checkout-store">'
        '<span class="field__label">Pickup store</span>'
        '<select class="field__control" id="checkout-store" name="store_id">'
        + store_options
        + "</select></label>"
        + field_error("store_id")
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Contact</legend>'
        + _text_field("first_name", "First name", form, errors, "given-name")
        + _text_field("last_name", "Last name", form, errors, "family-name")
        + _text_field("email", "Email", form, errors, "email", kind="email")
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Delivery address</legend>'
        '<p class="results-head__count">Required only when delivery is selected.</p>'
        + _text_field("address_1", "Street address", form, errors, "address-line1")
        + _text_field(
            "address_2", "Apartment, suite (optional)", form, errors, "address-line2"
        )
        + _text_field("city", "City", form, errors, "address-level2")
        + _text_field("state", "State (2 letters)", form, errors, "address-level1")
        + _text_field("zip", "ZIP code", form, errors, "postal-code")
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Local sandbox payment</legend>'
        '<p class="notice notice--sandbox"><strong>Local sandbox only.</strong> This '
        "clone never accepts a card number, CVV, expiry, bank or wallet credential. "
        "Choose one deterministic outcome below; the amount, currency and order "
        "fingerprint are computed on the server from your saved cart.</p>"
        + scenario_inputs
        + field_error("scenario_id")
        + "</fieldset>"
        + field_error("cart")
        + "</section>"
        + summary_panel(totals, cart, action_label="Place order", submit=True)
        + "</div></form></div>"
    )


def _text_field(
    name: str,
    label: str,
    form: Mapping[str, Any],
    errors: Mapping[str, str],
    autocomplete: str,
    *,
    kind: str = "text",
) -> str:
    error = (
        f'<span class="field__error">{esc(errors[name])}</span>' if name in errors else ""
    )
    return (
        f'<label class="field" for="checkout-{attr(name)}">'
        f'<span class="field__label">{esc(label)}</span>'
        f'<input class="field__control" id="checkout-{attr(name)}" type="{attr(kind)}"'
        f' name="{attr(name)}" value="{attr(form.get(name, ""))}"'
        f' autocomplete="{attr(autocomplete)}"></label>{error}'
    )


# ---------------------------------------------------------------------------
# order confirmation + account
# ---------------------------------------------------------------------------


def _order_line(item: Mapping[str, Any]) -> str:
    art = "/img/p/{}/front.svg".format(int(item["product_id"]))
    return (
        '<article class="cart-line">'
        f'<div class="cart-line__media"><img src="{attr(art)}"'
        f' width="320" height="320" alt="{attr(item["title"])}"></div>'
        f'<div><p class="product-card__brand">{esc(item["brand"])}</p>'
        f'<a class="product-card__title" href="/pd/{attr(item["slug"])}/{attr(item["product_id"])}">'
        f'{esc(item["title"])}</a>'
        f'<p class="fulfillment"><span>Qty {esc(item["quantity"])} &middot; '
        + esc("Store pickup" if item["fulfillment"] == "pickup" else "Delivery")
        + "</span></p></div>"
        f'<div class="cart-line__price"><span class="price__amount">'
        f'${esc(site_store.money(int(item["line_total_cents"])))}</span></div>'
        "</article>"
    )


def order_confirmation(order: Mapping[str, Any]) -> str:
    items = "".join(_order_line(item) for item in order["items"])
    if order["fulfillment"] == "pickup":
        store = order.get("store") or {}
        where = (
            f"Pickup at {store.get('name', 'your store')}, {store.get('city', '')}, "
            f"{store.get('state', '')}"
        )
    else:
        address = order.get("address") or {}
        where = (
            f"Delivery to {address.get('address_1', '')}, {address.get('city', '')}, "
            f"{address.get('state', '')} {address.get('zip', '')}"
        )
    mail = order.get("mail") or {}
    return (
        breadcrumbs([("Home", "/"), ("Orders", "/account/orders"), (order["order_number"], None)])
        + '<div class="shell section">'
        '<div class="order-banner">'
        f'<h1 class="page-title">Order {esc(order["order_number"])} is placed</h1>'
        f'<p>{esc(where)}</p>'
        f'<p><span class="tag tag--approved">payment {esc(order["payment_status"])}</span> '
        f'<span class="tag">scenario {esc(order["scenario_id"])}</span> '
        f'<span class="tag">mail {esc(mail.get("status", "none"))}</span></p>'
        '<p class="results-head__count">Simulated locally. No payment was taken and '
        "no message was delivered; the confirmation was written to this clone&#8217;s "
        "local outbox with template variables only.</p>"
        "</div>"
        '<div class="cart-layout"><section>'
        + items
        + "</section>"
        + summary_panel(
            {
                "subtotal_cents": order["subtotal_cents"],
                "savings_cents": order["savings_cents"],
                "delivery_cents": order["delivery_cents"],
                "tax_cents": order["tax_cents"],
                "total_cents": order["total_cents"],
            },
            {
                "units": sum(int(item["quantity"]) for item in order["items"]),
                "count": len(order["items"]),
            },
            action="/search?sort=top-sellers",
            action_label="Keep shopping",
        )
        + "</div></div>"
    )


def account_page(
    chrome: Chrome, *, account: Mapping[str, Any], orders: Sequence[Mapping[str, Any]]
) -> str:
    order_rows = "".join(
        "<tr>"
        f'<th scope="row"><a href="/orders/{attr(order["order_number"])}">'
        f'{esc(order["order_number"])}</a></th>'
        f'<td>{esc(order["fulfillment"])}</td>'
        f'<td>{esc(len(order["items"]))} items</td>'
        f'<td>${esc(site_store.money(int(order["total_cents"])))}</td>'
        f'<td><span class="tag tag--approved">{esc(order["payment_status"])}</span></td>'
        "</tr>"
        for order in orders
    )
    table = (
        '<table class="spec-table"><thead><tr><th>Order</th><th>Fulfillment</th>'
        "<th>Items</th><th>Total</th><th>Payment</th></tr></thead>"
        f"<tbody>{order_rows}</tbody></table>"
        if orders
        else '<div class="empty-state"><p>No orders in this clone yet.</p></div>'
    )
    return (
        breadcrumbs([("Home", "/"), ("Account", None)])
        + '<div class="shell section">'
        f'<h1 class="page-title">Hi, {esc(account.get("display_name", ""))}</h1>'
        f'<p>Signed in as {esc(account.get("contact_display", ""))}.</p>'
        '<section class="section"><h2 class="section__title">Order Status</h2>'
        + table
        + "</section>"
        '<form method="post" action="/account/sign-out">'
        '<button class="button button--outline" type="submit">Sign Out</button>'
        "</form>"
        "</div>"
    )


def orders_page(chrome: Chrome, *, orders: Sequence[Mapping[str, Any]]) -> str:
    if not orders:
        return (
            breadcrumbs([("Home", "/"), ("Order Status", None)])
            + '<div class="shell section"><h1 class="page-title">Order Status</h1>'
            '<div class="empty-state"><p>This browser session has no orders yet.</p>'
            '<p><a class="button button--outline" href="/cart">Go to your cart</a></p>'
            "</div></div>"
        )
    rows = "".join(
        "<tr>"
        f'<th scope="row"><a href="/orders/{attr(order["order_number"])}">'
        f'{esc(order["order_number"])}</a></th>'
        f'<td>{esc(order["customer_name"])}</td>'
        f'<td>{esc(order["fulfillment"])}</td>'
        f'<td>${esc(site_store.money(int(order["total_cents"])))}</td>'
        "</tr>"
        for order in orders
    )
    return (
        breadcrumbs([("Home", "/"), ("Order Status", None)])
        + '<div class="shell section"><h1 class="page-title">Order Status</h1>'
        '<table class="spec-table"><thead><tr><th>Order</th><th>Name</th>'
        "<th>Fulfillment</th><th>Total</th></tr></thead>"
        f"<tbody>{rows}</tbody></table></div>"
    )


# ---------------------------------------------------------------------------
# supporting pages
# ---------------------------------------------------------------------------


def departments_page(
    chrome: Chrome, *, categories: Sequence[Mapping[str, Any]], counts: Mapping[str, int]
) -> str:
    cards = "".join(
        '<article class="service-card">'
        + icon("grid", 24)
        + f'<h3>{esc(row["label"])}</h3>'
        f'<p>{esc(counts.get(str(row["id"]), 0))} products in this clone.</p>'
        f'<a class="button button--outline" href="/search?category={attr(row["id"])}">'
        "Shop department</a></article>"
        for row in categories
    )
    return (
        breadcrumbs([("Home", "/"), ("Shop All", None)])
        + '<div class="shell section"><h1 class="page-title">Shop All Departments</h1>'
        f'<div class="service-grid">{cards}</div></div>'
    )


def stores_page(chrome: Chrome, *, stores: Sequence[Mapping[str, Any]]) -> str:
    cards = "".join(
        '<article class="service-card">'
        + icon("store", 24)
        + f'<h3>{esc(row["name"])}</h3>'
        f'<p>{esc(row["city"])}, {esc(row["state"])} {esc(row["zip"])}<br>'
        f'Closes at {esc(row["closes_at"])}</p>'
        '<form method="post" action="/preferences">'
        f'<input type="hidden" name="store_id" value="{attr(row["id"])}">'
        f'<input type="hidden" name="postal_code" value="{attr(row["zip"])}">'
        '<input type="hidden" name="next" value="/stores">'
        '<button class="button button--outline" type="submit">Make this my store</button>'
        "</form></article>"
        for row in stores
    )
    return (
        breadcrumbs([("Home", "/"), ("Store Locator", None)])
        + '<div class="shell section"><h1 class="page-title">Store Locator</h1>'
        '<p>Four synthetic stores back the pickup selector in this clone.</p>'
        f'<div class="service-grid">{cards}</div></div>'
    )


def info_page(chrome: Chrome, *, title: str, blocks: Sequence[str]) -> str:
    body = "".join(f"<p>{esc(block)}</p>" for block in blocks)
    return (
        breadcrumbs([("Home", "/"), (title, None)])
        + f'<div class="shell section"><h1 class="page-title">{esc(title)}</h1>'
        f"{body}</div>"
    )


def external_boundary(chrome: Chrome, *, slug: str) -> str:
    return (
        breadcrumbs([("Home", "/"), ("External link", None)])
        + '<div class="shell section"><h1 class="page-title">External link boundary</h1>'
        '<p class="notice">This offline clone does not open third-party or legal '
        f"destinations. The source page linked to <strong>{esc(slug)}</strong>; no "
        "remote request was made and nothing was fetched.</p>"
        '<p><a class="button button--outline" href="/">Return to the home page</a></p>'
        "</div>"
    )


def not_found(chrome: Chrome, *, path: str) -> str:
    return (
        '<div class="shell section"><h1 class="page-title">We can&#8217;t find that page</h1>'
        f"<p>Nothing is served at <code>{esc(path)}</code> in this offline clone.</p>"
        '<p><a class="button button--primary" href="/">Back to the home page</a> '
        '<a class="button button--outline" href="/departments">Shop all departments</a></p>'
        "</div>"
    )