---
import Layout from "../../../layouts/Layout.astro";
import ProductCard from "../../../components/ProductCard.astro";
import { products, getProduct, productsByCategory } from "../../../data/products";
import { getCategory } from "../../../data/categories";
import type { Locale } from "../../../i18n/config";
import { useTranslations } from "../../../i18n/ui";
import { formatPrice } from "../../../i18n/format";
import { effektiverPreis, rabattLabel, hatAktivenRabatt } from "../../../data/rabatt";

export function getStaticPaths() {
  return products.map((p) => ({ params: { slug: p.slug } }));
}

const lang: Locale = "ch";
const t = useTranslations(lang);
const { slug } = Astro.params;
const product = getProduct(slug!)!;
const category = getCategory(product.kategorie);
const empfehlungen = productsByCategory(product.kategorie).filter((p) => p.slug !== product.slug).slice(0, 3);

const name = product.name[lang];
const desc = product.beschreibung[lang];

const badgeLabel: Record<string, string> = { neu: t.badge.neu, bestseller: t.badge.bestseller, sale: t.badge.sale, handgemacht: t.badge.handgemacht };
const finalPrice = effektiverPreis(product);
const discountBadge = rabattLabel(product);
const showOldAsPreis = !product.preisAlt && hatAktivenRabatt(product);
const mengenrabatt = product.rabatt?.mengenrabatt ?? [];

const felder: [string, string | undefined][] = [
  [t.product.articleNo, product.artikelnummer],
  [t.product.material, product.material],
  [t.product.size, product.groesse],
  [t.product.colors, product.farben?.join(", ")],
  [t.product.included, product.lieferumfang],
  [t.product.care, product.pflegehinweise],
  [t.product.delivery, product.lieferzeit],
];
---
<Layout title={name} description={desc} lang={lang} path={`/produkt/${product.slug}/`}>
  <section class="section-tight">
    <div class="container">
      <p class="small breadcrumb">
        <a href="/ch/shop/">{t.shop.breadcrumbShop}</a> / <a href={`/ch/shop/${product.kategorie}/`}>{category?.name[lang]}</a> / <strong>{name}</strong>
      </p>

      <div class="grid grid-2 product-detail">
        <div>
          {product.bilder && product.bilder.length > 0 ? (
            <>
              <img id="product-hero-img" class="product-photo product-hero" src={product.bilder[0]} alt={name} />
              {product.bilder.length > 1 && (
                <div class="thumb-row">
                  {product.bilder.map((bild) => (
                    <img class="product-photo thumb" src={bild} alt={name} data-full={bild} />
                  ))}
                </div>
              )}
            </>
          ) : (
            <div class="img-placeholder product-hero" role="img" aria-label={`${t.common.photoSoon}: ${name}`}>
              {t.common.photoSoon}<br /><span class="small">{t.product.photoNote}</span>
            </div>
          )}
        </div>

        <div>
          <div class="badge-row">
            {product.badges.map((b) => <span class={`badge ${b === "sale" ? "badge-sale" : ""}`}>{badgeLabel[b]}</span>)}
            {product.bestand === 0 && <span class="badge badge-sold-out">{t.badge.ausverkauft}</span>}
          </div>
          <h1>{name}</h1>
          <div class="price-row-detail">
            {product.preisAlt && <span class="price-old">{formatPrice(product.preisAlt, lang)}</span>}
            {showOldAsPreis && <span class="price-old">{formatPrice(product.preis, lang)}</span>}
            <span class="price-detail">{formatPrice(finalPrice, lang)}</span>
            {discountBadge && <span class="badge badge-rabatt">{discountBadge}</span>}
          </div>
          {mengenrabatt.length > 0 && (
            <ul class="mengenrabatt-list small">
              {mengenrabatt.map((stufe) => <li>{t.cart.mengenrabattTier(String(stufe.abMenge), String(stufe.prozent))}</li>)}
            </ul>
          )}
          <p class="small">{t.common.vatNote} · {t.common.plusShipping}</p>
          <p class="lead">{desc}</p>

          <div class="qty-row">
            <label for="qty">{t.common.quantity}</label>
            <div class="qty-stepper">
              <button type="button" id="qty-dec" aria-label="−">−</button>
              <input type="number" id="qty" min="1" max={product.bestand} value={product.bestand > 0 ? 1 : 0} inputmode="numeric" data-bestand={product.bestand} />
              <button type="button" id="qty-inc" aria-label="+">+</button>
            </div>
            <button
              class="btn btn-primary"
              id="add-to-cart"
              disabled={product.bestand === 0}
              data-slug={product.slug}
              data-name={name}
              data-preis={finalPrice}
              data-bestand={product.bestand}
            >
              {product.bestand === 0 ? t.common.soldOut : t.common.addToCart}
            </button>
          </div>
          <p class="small" id="stock-hint" style="display:none;"></p>
          <p class="small" id="add-confirm" role="status" style="display:none; color: var(--c-accent);">{t.common.addedToCart}</p>

          {felder.some(([, v]) => v) && (
            <table class="specs">
              <tbody>
                {felder.filter(([, v]) => v).map(([k, v]) => (
                  <tr><th>{k}</th><td>{v}</td></tr>
                ))}
              </tbody>
            </table>
          )}

          <div class="todo-note">{t.product.todoFields}</div>
        </div>
      </div>
    </div>
  </section>

  {empfehlungen.length > 0 && (
    <section class="section-tight">
      <div class="container">
        <h2>{t.product.recommendations}</h2>
        <div class="grid grid-3">{empfehlungen.map((p) => <ProductCard product={p} lang={lang} />)}</div>
      </div>
    </section>
  )}
