# -*- coding: utf-8 -*-
"""
Superium — shop flow pages
==========================

market.html    listing with filter sidebar, sort, grid/list, pagination
product.html   gallery, buybox, other sellers, specs, reviews
cart.html      basket lines with steppers and a sticky invoice
vendors.html   the same basket priced across nearby stores  ← marketplace step
store.html     one vendor's storefront with a docked basket

vendors.html and store.html are what make this a marketplace rather than a
single shop: you build a basket first, then choose who fills it.
"""

from __future__ import annotations

from components import breadcrumb, empty_state, fa, product_card, product_grid, rail, section_head
from layout import CATEGORY_META, icon

# --------------------------------------------------------------------------
# Sample vendors — the marketplace's supply side
# --------------------------------------------------------------------------

VENDORS = [
    {
        "slug": "luxe",
        "name": "سوپرمارکت لوکس - یاران دریان (جردن)",
        "rating": "۴.۵",
        "eta": "۴۵",
        "fee": "۲,۰۰۰",
        "tags": ["pro", "ارسال رایگان"],
        "missing": 0,
        "delta": 0,
    },
    {
        "slug": "isar",
        "name": "سوپرمارکت ایثار - یاران دریان (جردن)",
        "rating": "۳.۸",
        "eta": "۱۹",
        "fee": "۲,۰۰۰",
        "tags": ["pro", "ارسال توربو"],
        "missing": 1,
        "delta": -4,
    },
    {
        "slug": "zafar",
        "name": "سوپرمارکت ظفر (آرش)",
        "rating": "۳.۹",
        "eta": "۴۵",
        "fee": "۳۴,۰۰۰",
        "tags": ["تضمین تاریخ"],
        "missing": 1,
        "delta": -7,
    },
    {
        "slug": "sun",
        "name": "سوپرمارکت سان - یاران دریان (الهیه)",
        "rating": "۴.۲",
        "eta": "۴۵",
        "fee": "۳۴,۰۰۰",
        "tags": ["تضمین تاریخ"],
        "missing": 2,
        "delta": -11,
    },
    {
        "slug": "andia",
        "name": "سوپرمارکت آندیا - شعبه پناه (جردن)",
        "rating": "جدید",
        "eta": "۴۵",
        "fee": "۳۰,۰۰۰",
        "tags": [],
        "missing": 1,
        "delta": 3,
    },
    {
        "slug": "rozhan",
        "name": "سوپرمارکت روژان (جردن)",
        "rating": "۳.۴",
        "eta": "۴۵",
        "fee": "۳۱,۲۰۰",
        "tags": ["تضمین تاریخ"],
        "missing": 2,
        "delta": 6,
    },
]

BRANDS = ["کاله", "میهن", "پگاه", "روزانه", "دامداران", "مینو", "شیرین‌عسل", "گلرنگ"]

SORTS = [
    ("relevance", "مرتبط‌ترین"),
    ("discount", "بیشترین تخفیف"),
    ("cheap", "ارزان‌ترین"),
    ("expensive", "گران‌ترین"),
    ("new", "جدیدترین"),
]


# ==========================================================================
# market.html
# ==========================================================================


