# -*- coding: utf-8 -*-
"""
Superium — checkout flow
========================

checkout.html     courier ⇄ pickup toggle, timing, discount codes, payment
address-map.html  real OpenStreetMap picker (Leaflet), centre-pin style
address-add.html  manual address entry

The courier/pickup toggle is the spine of this page: switching it swaps the
map panel, the timing options and the shipping line of the invoice, exactly
as the reference flow does.
"""

from __future__ import annotations

from components import breadcrumb, empty_state
from layout import icon

BANKS = [
    ("saman", "بانک سامان"),
    ("pasargad", "پاسارگاد"),
    ("mellat", "بانک ملت"),
    ("ap", "آپ"),
    ("parsian", "بانک پارسیان"),
]

PREP_SLOTS = [
    ("fast", "سریع", "تحویل تا ۴۵ دقیقه", "۶,۰۰۰ تومان ویژه شما", True),
    ("later", "ارسال در زمان دیگر", "تحویل در زمان دلخواه", "۶,۰۰۰ تومان ویژه شما", False),
]

PICKUP_SLOTS = [
    ("now", "دریافت حضوری از فروشگاه", "آماده‌سازی تا ۱۵ دقیقه", "رایگان ویژه شما", True),
]


def live_map(
    *,
    lat: float = 35.7719,
    lng: float = 51.4344,
    zoom: int = 15,
    interactive: bool = False,
    label: str = "",
) -> str:
    """
    A real OpenStreetMap map, rendered by Leaflet (vendored in
    assets/vendor/leaflet — no CDN, no API key).

    The schematic SVG below it stays as a fallback: if Leaflet or the tile
    server is unreachable, the drawing shows through instead of an empty box.

    interactive=True gives a draggable/zoomable map with a fixed centre pin
    for picking an address; False renders a still preview with a marker.
    """
    return (
        f'<div class="sp-map-live" data-sp-map-live '
        f'data-lat="{lat}" data-lng="{lng}" data-zoom="{zoom}" '
        f'data-interactive="{"1" if interactive else "0"}" '
        f'data-label="{label}"></div>'
        + _map_svg(label)
    )


def _map_svg(pin_label: str = "") -> str:
    """
    Fallback drawing shown when the live map cannot load (offline, blocked
    tile host). Weighs nothing and needs no network.
    """
    label = (
        f'<rect x="-34" y="-47" width="68" height="21" rx="6" fill="var(--sp-text)" />'
        f'<text x="0" y="-32.5" fill="var(--sp-surface)" font-size="11" '
        f'text-anchor="middle" font-family="Vazirmatn, sans-serif">{pin_label}</text>'
        if pin_label
        else ""
    )

    # Blocks laid on a 120×90 street grid.
    blocks = "".join(
        f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="3" />'
        for x, y, w, h in [
            (18, 16, 84, 52), (138, 16, 60, 52), (234, 16, 84, 52),
            (354, 16, 60, 52), (450, 16, 84, 52), (570, 16, 60, 52),
            (666, 16, 84, 52), (786, 16, 60, 52), (882, 16, 84, 52),
            (18, 106, 60, 52), (114, 106, 84, 52), (234, 106, 60, 52),
            (330, 106, 84, 52), (450, 106, 60, 52), (546, 106, 84, 52),
            (666, 106, 60, 52), (762, 106, 84, 52), (882, 106, 60, 52),
            (18, 196, 84, 44), (138, 196, 60, 44), (234, 196, 84, 44),
            (354, 196, 60, 44), (450, 196, 84, 44), (570, 196, 60, 44),
            (666, 196, 84, 44), (786, 196, 60, 44), (882, 196, 84, 44),
        ]
    )

    return f"""
      <svg class="sp-map-canvas" viewBox="0 0 960 260" role="img"
           aria-label="نقشه محدوده تحویل" preserveAspectRatio="xMidYMid slice">
        <rect width="960" height="260" fill="var(--sp-surface-2)" />
        <g fill="var(--sp-border)" opacity="0.6">{blocks}</g>
        <g stroke="var(--sp-border-strong)" stroke-width="7" opacity="0.75">
          <path d="M0 88h960M0 178h960" />
          <path d="M114 0v260M330 0v260M546 0v260M762 0v260" />
        </g>
        <path d="M0 133h960" stroke="var(--sp-border-strong)" stroke-width="12" />
        <g opacity="0.45" fill="var(--sp-accent)">
          <rect x="600" y="196" width="84" height="44" rx="6" />
          <rect x="234" y="16" width="84" height="52" rx="6" />
        </g>
        <g transform="translate(480 118)">
          <ellipse cx="0" cy="27" rx="13" ry="4" fill="rgba(0,0,0,.22)" />
          <path d="M0 24C0 24 14 10 14 -1A14 14 0 10-14 -1C-14 10 0 24 0 24z"
                fill="var(--sp-primary)" />
          <circle cx="0" cy="-1" r="5" fill="#fff" />
          {label}
        </g>
      </svg>"""