</Layout>

<script define:vars={{ onlyLeftTemplate: t.common.onlyXLeft("__N__"), maxInCartText: t.common.maxInCart, maxInCartShortText: t.common.maxInCartShort, soldOutText: t.common.soldOut, addToCartText: t.common.addToCart }}>
  window.__productStockVars = { onlyLeftTemplate, maxInCartText, maxInCartShortText, soldOutText, addToCartText };
</script>
<script>
  import { addToCart, getCart } from "../../../scripts/cart";
  const { onlyLeftTemplate, maxInCartText, maxInCartShortText, soldOutText, addToCartText } = (window as any).__productStockVars;
  const btn = document.getElementById("add-to-cart") as HTMLButtonElement | null;
  const qtyInput = document.getElementById("qty") as HTMLInputElement;
  const confirm = document.getElementById("add-confirm")!;
  const stockHint = document.getElementById("stock-hint")!;
  const bestand = Number(qtyInput.dataset.bestand || 0);
  const slug = btn?.dataset.slug;

  // Nie mehr in den Warenkorb legen können, als tatsächlich auf Lager ist — zählt dabei mit,
  // was von diesem Produkt schon im Warenkorb liegt (nicht nur die aktuelle Eingabe hier).
  function bereitsImWarenkorb() {
    return getCart().find((i) => i.slug === slug)?.menge ?? 0;
  }
  function maxJetztHinzufuegbar() {
    return Math.max(0, bestand - bereitsImWarenkorb());
  }
  function clamp() {
    const max = maxJetztHinzufuegbar();
    let val = Math.max(0, Math.floor(Number(qtyInput.value) || 0));
    if (val > max) val = max;
    if (val < 1 && max > 0) val = 1;
    qtyInput.value = String(val);
    qtyInput.max = String(max);

    if (btn) {
      if (bestand === 0) {
        btn.disabled = true;
        btn.textContent = soldOutText;
      } else if (max === 0) {
        btn.disabled = true;
        btn.textContent = maxInCartShortText;
        stockHint.style.display = "block";
        stockHint.textContent = maxInCartText;
      } else {
        btn.disabled = false;
        btn.textContent = addToCartText;
        if (max <= 5) {
          stockHint.style.display = "block";
          stockHint.textContent = onlyLeftTemplate.replace("__N__", String(max));
        } else {
          stockHint.style.display = "none";
        }
      }
    }
    return val;
  }
  clamp();

  document.getElementById("qty-dec")?.addEventListener("click", () => {
    qtyInput.value = String(Math.max(1, Number(qtyInput.value) - 1));
    clamp();
  });
  document.getElementById("qty-inc")?.addEventListener("click", () => {
    qtyInput.value = String(Number(qtyInput.value) + 1);
    clamp();
  });
  qtyInput.addEventListener("input", clamp);
  qtyInput.addEventListener("change", clamp);

  btn?.addEventListener("click", () => {
    const menge = clamp();
    if (menge < 1) return;
    const { name, preis } = btn.dataset;
    addToCart({ slug: slug!, name: name!, preis: Number(preis) }, menge);
    confirm.style.display = "block";
    setTimeout(() => (confirm.style.display = "none"), 2500);
    clamp();
  });

  // Klick auf ein Miniaturbild zeigt es groß im Hauptbild an (mehrere Produktfotos).
  const heroImg = document.getElementById("product-hero-img") as HTMLImageElement | null;
  document.querySelectorAll<HTMLImageElement>(".thumb.product-photo").forEach((thumb) => {
    thumb.addEventListener("click", () => {
      if (heroImg && thumb.dataset.full) heroImg.src = thumb.dataset.full;
    });
  });
</script>