def market(products: list[dict], categories: list[dict]) -> str:
    cat_checks = "".join(
        f"""<label class="sp-check">
          <input type="checkbox" value="{slug}" @change="toggleCategory('{slug}')"
                 :checked="activeCategories.includes('{slug}')" />
          <span>{title}</span>
        </label>"""
        for slug, title in CATEGORY_META
    )

    brand_checks = "".join(
        f'<label class="sp-check"><input type="checkbox" /><span>{b}</span></label>'
        for b in BRANDS
    )

    sort_buttons = "".join(
        f"""<button type="button" class="sp-sort-btn" :class="{{ 'is-active': sort === '{key}' }}"
             @click="setSort('{key}')">{label}</button>"""
        for key, label in SORTS
    )

    sort_sheet = "".join(
        f"""<button type="button" class="sp-option" :class="{{ 'is-active': sort === '{key}' }}"
             @click="setSort('{key}'); sortSheet = false">
          <span class="sp-option-dot"></span>
          <span class="sp-option-body"><span class="sp-option-title">{label}</span></span>
        </button>"""
        for key, label in SORTS
    )

    chips = "".join(
        f"""<button type="button" class="sp-chip"
             :class="{{ 'is-active': activeCategories.includes('{slug}') }}"
             @click="toggleCategory('{slug}')">{title}</button>"""
        for slug, title in CATEGORY_META
    )

    return f"""
      <div class="sp-container" x-data="superiumMarket()" x-init="initMarket($el)">
        {breadcrumb([("home-1-fresh.html", "خانه"), ("market.html", "همه کالاها")])}

        <!-- Sub-category chips -->
        <div class="sp-chip-row" style="margin-block-end:14px">
          <button type="button" class="sp-chip" :class="{{ 'is-active': activeCategories.length === 0 }}"
                  @click="clearCategories()">همه</button>
          {chips}
        </div>

        <div class="sp-shell sp-shell--start">
          <!-- ============ Filters ============ -->
          <aside class="sp-filters" :class="{{ 'is-open': filterOpen }}">
            <div class="sp-filters-head">
              <b>فیلترها</b>
              <button type="button" class="sp-icon-btn sp-filters-close" @click="filterOpen = false"
                      aria-label="بستن فیلترها">{icon("close", 20)}</button>
            </div>

            <div class="sp-filter-block">
              <div class="sp-filter-title">دسته‌بندی</div>
              {cat_checks}
            </div>

            <div class="sp-filter-block">
              <div class="sp-filter-title">محدوده قیمت (تومان)</div>
              <input type="range" class="sp-range" min="20000" :max="priceCeiling"
                     step="10000" x-model.number="maxPrice" />
              <div class="sp-filter-range-labels">
                <span x-text="fa(20000)"></span>
                <span x-text="fa(maxPrice) + ' و کمتر'"></span>
              </div>
            </div>

            <div class="sp-filter-block">
              <div class="sp-filter-title">برند</div>
              <div class="sp-filter-scroll">{brand_checks}</div>
            </div>

            <div class="sp-filter-block">
              <div class="sp-filter-title">گزینه‌های سریع</div>
              <label class="sp-check">
                <input type="checkbox" x-model="onlyDiscount" /><span>فقط تخفیف‌دارها</span>
              </label>
              <label class="sp-check">
                <input type="checkbox" checked /><span>فقط کالاهای موجود</span>
              </label>
              <label class="sp-check">
                <input type="checkbox" /><span>ارسال رایگان</span>
              </label>
            </div>

            <button type="button" class="sp-btn sp-btn--ghost sp-btn--block" @click="resetFilters()">
              حذف فیلترها
            </button>
          </aside>

          <!-- ============ Results ============ -->
          <section>
            <!-- Mobile filter / sort bar -->
            <div class="sp-mobile-toolbar">
              <button type="button" class="sp-btn sp-btn--ghost sp-btn--sm" @click="filterOpen = true">
                {icon("filter", 17)}<span>فیلتر</span>
              </button>
              <button type="button" class="sp-btn sp-btn--ghost sp-btn--sm" @click="sortSheet = true">
                {icon("sort", 17)}<span>مرتب‌سازی</span>
              </button>
            </div>

            <!-- Desktop toolbar -->
            <div class="sp-toolbar">
              <div class="sp-sort-row">
                <span class="sp-toolbar-label">{icon("sort", 17)} مرتب‌سازی:</span>
                {sort_buttons}
              </div>
              <div class="sp-toolbar-end">
                <span class="sp-toolbar-count" x-text="fa(visible.length) + ' کالا'"></span>
                <div class="sp-view-toggle">
                  <button type="button" :class="{{ 'is-active': view === 'grid' }}"
                          @click="view = 'grid'" aria-label="نمای شبکه">{icon("grid", 17)}</button>
                  <button type="button" :class="{{ 'is-active': view === 'list' }}"
                          @click="view = 'list'" aria-label="نمای لیست">{icon("list", 17)}</button>
                </div>
              </div>
            </div>

            <!-- Active filter chips -->
            <div class="sp-chip-row" x-show="activeCategories.length || query || onlyDiscount" x-cloak
                 style="margin-block-end:12px">
              <template x-for="slug in activeCategories" :key="slug">
                <button type="button" class="sp-chip is-active" @click="toggleCategory(slug)">
                  <span x-text="categoryTitle(slug)"></span>
                  <span aria-hidden="true">×</span>
                </button>
              </template>
              <button type="button" class="sp-chip is-active" x-show="query" @click="query = ''">
                <span x-text="'جستجو: ' + query"></span><span aria-hidden="true">×</span>
              </button>
              <button type="button" class="sp-chip is-active" x-show="onlyDiscount"
                      @click="onlyDiscount = false">
                <span>فقط تخفیف‌دار</span><span aria-hidden="true">×</span>
              </button>
            </div>

            <!-- Grid: rendered from the catalogue so filtering is live -->
            <div :class="view === 'grid' ? 'sp-product-grid' : 'sp-product-list'">
              <template x-for="p in paged" :key="p.id">
                <article class="sp-product-card" :class="{{ 'is-row': view === 'list' }}">
                  <div class="sp-product-flags" x-show="p.discountRatio > 0" x-cloak>
                    <span class="sp-badge sp-badge--discount" x-text="fa(p.discountRatio) + '٪'"></span>
                  </div>
                  <button type="button" class="sp-product-wish"
                          :class="{{ 'is-active': isFavourite(p.id) }}"
                          @click="toggleFavourite(p.id)" aria-label="علاقه‌مندی">
                    {icon("heart", 17)}
                  </button>
                  <a :href="'product.html?id=' + p.id" class="sp-product-img-wrap">
                    <img class="sp-product-photo" :src="p.image" :alt="p.title"
                         width="600" height="600" loading="lazy" />
                  </a>
                  <div class="sp-product-body">
                    <a :href="'product.html?id=' + p.id" class="sp-product-title" x-text="p.title"></a>
                    <div class="sp-product-foot">
                      <div class="sp-product-prices">
                        <div class="sp-product-price-old" x-show="p.discountRatio > 0" x-cloak
                             x-text="fa(p.price)"></div>
                        <div class="sp-product-price">
                          <span class="sp-product-price-from">از</span>
                          <span x-text="fa(p.final)"></span><small>تومان</small>
                        </div>
                      </div>
                      <template x-if="qtyOf(p.id) === 0">
                        <button type="button" class="sp-qty-add" @click="addToCart(p.id)"
                                aria-label="افزودن به سبد">{icon("plus", 18)}</button>
                      </template>
                      <template x-if="qtyOf(p.id) > 0">
                        <div class="sp-qty">
                          <button type="button" @click="addToCart(p.id)" aria-label="افزایش">
                            {icon("plus", 16)}</button>
                          <span class="sp-qty-val" x-text="fa(qtyOf(p.id))"></span>
                          <button type="button" @click="decrement(p.id)" aria-label="کاهش">
                            {icon("minus", 16)}</button>
                        </div>
                      </template>
                    </div>
                  </div>
                </article>
              </template>
            </div>

            <!-- Empty state -->
            <div x-show="visible.length === 0" x-cloak>
              {empty_state(
                  "کالایی با این فیلترها پیدا نشد",
                  "بازه قیمت را بازتر کنید یا چند دسته‌بندی را از حالت انتخاب خارج کنید.",
              )}
            </div>

            <!-- Pagination -->
            <nav class="sp-pagination" x-show="pageCount > 1" x-cloak aria-label="صفحه‌بندی">
              <button type="button" class="sp-page-btn" @click="goTo(current - 1)"
                      :disabled="current === 1" aria-label="صفحه قبل">{icon("chevron-end", 18)}</button>
              <template x-for="n in pageCount" :key="n">
                <button type="button" class="sp-page-btn" :class="{{ 'is-active': current === n }}"
                        @click="goTo(n)" x-text="fa(n)"></button>
              </template>
              <button type="button" class="sp-page-btn" @click="goTo(current + 1)"
                      :disabled="current === pageCount" aria-label="صفحه بعد">
                {icon("chevron-start", 18)}</button>
            </nav>

            <div class="sp-footer-seo" style="border:none">
              <b>خرید آنلاین سوپرمارکتی</b><br />
              قیمت‌ها همان قیمت درب فروشگاه است. پس از بستن سبد، آن را بین
              فروشگاه‌های اطراف مقایسه می‌کنیم تا ارزان‌ترین گزینه‌ی موجود را
              انتخاب کنید.
            </div>
          </section>
        </div>

        <!-- Sort bottom sheet (mobile) -->
        <div class="sp-overlay" x-show="sortSheet" x-cloak @click="sortSheet = false"
             x-transition.opacity></div>
        <div class="sp-sheet" x-show="sortSheet" x-cloak x-transition>
          <div class="sp-sheet-grip"></div>
          <div style="padding:0 16px 20px">
            <b style="display:block;margin-block-end:12px">مرتب‌سازی بر اساس</b>
            <div style="display:flex;flex-direction:column;gap:8px">{sort_sheet}</div>
          </div>
        </div>

        <!-- Filter backdrop (mobile) -->
        <div class="sp-overlay" x-show="filterOpen" x-cloak @click="filterOpen = false"
             x-transition.opacity></div>
      </div>"""


