# -*- coding: utf-8 -*-
"""
Superium — shared page chrome
=============================

Head, header, mega menu, mobile drawer, footer, floating buttons and the
script block. ``page()`` assembles them around a body fragment.

Every page in the package is produced from these functions by
``tools/build_pages.py``, which is why the header markup is identical
everywhere — edit it here once and rebuild.
"""

from __future__ import annotations

BRAND = "سوپردوپر مارکت"
BRAND_LATIN = "SuperDouper"

# --------------------------------------------------------------------------
# Icons — a small inline set. Stroke inherits currentColor.
# --------------------------------------------------------------------------

ICONS = {
    "search": '<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4" stroke-linecap="round"/>',
    "cart": (
        '<path d="M3 4h2l2.4 11.2a2 2 0 002 1.6h7.8a2 2 0 002-1.6L21 8H6" '
        'stroke-linecap="round" stroke-linejoin="round"/>'
        '<circle cx="10" cy="20" r="1.4"/><circle cx="18" cy="20" r="1.4"/>'
    ),
    "user": (
        '<circle cx="12" cy="8" r="4"/>'
        '<path d="M4 21c0-4 3.6-6.5 8-6.5s8 2.5 8 6.5" stroke-linecap="round"/>'
    ),
    "menu": '<path d="M3 6h18M3 12h18M3 18h18" stroke-linecap="round"/>',
    "close": '<path d="M6 6l12 12M18 6L6 18" stroke-linecap="round"/>',
    "pin": (
        '<path d="M12 21s7-5.7 7-11a7 7 0 10-14 0c0 5.3 7 11 7 11z" '
        'stroke-linejoin="round"/><circle cx="12" cy="10" r="2.6"/>'
    ),
    "heart": (
        '<path d="M12 20s-7.5-4.7-7.5-9.7A4.3 4.3 0 0112 7.4a4.3 4.3 0 017.5 2.9c0 5-7.5 9.7-7.5 9.7z" '
        'stroke-linejoin="round"/>'
    ),
    "plus": '<path d="M12 5v14M5 12h14" stroke-linecap="round"/>',
    "minus": '<path d="M5 12h14" stroke-linecap="round"/>',
    "trash": (
        '<path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13" stroke-linecap="round" '
        'stroke-linejoin="round"/>'
    ),
    "star": (
        '<path d="M12 4l2.5 5.1 5.6.8-4 3.9 1 5.6-5.1-2.7-5.1 2.7 1-5.6-4-3.9 5.6-.8z" '
        'fill="currentColor" stroke="none"/>'
    ),
    "chevron-start": '<path d="M15 6l-6 6 6 6" stroke-linecap="round" stroke-linejoin="round"/>',
    "chevron-end": '<path d="M9 6l6 6-6 6" stroke-linecap="round" stroke-linejoin="round"/>',
    "chevron-down": '<path d="M6 9l6 6 6-6" stroke-linecap="round" stroke-linejoin="round"/>',
    "arrow-up": '<path d="M12 19V5M6 11l6-6 6 6" stroke-linecap="round" stroke-linejoin="round"/>',
    "check": '<path d="M5 12.5l4.5 4.5L19 7" stroke-linecap="round" stroke-linejoin="round"/>',
    "check-circle": '<circle cx="12" cy="12" r="9"/><path d="M8 12.4l2.7 2.7L16 9.5" stroke-linecap="round" stroke-linejoin="round"/>',
    "truck": (
        '<path d="M3 16V6h11v10M14 10h4l3 3v3h-7" stroke-linejoin="round"/>'
        '<circle cx="7" cy="17.5" r="1.8"/><circle cx="17" cy="17.5" r="1.8"/>'
    ),
    "walk": (
        '<circle cx="13" cy="4.5" r="1.8"/>'
        '<path d="M9 21l2.5-5.5L10 12l-.5-3.5 4-1 2 3 3 1M11.5 15.5L8.5 12" '
        'stroke-linecap="round" stroke-linejoin="round"/>'
    ),
    "shield": (
        '<path d="M12 3l7 3v6c0 4.4-3 7.9-7 9-4-1.1-7-4.6-7-9V6z" stroke-linejoin="round"/>'
        '<path d="M9 12.2l2 2 4-4.2" stroke-linecap="round" stroke-linejoin="round"/>'
    ),
    "clock": '<circle cx="12" cy="12" r="9"/><path d="M12 7v5.3l3.2 2" stroke-linecap="round"/>',
    "tag": (
        '<path d="M3 12.5V4h8.5L21 13.5 12.5 22z" stroke-linejoin="round"/>'
        '<circle cx="7.8" cy="8.2" r="1.4"/>'
    ),
    "gift": (
        '<path d="M4 11h16v9H4zM3 7h18v4H3zM12 7v13" stroke-linejoin="round"/>'
        '<path d="M12 7S10.5 3 8.4 3.6 8 7 12 7zM12 7s1.5-4 3.6-3.4S16 7 12 7z" '
        'stroke-linejoin="round"/>'
    ),
    "headset": (
        '<path d="M4 14v-2a8 8 0 1116 0v2" stroke-linecap="round"/>'
        '<path d="M4 14h3v5H5.5A1.5 1.5 0 014 17.5zM20 14h-3v5h1.5a1.5 1.5 0 001.5-1.5z" '
        'stroke-linejoin="round"/>'
    ),
    "phone": (
        '<path d="M5 4h4l1.6 4-2.2 1.6a12 12 0 006 6L16 13.4l4 1.6v4a1 1 0 01-1.1 1A16.5 16.5 0 014 5.1 1 1 0 015 4z" '
        'stroke-linejoin="round"/>'
    ),
    "mail": '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 6.5l8.5 6 8.5-6" stroke-linecap="round"/>',
    "box": (
        '<path d="M12 3l8 4.2v9.6L12 21l-8-4.2V7.2z" stroke-linejoin="round"/>'
        '<path d="M4 7.2l8 4.3 8-4.3M12 11.5V21" stroke-linejoin="round"/>'
    ),
    "list": '<path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01" stroke-linecap="round"/>',
    "grid": '<rect x="3.5" y="3.5" width="7" height="7" rx="1.5"/><rect x="13.5" y="3.5" width="7" height="7" rx="1.5"/><rect x="3.5" y="13.5" width="7" height="7" rx="1.5"/><rect x="13.5" y="13.5" width="7" height="7" rx="1.5"/>',
    "filter": '<path d="M4 6h16M7 12h10M10 18h4" stroke-linecap="round"/>',
    "sort": '<path d="M7 4v16M7 20l-3-3M17 20V4M17 4l3 3" stroke-linecap="round" stroke-linejoin="round"/>',
    "logout": (
        '<path d="M10 5H6a1 1 0 00-1 1v12a1 1 0 001 1h4" stroke-linecap="round"/>'
        '<path d="M15 8l4 4-4 4M19 12H9" stroke-linecap="round" stroke-linejoin="round"/>'
    ),
    "target": '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3" stroke-linecap="round"/>',
    "home": (
        '<path d="M4 10.5L12 4l8 6.5V20a1 1 0 01-1 1h-4v-6H9v6H5a1 1 0 01-1-1z" '
        'stroke-linejoin="round"/>'
    ),
    "briefcase": (
        '<rect x="3" y="7.5" width="18" height="12.5" rx="2"/>'
        '<path d="M9 7.5V5.5a1.5 1.5 0 011.5-1.5h3A1.5 1.5 0 0115 5.5v2" stroke-linejoin="round"/>'
    ),
    "wallet": (
        '<rect x="3" y="6" width="18" height="13" rx="2.5"/>'
        '<path d="M3 10h18M17 14.5h.01" stroke-linecap="round"/>'
    ),
    "percent": '<path d="M6 18L18 6" stroke-linecap="round"/><circle cx="7.5" cy="7.5" r="2.2"/><circle cx="16.5" cy="16.5" r="2.2"/>',
    "info": '<circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.8h.01" stroke-linecap="round"/>',
    "store": (
        '<path d="M4 9.5h16V20a1 1 0 01-1 1H5a1 1 0 01-1-1z" stroke-linejoin="round"/>'
        '<path d="M3.2 9.5L5 4h14l1.8 5.5a3 3 0 01-5.6 1 3 3 0 01-5.6 0 3 3 0 01-5.6-1z" '
        'stroke-linejoin="round"/>'
    ),
    "empty-cart": (
        '<path d="M6 8h36l-4 22a3 3 0 01-3 2.5H13A3 3 0 0110 30z" stroke-linejoin="round"/>'
        '<circle cx="18" cy="40" r="3"/><circle cx="34" cy="40" r="3"/>'
        '<path d="M19 17l10 10M29 17L19 27" stroke-linecap="round"/>'
    ),
}