# ==========================================================================
# checkout.html
# ==========================================================================


def checkout() -> str:
    banks = "".join(
        f"""<button type="button" class="sp-option" :class="{{ 'is-active': bank === '{key}' }}"
             @click="bank = '{key}'">
          <span class="sp-option-dot"></span>
          <span class="sp-option-body"><span class="sp-option-title">{label}</span></span>
          <span class="sp-bank-mark">{icon("wallet", 20)}</span>
        </button>"""
        for key, label in BANKS
    )

    def slots(rows, model):
        return "".join(
            f"""<button type="button" class="sp-option"
                 :class="{{ 'is-active': {model} === '{key}' }}" @click="{model} = '{key}'">
              <span class="sp-option-dot"></span>
              <span class="sp-option-body">
                <span class="sp-option-title">{title}</span>
                <span class="sp-option-meta">{meta} &nbsp;|&nbsp; {price}</span>
              </span>
              <span class="sp-option-icon">{icon("clock", 24)}</span>
            </button>"""
            for key, title, meta, price, _ in rows
        )

    return f"""
      <div class="sp-container" x-data="superiumCheckout()">
        {breadcrumb([
            ("home-1-fresh.html", "خانه"),
            ("cart.html", "سبد خرید"),
            ("checkout.html", "بررسی نهایی"),
        ])}

        <ol class="sp-steps">
          <li class="is-done"><span>{icon("check", 14)}</span>سبد خرید</li>
          <li class="is-done"><span>{icon("check", 14)}</span>انتخاب فروشگاه</li>
          <li class="is-active"><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>
          <!-- ============ Main column ============ -->
          <section>
            <div class="sp-section-head">
              <div>
                <h1 class="sp-section-title">بررسی نهایی</h1>
                <div class="sp-section-sub">سوپرمارکت لوکس - یاران دریان (جردن)</div>
              </div>
            </div>

            <!-- Delivery mode -->
            <div class="sp-mode-toggle" role="tablist" aria-label="شیوه دریافت">
              <button type="button" role="tab" :aria-selected="mode === 'courier'"
                      :class="{{ 'is-active': mode === 'courier' }}" @click="mode = 'courier'">
                {icon("truck", 18)}<span>ارسال با پیک</span>
              </button>
              <button type="button" role="tab" :aria-selected="mode === 'pickup'"
                      :class="{{ 'is-active': mode === 'pickup' }}" @click="mode = 'pickup'">
                {icon("walk", 18)}<span>دریافت حضوری</span>
              </button>
            </div>

            <!-- Map + address / store -->
            <div class="sp-card" style="overflow:hidden;margin-block-end:16px">
              <div class="sp-map-frame">{live_map(zoom=15)}</div>

              <div class="sp-address-bar" x-show="mode === 'courier'" x-cloak>
                <span class="sp-address-icon">{icon("pin", 20)}</span>
                <div class="sp-address-body">
                  <div class="sp-address-title">
                    ارسال به منزل {icon("chevron-down", 15)}
                  </div>
                  <div class="sp-address-text">
                    تهران، محله زرگنده، شریعتی، سیما جنوبی، پلاک ۸، طبقه ۳
                  </div>
                </div>
                <a href="address-map.html" class="sp-btn sp-btn--ghost sp-btn--sm">تغییر آدرس</a>
              </div>

              <div class="sp-address-bar" x-show="mode === 'pickup'" x-cloak>
                <span class="sp-address-icon">{icon("store", 20)}</span>
                <div class="sp-address-body">
                  <div class="sp-address-title">سوپرمارکت لوکس - یاران دریان (جردن)</div>
                  <div class="sp-address-text">امانیه، بلوار نلسون ماندلا، خ ناهید شرقی</div>
                </div>
                <a href="address-map.html" class="sp-btn sp-btn--ghost sp-btn--sm">مسیریابی</a>
              </div>
            </div>

            <!-- Timing -->
            <div class="sp-card sp-card-pad" style="margin-block-end:16px">
              <div class="sp-panel-head">
                <b x-text="mode === 'courier' ? 'زمان ارسال' : 'زمان آماده‌سازی'"></b>
                <span class="sp-powered" dir="ltr">Powered by {icon("truck", 15)} SuperiumBox</span>
              </div>
              <div style="display:flex;flex-direction:column;gap:10px">
                <div x-show="mode === 'courier'" x-cloak
                     style="display:flex;flex-direction:column;gap:10px">
                  {slots(PREP_SLOTS, "slot")}
                </div>
                <div x-show="mode === 'pickup'" x-cloak>
                  {slots(PICKUP_SLOTS, "slot")}
                </div>
              </div>
            </div>

            <!-- Codes -->
            <div class="sp-card" style="margin-block-end:16px">
              <button type="button" class="sp-accordion-head" @click="codeOpen = !codeOpen"
                      :aria-expanded="codeOpen">
                {icon("percent", 20)}<span>کد تخفیف دارید؟</span>
                <span class="sp-accordion-chevron" :class="{{ 'is-open': codeOpen }}">
                  {icon("chevron-down", 18)}
                </span>
              </button>
              <div class="sp-accordion-body" x-show="codeOpen" x-cloak x-collapse>
                <form style="display:flex;gap:8px" @submit.prevent="applyCode()">
                  <input type="text" class="sp-input" x-model="code"
                         placeholder="کد تخفیف را وارد کنید" />
                  <button type="submit" class="sp-btn sp-btn--primary">اعمال</button>
                </form>
                <p class="sp-hint" x-show="codeMsg" x-cloak x-text="codeMsg"></p>
              </div>

              <hr class="sp-divider" style="margin:0" />

              <button type="button" class="sp-accordion-head" @click="giftOpen = !giftOpen"
                      :aria-expanded="giftOpen">
                {icon("gift", 20)}<span>ثبت کد کالابرگ</span>
                <span class="sp-badge sp-badge--warning">از کجا دریافت کنم؟</span>
                <span class="sp-accordion-chevron" :class="{{ 'is-open': giftOpen }}">
                  {icon("chevron-down", 18)}
                </span>
              </button>
              <div class="sp-accordion-body" x-show="giftOpen" x-cloak x-collapse>
                <form style="display:flex;gap:8px" @submit.prevent="notify('کد کالابرگ ثبت شد')">
                  <input type="text" class="sp-input" placeholder="کد ۱۶ رقمی کالابرگ" />
                  <button type="submit" class="sp-btn sp-btn--primary">ثبت</button>
                </form>
              </div>
            </div>

            <!-- Payment -->
            <div class="sp-card sp-card-pad">
              <div class="sp-panel-head"><b>پرداخت آنلاین با</b></div>
              <button type="button" class="sp-option" :class="{{ 'is-active': bank === 'credit' }}"
                      @click="bank = 'credit'" style="margin-block-end:10px">
                <span class="sp-option-dot"></span>
                <span class="sp-option-body">
                  <span class="sp-option-title">پرداخت با اعتبار سوپریوم</span>
                  <span class="sp-option-meta">مانده اعتبار ماهانه: ۲,۰۰۰,۰۰۰ تومان</span>
                </span>
                <span class="sp-option-icon">{icon("wallet", 24)}</span>
              </button>
              <div style="display:flex;flex-direction:column;gap:10px">{banks}</div>
            </div>
          </section>

          <!-- ============ Invoice ============ -->
          <aside class="sp-card sp-card-pad sp-sticky">
            <div class="sp-section-head">
              <h2 class="sp-section-title">صورتحساب</h2>
              <a href="cart.html" class="sp-section-more">
                <span>مشاهده کالاها</span>{icon("chevron-start", 15)}
              </a>
            </div>

            <div class="sp-invoice">
              <div class="sp-invoice-row">
                <span>مجموع کالاها</span><span x-text="toman(cartGross)"></span>
              </div>
              <div class="sp-invoice-row sp-invoice-row--save" x-show="totalSaving > 0" x-cloak>
                <span>سود شما از این خرید</span><span x-text="toman(totalSaving)"></span>
              </div>
              <div class="sp-invoice-row">
                <span>هزینه آماده‌سازی</span><span x-text="toman(prepFee)"></span>
              </div>
              <div class="sp-invoice-row">
                <span>هزینه ارسال</span>
                <span x-show="mode === 'pickup'" x-cloak>
                  <span class="sp-badge sp-badge--brand">Pro</span> رایگان
                </span>
                <span x-show="mode === 'courier'" x-cloak>
                  <span class="sp-badge sp-badge--brand">Pro</span>
                  <span x-text="toman(shippingFee)"></span>
                </span>
              </div>
              <hr class="sp-divider" />
              <div class="sp-invoice-row sp-invoice-row--total">
                <span>مبلغ قابل پرداخت</span><b x-text="toman(payable)"></b>
              </div>
            </div>

            <button type="button" class="sp-accordion-head" style="padding-inline:0"
                    @click="noteOpen = !noteOpen">
              {icon("list", 19)}<span>افزودن یادداشت برای فروشگاه</span>
              <span class="sp-accordion-chevron" :class="{{ 'is-open': noteOpen }}">
                {icon("chevron-down", 18)}
              </span>
            </button>
            <div x-show="noteOpen" x-cloak x-collapse>
              <textarea class="sp-textarea" placeholder="مثلاً: میوه‌ها را رسیده انتخاب کنید"
                        style="min-block-size:80px"></textarea>
            </div>

            <button type="button" class="sp-btn sp-btn--primary sp-btn--block sp-btn--lg"
                    style="margin-block-start:14px" @click="submitOrder()">
              تأیید و پرداخت
            </button>
          </aside>
        </div>

        <!-- Success -->
        <div class="sp-modal-backdrop" x-show="done" x-cloak @click.self="done = false"
             x-transition.opacity>
          <div class="sp-modal" role="dialog" aria-modal="true">
            <div class="sp-modal-body" style="text-align:center;padding-block:34px">
              <div class="sp-success-mark">{icon("check", 34)}</div>
              <h2 class="sp-modal-title" style="margin-block:16px 8px">سفارش شما ثبت شد</h2>
              <p class="sp-empty-text" style="margin-inline:auto">
                کد پیگیری: <b>SP-۱۴۰۵۰۳۱۲</b><br />
                فروشگاه در حال جمع‌آوری سبد شماست.
              </p>
              <div style="display:flex;gap:10px;justify-content:center;margin-block-start:20px">
                <a href="profile-orders.html" class="sp-btn sp-btn--primary">پیگیری سفارش</a>
                <a href="home-1-fresh.html" class="sp-btn sp-btn--ghost">بازگشت به خانه</a>
              </div>
            </div>
          </div>
        </div>
      </div>"""