# ==========================================================================
# product.html
# ==========================================================================


def product(products: list[dict]) -> str:
    hero = products[0]
    related = [p for p in products if p["category"] == hero["category"]][1:13]

    sellers = "".join(
        f"""
        <div class="sp-seller-row">
          <div class="sp-seller-info">
            <div class="sp-seller-name">{v['name']}</div>
            <div class="sp-seller-meta">
              {icon("star", 14)}<span>{v['rating']}</span>
              <span class="sp-breadcrumb-sep">·</span>
              <span>ارسال تا {v['eta']} دقیقه</span>
            </div>
          </div>
          <div class="sp-seller-price">
            <b>{fa(hero['final'] + i * 2500)}</b><small>تومان</small>
          </div>
          <button type="button" class="sp-btn sp-btn--soft sp-btn--sm"
                  @click="addToCart('{hero['id']}')">افزودن</button>
        </div>"""
        for i, v in enumerate(VENDORS[:4])
    )

    specs = "".join(
        f'<div class="sp-spec-row"><span>{k}</span><b>{v}</b></div>'
        for k, v in [
            ("دسته‌بندی", hero["categoryTitle"]),
            ("کشور سازنده", "ایران"),
            ("شرایط نگهداری", "دمای خنک و دور از نور مستقیم"),
            ("نوع بسته‌بندی", "بسته‌بندی اصلی کارخانه"),
            ("کد کالا", "SP-" + fa(str(hero["id"]).split("-")[-1])),
        ]
    )

    reviews = "".join(
        f"""
        <article class="sp-review">
          <div class="sp-review-head">
            <div class="sp-user-avatar" style="inline-size:36px;block-size:36px">{name[0]}</div>
            <div>
              <b>{name}</b>
              <div class="sp-review-stars">{"".join(icon("star", 14) for _ in range(stars))}</div>
            </div>
            <span class="sp-review-date">{date}</span>
          </div>
          <p class="sp-review-text">{text}</p>
        </article>"""
        for name, stars, date, text in [
            ("مریم ک.", 5, "۳ روز پیش",
             "بسته‌بندی سالم بود و تاریخ انقضا هم دور. سفارش زیر ۴۰ دقیقه رسید."),
            ("علی ر.", 4, "۱ هفته پیش",
             "کیفیت خوب، فقط کاش گزینه‌ی بسته‌ی بزرگ‌تر هم داشت."),
            ("سحر م.", 5, "۲ هفته پیش",
             "همیشه از همین فروشگاه می‌گیرم. قیمت با درب مغازه یکی است."),
        ]
    )

    return f"""
      <div class="sp-container">
        {breadcrumb([
            ("home-1-fresh.html", "خانه"),
            ("market.html", "همه کالاها"),
            (f"market.html?c={hero['category']}", hero["categoryTitle"]),
            ("#", hero["title"]),
        ])}

        <div class="sp-product-page" x-data="superiumProduct()">
          <!-- Gallery -->
          <div class="sp-gallery">
            <div class="sp-gallery-main">
              <img :src="active" alt="{hero['title']}" width="600" height="600" />
              <span class="sp-badge sp-badge--discount sp-gallery-flag"
                    style="{'' if hero['discountRatio'] else 'display:none'}">
                {fa(hero['discountRatio'])}٪
              </span>
            </div>
            <div class="sp-gallery-thumbs">
              <template x-for="(src, i) in shots" :key="i">
                <button type="button" class="sp-gallery-thumb" :class="{{ 'is-active': active === src }}"
                        @click="active = src" aria-label="تصویر کالا">
                  <img :src="src" alt="" width="80" height="80" />
                </button>
              </template>
            </div>
          </div>

          <!-- Info -->
          <div class="sp-product-info">
            <h1 class="sp-product-heading">{hero['title']}</h1>
            <div class="sp-product-meta">
              <span class="sp-product-rating">{icon("star", 15)} ۴.۶ (۱۲۸ نظر)</span>
              <span class="sp-breadcrumb-sep">·</span>
              <a href="market.html?c={hero['category']}">{hero['categoryTitle']}</a>
            </div>

            <ul class="sp-feature-list">
              <li>{icon("check", 16)}<span>تضمین اصالت و تاریخ انقضا</span></li>
              <li>{icon("check", 16)}<span>قیمت برابر با درب فروشگاه</span></li>
              <li>{icon("check", 16)}<span>امکان مرجوعی هنگام تحویل</span></li>
            </ul>

            <!-- Other sellers -->
            <section class="sp-sellers">
              <div class="sp-filter-title">فروشندگان این کالا</div>
              {sellers}
            </section>
          </div>

          <!-- Buybox -->
          <aside class="sp-buybox sp-sticky">
            <div class="sp-buybox-vendor">
              {icon("store", 20)}
              <div>
                <b>فروشنده منتخب</b>
                <span>سوپرمارکت لوکس - جردن</span>
              </div>
            </div>
            <div class="sp-buybox-delivery">
              {icon("truck", 18)}<span>ارسال امروز، تا ۴۵ دقیقه</span>
            </div>
            <hr class="sp-divider" />
            <div class="sp-buybox-price">
              <div>
                <span class="sp-price-strike"
                      style="{'' if hero['discountRatio'] else 'display:none'}">
                  {fa(hero['price'])}
                </span>
                <b>{fa(hero['final'])} <small>تومان</small></b>
              </div>
              <span class="sp-badge sp-badge--discount"
                    style="{'' if hero['discountRatio'] else 'display:none'}">
                {fa(hero['discountRatio'])}٪
              </span>
            </div>

            <template x-if="qtyOf('{hero['id']}') === 0">
              <button type="button" class="sp-btn sp-btn--primary sp-btn--block sp-btn--lg"
                      @click="addToCart('{hero['id']}')">افزودن به سبد خرید</button>
            </template>
            <template x-if="qtyOf('{hero['id']}') > 0">
              <div class="sp-buybox-qty">
                <div class="sp-qty" style="inline-size:100%;justify-content:space-between">
                  <button type="button" @click="addToCart('{hero['id']}')" aria-label="افزایش">
                    {icon("plus", 18)}</button>
                  <span class="sp-qty-val" x-text="fa(qtyOf('{hero['id']}')) + ' عدد در سبد'"></span>
                  <button type="button" @click="decrement('{hero['id']}')" aria-label="کاهش">
                    {icon("minus", 18)}</button>
                </div>
                <a href="cart.html" class="sp-btn sp-btn--soft sp-btn--block">مشاهده سبد خرید</a>
              </div>
            </template>

            <div class="sp-buybox-trust">
              <span>{icon("shield", 16)} ضمانت سلامت کالا</span>
              <span>{icon("wallet", 16)} امکان پرداخت در محل</span>
            </div>
          </aside>
        </div>

        <!-- Mobile buybox -->
        <div class="sp-mobile-buybox">
          <div>
            <span class="sp-price-strike"
                  style="{'' if hero['discountRatio'] else 'display:none'}">{fa(hero['price'])}</span>
            <b>{fa(hero['final'])} <small>تومان</small></b>
          </div>
          <button type="button" class="sp-btn sp-btn--primary" @click="addToCart('{hero['id']}')">
            افزودن به سبد
          </button>
        </div>

        <!-- Description + specs -->
        <section class="sp-section">
          <div class="sp-panel-grid">
            <div class="sp-card sp-card-pad">
              <h2 class="sp-section-title" style="margin-block-end:10px">معرفی کالا</h2>
              <p class="sp-footer-about">
                {hero['title']} یکی از پرفروش‌ترین اقلام دسته‌ی
                «{hero['categoryTitle']}» است. تمام اقلام این دسته با زنجیره‌ی
                سرد و بسته‌بندی اصلی کارخانه تحویل می‌شوند و پیش از ارسال، تاریخ
                انقضای آن‌ها بررسی می‌شود. اگر کالای دریافتی با آنچه سفارش
                داده‌اید تفاوت داشت، همان لحظه‌ی تحویل می‌توانید آن را مرجوع کنید.
              </p>
            </div>
            <div class="sp-card sp-card-pad">
              <h2 class="sp-section-title" style="margin-block-end:10px">مشخصات</h2>
              <div class="sp-specs">{specs}</div>
            </div>
          </div>
        </section>

        <!-- Reviews -->
        <section class="sp-section">
          {section_head("نظرات خریداران", subtitle="۱۲۸ نظر ثبت‌شده برای این کالا")}
          <div class="sp-reviews">{reviews}</div>
        </section>

        {rail("کالاهای مشابه", related, more_href=f"market.html?c={hero['category']}")}
      </div>"""


