# -*- coding: utf-8 -*-
"""
Superium — the three homepages
==============================

Each homepage is a different layout architecture, not a recolour:

  home-1-fresh     warm     A — full-bleed collage hero, category board with
                            sub-category chips,
                            horizontal product rails, wide footer
  home-2-aqua      cool     B — split hero with an overlapping delivery card,
                            square category grid, bento featured block,
                            compact footer + newsletter
  home-3-graphite  neutral  C — dark banner hero, numbered shelf index whose
                            thumbs colourise on hover, dense price-forward
                            grid, slim footer

Palettes live in assets/css/superium-palettes.css under the matching
body.sp-theme--* class; nothing here hard-codes a colour.
"""

from __future__ import annotations

from components import (
    banner_row,
    banner_strip,
    category_board,
    category_grid,
    category_index,
    category_rail,
    category_tiles,
    fa,
    product_card,
    product_grid,
    promo_banner,
    rail,
    section_head,
)
from layout import icon


def _pick(products: list[dict], slug: str, n: int, offset: int = 0) -> list[dict]:
    rows = [p for p in products if p["category"] == slug]
    return rows[offset : offset + n]


def _discounted(products: list[dict], n: int) -> list[dict]:
    rows = sorted(
        [p for p in products if p.get("discountRatio", 0) > 0],
        key=lambda p: -p["discountRatio"],
    )
    return rows[:n]


# ==========================================================================
# 1 — FRESH (warm)
# ==========================================================================