def icon(name: str, size: int = 24, cls: str = "", stroke: float = 1.7) -> str:
    body = ICONS.get(name, "")
    klass = f' class="{cls}"' if cls else ""
    return (
        f'<svg{klass} width="{size}" height="{size}" viewBox="0 0 24 24" fill="none" '
        f'stroke="currentColor" stroke-width="{stroke}" aria-hidden="true">{body}</svg>'
    )


def logo_mark(size: int = 34) -> str:
    """
    SuperDouper mark: a shopping basket whose handle doubles as an S curve.
    Uses currentColor so it inherits the palette on every homepage.
    """
    return (
        f'<svg class="sp-logo-mark" width="{size}" height="{size}" viewBox="0 0 40 40" '
        'fill="none" aria-hidden="true">'
        '<rect x="4" y="14" width="32" height="21" rx="5" fill="currentColor" '
        'opacity="0.14"/>'
        '<path d="M6.5 15.5h27l-2.4 16.2a3.2 3.2 0 01-3.2 2.8H12.1a3.2 3.2 0 01-3.2-2.8z" '
        'stroke="currentColor" stroke-width="2.4" stroke-linejoin="round"/>'
        '<path d="M14 15.5c0-5 2.7-8 6-8s6 3 6 8" stroke="currentColor" '
        'stroke-width="2.4" stroke-linecap="round"/>'
        '<path d="M16.5 22.5v5.5M23.5 22.5v5.5" stroke="currentColor" '
        'stroke-width="2.4" stroke-linecap="round"/>'
        "</svg>"
    )