# ==========================================================================
# cart.html
# ==========================================================================


def cart() -> str:
    return f"""
      <div class="sp-container">
        {breadcrumb([("home-1-fresh.html", "خانه"), ("cart.html", "سبد خرید")])}

        <!-- Steps -->
        <ol class="sp-steps">
          <li class="is-active"><span>۱</span>سبد خرید</li>
          <li><span>۲</span>انتخاب فروشگاه</li>
          <li><span>۳</span>تحویل و پرداخت</li>
        </ol>

        <div x-show="cart.length === 0" x-cloak>
          {empty_state(
              "سبد خرید شما خالی است",
              "هنوز کالایی اضافه نکرده‌اید. از دسته‌بندی‌ها شروع کنید یا سری به تخفیف‌های امروز بزنید.",
              "market.html",
              "شروع خرید",
          )}
        </div>

        <div class="sp-shell" x-show="cart.length > 0" x-cloak>
          <!-- Lines -->
          <section class="sp-card sp-card-pad">
            <div class="sp-section-head">
              <h1 class="sp-section-title">
                سبد خرید (<span x-text="fa(cartCount)"></span> کالا)
              </h1>
              <button type="button" class="sp-btn sp-btn--danger sp-btn--sm" @click="clearCart()">
                {icon("trash", 16)}<span>حذف سبد</span>
              </button>
            </div>

            <template x-for="line in cart" :key="line.id">
              <div class="sp-cart-line">
                <img class="sp-cart-line-thumb" :src="line.image" :alt="line.title"
                     width="88" height="88" />
                <div class="sp-cart-line-body">
                  <a :href="'product.html?id=' + line.id" class="sp-cart-line-title"
                     x-text="line.title"></a>
                  <div class="sp-cart-line-meta">
                    {icon("store", 14)}<span>سوپرمارکت لوکس - جردن</span>
                  </div>
                  <div class="sp-cart-line-foot">
                    <div class="sp-qty">
                      <button type="button" @click="addToCart(line.id)" aria-label="افزایش">
                        {icon("plus", 16)}</button>
                      <span class="sp-qty-val" x-text="fa(line.qty)"></span>
                      <button type="button" @click="decrement(line.id)"
                              :aria-label="line.qty === 1 ? 'حذف' : 'کاهش'">
                        <template x-if="line.qty === 1">{icon("trash", 16)}</template>
                        <template x-if="line.qty > 1">{icon("minus", 16)}</template>
                      </button>
                    </div>
                    <div class="sp-cart-line-prices">
                      <span class="sp-price-strike" x-show="line.price > line.final" x-cloak
                            x-text="fa(line.price * line.qty)"></span>
                      <b x-text="toman(line.final * line.qty)"></b>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </section>

          <!-- Invoice -->
          <aside class="sp-card sp-card-pad sp-sticky">
            <h2 class="sp-section-title" style="margin-block-end:14px">خلاصه سفارش</h2>
            <div class="sp-invoice">
              <div class="sp-invoice-row">
                <span>قیمت کالاها (<span x-text="fa(cartCount)"></span>)</span>
                <span x-text="toman(cartGross)"></span>
              </div>
              <div class="sp-invoice-row sp-invoice-row--save" x-show="cartSaving > 0" x-cloak>
                <span>سود شما از این خرید</span>
                <span x-text="toman(cartSaving)"></span>
              </div>
              <div class="sp-invoice-row">
                <span>هزینه ارسال</span>
                <span class="sp-muted">در مرحله بعد</span>
              </div>
              <hr class="sp-divider" />
              <div class="sp-invoice-row sp-invoice-row--total">
                <span>مبلغ قابل پرداخت</span>
                <b x-text="toman(cartTotal)"></b>
              </div>
            </div>
            <a href="vendors.html" class="sp-btn sp-btn--primary sp-btn--block sp-btn--lg"
               style="margin-block-start:16px">
              ادامه فرآیند خرید
            </a>
            <p class="sp-hint" style="text-align:center;margin-block-start:10px">
              در مرحله بعد قیمت سبد شما بین فروشگاه‌های اطراف مقایسه می‌شود.
            </p>
          </aside>
        </div>
      </div>"""


