"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { ArrowLeft, ArrowRight, ChevronLeft, ChevronRight, CircleGauge, Flame, Layers3, Ruler, Sparkles, Timer, Touchpad } from "lucide-react";
import { m, useReducedMotion, useScroll, useTransform } from "framer-motion";
import { getProductCatalogFacets, getProductCookingSystem, getProductFormatLabels, localizeProductName, localizeSurface } from "@/lib/product-i18n";
import type { CollectionLocale, NordenCollection } from "@/lib/collections";

type StoryProduct = { id: string; slug: string; name: string; nameTr?: string | null; nameEn?: string | null; nameRu?: string | null; widthCm: number | null; surface: string | null; image: string };
type Chapter = { title: string; body: string; detail: string; image?: string; icon: "size" | "control" | "power" | "surface" | "choice" };

const shared = {
  tr: { back: "Tüm koleksiyonlar", eyebrow: "tasarım hikâyesi", scroll: "Hikâyeyi kaydır", family: "model ailesi", familyBody: "Yayımlanmış gerçek ürün görselleri, ölçüleri, yüzeyleri ve pişirme teknolojileriyle seri seçenekleri.", view: "Ürünü incele", matrix: "ÜRÜN MATRİSİ", index: "Konfigürasyon indeksi", models: "Yayımlanmış model", dimensions: "Mevcut ölçüler", surfaces: "Yüzey / teknoloji", continue: "Model ailesine geçin", browse: "Tüm seri ürünlerini filtrele", previous: "Önceki ürünler", next: "Sonraki ürünler" },
  en: { back: "All collections", eyebrow: "design story", scroll: "Scroll the story", family: "model family", familyBody: "Published series options with real product imagery, dimensions, surfaces and cooking technologies.", view: "View product", matrix: "PRODUCT MATRIX", index: "Configuration index", models: "Published models", dimensions: "Available widths", surfaces: "Surface / technology", continue: "Continue to the model family", browse: "Browse all series products", previous: "Previous products", next: "Next products" },
  ru: { back: "Все коллекции", eyebrow: "история дизайна", scroll: "Листайте историю", family: "семейство моделей", familyBody: "Опубликованные варианты серии с реальными изображениями, размерами, поверхностями и технологиями нагрева.", view: "Смотреть изделие", matrix: "МАТРИЦА МОДЕЛЕЙ", index: "Индекс конфигураций", models: "Опубликованные модели", dimensions: "Доступные размеры", surfaces: "Поверхность / технология", continue: "Перейти к семейству моделей", browse: "Все изделия серии", previous: "Предыдущие модели", next: "Следующие модели" },
} satisfies Record<CollectionLocale, Record<string, string>>;

function buildChapters(collection: NordenCollection, locale: CollectionLocale): Chapter[] {
  const electric = collection.seriesFilter === "VTC";
  const localizedSizes = locale === "ru" ? collection.sizes.replace(/cm/gi, "см") : collection.sizes;
  if (locale === "en") {
    return electric ? [
      { title: "Four dimensions. One uninterrupted surface.", body: `${collection.name} layouts span ${collection.sizes}, bringing electric cooking into different kitchen plans.`, detail: collection.sizes.toUpperCase(), icon: "size" },
      { title: "Control begins at a touch.", body: "Touch control and nine heat levels support direct, clearly stepped temperature adjustment on standard products.", detail: "TOUCH CONTROL · 9 HEAT LEVELS", icon: "control" },
      { title: "Each zone keeps its own rhythm.", body: "Individual zone timers, Pause & Resume and child lock are available across much of the standard Vitroceramic range; final equipment is confirmed by model.", detail: "TIMER · PAUSE & RESUME · CHILD LOCK", icon: "power" },
      { title: "A flat surface, built for clarity.", body: "The smooth vitroceramic glass brings heating areas and controls into one clean, easy-to-maintain plane.", detail: "VITROCERAMIC GLASS", icon: "surface" },
      { title: "Choose the layout that fits the worktop.", body: "Zone count, zone diameter and optional Plug-and-Play configuration vary by model and requested setup.", detail: "MODEL-DEPENDENT CONFIGURATION", icon: "choice" },
    ] : gasChaptersEn(collection);
  }
  if (locale === "ru") {
    return electric ? [
      { title: "Четыре размера. Единая поверхность.", body: `Компоновки ${collection.name} представлены в размерах ${localizedSizes} для разных кухонных планировок.`, detail: localizedSizes.toUpperCase(), icon: "size" },
      { title: "Управление начинается с касания.", body: "Сенсорное управление и девять уровней нагрева обеспечивают понятную ступенчатую регулировку температуры.", detail: "СЕНСОРНОЕ УПРАВЛЕНИЕ · 9 УРОВНЕЙ", icon: "control" },
      { title: "У каждой зоны свой ритм.", body: "Таймеры отдельных зон, Pause & Resume и блокировка от детей доступны во многих стандартных моделях; комплектация уточняется по коду.", detail: "ТАЙМЕР · PAUSE & RESUME · БЛОКИРОВКА", icon: "power" },
      { title: "Ровная и понятная поверхность.", body: "Гладкая стеклокерамика объединяет зоны нагрева и управление в одной легко очищаемой плоскости.", detail: "СТЕКЛОКЕРАМИКА", icon: "surface" },
      { title: "Компоновка под вашу столешницу.", body: "Количество и диаметр зон, а также опция Plug-and-Play зависят от модели и выбранной конфигурации.", detail: "КОНФИГУРАЦИЯ ЗАВИСИТ ОТ МОДЕЛИ", icon: "choice" },
    ] : gasChaptersRu(collection);
  }
  return electric ? [
    { title: "Dört ölçü. Kesintisiz tek yüzey.", body: `${collection.name}; ${collection.sizes} yerleşimleriyle elektrikli pişirmeyi farklı mutfak planlarına taşır.`, detail: collection.sizes.toUpperCase(), icon: "size" },
    { title: "Kontrol tek dokunuşla başlar.", body: "Dokunmatik kontrol ve dokuz ısı seviyesi, standart ürünlerde sıcaklığı doğrudan ve görünür adımlarla yönetir.", detail: "DOKUNMATİK KONTROL · 9 ISI SEVİYESİ", icon: "control" },
    { title: "Her bölgenin kendi ritmi.", body: "Bölgesel zamanlayıcı, Pause & Resume ve çocuk kilidi standart Vitroceramic ürünlerin çoğunda bulunur; kesin donanım model koduna göre belirlenir.", detail: "ZAMANLAYICI · PAUSE & RESUME · ÇOCUK KİLİDİ", icon: "power" },
    { title: "Düz, temiz ve anlaşılır yüzey.", body: "Pürüzsüz vitroceramic cam; ısıtma bölgeleriyle kontrol alanını kolay temizlenen tek bir düzlemde buluşturur.", detail: "VITROCERAMIC CAM", icon: "surface" },
    { title: "Tezgâha uyan yerleşimi seçin.", body: "Bölge sayısı, bölge çapı ve opsiyonel Plug-and-Play yapı modele ve istenen konfigürasyona göre değişir.", detail: "MODELE BAĞLI KONFİGÜRASYON", icon: "choice" },
  ] : gasChaptersTr(collection);
}