def logo(href: str = "home-1-fresh.html") -> str:
    return (
        f'<a href="{href}" class="sp-logo" aria-label="{BRAND}">'
        f"{logo_mark()}"
        '<span class="sp-logo-text">'
        f"<b>{BRAND_LATIN}</b><span>{BRAND}</span>"
        "</span></a>"
    )


# --------------------------------------------------------------------------
# Navigation model
# --------------------------------------------------------------------------

HOMES = [
    ("home-1-fresh.html", "دموی ۱ - تازه"),
    ("home-2-aqua.html", "دموی ۲ - آکوا"),
    ("home-3-graphite.html", "دموی ۳ - گرافیت"),
]

NAV_LINKS = [
    ("market.html", "همه دسته‌بندی‌ها", False),
    ("market.html?sort=discount", "تخفیف‌دارها", True),
    ("market.html?c=produce", "میوه و سبزیجات"),
    ("market.html?c=dairy", "لبنیات"),
    ("market.html?c=snacks", "تنقلات"),
    ("vendors.html", "فروشگاه‌های اطراف"),
    ("support.html", "پشتیبانی"),
]

MEGA_COLUMNS = {
    "dairy": [
        ("شیر", ["شیر پرچرب", "شیر کم‌چرب", "شیر بدون لاکتوز", "شیر طعم‌دار"]),
        ("ماست", ["ماست همزده", "ماست چکیده", "ماست موسیر", "ماست یونانی"]),
        ("پنیر", ["پنیر سفید", "پنیر خامه‌ای", "پنیر پیتزا", "پنیر مثلثی"]),
        ("سایر", ["خامه", "کره", "دوغ", "کشک"]),
    ],
    "produce": [
        ("میوه تازه", ["سیب", "موز", "پرتقال", "انگور"]),
        ("سبزیجات", ["گوجه فرنگی", "خیار", "کاهو", "فلفل دلمه"]),
        ("صیفی‌جات", ["سیب‌زمینی", "پیاز", "هویج", "بادمجان"]),
        ("سبزی آماده", ["سبزی قورمه", "سبزی پلویی", "سبزی آش", "قارچ"]),
    ],
    "drinks": [
        ("نوشابه", ["کولا", "پرتقالی", "لیمویی", "بدون قند"]),
        ("آبمیوه", ["نکتار", "طبیعی", "کنسانتره", "میوه مخلوط"]),
        ("چای و قهوه", ["چای کیسه‌ای", "چای سیاه", "قهوه فوری", "اسپرسو"]),
        ("سایر", ["آب معدنی", "ماءالشعیر", "دمنوش", "انرژی‌زا"]),
    ],
    "snacks": [
        ("چیپس و اسنک", ["چیپس ساده", "چیپس فلفلی", "پفک", "اسنک حلقه‌ای"]),
        ("شکلات", ["تخته‌ای", "ویفر", "کاکائویی", "تلخ"]),
        ("بیسکویت و کیک", ["بیسکویت کرم‌دار", "ساقه طلایی", "کیک", "کلوچه"]),
        ("خشکبار", ["پسته", "بادام", "تخمه", "خرما"]),
    ],
    "pantry": [
        ("برنج و حبوبات", ["برنج ایرانی", "برنج خارجی", "عدس", "لوبیا"]),
        ("ماکارونی", ["اسپاگتی", "فرمی", "رشته آش", "لازانیا"]),
        ("روغن و رب", ["روغن مایع", "روغن زیتون", "رب گوجه", "سرکه"]),
        ("نان", ["لواش", "بربری", "تست", "باگت"]),
    ],
    "breakfast": [
        ("عسل و مربا", ["عسل طبیعی", "مربای آلبالو", "مربای هویج", "مربای توت"]),
        ("کره و شکلات", ["کره بادام", "شکلات صبحانه", "حلوا شکری", "ارده"]),
        ("غلات", ["کورن‌فلکس", "گرانولا", "جو دوسر", "مسلی"]),
        ("سایر", ["تخم مرغ", "سرشیر", "خامه صبحانه", "پنیر صبحانه"]),
    ],
    "cleaning": [
        ("شوینده", ["مایع ظرفشویی", "پودر لباسشویی", "مایع لباسشویی", "نرم‌کننده"]),
        ("نظافت", ["سفیدکننده", "جرم‌گیر", "اسپری چندمنظوره", "دستکش"]),
        ("بهداشت شخصی", ["شامپو", "صابون", "خمیردندان", "مسواک"]),
        ("کاغذی", ["دستمال کاغذی", "دستمال توالت", "دستمال مرطوب", "نوار بهداشتی"]),
    ],
    "baby": [
        ("پوشک", ["سایز ۲", "سایز ۳", "سایز ۴", "شورت آموزشی"]),
        ("تغذیه", ["شیر خشک", "غذای کمکی", "پوره میوه", "بیسکویت کودک"]),
        ("مراقبت", ["شامپو بچه", "لوسیون", "کرم زیر پوشک", "دستمال مرطوب"]),
        ("لوازم", ["شیشه شیر", "پستانک", "ظرف غذا", "حوله"]),
    ],
    "frozen": [
        ("بستنی", ["چوبی", "قیفی", "لیوانی", "فالوده"]),
        ("فرآورده گوشتی", ["سوسیس", "کالباس", "ژامبون", "همبرگر"]),
        ("منجمد", ["ناگت", "فیله سوخاری", "سبزی منجمد", "نخود سبز"]),
        ("پروتئین", ["مرغ", "گوشت چرخ‌کرده", "ماهی", "میگو"]),
    ],
    "home": [
        ("یکبار مصرف", ["ظرف", "لیوان", "بشقاب", "سفره"]),
        ("بسته‌بندی", ["فویل", "سلفون", "کیسه فریزر", "کیسه زباله"]),
        ("نظافت", ["اسکاچ", "سیم ظرفشویی", "تی", "جارو"]),
        ("متفرقه", ["باتری", "لامپ", "چسب", "قوطی نگهدارنده"]),
    ],
}