def home_fresh(products: list[dict], categories: list[dict]) -> str:
    hero_tiles = "".join(
        f"""
          <a href="market.html?c={c['slug']}" class="sp-hero-tile">
            <img src="assets/images/categories/{c['slug']}.webp" alt="" width="200"
                 height="200" loading="{'eager' if i < 2 else 'lazy'}" />
            <span>{c['title']}</span>
          </a>"""
        for i, c in enumerate(categories[:4])
    )

    return f"""
      <!-- ===== HERO: collage + address bar ===== -->
      <section class="sp-hero-fresh">
        <div class="sp-container">
          <div class="sp-hero-fresh-grid">
            <div class="sp-hero-fresh-copy">
              <span class="sp-hero-eyebrow">ارسال از سوپرمارکت‌های محله</span>
              <h1 class="sp-hero-title">
                خرید سوپرمارکتی،<br />
                <em>تازه‌تر و سریع‌تر</em>
              </h1>
              <p class="sp-hero-lead">
                سبد خریدتان را ببندید تا قیمتش را بین فروشگاه‌های اطراف مقایسه
                کنیم. همان قیمت درب فروشگاه، تحویل زیر ۴۵ دقیقه.
              </p>

              <form class="sp-hero-search" @submit.prevent role="search">
                <div class="sp-hero-search-loc">
                  {icon("pin", 18)}<span>جردن، بلوار نلسون ماندلا</span>
                </div>
                <div class="sp-hero-search-field">
                  {icon("search", 19)}
                  <input type="search" placeholder="چه چیزی لازم دارید؟"
                         aria-label="جستجوی کالا" />
                </div>
                <button type="submit" class="sp-btn sp-btn--primary">جستجو</button>
              </form>

              <div class="sp-hero-stats">
                <div><b>۱۹</b><span>فروشگاه اطراف شما</span></div>
                <div><b>۴۵</b><span>دقیقه تا تحویل</span></div>
                <div><b>۰</b><span>هزینه جمع‌آوری سفارش</span></div>
              </div>
            </div>

            <div class="sp-hero-fresh-collage">{hero_tiles}</div>
          </div>
        </div>
      </section>

      <div class="sp-container">
        <!-- ===== Category rail ===== -->
        <section class="sp-section">
          {section_head("خرید از دسته‌بندی‌ها", "market.html",
                        f"{fa(len(categories))} دسته‌بندی، "
                        f"{fa(len(products))} قلم کالای روزانه")}
          {category_board(categories, products)}
        </section>

        <!-- ===== Promo rail ===== -->
        {rail(
            "ویژه خرید اول!",
            _discounted(products, 12),
            more_href="market.html?sort=discount",
            subtitle="تخفیف‌های امروز، تا پایان موجودی",
            promo=True,
        )}

        <!-- ===== Delivery promise ===== -->
        <section class="sp-section">
          <div class="sp-promise">
            <div class="sp-promise-item">
              {icon("walk", 30, stroke=1.5)}
              <div><b>دریافت حضوری</b><span>آماده‌سازی تا ۱۵ دقیقه، رایگان</span></div>
            </div>
            <div class="sp-promise-item">
              {icon("truck", 30, stroke=1.5)}
              <div><b>ارسال با پیک</b><span>تحویل تا ۴۵ دقیقه درب منزل</span></div>
            </div>
            <div class="sp-promise-item">
              {icon("shield", 30, stroke=1.5)}
              <div><b>تضمین تاریخ</b><span>کالای تاریخ‌گذشته تحویل نمی‌گیرید</span></div>
            </div>
            <div class="sp-promise-item">
              {icon("percent", 30, stroke=1.5)}
              <div><b>قیمت فروشگاه</b><span>بدون افزایش قیمت، بدون کارمزد</span></div>
            </div>
          </div>
        </section>

        {rail("تازه‌تر از تازه", _pick(products, "produce", 12),
              more_href="market.html?c=produce",
              subtitle="میوه و سبزیجات، هر روز صبح از میدان")}

        <!-- ===== Banner section 1 of 2 ===== -->
        {banner_row([
            promo_banner("market.html?c=dairy", "تا ۲۵٪ تخفیف", "لبنیات صبحانه",
                         "شیر، پنیر، خامه و ماست تازه‌ی روز",
                         variant="a", image="dairy"),
            promo_banner("market.html?c=cleaning", "پیشنهاد هفته", "شوینده و بهداشتی",
                         "خانه‌تکانی را ارزان‌تر تمام کنید",
                         variant="b", image="cleaning"),
        ])}

        {rail("خنک شو!", _pick(products, "drinks", 12),
              more_href="market.html?c=drinks",
              subtitle="نوشیدنی، بستنی و هر چیز خنک")}

        <!-- ===== Banner section 2 of 2 ===== -->
        {banner_strip("market.html?sort=discount", "سبد هفتگی",
                      "یک بار سفارش، خرید کل هفته",
                      "اقلام پرمصرف خانه را یک‌جا سفارش دهید و در یک نوبت تحویل بگیرید.",
                      cta="مشاهده اقلام",
                      images=["pantry", "dairy", "produce", "home"],
                      variant="warm")}

        {rail("قفسه تنقلات", _pick(products, "snacks", 12),
              more_href="market.html?c=snacks")}

        {rail("سبد هفتگی خانه", _pick(products, "pantry", 12),
              more_href="market.html?c=pantry",
              subtitle="برنج، روغن، حبوبات و نان")}
      </div>"""


# ==========================================================================
# 2 — AQUA (cool)
# ==========================================================================