function gasChaptersTr(collection: NordenCollection): Chapter[] { return [
  { title: "Ölçek değişir. Tasarım karakteri kalır.", body: `${collection.sizes} yerleşimleri, ${collection.name} serisinin kendine özgü ızgara geometrisini farklı mutfak ölçülerine taşır.`, detail: collection.sizes.toUpperCase(), icon: "size" },
  { title: "Alev, dokuz kontrollü adımda.", body: "ChronoFlame, alev seviyesini 1’den 9’a kadar görünür ve tekrar edilebilir biçimde ayarlamaya yönelik opsiyonel bir kontrol yaklaşımıdır.", detail: "CHRONOFLAME · OPSİYONEL", image: "/media/story/catalog/chrono-9-level-960.webp", icon: "control" },
  { title: "Wok merkezinde gerçek güç.", body: "Sabaf Wok 3,6 kW standart veya modele bağlı yapıdadır. Talebe göre 4,0 kW seçeneği sunulabilir.", detail: "3,6 KW · OPSİYONEL 4,0 KW", icon: "power" },
  { title: "Dökümün dengesi. Yüzeyin imzası.", body: `Döküm ızgara seçenekleri pişirme kaplarını dengede tutar. ${collection.surfaces.tr} yüzey seçenekleri serinin tasarım çizgisini tamamlar.`, detail: "DÖKÜM IZGARA · OTOMATİK ATEŞLEME", icon: "surface" },
  { title: "Bir yüzey değil, bir seçim sistemi.", body: "White, Black, Beige ve Gray camlar Glossy veya Matte seçilebilir. Cam kalınlığı modele göre 6 mm veya 8 mm olabilir. 60 cm siyah camlı 2+2 hibrit model, iki gazlı brülör ile iki elektrikli Ceran alanını birleştirir.", detail: "SIYAH CAM · INOX · GAZ + CERAN", image: collection.inoxImage, icon: "choice" },
]; }
function gasChaptersEn(collection: NordenCollection): Chapter[] { return [
  { title: "Scale changes. Character remains.", body: `${collection.sizes} layouts carry the distinctive ${collection.name} pan-support geometry into different kitchen dimensions.`, detail: collection.sizes.toUpperCase(), icon: "size" },
  { title: "Nine visible levels of flame.", body: "ChronoFlame is an optional control approach designed to make flame levels from 1 to 9 visible and repeatable.", detail: "CHRONOFLAME · OPTIONAL", image: "/media/story/catalog/chrono-9-level-960.webp", icon: "control" },
  { title: "Real power at the centre of the Wok.", body: "Sabaf Wok 3.6 kW is standard or model dependent. A 4.0 kW alternative can be specified on request.", detail: "3.6 KW · OPTIONAL 4.0 KW", icon: "power" },
  { title: "Cast-iron balance. A signature surface.", body: `Cast-iron supports stabilise cookware. ${collection.surfaces.en} surface options complete the series design language.`, detail: "CAST IRON · AUTOMATIC IGNITION", icon: "surface" },
  { title: "Not one surface. A system of choices.", body: "White, Black, Beige and Gray glass can be Glossy or Matte. Glass may be 6 mm or 8 mm depending on model. The 60 cm black-glass 2+2 hybrid combines two gas burners with two electric Ceran zones.", detail: "BLACK GLASS · INOX · GAS + CERAN", image: collection.inoxImage, icon: "choice" },
]; }
function gasChaptersRu(collection: NordenCollection): Chapter[] { return [
  { title: "Размер меняется. Характер остаётся.", body: `Компоновки ${collection.sizes.replace(/cm/gi, "см")} переносят характерную геометрию решёток ${collection.name} в кухни разных размеров.`, detail: collection.sizes.replace(/cm/gi, "см").toUpperCase(), icon: "size" },
  { title: "Девять видимых уровней пламени.", body: "ChronoFlame — дополнительный способ управления с видимыми уровнями пламени от 1 до 9.", detail: "CHRONOFLAME · ОПЦИЯ", image: "/media/story/catalog/chrono-9-level-960.webp", icon: "control" },
  { title: "Настоящая мощность Wok.", body: "Sabaf Wok 3,6 кВт — стандарт или зависит от модели. По запросу доступен вариант 4,0 кВт.", detail: "3,6 КВТ · ОПЦИЯ 4,0 КВТ", icon: "power" },
  { title: "Баланс чугуна. Характер поверхности.", body: `Чугунные опоры стабилизируют посуду. Варианты ${collection.surfaces.ru} завершают язык дизайна серии.`, detail: "ЧУГУН · АВТОПОДЖИГ", icon: "surface" },
  { title: "Система выбора поверхности.", body: "Стекло White, Black, Beige и Gray доступно в Glossy или Matte. Толщина зависит от модели: 6 или 8 мм. Гибридная модель 60 см из чёрного стекла объединяет две газовые конфорки и две электрические зоны Ceran.", detail: "ЧЁРНОЕ СТЕКЛО · INOX · ГАЗ + CERAN", image: collection.inoxImage, icon: "choice" },
]; }