CATEGORY_META = [
    ("dairy", "لبنیات و پروتئین"),
    ("produce", "میوه و سبزیجات تازه"),
    ("drinks", "نوشیدنی"),
    ("snacks", "تنقلات و شکلات"),
    ("pantry", "خواربار و نان"),
    ("breakfast", "صبحانه"),
    ("cleaning", "شوینده و بهداشتی"),
    ("baby", "کودک و نوزاد"),
    ("frozen", "یخچالی و منجمد"),
    ("home", "خانه و آشپزخانه"),
]


# --------------------------------------------------------------------------
# Head
# --------------------------------------------------------------------------


def head(title: str, description: str, extra_css: list[str] | None = None) -> str:
    # An entry containing "/" is a path under assets/ (e.g. a vendored
    # stylesheet); a bare name is resolved against assets/css/.
    sheets = [
        "css/output.css",
        "css/swiper-bundle.min.css",
        "css/superium-palettes.css",
        "css/superium.css",
    ] + [n if "/" in n else f"css/{n}" for n in (extra_css or [])]
    css = "\n    ".join(
        f'<link rel="stylesheet" href="assets/{name}" />' for name in sheets
    )
    return f"""<!doctype html>
<html lang="fa" dir="rtl">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{title} | {BRAND}</title>
    <meta name="description" content="{description}" />
    <meta property="og:title" content="{title} | {BRAND}" />
    <meta property="og:description" content="{description}" />
    <meta property="og:type" content="website" />
    <link rel="icon" href="assets/images/brand/favicon.svg" type="image/svg+xml" />
    {css}
  </head>"""


# --------------------------------------------------------------------------
# Header
# --------------------------------------------------------------------------


def _mega() -> str:
    sidebar = "\n".join(
        f'<button type="button" class="sp-mega-cat" :class="{{ \'is-active\': megaCat === \'{slug}\' }}" '
        f"@mouseenter=\"megaCat = '{slug}'\" @focus=\"megaCat = '{slug}'\">"
        f'<img src="assets/images/categories/{slug}.webp" alt="" width="26" height="26" loading="lazy" />'
        f"<span>{title}</span></button>"
        for slug, title in CATEGORY_META
    )

    panels = []
    for slug, _ in CATEGORY_META:
        cols = "\n".join(
            '<div><div class="sp-mega-col-title">{}</div><div class="sp-mega-col-links">{}</div></div>'.format(
                group,
                "".join(
                    f'<a href="market.html?c={slug}">{link}</a>' for link in links
                ),
            )
            for group, links in MEGA_COLUMNS[slug]
        )
        panels.append(
            f"<div x-show=\"megaCat === '{slug}'\" x-cloak class=\"sp-mega-columns\">{cols}</div>"
        )

    return f"""
        <!-- Mega menu -->
        <div class="sp-mega-wrap" x-show="megaOpen" x-cloak
             @mouseleave="megaOpen = false" x-transition.opacity>
          <div class="sp-mega">
            <div class="sp-mega-sidebar">{sidebar}</div>
            <div class="sp-mega-content">{"".join(panels)}</div>
          </div>
        </div>"""