# ==========================================================================
# address-map.html
# ==========================================================================


def address_map() -> str:
    return f"""
      <!-- The map picker is plain JS (superium-map.js), not an Alpine
           component - it binds to [data-sp-map] on the frame below. -->
      <div class="sp-container">
        {breadcrumb([
            ("home-1-fresh.html", "خانه"),
            ("profile-addresses.html", "آدرس‌ها"),
            ("address-map.html", "انتخاب روی نقشه"),
        ])}

        <div class="sp-shell">
          <section class="sp-card" style="overflow:hidden">
            <div class="sp-panel-head" style="padding:16px 18px">
              <b>محل تحویل سفارش را انتخاب کنید</b>
              <a href="profile-addresses.html" class="sp-section-more">
                {icon("chevron-end", 16)}<span>بازگشت</span>
              </a>
            </div>

            <!-- City + search -->
            <div class="sp-map-search">
              <select class="sp-select" style="max-inline-size:130px" aria-label="انتخاب شهر">
                <option>تهران</option><option>کرج</option><option>مشهد</option>
                <option>اصفهان</option><option>شیراز</option>
              </select>
              <div class="sp-search" style="flex:1">
                {icon("search", 19)}
                <input type="search" placeholder="جستجوی محله، خیابان و ..."
                       aria-label="جستجوی نشانی" />
              </div>
            </div>

            <!-- Draggable pin map -->
            <div class="sp-map-frame sp-map-frame--tall" data-sp-map>
              {live_map(interactive=True, zoom=16, label="محل تحویل")}
              <button type="button" class="sp-map-pin" data-sp-map-pin
                      aria-label="جابه‌جایی پین روی نقشه">
                {icon("pin", 30)}
              </button>
              <div class="sp-map-hint" data-sp-map-hint>
                برای انتخاب محل تحویل، نقشه را حرکت دهید
              </div>
              <button type="button" class="sp-map-locate" data-sp-map-locate>
                {icon("target", 18)}<span>موقعیت من</span>
              </button>
            </div>

            <div class="sp-map-foot">
              <div>
                <div class="sp-address-title">نشانی انتخاب‌شده</div>
                <div class="sp-address-text" data-sp-map-address>
                  تهران، محله زرگنده، شریعتی، سیما جنوبی
                </div>
              </div>
              <a href="address-add.html" class="sp-btn sp-btn--primary sp-btn--lg">تأیید موقعیت</a>
            </div>
          </section>

          <!-- Saved addresses -->
          <aside class="sp-card sp-card-pad sp-sticky" x-data="{{ saved: 'home' }}">
            <h2 class="sp-section-title" style="margin-block-end:12px">آدرس‌های ذخیره‌شده</h2>

            <button type="button" class="sp-option"
                    :class="{{ 'is-active': saved === 'home' }}" @click="saved = 'home'">
              <span class="sp-option-dot"></span>
              <span class="sp-option-body">
                <span class="sp-option-title">خانه</span>
                <span class="sp-option-meta">تهران، زرگنده، سیما جنوبی، پلاک ۸</span>
              </span>
              <span class="sp-option-icon">{icon("home", 22)}</span>
            </button>

            <button type="button" class="sp-option" style="margin-block-start:10px"
                    :class="{{ 'is-active': saved === 'work' }}" @click="saved = 'work'">
              <span class="sp-option-dot"></span>
              <span class="sp-option-body">
                <span class="sp-option-title">محل کار</span>
                <span class="sp-option-meta">تهران، جردن، بلوار نلسون ماندلا، پلاک ۲۴</span>
              </span>
              <span class="sp-option-icon">{icon("briefcase", 22)}</span>
            </button>

            <div class="sp-out-of-range">
              {icon("info", 18)}
              <div>
                <b>خارج از محدوده</b>
                <span>قم، سعادتی، بلوار جمهوری اسلامی - این آدرس فعلاً پوشش داده نمی‌شود.</span>
              </div>
            </div>

            <a href="address-add.html" class="sp-btn sp-btn--outline sp-btn--block"
               style="margin-block-start:14px">
              {icon("plus", 18)}<span>افزودن آدرس جدید</span>
            </a>
          </aside>
        </div>
      </div>"""