# ==========================================================================
# vendors.html — the marketplace comparison step
# ==========================================================================


def vendors(products: list[dict]) -> str:
    cards = []
    for v in VENDORS:
        badges = "".join(
            f'<span class="sp-badge sp-badge--brand">{t}</span>'
            if t == "pro"
            else f'<span class="sp-badge sp-badge--success">{icon("check-circle", 13)}{t}</span>'
            for t in v["tags"]
        )

        # Each store shows the basket's items; some are out of stock here.
        items = f"""
            <template x-for="(line, i) in cart" :key="line.id">
              <div class="sp-vendor-item" :class="{{ 'is-out': i < {v['missing']} }}">
                <img :src="line.image" :alt="line.title" width="64" height="64" />
                <span class="sp-vendor-item-qty" x-text="fa(line.qty)"></span>
                <template x-if="i < {v['missing']}">
                  <span class="sp-vendor-item-out">ناموجود</span>
                </template>
                <template x-if="i >= {v['missing']}">
                  <span class="sp-vendor-item-price"
                        x-text="fa(Math.round(line.final * line.qty * {1 + v['delta'] / 100:.2f}))"></span>
                </template>
              </div>
            </template>"""

        sub = (
            f'<button type="button" class="sp-btn sp-btn--outline sp-btn--sm">انتخاب جایگزین</button>'
            if v["missing"]
            else ""
        )

        cards.append(f"""
        <article class="sp-vendor-card">
          <header class="sp-vendor-head">
            <div class="sp-vendor-logo">{icon("store", 24)}</div>
            <div class="sp-vendor-titles">
              <div class="sp-vendor-name">{v['name']} {badges}</div>
              <div class="sp-vendor-meta">
                {icon("star", 14)}<span>{v['rating']}</span>
                <span class="sp-breadcrumb-sep">|</span>
                <span>تا {v['eta']} دقیقه</span>
                <span class="sp-breadcrumb-sep">|</span>
                <span>{v['fee']} تومان</span>
              </div>
            </div>
          </header>

          <div class="sp-vendor-items">{items}</div>
          <div class="sp-vendor-sub">{sub}</div>

          <footer class="sp-vendor-foot">
            <div class="sp-vendor-total">
              <span>جمع کل</span>
              <b x-text="toman(Math.round(cartTotal * {1 + v['delta'] / 100:.2f}))"></b>
            </div>
            <a href="store.html" class="sp-btn sp-btn--primary">ادامه با این فروشگاه</a>
          </footer>
        </article>""")

    return f"""
      <div class="sp-container">
        {breadcrumb([
            ("home-1-fresh.html", "خانه"),
            ("cart.html", "سبد خرید"),
            ("vendors.html", "انتخاب فروشگاه"),
        ])}

        <ol class="sp-steps">
          <li class="is-done"><span>{icon("check", 14)}</span>سبد خرید</li>
          <li class="is-active"><span>۲</span>انتخاب فروشگاه</li>
          <li><span>۳</span>تحویل و پرداخت</li>
        </ol>

        <div class="sp-section-head">
          <div>
            <h1 class="sp-section-title">کدام فروشگاه سبد شما را جمع کند؟</h1>
            <div class="sp-section-sub">
              ۶ فروشگاه در محدوده‌ی شما این سبد را پوشش می‌دهند. کالاهای ناموجود
              با علامت خاکستری مشخص شده‌اند و می‌توانید برایشان جایگزین انتخاب کنید.
            </div>
          </div>
          <a href="cart.html" class="sp-section-more">
            {icon("chevron-end", 16)}<span>بازگشت به سبد</span>
          </a>
        </div>

        <div x-show="cart.length === 0" x-cloak>
          {empty_state(
              "برای مقایسه فروشگاه‌ها، اول سبد خرید بسازید",
              "چند کالا به سبد اضافه کنید تا قیمت آن را بین فروشگاه‌های اطراف مقایسه کنیم.",
              "market.html",
              "شروع خرید",
          )}
        </div>

        <div class="sp-vendor-grid" x-show="cart.length > 0" x-cloak>
          {"".join(cards)}
        </div>
      </div>"""