def homes_menu() -> str:
    """The three homepages as menu rows, with a swatch of each palette."""
    return "".join(
        f'<a href="{href}" class="sp-menu-item">'
        f'<span class="sp-home-dot sp-home-dot--{href.split("-")[-1].replace(".html", "")}"></span>'
        f"<span>{label}</span></a>"
        for href, label in HOMES
    )


def header(active: str = "") -> str:
    nav = "\n".join(
        '<a href="{href}" class="sp-nav-link{hot}">{label}</a>'.format(
            href=item[0],
            label=item[1],
            hot=" sp-nav-link--hot" if len(item) > 2 and item[2] else "",
        )
        for item in NAV_LINKS
    )

    return f"""
    <!-- ================= HEADER ================= -->
    <header class="sp-header">
      <div class="sp-container">

        <!-- Row: mobile bar -->
        <div class="sp-mobile-bar sp-header-row">
          <button type="button" class="sp-hamburger" @click="mobileMenuOpen = true"
                  aria-label="باز کردن منو">{icon("menu")}</button>
          {logo()}
          <button type="button" class="sp-icon-btn" @click="cartOpen = !cartOpen"
                  aria-label="سبد خرید">
            {icon("cart", 22)}
            <span class="sp-cart-badge" x-show="cartCount > 0" x-cloak x-text="fa(cartCount)"></span>
          </button>
        </div>

        <!-- Row: desktop top -->
        <div class="sp-header-row sp-header-row--top">
          {logo()}
          <a href="address-map.html" class="sp-location">
            {icon("pin", 17)}
            <span class="sp-location-text">تهران، جردن - بلوار نلسون ماندلا</span>
            {icon("chevron-down", 15)}
          </a>
          <form class="sp-search" role="search" @submit.prevent>
            {icon("search", 19)}
            <input type="search" placeholder="جستجوی کالا، برند و فروشگاه"
                   aria-label="جستجو در فروشگاه" />
          </form>
          <div class="sp-header-actions">
            <!-- Demo switcher: jump between the three homepages -->
            <div class="sp-dropdown-wrap sp-homes" @click.outside="homesOpen = false">
              <button type="button" class="sp-user-trigger" @click="homesOpen = !homesOpen"
                      :aria-expanded="homesOpen">
                {icon("grid", 18)}<span>دموها</span>{icon("chevron-down", 15)}
              </button>
              <div class="sp-dropdown-panel sp-dropdown-panel--sm" x-show="homesOpen"
                   x-cloak x-transition.opacity>
                <nav class="sp-menu">
                  {homes_menu()}
                  <hr class="sp-divider" />
                  <a href="demo.html" class="sp-menu-item">
                    {icon("box", 19)}<span>صفحه معرفی قالب</span>
                  </a>
                </nav>
              </div>
            </div>

            <!-- User -->
            <div class="sp-dropdown-wrap" @click.outside="userOpen = false">
              <button type="button" class="sp-user-trigger" @click="userOpen = !userOpen">
                {icon("user", 19)}<span>حساب کاربری</span>
              </button>
              <div class="sp-dropdown-panel" x-show="userOpen" x-cloak x-transition.opacity>
                <div class="sp-user-head">
                  <div class="sp-user-avatar">ز</div>
                  <div>
                    <div class="sp-user-name">زهرا احمدی</div>
                    <div class="sp-user-phone">۰۹۳۹۹۹۹۹۹۹۹</div>
                  </div>
                </div>
                <nav class="sp-menu">
                  <a href="profile.html" class="sp-menu-item">{icon("user", 19)}<span>اطلاعات حساب</span></a>
                  <a href="profile-orders.html" class="sp-menu-item">{icon("box", 19)}<span>سفارش‌های من</span></a>
                  <a href="profile-addresses.html" class="sp-menu-item">{icon("pin", 19)}<span>آدرس‌ها</span></a>
                  <a href="support.html" class="sp-menu-item">{icon("headset", 19)}<span>پشتیبانی</span></a>
                  <a href="login.html" class="sp-menu-item sp-menu-item--logout">{icon("logout", 19)}<span>خروج</span></a>
                </nav>
              </div>
            </div>

            <span class="sp-header-divider"></span>

            <!-- Cart -->
            <div class="sp-dropdown-wrap" @click.outside="cartOpen = false">
              <button type="button" class="sp-icon-btn" @click="cartOpen = !cartOpen"
                      aria-label="سبد خرید">
                {icon("cart", 22)}
                <span class="sp-cart-badge" x-show="cartCount > 0" x-cloak x-text="fa(cartCount)"></span>
              </button>
              <div class="sp-dropdown-panel" x-show="cartOpen" x-cloak x-transition.opacity>
                <div class="sp-dropdown-head">
                  <span class="sp-dropdown-head-title">سبد خرید</span>
                  <span class="sp-dropdown-head-count" x-text="fa(cartCount) + ' کالا'"></span>
                </div>
                <div class="sp-dropdown-body">
                  <template x-if="cart.length === 0">
                    <p class="sp-empty-text" style="padding:24px 8px;text-align:center">
                      سبد خرید شما خالی است.
                    </p>
                  </template>
                  <template x-for="line in cart" :key="line.id">
                    <div class="sp-mini-item">
                      <img class="sp-mini-item-thumb" :src="line.image" :alt="line.title"
                           width="50" height="50" />
                      <div class="sp-mini-item-info">
                        <div class="sp-mini-item-title" x-text="line.title"></div>
                        <div class="sp-mini-item-price"
                             x-text="fa(line.qty) + ' × ' + toman(line.final)"></div>
                      </div>
                      <button type="button" class="sp-icon-btn" style="inline-size:32px;block-size:32px"
                              @click="removeFromCart(line.id)" aria-label="حذف">
                        {icon("trash", 17)}
                      </button>
                    </div>
                  </template>
                </div>
                <div class="sp-dropdown-foot" x-show="cart.length > 0" x-cloak>
                  <div class="sp-dropdown-total">
                    <span>مبلغ قابل پرداخت</span><b x-text="toman(cartTotal)"></b>
                  </div>
                  <a href="cart.html" class="sp-btn sp-btn--primary sp-btn--block">مشاهده سبد خرید</a>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Row: nav -->
        <nav class="sp-nav-row sp-nav-mega-anchor" aria-label="ناوبری اصلی">
          <button type="button" class="sp-nav-link" @mouseenter="megaOpen = true"
                  @click="megaOpen = !megaOpen" :aria-expanded="megaOpen">
            {icon("grid", 17)}<span>دسته‌بندی کالاها</span>
          </button>
          <div class="sp-nav-links">{nav}</div>
        </nav>
        {_mega()}
      </div>
    </header>

    <!-- Search band - small screens only. Deliberately outside <header> so the
         sticky bar stays a single compact row on phones. -->
    <div class="sp-search-band">
      <div class="sp-container">
        <form class="sp-search" role="search" @submit.prevent>
          {icon("search", 19)}
          <input type="search" placeholder="جستجو بین همه کالاها"
                 aria-label="جستجو در فروشگاه" />
        </form>
      </div>
    </div>"""