def home_aqua(products: list[dict], categories: list[dict]) -> str:
    bento_lead = _discounted(products, 1)[0]
    bento_rest = _discounted(products, 9)[1:]

    bento_cards = "".join(f'<div class="sp-bento-cell">{product_card(p)}</div>'
                          for p in bento_rest)

    return f"""
      <!-- ===== HERO: split with overlapping delivery card ===== -->
      <section class="sp-hero-aqua">
        <div class="sp-container">
          <div class="sp-hero-aqua-grid">
            <div class="sp-hero-aqua-copy">
              <span class="sp-hero-eyebrow">{icon("check-circle", 16)} ۱۹ فروشگاه در محدوده شما</span>
              <h1 class="sp-hero-title">
                همه‌ی خرید هفته،<br />یک سفارش
              </h1>
              <p class="sp-hero-lead">
                یک بار سبد ببندید. ما قیمت آن را بین سوپرمارکت‌های اطراف مقایسه
                می‌کنیم و ارزان‌ترین گزینه‌ی موجود را به شما نشان می‌دهیم.
              </p>
              <div class="sp-hero-actions">
                <a href="market.html" class="sp-btn sp-btn--primary sp-btn--lg">شروع خرید</a>
                <a href="vendors.html" class="sp-btn sp-btn--ghost sp-btn--lg">
                  مقایسه فروشگاه‌ها
                </a>
              </div>
              <div class="sp-hero-trust">
                {icon("shield", 18)}<span>ضمانت اصالت و تاریخ انقضا روی تمام اقلام</span>
              </div>
            </div>

            <div class="sp-hero-aqua-media">
              <img src="assets/images/categories/produce.webp" alt="سبد خرید تازه"
                   width="520" height="520" loading="eager" />
              <!-- Delivery card overlapping the photo edge -->
              <div class="sp-slot-card" x-data="{{ slot: 'fast' }}">
                <div class="sp-slot-card-head">
                  {icon("clock", 20)}<b>زمان تحویل را انتخاب کنید</b>
                </div>
                <button type="button" class="sp-option"
                        :class="{{ 'is-active': slot === 'fast' }}" @click="slot = 'fast'">
                  <span class="sp-option-dot"></span>
                  <span class="sp-option-body">
                    <span class="sp-option-title">سریع‌ترین زمان</span>
                    <span class="sp-option-meta">تحویل تا ۴۵ دقیقه · ۶,۰۰۰ تومان</span>
                  </span>
                </button>
                <button type="button" class="sp-option"
                        :class="{{ 'is-active': slot === 'evening' }}" @click="slot = 'evening'">
                  <span class="sp-option-dot"></span>
                  <span class="sp-option-body">
                    <span class="sp-option-title">امروز، ۱۸ تا ۲۰</span>
                    <span class="sp-option-meta">ارسال رایگان برای اعضای پرو</span>
                  </span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      <div class="sp-container">
        <!-- ===== Category grid ===== -->
        <section class="sp-section">
          {section_head("دسته‌بندی‌ها", "market.html", "همه‌ی قفسه‌های فروشگاه")}
          {category_grid(categories)}
        </section>

        <!-- ===== Bento featured ===== -->
        <section class="sp-section">
          {section_head("پیشنهاد ویژه امروز", "market.html?sort=discount")}
          <div class="sp-bento">
            <a href="product.html?id={bento_lead['id']}" class="sp-bento-lead">
              <div class="sp-bento-lead-copy">
                <span class="sp-badge sp-badge--discount">
                  {fa(bento_lead['discountRatio'])}٪ تخفیف
                </span>
                <b>{bento_lead['title']}</b>
                <div class="sp-bento-lead-price">
                  <span class="sp-price-strike">{fa(bento_lead['price'])}</span>
                  <strong>{fa(bento_lead['final'])} <small>تومان</small></strong>
                </div>
              </div>
              <div class="sp-bento-lead-media">
                <img src="{bento_lead['image']}" alt="{bento_lead['title']}"
                     width="420" height="420" loading="lazy" />
              </div>
              <span class="sp-btn sp-btn--primary">مشاهده و خرید</span>
            </a>
            {bento_cards}

            <!-- Fills the three cells the 2×2 lead leaves empty on the last
                 row at ≥1200px; a full-width band below that. -->
            <a href="market.html?sort=discount" class="sp-bento-banner">
              <div class="sp-bento-banner-copy">
                <span class="sp-promo-kicker">ارسال رایگان</span>
                <b>سفارش بالای ۲۵۰ هزار تومان، بدون هزینه ارسال</b>
                <p>برای اعضای پرو در همه‌ی فروشگاه‌های طرف قرارداد</p>
                <span class="sp-btn sp-btn--primary">مشاهده تخفیف‌ها</span>
              </div>
              <span class="sp-bento-banner-art" aria-hidden="true">
                <img src="assets/images/banners/free-delivery.svg" alt=""
                     width="240" height="240" loading="lazy" />
              </span>
            </a>
          </div>
        </section>

        {rail("لبنیات و صبحانه", _pick(products, "dairy", 12),
              more_href="market.html?c=dairy")}

        <!-- ===== Banner section 1 of 2 ===== -->
        <section class="sp-section">
          <div class="sp-banner-grid-3">
            <a href="market.html?c=baby" class="sp-promo-banner sp-promo-banner--c">
              <div><span class="sp-promo-kicker">کودک و نوزاد</span>
                   <b>پوشک و شیرخشک</b><p>ارسال فوری، هر ساعت از شبانه‌روز</p></div>
            </a>
            <a href="market.html?c=frozen" class="sp-promo-banner sp-promo-banner--d">
              <div><span class="sp-promo-kicker">یخچالی و منجمد</span>
                   <b>زنجیره سرد</b><p>با بسته‌بندی ایزوله تحویل می‌گیرید</p></div>
            </a>
            <a href="market.html?c=home" class="sp-promo-banner sp-promo-banner--e">
              <div><span class="sp-promo-kicker">خانه و آشپزخانه</span>
                   <b>لوازم مصرفی</b><p>هر چیزی که در کابینت تمام شده</p></div>
            </a>
          </div>
        </section>

        {rail("خواربار و نان", _pick(products, "pantry", 12),
              more_href="market.html?c=pantry")}

        <!-- ===== Banner section 2 of 2 ===== -->
        {banner_row([
            promo_banner("market.html?c=breakfast", "صبحانه‌ی کامل", "میز صبحانه",
                         "عسل، مربا، کره و نان تازه - همه در یک سفارش",
                         variant="a", image="breakfast"),
            promo_banner("market.html?c=snacks", "برای مهمانی", "تنقلات و شکلات",
                         "چیپس، شکلات و خشکبار برای شب‌های دورهمی",
                         variant="b", image="snacks"),
        ])}

        {rail("شوینده و بهداشتی", _pick(products, "cleaning", 12),
              more_href="market.html?c=cleaning")}
      </div>"""