export default function SeriesStoryExperience({ collection, locale, products }: { collection: NordenCollection; locale: CollectionLocale; products: StoryProduct[] }) {
  const t = shared[locale];
  const chapters = buildChapters(collection, locale);
  const reduceMotion = useReducedMotion();
  const productTrackRef = useRef<HTMLDivElement>(null);
  const [productPage, setProductPage] = useState(0);
  const [productStepPx, setProductStepPx] = useState(296);
  const [visibleProductCount, setVisibleProductCount] = useState(1);
  useEffect(() => {
    const track = productTrackRef.current;
    if (!track) return;
    const measure = () => {
      const firstCard = track.querySelector<HTMLElement>("[data-product-card]");
      const step = (firstCard?.getBoundingClientRect().width ?? 280) + 16;
      setProductStepPx(step);
      setVisibleProductCount(Math.max(1, Math.floor((track.clientWidth + 16) / step)));
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(track);
    return () => observer.disconnect();
  }, []);
  const maximumProductPage = Math.max(0, products.length - visibleProductCount);
  const currentProductPage = Math.min(productPage, maximumProductPage);
  const scrollProducts = (direction: -1 | 1) => {
    setProductPage((current) => Math.min(maximumProductPage, Math.max(0, Math.min(current, maximumProductPage) + direction * visibleProductCount)));
  };
  const availableWidths = Array.from(new Set(products.map((product) => product.widthCm).filter((width): width is number => width !== null))).sort((a, b) => a - b);
  const availableSurfaces = Array.from(new Set(products
    .flatMap((product) => getProductCatalogFacets(product))
    .map((surface) => localizeSurface(surface, locale))
    .filter((surface): surface is string => Boolean(surface))));

  return <main className="overflow-clip pt-24" style={{ background: "var(--surface-0)", color: "var(--fg-primary)" }}>
    <section className="relative isolate flex min-h-[calc(100svh-6rem)] items-center overflow-hidden border-b" style={{ borderColor: "var(--border)", background: "linear-gradient(115deg, var(--surface-0) 18%, var(--surface-1))" }}>
      <m.div aria-hidden initial={{ opacity: 0 }} animate={{ opacity: .04 }} transition={{ duration: 1.2 }} className="absolute inset-x-0 top-[13%] overflow-hidden whitespace-nowrap text-[24vw] font-semibold uppercase leading-none tracking-[-.09em]">{collection.name}</m.div>
      <div className="relative z-10 mx-auto grid w-full max-w-[100rem] items-center gap-5 px-6 py-10 md:px-12 lg:grid-cols-[.72fr_1.28fr]">
        <div className="relative z-20">
          <m.div initial={reduceMotion ? false : { opacity: 0, x: -90 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: .8 }}><Link href={`/${locale}/collections`} className="inline-flex items-center gap-2 text-[10px] uppercase tracking-[.17em]" style={{ color: "var(--fg-muted)" }}><ArrowLeft size={13}/>{t.back}</Link></m.div>
          <m.p initial={reduceMotion ? false : { opacity: 0, x: -100 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: .12, duration: .8 }} className="mt-12 font-mono text-[10px] uppercase tracking-[.24em]" style={{ color: "var(--ember)" }}>{collection.name} · {t.eyebrow}</m.p>
          <h1 aria-label={collection.name} className={`mt-4 overflow-hidden whitespace-nowrap font-medium leading-[.94] tracking-[-.06em] ${collection.name.length > 9 ? "text-5xl md:text-6xl lg:text-[4.8rem]" : "text-6xl md:text-8xl lg:text-[7rem]"}`}>{Array.from(collection.name).map((letter, index) => <m.span aria-hidden key={`${letter}-${index}`} className="inline-block" initial={reduceMotion ? false : { y: "115%", rotate: 4 }} animate={{ y: 0, rotate: 0 }} transition={{ delay: .18 + index * .07, duration: .7, ease: [0.16, 1, 0.3, 1] }}>{letter}</m.span>)}</h1>
          <m.p initial={reduceMotion ? false : { opacity: 0, x: -80 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: .55, duration: .8 }} className="mt-5 text-xl font-medium">{collection.tagline[locale]}</m.p>
          <m.p initial={reduceMotion ? false : { opacity: 0, x: -80 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: .68, duration: .8 }} className="mt-4 max-w-xl text-base leading-7" style={{ color: "var(--fg-secondary)" }}>{collection.story[locale]}</m.p>
          <m.div initial={reduceMotion ? false : { opacity: 0, y: 18 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: .9 }} className="mt-9 flex items-center gap-3 text-[9px] uppercase tracking-[.18em]" style={{ color: "var(--fg-muted)" }}><span className="h-px w-12" style={{ background: "var(--ember)" }}/>{t.scroll}</m.div>
        </div>
        <m.div initial={reduceMotion ? false : { opacity: 0, x: 150, scale: .86 }} animate={{ opacity: 1, x: 0, scale: 1 }} transition={{ duration: 1.2, ease: [0.16, 1, 0.3, 1] }} className="relative min-h-[390px] md:min-h-[620px]">
          <TechnicalVisualDecor />
          <Image src={collection.image} alt={`${collection.name} 60 cm`} fill loading="eager" fetchPriority="high" sizes="(max-width:1024px) 100vw, 62vw" className="z-10 object-contain drop-shadow-[0_38px_55px_rgba(0,0,0,.58)]"/>
        </m.div>
      </div>
    </section>

    <section className="relative mx-auto max-w-[100rem] px-6 md:px-12">
      <div className="relative z-10">
        {chapters.map((chapter, index) => <ChapterScene key={chapter.title} chapter={chapter} index={index} locale={locale} collection={collection} products={products} reduceMotion={Boolean(reduceMotion)}/>) }
      </div>
    </section>

    <ProductIndexBridge
      collection={collection}
      locale={locale}
      productCount={products.length}
      widths={availableWidths}
      surfaces={availableSurfaces}
      reduceMotion={Boolean(reduceMotion)}
    />

    <section className="border-t px-6 py-24 md:px-12 md:py-32" style={{ borderColor: "var(--border)", background: "var(--surface-1)" }}>
      <div className="mx-auto max-w-[100rem]">
        <m.div initial={reduceMotion ? false : { opacity: 0, x: -90 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true, amount: .35 }}><p className="font-mono text-[10px] uppercase tracking-[.22em]" style={{ color: "var(--ember)" }}>{collection.name} · {t.matrix}</p><h2 className="mt-4 text-4xl font-medium tracking-[-.045em] md:text-7xl">{collection.name} {t.family}</h2><p className="mt-5 max-w-2xl text-base leading-7" style={{ color: "var(--fg-secondary)" }}>{t.familyBody}</p></m.div>
        <div className="mt-14 overflow-hidden pb-6">
          <div ref={productTrackRef} data-product-page={currentProductPage} className="flex gap-4 transition-transform duration-700 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none" style={{ transform: `translate3d(-${currentProductPage * productStepPx}px,0,0)` }}>{products.map((product, index) => <m.article data-product-card={index} onFocusCapture={() => setProductPage(Math.min(index, maximumProductPage))} key={product.id} initial={reduceMotion ? false : { opacity: 0, y: 45 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: "-60px" }} transition={{ delay: (index % 5) * .055 }} className="group min-w-[280px] overflow-hidden rounded-[26px] border md:min-w-[360px]" style={{ borderColor: "var(--border)", background: "var(--surface-0)" }}><Link href={`/${locale}/products/${product.slug}`} className="block rounded-[26px] outline-none focus-visible:ring-2 focus-visible:ring-ember focus-visible:ring-offset-4 focus-visible:ring-offset-surface-1"><div className="relative aspect-square overflow-hidden"><TechnicalVisualDecor/><Image src={product.image} alt={localizeProductName(product, locale)} fill sizes="360px" className="relative z-10 object-contain p-7 transition-transform duration-700 group-hover:scale-110 motion-reduce:transition-none motion-reduce:group-hover:scale-100"/></div><div className="border-t p-5" style={{ borderColor: "var(--border)" }}><div className="flex justify-between gap-3 text-[9px] uppercase tracking-[.15em]" style={{ color: "var(--ember)" }}><span className="min-w-0 truncate">{getProductFormatLabels(product, locale).join(" · ") || collection.name}</span><span className="shrink-0">{product.widthCm ? `${product.widthCm} ${locale === "ru" ? "см" : "cm"}` : ""}</span></div><h3 className="mt-3 line-clamp-2 text-lg font-medium">{localizeProductName(product, locale)}</h3><span className="mt-5 inline-flex items-center gap-2 text-[9px] uppercase tracking-[.15em]" style={{ color: "var(--fg-muted)" }}>{t.view}<ArrowRight size={12}/></span></div></Link></m.article>)}</div>
        </div>
        <div className="mt-8 flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
          <Link href={`/${locale}/products?category=hobs&series=${encodeURIComponent(collection.slug)}`} className="inline-flex min-h-11 w-fit items-center gap-3 rounded-full border px-6 text-[10px] font-medium uppercase tracking-[.16em] transition-colors hover:border-ember hover:text-ember focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember" style={{ borderColor: "var(--accent-border)", color: "var(--ember-bright)" }}>{t.browse}<ArrowRight size={14}/></Link>
          <div className="flex items-center gap-2" aria-label={`${collection.name} ${t.family}`}>
            <span aria-live="polite" className="mr-2 min-w-20 text-center font-mono text-[9px] tracking-[.16em]" style={{ color: "var(--fg-muted)" }}>{String(currentProductPage + 1).padStart(2, "0")}—{String(Math.min(currentProductPage + visibleProductCount, products.length)).padStart(2, "0")} / {String(products.length).padStart(2, "0")}</span>
            <button type="button" disabled={currentProductPage === 0} onClick={() => scrollProducts(-1)} aria-label={t.previous} className="flex h-12 w-12 items-center justify-center rounded-full border transition-colors hover:border-ember hover:text-ember focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember disabled:cursor-not-allowed disabled:opacity-30" style={{ borderColor: "var(--border)", color: "var(--fg-secondary)" }}><ChevronLeft size={18}/></button>
            <button type="button" disabled={currentProductPage >= maximumProductPage} onClick={() => scrollProducts(1)} aria-label={t.next} className="flex h-12 w-12 items-center justify-center rounded-full border transition-colors hover:border-ember hover:text-ember focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember disabled:cursor-not-allowed disabled:opacity-30" style={{ borderColor: "var(--border)", color: "var(--fg-secondary)" }}><ChevronRight size={18}/></button>
          </div>
        </div>
      </div>
    </section>
  </main>;
}

function ProductIndexBridge({ collection, locale, productCount, widths, surfaces, reduceMotion }: { collection: NordenCollection; locale: CollectionLocale; productCount: number; widths: number[]; surfaces: string[]; reduceMotion: boolean }) {
  const t = shared[locale];
  const metrics = [
    { label: t.models, value: String(productCount).padStart(2, "0") },
    { label: t.dimensions, value: widths.length ? widths.map((width) => `${width}`).join(" · ") + ` ${locale === "ru" ? "см" : "cm"}` : collection.sizes.replace(/cm$/i, locale === "ru" ? "см" : "cm") },
    { label: t.surfaces, value: surfaces.length ? surfaces.join(" · ") : collection.surfaces[locale] },
  ];

  return <section className="relative overflow-hidden border-t px-6 py-20 md:px-12 md:py-28" style={{ borderColor: "var(--border)", background: "var(--surface-0)" }}>
    <m.p aria-hidden initial={{ opacity: 0 }} whileInView={{ opacity: .025 }} className="pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2 whitespace-nowrap text-center text-[18vw] font-semibold uppercase leading-none tracking-[-.08em]">{collection.name}</m.p>
    <div className="relative mx-auto max-w-[100rem]">
      <m.div initial={reduceMotion ? false : { opacity: 0, y: 34 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, amount: .35 }} className="flex flex-col justify-between gap-8 border-b pb-10 md:flex-row md:items-end" style={{ borderColor: "var(--border)" }}>
        <div>
          <p className="font-mono text-[9px] uppercase tracking-[.22em]" style={{ color: "var(--ember)" }}>{collection.name} · {t.index}</p>
          <h2 className="mt-4 max-w-4xl text-4xl font-medium leading-[1.02] tracking-[-.05em] md:text-6xl">{collection.tagline[locale]}</h2>
        </div>
        <Link href={`/${locale}/products?category=hobs&series=${encodeURIComponent(collection.slug)}`} className="flex min-h-11 items-center gap-3 rounded-full border px-5 font-mono text-[8px] uppercase tracking-[.17em] transition-colors hover:border-ember hover:text-ember focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember" style={{ borderColor: "var(--border)", color: "var(--fg-muted)" }}><span className="h-px w-8" style={{ background: "var(--ember)" }}/>{t.continue}<ArrowRight size={12}/></Link>
      </m.div>
      <div className="grid md:grid-cols-3">
        {metrics.map((metric, index) => <m.div
          key={metric.label}
          initial={reduceMotion ? false : { opacity: 0, y: 26 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, amount: .5 }}
          transition={{ delay: index * .08 }}
          className="border-b py-8 md:border-b-0 md:border-r md:px-8 md:py-10 first:md:pl-0 last:md:border-r-0"
          style={{ borderColor: "var(--border)" }}
        >
          <span className="font-mono text-[8px] uppercase tracking-[.18em]" style={{ color: "var(--fg-muted)" }}>{metric.label}</span>
          <strong className="mt-3 block text-2xl font-medium tracking-[-.03em] md:text-3xl">{metric.value}</strong>
        </m.div>)}
      </div>
    </div>
  </section>;
}

function ChapterScene({ chapter, index, locale, collection, products, reduceMotion }: { chapter: Chapter; index: number; locale: CollectionLocale; collection: NordenCollection; products: StoryProduct[]; reduceMotion: boolean }) {
  const sceneRef = useRef<HTMLElement>(null);
  const mediaLeft = index % 2 === 1;
  const { scrollYProgress } = useScroll({ target: sceneRef, offset: ["start end", "end start"] });
  const mediaScale = useTransform(scrollYProgress, [0, .48, 1], [.86, 1, .95]);
  const mediaY = useTransform(scrollYProgress, [0, .5, 1], [70, 0, -42]);
  const mediaRotate = useTransform(scrollYProgress, [0, .5, 1], [mediaLeft ? -2.2 : 2.2, 0, mediaLeft ? 1 : -1]);
  const icons = { size: <Ruler/>, control: <CircleGauge/>, power: <Flame/>, surface: <Layers3/>, choice: <Sparkles/> };
  if (chapter.icon === "control" && chapter.detail.includes("TOUCH")) icons.control = <Touchpad/>;
  if (chapter.icon === "power" && chapter.detail.includes("TIMER")) icons.power = <Timer/>;
  return <article ref={sceneRef} data-story-chapter={index + 1} className="grid min-h-0 items-center gap-10 border-b py-16 md:py-20 lg:min-h-[88svh] lg:grid-cols-2 lg:gap-16" style={{ borderColor: "var(--border)" }}>
    <m.div
      style={reduceMotion ? undefined : { scale: mediaScale, y: mediaY, rotate: mediaRotate }}
      initial={reduceMotion ? false : { opacity: 0 }}
      whileInView={{ opacity: 1 }}
      viewport={{ amount: .25 }}
      transition={{ duration: .8, ease: [0.16, 1, 0.3, 1] }}
      className={`order-1 min-w-0 ${mediaLeft ? "lg:order-1" : "lg:order-2"}`}
    >
      <div data-story-visual={chapter.icon}>
        <ChapterVisual chapter={chapter} index={index} locale={locale} collection={collection} products={products} />
      </div>
    </m.div>
    <m.div
      initial={reduceMotion ? false : { opacity: 0, x: mediaLeft ? 150 : -150 }}
      whileInView={{ opacity: 1, x: 0 }}
      viewport={{ amount: .42 }}
      transition={{ duration: 1, ease: [0.16, 1, 0.3, 1] }}
      className={`order-2 w-full ${mediaLeft ? "lg:order-2 lg:text-right" : "lg:order-1 lg:text-left"}`}
    >
      <span className={`flex h-11 w-11 items-center justify-center rounded-full border ${mediaLeft ? "lg:ml-auto" : "mr-auto"}`} style={{ borderColor: "var(--accent-border)", color: "var(--ember)" }}>{icons[chapter.icon]}</span>
      <span className="mt-7 block font-mono text-[10px] tracking-[.22em]" style={{ color: "var(--ember)" }}>{String(index + 1).padStart(2, "0")}</span>
      <h2 className="mt-5 overflow-hidden text-4xl font-medium leading-[1.04] tracking-[-.045em] md:text-6xl">{chapter.title.split(" ").map((word, i) => <m.span key={`${word}-${i}`} initial={reduceMotion ? false : { opacity: 0, y: 34 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: false }} transition={{ delay: i * .045 }} className="mr-[.2em] inline-block">{word}</m.span>)}</h2>
      <m.p initial={reduceMotion ? false : { opacity: 0, x: mediaLeft ? 50 : -50 }} whileInView={{ opacity: 1, x: 0 }} transition={{ delay: .22, duration: .65 }} className={`mt-7 max-w-2xl text-lg leading-8 ${mediaLeft ? "lg:ml-auto" : "mr-auto"}`} style={{ color: "var(--fg-secondary)" }}>{chapter.body}</m.p>
      <p className="mt-8 font-mono text-[9px] uppercase leading-6 tracking-[.16em]" style={{ color: "var(--fg-muted)" }}>{chapter.detail}</p>
      {index === 4 && <SurfacePalette locale={locale} />}
    </m.div>
  </article>;
}

function ChapterVisual({ chapter, index, locale, collection, products }: { chapter: Chapter; index: number; locale: CollectionLocale; collection: NordenCollection; products: StoryProduct[] }) {
  const electric = collection.seriesFilter === "VTC";
  const visualCopy = locale === "tr"
    ? { lineup: "Yayımlanmış gerçek ölçüler", top: "Gerçek ürün üst görünüşü", wok: "Wok donanımlı gerçek model", control: "Kontrol yüzeyi detayı", choices: "Gerçek yüzey ve model seçenekleri" }
    : locale === "ru"
      ? { lineup: "Реальные опубликованные размеры", top: "Реальный вид изделия сверху", wok: "Реальная модель с Wok", control: "Деталь панели управления", choices: "Реальные варианты поверхности и моделей" }
      : { lineup: "Published real dimensions", top: "Real product top view", wok: "Real Wok-equipped model", control: "Control-surface detail", choices: "Real surface and model choices" };

  if (index === 0) return <SizeLineup collection={collection} locale={locale} products={products} caption={visualCopy.lineup} />;

  if (index === 1) {
    const controlProduct = products.find((product) => product.widthCm === 60) ?? products[0];
    const detailImage = electric && controlProduct
      ? controlProduct.image.replace(/01-perspective\.webp$/i, "03-detail.webp")
      : chapter.image;
    return <TechnicalImageFrame src={detailImage || collection.image} alt={visualCopy.control} caption={visualCopy.control} cover={Boolean(chapter.image)} />;
  }

  if (index === 2) {
    if (electric) {
      const controlProduct = products.find((product) => product.widthCm === 60) ?? products[0];
      const detailImage = controlProduct?.image.replace(/01-perspective\.webp$/i, "03-detail.webp") ?? collection.image;
      return <TechnicalImageFrame src={detailImage} alt={visualCopy.control} caption={visualCopy.control} cover />;
    }
    const wokProduct = products.find((product) => product.widthCm === 60 && /\bwok\b/i.test(product.name) && !/inox/i.test(product.surface || ""))
      ?? products.find((product) => product.widthCm === 60 && /\bwok\b/i.test(product.name))
      ?? products.find((product) => /\bwok\b/i.test(product.name))
      ?? products.find((product) => product.widthCm === 60)
      ?? products[0];
    return <TechnicalImageFrame src={wokProduct?.image || collection.image} alt={wokProduct ? localizeProductName(wokProduct, locale) : visualCopy.wok} caption={wokProduct ? localizeProductName(wokProduct, locale) : visualCopy.wok} />;
  }

  if (index === 3) return <TechnicalImageFrame src={collection.topImage} alt={`${collection.name} · ${visualCopy.top}`} caption={`${collection.name} · ${visualCopy.top}`} />;

  return <SurfaceVariants collection={collection} locale={locale} products={products} caption={visualCopy.choices} />;
}

function SizeLineup({ collection, locale, products, caption }: { collection: NordenCollection; locale: CollectionLocale; products: StoryProduct[]; caption: string }) {
  const byWidth = new Map<number, StoryProduct>();
  for (const product of products) {
    if (product.widthCm !== null && !byWidth.has(product.widthCm)) byWidth.set(product.widthCm, product);
  }
  const lineup = [...byWidth.entries()].sort(([a], [b]) => a - b).slice(0, 4);

  return <div className="relative overflow-hidden rounded-[32px] border p-5 md:p-7" style={{ borderColor: "var(--border)", background: "radial-gradient(circle at 50% 42%, color-mix(in srgb, var(--ember) 10%, transparent), var(--surface-1) 68%)" }}>
    <TechnicalVisualDecor />
    <p className="relative z-30 font-mono text-[9px] uppercase tracking-[.18em]" style={{ color: "var(--ember)" }}>{caption}</p>
    <div className={`relative z-10 mt-5 grid gap-3 ${lineup.length > 3 ? "grid-cols-2 xl:grid-cols-4" : "grid-cols-3"}`}>
      {lineup.map(([width, product]) => <div key={product.id} className="min-w-0 rounded-2xl border p-3" style={{ borderColor: "var(--border)", background: "color-mix(in srgb, var(--surface-0) 82%, transparent)" }}>
        <div className="relative aspect-[4/5]"><Image src={product.image} alt={localizeProductName(product, locale)} fill sizes="(max-width:1024px) 42vw, 12vw" className="object-contain" /></div>
        <strong className="mt-2 block text-center text-xl font-medium">{width}<span className="ml-1 text-[9px] uppercase tracking-[.12em]" style={{ color: "var(--fg-muted)" }}>{locale === "ru" ? "см" : "cm"}</span></strong>
      </div>)}
    </div>
    {lineup.length === 0 && <TechnicalImageFrame src={collection.image} alt={collection.name} caption={caption} />}
  </div>;
}

function TechnicalImageFrame({ src, alt, caption, cover = false }: { src: string; alt: string; caption: string; cover?: boolean }) {
  return <div className="relative aspect-[4/3] overflow-hidden rounded-[32px] border" style={{ borderColor: "var(--border)", background: "radial-gradient(circle at 50% 45%, color-mix(in srgb, var(--ember) 9%, transparent), var(--surface-1) 70%)" }}>
    <TechnicalVisualDecor />
    <Image src={src} alt={alt} fill sizes="(max-width:1024px) 100vw, 48vw" className={`z-10 ${cover ? "object-cover" : "object-contain p-6 md:p-9"}`} />
    <div className="absolute inset-x-0 bottom-0 z-30 bg-gradient-to-t from-black/85 to-transparent px-5 pb-5 pt-14">
      <p className="font-mono text-[8px] uppercase leading-5 tracking-[.16em] text-white/70">{caption}</p>
    </div>
  </div>;
}

function SurfaceVariants({ collection, locale, products, caption }: { collection: NordenCollection; locale: CollectionLocale; products: StoryProduct[]; caption: string }) {
  const glass = products.find((product) => product.surface === "Siyah Cam" && getProductCookingSystem(product) === "gas");
  const inox = products.find((product) => product.surface === "Inox");
  const ceran = products.find((product) => getProductCookingSystem(product) !== "gas");
  const alternatives = [glass, inox, ceran].filter((product, index, items): product is StoryProduct => Boolean(product) && items.findIndex((candidate) => candidate?.id === product?.id) === index);
  if (alternatives.length === 0 && products[0]) alternatives.push(products[0]);
  if (alternatives.length === 1) {
    const second = products.find((product) => product.id !== alternatives[0].id && product.widthCm !== alternatives[0].widthCm);
    if (second) alternatives.push(second);
  }

  return <div className="relative overflow-hidden rounded-[32px] border p-5 md:p-7" style={{ borderColor: "var(--border)", background: "var(--surface-1)" }}>
    <TechnicalVisualDecor />
    <p className="relative z-30 font-mono text-[9px] uppercase tracking-[.18em]" style={{ color: "var(--ember)" }}>{caption}</p>
    <div className={`relative z-10 mt-5 grid gap-4 ${alternatives.length > 2 ? "grid-cols-2 md:grid-cols-3" : alternatives.length > 1 ? "grid-cols-2" : "grid-cols-1"}`}>
      {alternatives.map((product) => <div key={product.id} className="min-w-0 overflow-hidden rounded-2xl border" style={{ borderColor: "var(--border)", background: "var(--surface-0)" }}>
        <div className="relative aspect-square overflow-hidden"><TechnicalVisualDecor/><Image src={product.image} alt={localizeProductName(product, locale)} fill sizes="(max-width:1024px) 44vw, 22vw" className="z-10 object-contain p-4 md:p-6" /></div>
        <div className="border-t p-3" style={{ borderColor: "var(--border)" }}><p className="truncate text-xs font-medium">{localizeProductName(product, locale)}</p><span className="mt-1 block truncate font-mono text-[7px] uppercase tracking-[.13em]" style={{ color: "var(--fg-muted)" }}>{getProductFormatLabels(product, locale).join(" · ") || collection.name} · {product.widthCm ?? "—"} {locale === "ru" ? "см" : "cm"}</span></div>
      </div>)}
    </div>
  </div>;
}

function TechnicalVisualDecor() {
  return <div aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden">
    <span className="absolute left-5 top-5 z-20 flex items-center gap-2 opacity-65"><span className="h-px w-9" style={{ background: "var(--ember)" }}/><span className="h-1.5 w-1.5 rounded-full border" style={{ borderColor: "var(--ember)" }}/></span>
    <span className="absolute bottom-5 right-5 z-20 flex items-center gap-2 opacity-45"><span className="h-1.5 w-1.5 rounded-full border" style={{ borderColor: "var(--ember)" }}/><span className="h-px w-12" style={{ background: "var(--ember)" }}/></span>
  </div>;
}

function SurfacePalette({ locale }: { locale: CollectionLocale }) {
  const finish = locale === "tr" ? "Parlak · Mat" : locale === "ru" ? "Глянцевое · Матовое" : "Glossy · Matte";
  const colors = [
    { name: locale === "ru" ? "Белый" : "White", value: "#f1f0eb" },
    { name: locale === "ru" ? "Чёрный" : "Black", value: "#151517" },
    { name: locale === "ru" ? "Бежевый" : "Beige", value: "#c39b6d" },
    { name: locale === "ru" ? "Серый" : "Gray", value: "#aaa9a5" },
  ];
  return <div className="mt-9 rounded-2xl border p-4" style={{ borderColor: "var(--border)", background: "var(--surface-1)" }}>
    <div className={`flex gap-4 ${locale === "ru" ? "gap-3" : ""}`}>{colors.map((color) => <div key={color.name} className="text-center"><span className="mx-auto block h-9 w-9 rounded-full border-2 shadow-inner" style={{ background: color.value, borderColor: "var(--surface-2)" }}/><span className="mt-2 block text-[7px] uppercase tracking-[.08em]" style={{ color: "var(--fg-muted)" }}>{color.name}</span></div>)}</div>
    <p className="mt-4 font-mono text-[8px] uppercase tracking-[.15em]" style={{ color: "var(--fg-muted)" }}>{finish}</p>
  </div>;
}
