# -*- coding: utf-8 -*-
"""
Superium — reusable markup components
=====================================

Server-side (build-time) renderers for the pieces that repeat across pages:
product cards, category displays, rails, breadcrumbs.

Cards are rendered as static HTML rather than Alpine templates so the pages
are crawlable and work with JavaScript disabled. The interactive bits — the
quantity stepper, the wishlist heart — are Alpine-bound on top of that static
markup.
"""

from __future__ import annotations

from layout import icon


def fa(value) -> str:
    """1234567 -> ۱,۲۳۴,۵۶۷ (build-time twin of the JS helper)."""
    return f"{int(value):,}".translate(str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹"))


# --------------------------------------------------------------------------
# Product card
# --------------------------------------------------------------------------


def product_card(p: dict, *, rail: bool = False, show_stamp: bool = False) -> str:
    """
    One product card.

    rail        wraps in a swiper-slide
    show_stamp  adds the subsidy stamp seen on staple goods
    """
    pid = p["id"]
    has_discount = p.get("discountRatio", 0) > 0

    flags = []
    if has_discount:
        flags.append(
            f'<span class="sp-badge sp-badge--discount">{fa(p["discountRatio"])}٪</span>'
        )
    if show_stamp:
        flags.append('<span class="sp-badge sp-badge--stamp"><span>کالا</span><span>برگ</span></span>')
    flags_html = f'<div class="sp-product-flags">{"".join(flags)}</div>' if flags else ""

    old_price = (
        f'<div class="sp-product-price-old">{fa(p["price"])}</div>' if has_discount else ""
    )

    card = f"""<article class="sp-product-card">
  {flags_html}
  <button type="button" class="sp-product-wish"
          :class="{{ 'is-active': isFavourite('{pid}') }}"
          @click="toggleFavourite('{pid}')" aria-label="افزودن به علاقه‌مندی‌ها">
    {icon("heart", 17)}
  </button>
  <a href="product.html?id={pid}" class="sp-product-img-wrap">
    <img class="sp-product-photo" src="{p['image']}" alt="{p['title']}"
         width="600" height="600" loading="lazy" />
  </a>
  <a href="product.html?id={pid}" class="sp-product-title">{p['title']}</a>
  <div class="sp-product-foot">
    <div class="sp-product-prices">
      {old_price}
      <div class="sp-product-price">
        <span class="sp-product-price-from">از</span>
        <span>{fa(p['final'])}</span><small>تومان</small>
      </div>
    </div>
    <template x-if="qtyOf('{pid}') === 0">
      <button type="button" class="sp-qty-add" @click="addToCart('{pid}')"
              aria-label="افزودن به سبد">{icon("plus", 18)}</button>
    </template>
    <template x-if="qtyOf('{pid}') > 0">
      <div class="sp-qty">
        <button type="button" @click="addToCart('{pid}')" aria-label="افزایش">{icon("plus", 16)}</button>
        <span class="sp-qty-val" x-text="fa(qtyOf('{pid}'))"></span>
        <button type="button" @click="decrement('{pid}')" aria-label="کاهش">{icon("minus", 16)}</button>
      </div>
    </template>
  </div>
</article>"""

    return f'<div class="swiper-slide">{card}</div>' if rail else card


def product_grid(products: list[dict], *, stamp_every: int = 0) -> str:
    cards = [
        product_card(p, show_stamp=bool(stamp_every) and i % stamp_every == 0)
        for i, p in enumerate(products)
    ]
    return f'<div class="sp-product-grid">{"".join(cards)}</div>'


# --------------------------------------------------------------------------
# Rails
# --------------------------------------------------------------------------


def rail(
    title: str,
    products: list[dict],
    *,
    more_href: str = "market.html",
    subtitle: str = "",
    promo: bool = False,
) -> str:
    """A horizontal product rail with its own prev/next buttons."""
    slides = "".join(product_card(p, rail=True) for p in products)
    sub = f'<div class="sp-section-sub">{subtitle}</div>' if subtitle else ""
    wrap_class = "sp-rail sp-rail--promo" if promo else "sp-rail"

    return f"""
      <section class="sp-section" data-sp-rail-scope>
        <div class="{wrap_class}">
          <div class="sp-section-head">
            <div>
              <h2 class="sp-section-title">{title}</h2>
              {sub}
            </div>
            <div style="display:flex;align-items:center;gap:8px">
              <a href="{more_href}" class="sp-section-more">
                <span>مشاهده همه</span>{icon("chevron-start", 16)}
              </a>
              <button type="button" class="sp-rail-nav" data-sp-rail-prev aria-label="قبلی">
                {icon("chevron-end", 18)}
              </button>
              <button type="button" class="sp-rail-nav" data-sp-rail-next aria-label="بعدی">
                {icon("chevron-start", 18)}
              </button>
            </div>
          </div>
          <div class="swiper" data-sp-rail>
            <div class="swiper-wrapper">{slides}</div>
          </div>
        </div>
      </section>"""


# --------------------------------------------------------------------------
# Category displays
# --------------------------------------------------------------------------


# Per-category tint, presentation only — the catalogue itself stays colour-free.
# Each value feeds --sp-cat-tint on the card; unknown slugs fall back to the
# palette's primary, so adding a category never breaks the board.
# The tint is also chip text on hover, so every value clears 4.5:1 on white.
CATEGORY_TINTS = {
    "dairy": "#2563d6",
    "produce": "#12803c",
    "drinks": "#c62c3d",
    "snacks": "#8226d6",
    "pantry": "#a35f12",
    "breakfast": "#9a6106",
    "cleaning": "#0e7d8a",
    "baby": "#c22b74",
    "frozen": "#1b6ea8",
    "home": "#6021c4",
}


def _category_subs(products: list[dict], slug: str, limit: int = 3) -> list[str]:
    """
    The most common opening word of a category's product titles — «شیر»,
    «ماست», «پنیر» …  Derived from the catalogue rather than hand-written, so
    every sub-link is guaranteed to return rows on the market page.
    """
    counts: dict[str, int] = {}
    for p in products:
        if p["category"] != slug:
            continue
        head = p["title"].split(" ")[0]
        if len(head) > 2:
            counts[head] = counts.get(head, 0) + 1
    ranked = sorted(counts.items(), key=lambda kv: -kv[1])
    return [word for word, _ in ranked[:limit]]


def category_board(categories: list[dict], products: list[dict]) -> str:
    """
    Category cards with a tinted photo well, the category's item count and its
    top sub-categories as chips — the FRESH homepage's category section.
    """
    cards = []
    for c in categories:
        slug = c["slug"]
        tint = CATEGORY_TINTS.get(slug, "var(--sp-primary)")
        count = sum(1 for p in products if p["category"] == slug)
        tags = "".join(
            f'<a href="market.html?c={slug}&amp;q={word}" class="sp-cat-tag">{word}</a>'
            for word in _category_subs(products, slug)
        )
        cards.append(
            f"""<article class="sp-cat-brick" style="--sp-cat-tint:{tint}">
          <a href="market.html?c={slug}" class="sp-cat-brick-main">
            <span class="sp-cat-brick-art">
              <img src="assets/images/categories/{slug}.webp" alt="{c['title']}"
                   width="96" height="96" loading="lazy" />
            </span>
            <span class="sp-cat-brick-text">
              <b class="sp-cat-brick-title">{c['title']}</b>
              <span class="sp-cat-brick-count">{fa(count)} کالا</span>
            </span>
            <span class="sp-cat-brick-go" aria-hidden="true">{icon("chevron-start", 16)}</span>
          </a>
          <div class="sp-cat-brick-tags">{tags}</div>
        </article>"""
        )

    return f'<div class="sp-cat-board">{"".join(cards)}</div>'


def category_rail(categories: list[dict]) -> str:
    items = "".join(
        f'<a href="market.html?c={c["slug"]}" class="sp-cat-pill">'
        f'<img class="sp-cat-pill-img" src="assets/images/categories/{c["slug"]}.webp" '
        f'alt="{c["title"]}" width="84" height="84" loading="lazy" />'
        f'<span class="sp-cat-pill-label">{c["title"]}</span></a>'
        for c in categories
    )
    return f'<div class="sp-cat-rail">{items}</div>'


def category_grid(categories: list[dict]) -> str:
    items = "".join(
        f'<a href="market.html?c={c["slug"]}" class="sp-cat-card">'
        f'<img src="assets/images/categories/{c["slug"]}.webp" alt="" '
        f'width="96" height="96" loading="lazy" />'
        f'<span>{c["title"]}</span></a>'
        for c in categories
    )
    return f'<div class="sp-cat-grid">{items}</div>'


def category_index(categories: list[dict], products: list[dict]) -> str:
    """
    A numbered directory of the shelves — GRAPHITE's category display.

    Rows rather than photo cards: the dark palette then carries ten small light
    thumbs instead of ten full-bleed white blocks, and the section reads as an
    index next to the price-forward grid below it.
    """
    rows = []
    for i, c in enumerate(categories, start=1):
        slug = c["slug"]
        count = sum(1 for p in products if p["category"] == slug)
        subs = "، ".join(_category_subs(products, slug, 3))
        rows.append(
            f"""<a href="market.html?c={slug}" class="sp-cat-row">
          <span class="sp-cat-row-num">{fa(i).rjust(2, "۰")}</span>
          <span class="sp-cat-row-thumb">
            <img src="assets/images/categories/{slug}.webp" alt="" width="54"
                 height="54" loading="lazy" />
          </span>
          <span class="sp-cat-row-text">
            <b>{c['title']}</b>
            <span class="sp-cat-row-subs">{subs}</span>
          </span>
          <span class="sp-cat-row-lead" aria-hidden="true"></span>
          <span class="sp-cat-row-count">{fa(count)} کالا</span>
          <span class="sp-cat-row-go" aria-hidden="true">{icon("chevron-start", 15)}</span>
        </a>"""
        )

    return f'<div class="sp-cat-index">{"".join(rows)}</div>'


def category_tiles(categories: list[dict]) -> str:
    items = "".join(
        f'<a href="market.html?c={c["slug"]}" class="sp-cat-tile">'
        f'<img src="assets/images/categories/{c["slug"]}.webp" alt="" '
        f'width="400" height="300" loading="lazy" />'
        f'<span class="sp-cat-tile-label">{c["title"]}</span></a>'
        for c in categories
    )
    return f'<div class="sp-cat-grid">{items}</div>'


# --------------------------------------------------------------------------
# Misc
# --------------------------------------------------------------------------


def breadcrumb(trail: list[tuple[str, str]]) -> str:
    """trail: [(href, label), ...] — the last item renders as plain text."""
    parts = []
    for i, (href, label) in enumerate(trail):
        last = i == len(trail) - 1
        parts.append(f"<span>{label}</span>" if last else f'<a href="{href}">{label}</a>')
        if not last:
            parts.append('<span class="sp-breadcrumb-sep">/</span>')
    return f'<nav class="sp-breadcrumb" aria-label="مسیر">{"".join(parts)}</nav>'


def section_head(title: str, more_href: str = "", subtitle: str = "") -> str:
    sub = f'<div class="sp-section-sub">{subtitle}</div>' if subtitle else ""
    more = (
        f'<a href="{more_href}" class="sp-section-more"><span>مشاهده همه</span>'
        f'{icon("chevron-start", 16)}</a>'
        if more_href
        else ""
    )
    return f"""<div class="sp-section-head">
      <div><h2 class="sp-section-title">{title}</h2>{sub}</div>{more}
    </div>"""


def empty_state(title: str, text: str, cta_href: str = "", cta_label: str = "") -> str:
    cta = (
        f'<a href="{cta_href}" class="sp-btn sp-btn--primary">{cta_label}</a>'
        if cta_href
        else ""
    )
    return f"""<div class="sp-empty">
      <svg width="76" height="76" viewBox="0 0 48 48" fill="none" stroke="currentColor"
           stroke-width="2" aria-hidden="true">
        <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"/>
      </svg>
      <div class="sp-empty-title">{title}</div>
      <p class="sp-empty-text">{text}</p>
      {cta}
    </div>"""


# --------------------------------------------------------------------------
# Promotional banners
# --------------------------------------------------------------------------


def promo_banner(
    href: str,
    kicker: str,
    title: str,
    text: str,
    *,
    variant: str = "a",
    cta: str = "خرید",
    image: str | None = None,
) -> str:
    """One promo card. `image` is a category slug; omit it for a text-only card."""
    art = (
        f'<img src="assets/images/categories/{image}.webp" alt="" width="200" '
        f'height="200" loading="lazy" />'
        if image
        else ""
    )
    return f"""<a href="{href}" class="sp-promo-banner sp-promo-banner--{variant}">
      <div>
        <span class="sp-promo-kicker">{kicker}</span>
        <b>{title}</b>
        <p>{text}</p>
        <span class="sp-btn sp-btn--primary sp-btn--sm">{cta}</span>
      </div>
      {art}
    </a>"""


def banner_row(banners: list[str], cols: int = 2) -> str:
    """A section of promo cards, sized to sit between two product rails."""
    return f"""
      <section class="sp-section">
        <div class="sp-banner-grid-{cols}">{"".join(banners)}</div>
      </section>"""


def banner_strip(
    href: str,
    kicker: str,
    title: str,
    text: str,
    *,
    cta: str = "مشاهده",
    images: list[str] | None = None,
    variant: str = "warm",
) -> str:
    """
    A full-width strip banner: copy on one side, a row of category shots on
    the other. Reads as a break between rails rather than another card grid.
    """
    art = "".join(
        f'<img src="assets/images/categories/{slug}.webp" alt="" width="120" '
        f'height="120" loading="lazy" />'
        for slug in (images or [])
    )
    return f"""
      <section class="sp-section">
        <a href="{href}" class="sp-strip sp-strip--{variant}">
          <div class="sp-strip-copy">
            <span class="sp-promo-kicker">{kicker}</span>
            <b>{title}</b>
            <p>{text}</p>
            <span class="sp-btn sp-btn--primary">{cta}</span>
          </div>
          <div class="sp-strip-art">{art}</div>
        </a>
      </section>"""