# ==========================================================================
# address-add.html
# ==========================================================================


def address_add() -> str:
    return f"""
      <div class="sp-container">
        {breadcrumb([
            ("home-1-fresh.html", "خانه"),
            ("profile-addresses.html", "آدرس‌ها"),
            ("address-add.html", "افزودن آدرس"),
        ])}

        <div class="sp-narrow">
          <div class="sp-card" style="overflow:hidden">
            <div class="sp-map-frame">{live_map(zoom=16, label="محل تحویل")}</div>

            <form class="sp-card-pad" @submit.prevent="notify('آدرس با موفقیت ثبت شد')">
              <div class="sp-section-head" style="margin-block-end:18px">
                <h1 class="sp-section-title">جزئیات آدرس</h1>
                <a href="address-map.html" class="sp-section-more">
                  {icon("pin", 15)}<span>ویرایش روی نقشه</span>
                </a>
              </div>

              <label class="sp-field">
                <span class="sp-label">نشانی <span class="sp-req">*</span></span>
                <textarea class="sp-textarea" required
                          placeholder="شهر، محله، خیابان اصلی و فرعی">شهر تهران، محله زرگنده، شریعتی، سیما جنوبی</textarea>
              </label>

              <div class="sp-form-row">
                <label class="sp-field">
                  <span class="sp-label">پلاک <span class="sp-req">*</span></span>
                  <input type="text" class="sp-input" placeholder="مثال: ۱۲" required
                         inputmode="numeric" />
                </label>
                <label class="sp-field">
                  <span class="sp-label">واحد</span>
                  <input type="text" class="sp-input" placeholder="مثال: ۴" inputmode="numeric" />
                </label>
                <label class="sp-field">
                  <span class="sp-label">کد پستی</span>
                  <input type="text" class="sp-input" placeholder="۱۰ رقم" inputmode="numeric"
                         maxlength="10" />
                </label>
              </div>

              <div class="sp-field">
                <span class="sp-label">عنوان آدرس (اختیاری)</span>
                <input type="text" class="sp-input" placeholder="مثال: خانه" />
                <div class="sp-chip-row" style="margin-block-start:10px">
                  <button type="button" class="sp-chip is-active">{icon("home", 16)}<span>خانه</span></button>
                  <button type="button" class="sp-chip">{icon("briefcase", 16)}<span>محل کار</span></button>
                  <button type="button" class="sp-chip">{icon("pin", 16)}<span>سایر</span></button>
                </div>
              </div>

              <hr class="sp-divider" />

              <div class="sp-form-row">
                <label class="sp-field">
                  <span class="sp-label">نام تحویل‌گیرنده <span class="sp-req">*</span></span>
                  <input type="text" class="sp-input" value="زهرا احمدی" required />
                </label>
                <label class="sp-field">
                  <span class="sp-label">موبایل تحویل‌گیرنده <span class="sp-req">*</span></span>
                  <input type="tel" class="sp-input" value="۰۹۳۹۹۹۹۹۹۹۹" required
                         inputmode="tel" />
                </label>
              </div>

              <label class="sp-check" style="margin-block-end:16px">
                <input type="checkbox" checked />
                <span>این آدرس را به‌عنوان آدرس پیش‌فرض ذخیره کن</span>
              </label>

              <div style="display:flex;gap:10px;flex-wrap:wrap">
                <button type="submit" class="sp-btn sp-btn--primary sp-btn--lg" style="flex:1">
                  تأیید آدرس
                </button>
                <a href="profile-addresses.html" class="sp-btn sp-btn--ghost sp-btn--lg">انصراف</a>
              </div>
            </form>
          </div>
        </div>
      </div>"""