# --------------------------------------------------------------------------
# Mobile drawer
# --------------------------------------------------------------------------


def drawer() -> str:
    links = "\n".join(
        f'<a href="{slug_href}" class="sp-menu-item">'
        f'<img src="assets/images/categories/{slug}.webp" alt="" width="22" height="22" '
        f'style="border-radius:5px" loading="lazy" /><span>{title}</span></a>'
        for slug, title in CATEGORY_META
        for slug_href in [f"market.html?c={slug}"]
    )
    return f"""
    <!-- Mobile drawer -->
    <div class="sp-overlay" x-show="mobileMenuOpen" x-cloak @click="mobileMenuOpen = false"
         x-transition.opacity></div>
    <aside class="sp-drawer" x-show="mobileMenuOpen" x-cloak
           x-transition:enter-start="-translate-x-full" role="dialog" aria-label="منوی موبایل">
      <div class="sp-drawer-head">
        {logo()}
        <button type="button" class="sp-icon-btn" @click="mobileMenuOpen = false"
                aria-label="بستن منو">{icon("close", 20)}</button>
      </div>
      <div class="sp-drawer-body">
        <a href="login.html" class="sp-btn sp-btn--primary sp-btn--block" style="margin-block-end:14px">
          ورود یا ثبت‌نام
        </a>
        <nav class="sp-menu" style="padding:0">
          {links}
          <hr class="sp-divider" />
          <div class="sp-menu-heading">دموهای صفحه اصلی</div>
          {homes_menu()}
          <hr class="sp-divider" />
          <a href="vendors.html" class="sp-menu-item">{icon("store", 19)}<span>فروشگاه‌های اطراف</span></a>
          <a href="profile-orders.html" class="sp-menu-item">{icon("box", 19)}<span>سفارش‌های من</span></a>
          <a href="support.html" class="sp-menu-item">{icon("headset", 19)}<span>پشتیبانی</span></a>
        </nav>
      </div>
      <div class="sp-drawer-foot">
        <a href="demo.html" class="sp-btn sp-btn--ghost sp-btn--block">صفحه معرفی قالب</a>
      </div>
    </aside>"""