# ==========================================================================
# store.html — a single vendor's storefront
# ==========================================================================


def store(products: list[dict], categories: list[dict]) -> str:
    cat_tiles = "".join(
        f"""<a href="market.html?c={c['slug']}" class="sp-store-cat">
          <img src="assets/images/categories/{c['slug']}.webp" alt="" width="56" height="56"
               loading="lazy" />
          <span>{c['title']}</span>
        </a>"""
        for c in categories
    )

    def pick(slug, n, off=0):
        return [p for p in products if p["category"] == slug][off : off + n]

    return f"""
      <div class="sp-container">
        <!-- Store banner -->
        <section class="sp-store-banner">
          <div class="sp-store-banner-main">
            <div class="sp-vendor-logo sp-vendor-logo--lg">{icon("store", 30)}</div>
            <div>
              <h1 class="sp-store-name">
                سوپرمارکت لوکس - یاران دریان (جردن)
                <span class="sp-badge sp-badge--brand">Pro</span>
              </h1>
              <div class="sp-vendor-meta">
                {icon("star", 14)}<span>۴.۵</span>
                <span class="sp-breadcrumb-sep">|</span><span>تا ۴۵ دقیقه</span>
                <span class="sp-breadcrumb-sep">|</span><span>۲,۰۰۰ تومان ویژه شما</span>
              </div>
              <div class="sp-store-tags">
                <span class="sp-badge sp-badge--success">{icon("truck", 13)} ارسال رایگان</span>
                <span class="sp-badge sp-badge--success">{icon("check-circle", 13)} تضمین تاریخ</span>
                <span class="sp-badge">{icon("walk", 13)} مراجعه حضوری</span>
              </div>
            </div>
          </div>
          <div class="sp-store-promo">
            {icon("gift", 20)}
            <span>ویژه پرو: حذف هزینه ارسال برای خرید بالای ۲۵۰ هزار تومان</span>
          </div>
        </section>

        <!-- In-store search -->
        <form class="sp-search sp-store-search" @submit.prevent role="search">
          {icon("search", 19)}
          <input type="search" placeholder="جستجو در سوپرمارکت لوکس - یاران دریان (جردن)"
                 aria-label="جستجو در این فروشگاه" />
        </form>

        <div class="sp-shell">
          <div>
            {rail("تخفیف نارنجی!", sorted(
                [p for p in products if p.get("discountRatio", 0) > 0],
                key=lambda p: -p["discountRatio"])[:12],
                subtitle="فقط در همین فروشگاه", promo=True)}

            <section class="sp-section">
              {section_head("دسته‌بندی‌های این فروشگاه")}
              <div class="sp-store-cats">{cat_tiles}</div>
            </section>

            {rail("تازه‌ترین‌های قفسه", pick("produce", 12), more_href="market.html?c=produce")}
            {rail("لبنیات", pick("dairy", 12), more_href="market.html?c=dairy")}
            {rail("نوشیدنی", pick("drinks", 12), more_href="market.html?c=drinks")}
            {rail("خواربار", pick("pantry", 12), more_href="market.html?c=pantry")}
          </div>

          <!-- Docked basket -->
          <aside class="sp-card sp-card-pad sp-sticky">
            <h2 class="sp-section-title" style="margin-block-end:12px">سبد خرید شما</h2>

            <div x-show="cart.length === 0" x-cloak>
              <p class="sp-empty-text" style="text-align:center;padding-block:20px">
                هنوز چیزی اضافه نکرده‌اید.
              </p>
            </div>

            <div x-show="cart.length > 0" x-cloak>
              <div style="max-block-size:340px;overflow-y:auto;margin-inline:-8px">
                <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="toman(line.final * line.qty)"></div>
                    </div>
                    <div class="sp-qty">
                      <button type="button" @click="addToCart(line.id)" aria-label="افزایش">
                        {icon("plus", 15)}</button>
                      <span class="sp-qty-val" x-text="fa(line.qty)"></span>
                      <button type="button" @click="decrement(line.id)" aria-label="کاهش">
                        {icon("minus", 15)}</button>
                    </div>
                  </div>
                </template>
              </div>
              <hr class="sp-divider" />
              <div class="sp-invoice-row sp-invoice-row--total">
                <span>جمع سبد</span><b x-text="toman(cartTotal)"></b>
              </div>
              <a href="checkout.html" class="sp-btn sp-btn--primary sp-btn--block sp-btn--lg"
                 style="margin-block-start:14px">تکمیل خرید</a>
            </div>
          </aside>
        </div>
      </div>"""