# ==========================================================================
# 3 — GRAPHITE (neutral / dark)
# ==========================================================================


def _hero_floats(products: list[dict]) -> str:
    """
    Decorative layer for the GRAPHITE hero: a few product shots drifting on a
    slow loop, plus small vector marks. Purely ornamental — aria-hidden, and
    the whole layer holds still under prefers-reduced-motion.

    Each pick is "the nth product of a category" rather than a hard-coded id,
    so the art survives a re-crawl.
    """
    picks = [
        ("produce", 1),    # bananas
        ("dairy", 0),      # milk carton
        ("drinks", 0),     # cola
        ("snacks", 0),     # crisps
        ("produce", 2),    # tomatoes
    ]

    shots = []
    for i, (slug, offset) in enumerate(picks, 1):
        rows = [p for p in products if p["category"] == slug]
        if len(rows) <= offset:
            continue
        item = rows[offset]
        shots.append(
            f'<span class="sp-float sp-float--{i}">'
            f'<img src="{item["thumb"]}" alt="" width="300" height="300" '
            f'loading="lazy" /></span>'
        )

    # Small marks: leaf and spark in green, plus and ring in white.
    marks = """
      <span class="sp-float-mark sp-float-mark--1" data-tone="green">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
          <path d="M20 4C10 4 4 9 4 16v4" stroke-linecap="round"/>
          <path d="M20 4c0 9-5 13-11 13H4" stroke-linejoin="round"/>
        </svg>
      </span>
      <span class="sp-float-mark sp-float-mark--2" data-tone="white">
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 2l1.9 6.4L20 10l-6.1 1.6L12 18l-1.9-6.4L4 10l6.1-1.6z"/>
        </svg>
      </span>
      <span class="sp-float-mark sp-float-mark--3" data-tone="green">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
          <path d="M12 5v14M5 12h14" stroke-linecap="round"/>
        </svg>
      </span>
      <span class="sp-float-mark sp-float-mark--4" data-tone="white">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="8"/>
        </svg>
      </span>"""

    return f'<div class="sp-hero-floats" aria-hidden="true">{"".join(shots)}{marks}</div>'