# --------------------------------------------------------------------------
# Footer
# --------------------------------------------------------------------------

FOOTER_SERVICES = [
    ("truck", "ارسال سریع تا ۴۵ دقیقه"),
    ("shield", "ضمانت اصالت و سلامت"),
    ("wallet", "پرداخت در محل"),
    ("headset", "پشتیبانی ۲۴ ساعته"),
]

FOOTER_COLUMNS = [
    (
        "با سوپردوپر",
        [("support.html", "درباره ما"), ("support.html", "تماس با ما"),
         ("support.html", "فرصت‌های شغلی"), ("support.html", "همکاری با فروشگاه‌ها")],
    ),
    (
        "خدمات مشتریان",
        [("support.html", "پرسش‌های متداول"), ("support.html", "رویه ارسال"),
         ("support.html", "شرایط مرجوعی"), ("support.html", "حریم خصوصی")],
    ),
    (
        "راهنمای خرید",
        [("market.html", "نحوه ثبت سفارش"), ("cart.html", "سبد خرید"),
         ("checkout.html", "شیوه‌های پرداخت"), ("profile-orders.html", "پیگیری سفارش")],
    ),
]


def footer(variant: str = "wide") -> str:
    """
    variant:
      wide    five columns + app badges + trust strip   (home-1 fresh)
      compact three columns + newsletter                (home-2 aqua)
      slim    single row of legal links                 (home-3 graphite)
      inner   the default for non-homepage pages
    """
    services = "".join(
        f'<div class="sp-service">{icon(name, 34, stroke=1.5)}<span>{label}</span></div>'
        for name, label in FOOTER_SERVICES
    )
    columns = "".join(
        '<div><div class="sp-footer-col-title">{}</div><div class="sp-footer-links">{}</div></div>'.format(
            title, "".join(f'<a href="{href}">{label}</a>' for href, label in links)
        )
        for title, links in FOOTER_COLUMNS
    )

    social = (
        '<div class="sp-footer-social">'
        + "".join(
            f'<a href="#" aria-label="{label}">{icon(ico, 18)}</a>'
            for ico, label in [("mail", "ایمیل"), ("phone", "تلفن"), ("headset", "پشتیبانی")]
        )
        + "</div>"
    )

    bottom = f"""
      <div class="sp-container">
        <div class="sp-footer-bottom">
          <span>کلیه حقوق این سایت متعلق به {BRAND} است. © ۱۴۰۵</span>
          <button type="button" class="sp-footer-back-top" @click="scrollTop()">
            {icon("arrow-up", 15)}<span>بازگشت به بالا</span>
          </button>
        </div>
      </div>"""

    if variant == "slim":
        return f"""
    <!-- ================= FOOTER (slim) ================= -->
    <footer class="sp-footer">
      <div class="sp-container">
        <div class="sp-footer-bottom" style="border-block-start:none">
          <div style="display:flex;align-items:center;gap:14px;flex-wrap:wrap">
            {logo()}
            <div class="sp-footer-links" style="flex-direction:row;gap:16px;flex-wrap:wrap">
              <a href="support.html">قوانین و مقررات</a>
              <a href="support.html">حریم خصوصی</a>
              <a href="support.html">پشتیبانی</a>
              <a href="demo.html">معرفی قالب</a>
            </div>
          </div>
          {social}
        </div>
      </div>
      {bottom}
    </footer>"""

    if variant == "compact":
        return f"""
    <!-- ================= FOOTER (compact) ================= -->
    <footer class="sp-footer">
      <div class="sp-container">
        <div class="sp-footer-services">{services}</div>
        <div class="sp-footer-grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">
          <div>
            {logo()}
            <p class="sp-footer-about" style="margin-block-start:12px">
              سفارش آنلاین از سوپرمارکت‌های محله، با قیمت خود فروشگاه و ارسال
              در کمتر از یک ساعت.
            </p>
            {social}
          </div>
          {columns}
          <div>
            <div class="sp-footer-col-title">خبرنامه</div>
            <p class="sp-footer-about" style="margin-block-end:10px">
              از تخفیف‌های هفتگی باخبر شوید.
            </p>
            <form @submit.prevent="notify('ایمیل شما ثبت شد')" style="display:flex;gap:8px">
              <input type="email" class="sp-input" placeholder="ایمیل شما" required />
              <button type="submit" class="sp-btn sp-btn--primary">ثبت</button>
            </form>
          </div>
        </div>
      </div>
      {bottom}
    </footer>"""

    # wide / inner
    return f"""
    <!-- ================= FOOTER ================= -->
    <footer class="sp-footer">
      <div class="sp-container">
        <div class="sp-footer-top">
          {logo()}
          <div class="sp-footer-apps">
            <a href="#" class="sp-footer-app-btn">{icon("box", 20)}<span>دریافت از بازار</span></a>
            <a href="#" class="sp-footer-app-btn">{icon("box", 20)}<span>دریافت از سیب‌اپ</span></a>
          </div>
        </div>
        <div class="sp-footer-services">{services}</div>
        <div class="sp-footer-grid">
          <div>
            <div class="sp-footer-col-title">{BRAND}</div>
            <p class="sp-footer-about">
              خرید سوپرمارکتی فوری از فروشگاه‌های محلی و زنجیره‌ای. سفارش خود را
              ثبت کنید، قیمت‌ها را بین فروشگاه‌های اطراف مقایسه کنید و در کمتر از
              یک ساعت تحویل بگیرید.
            </p>
            {social}
          </div>
          {columns}
          <div>
            <div class="sp-footer-col-title">نماد اعتماد</div>
            <div class="sp-footer-badges">
              <div class="sp-footer-badge">نماد اعتماد الکترونیکی</div>
              <div class="sp-footer-badge">ساماندهی</div>
            </div>
          </div>
        </div>
        <div class="sp-footer-seo">
          <b>{BRAND} - سوپرمارکت آنلاین</b><br />
          از لبنیات و میوه تازه تا شوینده و اقلام خانه؛ سبد خرید خود را ببندید و
          بگذارید نزدیک‌ترین فروشگاه آن را برایتان جمع کند. قیمت‌ها همان قیمت
          درب فروشگاه است و هزینه‌ای بابت جمع‌آوری سفارش پرداخت نمی‌کنید.
        </div>
      </div>
      {bottom}
    </footer>"""


# --------------------------------------------------------------------------
# Floating widgets + scripts
# --------------------------------------------------------------------------


def fabs() -> str:
    return f"""
    <!-- Floating buttons + support widget -->
    <div class="sp-support-panel" x-show="supportOpen" x-cloak x-transition.opacity>
      <div class="sp-support-head">
        <b>پشتیبانی {BRAND}</b><span>پاسخگوی شما هستیم</span>
      </div>
      <div class="sp-support-body">
        <a href="support.html" class="sp-menu-item">{icon("info", 19)}<span>پرسش‌های متداول</span></a>
        <a href="support.html" class="sp-menu-item">{icon("mail", 19)}<span>ارسال پیام</span></a>
        <a href="tel:+982100000000" class="sp-menu-item">{icon("phone", 19)}<span>تماس تلفنی</span></a>
      </div>
    </div>
    <div class="sp-fabs">
      <button type="button" class="sp-fab sp-fab--support" @click="supportOpen = !supportOpen"
              aria-label="پشتیبانی">{icon("headset", 22)}</button>
      <button type="button" class="sp-fab" @click="scrollTop()" aria-label="بازگشت به بالا">
        {icon("arrow-up", 22)}
      </button>
    </div>

    <!-- Toast -->
    <div class="sp-toast" x-show="toast" x-cloak x-transition.opacity>
      {icon("check-circle", 18)}<span x-text="toast"></span>
    </div>"""


def scripts(extra_js: list[str] | None = None) -> str:
    # Same convention as head(): a name with "/" is a path under assets/.
    extra = extra_js or []
    vendor = [n for n in extra if "/" in n]
    ours = [f"js/{n}" for n in extra if "/" not in n]
    files = vendor + ["data/products.js", "js/swiper-bundle.min.js", "js/superium.js"]
    files += ours
    tags = "\n    ".join(f'<script src="assets/{f}"></script>' for f in files)
    return f"""
    {tags}
    <script src="assets/js/alpine.js" defer></script>"""


# --------------------------------------------------------------------------
# Page assembly
# --------------------------------------------------------------------------


def page(
    *,
    title: str,
    description: str,
    body: str,
    theme: str = "fresh",
    footer_variant: str = "inner",
    extra_css: list[str] | None = None,
    extra_js: list[str] | None = None,
    with_header: bool = True,
    with_footer: bool = True,
    with_fabs: bool = True,
) -> str:
    parts = [head(title, description, extra_css)]
    parts.append(
        f'\n  <body class="sp-page sp-theme--{theme}" x-data="superium()" x-init="init()">'
    )
    parts.append('\n    <a href="#sp-main" class="sp-skip-link">پرش به محتوای اصلی</a>')
    if with_header:
        parts.append(header())
        parts.append(drawer())
    parts.append(f'\n    <main id="sp-main" class="sp-main">{body}\n    </main>')
    if with_footer:
        parts.append(footer(footer_variant))
    if with_fabs:
        parts.append(fabs())
    parts.append(scripts(extra_js))
    parts.append("\n  </body>\n</html>\n")
    return "".join(parts)