def home_graphite(products: list[dict], categories: list[dict]) -> str:
    deal = _discounted(products, 1)[0]
    dense = _discounted(products, 20)

    strip = "".join(
        f"""
            <a href="product.html?id={p['id']}" class="sp-deal-strip-item">
              <img src="{p['thumb']}" alt="{p['title']}" width="64" height="64" loading="lazy" />
              <div>
                <span class="sp-deal-strip-title">{p['title']}</span>
                <span class="sp-deal-strip-price">{fa(p['discountRatio'])}٪ تخفیف</span>
              </div>
            </a>"""
        for p in _discounted(products, 4)
    )

    return f"""
      <!-- ===== HERO: dark full-width banner + floating product art ===== -->
      <section class="sp-hero-graphite">
        {_hero_floats(products)}
        <div class="sp-container">
          <span class="sp-hero-eyebrow">شب‌ها هم باز است</span>
          <h1 class="sp-hero-title sp-hero-title--xl">
            سوپرمارکت،<br /><em>هر ساعت که لازم شد</em>
          </h1>
          <p class="sp-hero-lead">
            سفارش تا نیمه‌شب، تحویل زیر یک ساعت. قیمت‌ها همان قیمت قفسه است.
          </p>
          <div class="sp-hero-actions">
            <a href="market.html" class="sp-btn sp-btn--primary sp-btn--lg">شروع خرید</a>
            <a href="vendors.html" class="sp-btn sp-btn--ghost sp-btn--lg">فروشگاه‌های باز</a>
          </div>

          <div class="sp-hero-ticker">
            <span>{icon("truck", 16)} ارسال تا ۴۵ دقیقه</span>
            <span>{icon("shield", 16)} تضمین تاریخ انقضا</span>
            <span>{icon("wallet", 16)} پرداخت در محل</span>
            <span>{icon("percent", 16)} بدون کارمزد جمع‌آوری</span>
          </div>
        </div>
      </section>

      <div class="sp-container">
        <!-- ===== Deal of the day ===== -->
        <section class="sp-section">
          <div class="sp-deal">
            <div class="sp-deal-main">
              <span class="sp-deal-kicker">پیشنهاد امروز</span>
              <h2 class="sp-deal-title">{deal['title']}</h2>
              <div class="sp-deal-prices">
                <span class="sp-badge sp-badge--discount">{fa(deal['discountRatio'])}٪</span>
                <span class="sp-price-strike">{fa(deal['price'])}</span>
                <b>{fa(deal['final'])} <small>تومان</small></b>
              </div>
              <a href="product.html?id={deal['id']}" class="sp-btn sp-btn--primary">
                افزودن به سبد
              </a>
            </div>
            <img class="sp-deal-photo" src="{deal['image']}" alt="{deal['title']}"
                 width="320" height="320" loading="lazy" />
            <div class="sp-deal-strip">{strip}</div>
          </div>
        </section>

        <!-- ===== Shelf index ===== -->
        <section class="sp-section">
          {section_head("قفسه‌ها", "market.html")}
          {category_index(categories, products)}
        </section>

        <!-- ===== Dense price-forward grid ===== -->
        <section class="sp-section">
          {section_head("پرتخفیف‌ترین‌های امشب", "market.html?sort=discount",
                        "قیمت‌ها هر شب ساعت ۲۰ به‌روز می‌شوند")}
          {product_grid(dense)}
        </section>

        <!-- ===== Banner section 1 of 2 ===== -->
        {banner_strip("market.html?c=frozen", "زنجیره سرد", "منجمد، دقیقاً سرد",
                      "اقلام یخچالی با بسته‌بندی ایزوله و در کوتاه‌ترین زمان به دستتان می‌رسد.",
                      cta="قفسه یخچالی",
                      images=["frozen", "dairy", "breakfast", "drinks"],
                      variant="dark")}

        {rail("یخچالی و منجمد", _pick(products, "frozen", 12),
              more_href="market.html?c=frozen")}

        <!-- ===== Banner section 2 of 2 ===== -->
        {banner_row([
            promo_banner("market.html?c=drinks", "تا نیمه‌شب", "نوشیدنی سرد",
                         "نوشابه، آبمیوه و ماءالشعیر - هر ساعت از شب",
                         variant="c", image="drinks"),
            promo_banner("market.html?c=home", "لوازم مصرفی", "خانه و آشپزخانه",
                         "هر چیزی که در کابینت تمام شده است",
                         variant="d", image="home"),
        ])}

        {rail("نوشیدنی", _pick(products, "drinks", 12),
              more_href="market.html?c=drinks")}
      </div>"""
