"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { ArrowRight, Layers3 } from "lucide-react";
import { m, useReducedMotion } from "framer-motion";
import { useLocale } from "next-intl";
import TypewriterText from "@/components/TypewriterText";
import { getCollectionLocale, type NordenCollection } from "@/lib/collections";

const copy = {
  tr: {
    eyebrow: "Bir ürün değil, bir sistem",
    title: "Mutfağın ölçüsünden alevin karakterine kadar.",
    body: "Cam, Inox ve Vitroceramic yüzeyler; 30–90 cm ölçüler ve modele göre yapılandırılabilen pişirme bileşenleri. Norden kataloğu, tasarım kararlarını teknik gerçeklerle aynı düzlemde sunar.",
    explore: (count: number) => `${count} seriyi keşfet`,
    products: "Tüm ocakları karşılaştır",
    pillars: ["İşlev", "Dayanıklılık", "Kişiselleştirme", "Güç"],
  },
  en: {
    eyebrow: "Not a product, but a system",
    title: "From the dimensions of the kitchen to the character of the flame.",
    body: "Glass, Inox and Vitroceramic surfaces; 30–90 cm dimensions and model-dependent cooking components. The Norden catalogue presents design decisions and technical facts on the same plane.",
    explore: (count: number) => `Explore all ${count} series`,
    products: "Compare all hobs",
    pillars: ["Function", "Durability", "Customisation", "Power"],
  },
  ru: {
    eyebrow: "Не просто продукт, а система",
    title: "От размеров кухни до характера пламени.",
    body: "Поверхности из стекла, Inox и Vitroceramic; размеры 30–90 см и компоненты, зависящие от модели. Каталог Norden объединяет дизайнерские решения и технические факты.",
    explore: (count: number) => `Открыть ${count} серий`,
    products: "Сравнить все панели",
    pillars: ["Функция", "Надёжность", "Персонализация", "Мощность"],
  },
};

type SeriesTriangle = {
  clipPath: string;
  labelX: number;
  labelY: number;
  side: "left" | "right" | "center";
};

function getSeriesPoint(index: number, count: number) {
  const lastPoint = Math.max(count - 1, 1);
  return {
    x: index % 2 === 0 ? 0 : 100,
    y: (index / lastPoint) * 100,
  };
}

function getSeriesTriangle(index: number, count: number): SeriesTriangle {
  if (count <= 1) {
    return { clipPath: "polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)", labelX: 50, labelY: 50, side: "center" };
  }

  const lastIndex = count - 1;
  const formatPoint = ({ x, y }: { x: number; y: number }) => `${x}% ${y}%`;
  let points: Array<{ x: number; y: number }>;

  if (index === 0) {
    points = [getSeriesPoint(0, count), { x: 100, y: 0 }, getSeriesPoint(1, count)];
  } else if (index === lastIndex) {
    const lastPoint = getSeriesPoint(lastIndex, count);
    points = [
      getSeriesPoint(lastIndex - 1, count),
      { x: lastPoint.x === 0 ? 100 : 0, y: 100 },
      lastPoint,
    ];
  } else {
    points = [
      getSeriesPoint(index - 1, count),
      getSeriesPoint(index, count),
      getSeriesPoint(index + 1, count),
    ];
  }

  const centroidX = points.reduce((sum, point) => sum + point.x, 0) / points.length;

  return {
    clipPath: `polygon(${points.map(formatPoint).join(", ")})`,
    labelX: centroidX > 50 ? 74 : 26,
    labelY: points.reduce((sum, point) => sum + point.y, 0) / points.length,
    side: centroidX > 50 ? "right" : "left",
  };
}

export default function CategoryShowcase({ collections }: { collections: NordenCollection[] }) {
  const locale = getCollectionLocale(useLocale());
  const t = copy[locale];
  const reduceMotion = useReducedMotion();
  const [activeIndex, setActiveIndex] = useState(0);
  const collectionCount = collections.length;
  const activeCollection = collections[activeIndex] ?? collections[0];
  const seriesTriangles = collections.map((_, index) => getSeriesTriangle(index, collectionCount));
  const zigzagPoints = Array.from({ length: collectionCount }, (_, index) => {
    const { x, y } = getSeriesPoint(index, collectionCount);
    return `${x},${y}`;
  }).join(" ");

  return (
    <section id="categories" className="relative w-full overflow-hidden border-y px-6 py-16 md:px-12 md:py-20" style={{ background: "var(--surface-0)", borderColor: "var(--border)", color: "var(--fg-primary)" }}>
      <div aria-hidden="true" className="pointer-events-none absolute inset-0 opacity-70" style={{ background: "radial-gradient(circle at 82% 38%, rgba(204,145,78,.14), transparent 28%), linear-gradient(120deg, transparent 58%, rgba(255,255,255,.018))" }} />
      <m.div
        initial={reduceMotion ? false : { opacity: 0, y: 60 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true, amount: 0.25 }}
        transition={{ duration: 0.9, ease: [0.16, 1, 0.3, 1] }}
        className="relative mx-auto grid w-full max-w-[90rem] overflow-hidden rounded-[2rem] border lg:grid-cols-[1.15fr_.85fr]"
        style={{ borderColor: "var(--accent-border)", background: "var(--surface-1)", boxShadow: "var(--shadow-card)" }}
      >
        <div className="p-7 md:p-12">
          <div className="flex items-center gap-3">
            <Layers3 size={16} style={{ color: "var(--ember)" }} />
            <span className="eyebrow">{t.eyebrow}</span>
          </div>
          <h2 className="mt-7 max-w-4xl text-4xl font-medium leading-[1.03] tracking-[-.05em] md:text-6xl">
            <TypewriterText text={t.title} speed={21} />
          </h2>
          <p className="mt-7 max-w-3xl text-base leading-8 md:text-lg" style={{ color: "var(--fg-secondary)" }}>{t.body}</p>

          <div className="mt-10 grid grid-cols-2 border-y sm:grid-cols-4" style={{ borderColor: "var(--border)" }}>
            {t.pillars.map((pillar, index) => (
              <div key={pillar} className="border-b px-3 py-5 font-mono text-[9px] uppercase tracking-[.17em] odd:border-r sm:border-b-0 sm:border-r sm:last:border-r-0" style={{ borderColor: "var(--border)", color: index === 3 ? "var(--ember)" : "var(--fg-muted)" }}>
                <span className="mb-3 block text-[8px]">0{index + 1}</span>{pillar}
              </div>
            ))}
          </div>

          <div className="mt-9 flex flex-col gap-3 sm:flex-row sm:flex-wrap">
            <Link href={`/${locale}/collections`} className="group inline-flex min-h-12 items-center justify-center gap-3 rounded-full px-7 text-[10px] font-semibold uppercase tracking-[.16em] transition-transform hover:scale-[1.02]" style={{ background: "var(--ember)", color: "var(--surface-0)" }}>
              {t.explore(collectionCount)}<ArrowRight size={15} className="transition-transform group-hover:translate-x-1" />
            </Link>
            <Link href={`/${locale}/products?category=hobs`} className="group inline-flex min-h-12 items-center justify-center gap-3 rounded-full border px-7 text-[10px] font-semibold uppercase tracking-[.16em]" style={{ borderColor: "var(--border)", color: "var(--fg-secondary)" }}>
              {t.products}<ArrowRight size={15} className="transition-transform group-hover:translate-x-1" />
            </Link>
          </div>
        </div>

        <div
          className="relative min-h-[34rem] overflow-hidden border-t lg:min-h-0 lg:border-l lg:border-t-0"
          style={{ borderColor: "var(--border)" }}
          onMouseLeave={() => setActiveIndex(0)}
        >
          {activeCollection ? (
            <m.div
              key={activeCollection.slug}
              aria-hidden="true"
              initial={reduceMotion ? false : { opacity: 0, scale: 0.94, rotate: -2 }}
              animate={{ opacity: 1, scale: 1, rotate: 0 }}
              transition={{ duration: 0.55, ease: [0.16, 1, 0.3, 1] }}
              className="pointer-events-none absolute inset-10 md:inset-14 lg:inset-16"
            >
              <Image
                src={activeCollection.image}
                alt=""
                fill
                sizes="(max-width: 1024px) 88vw, 38vw"
                className="object-contain opacity-40 grayscale transition-[filter,opacity] duration-500"
              />
            </m.div>
          ) : null}

          <div
            aria-hidden="true"
            className="pointer-events-none absolute inset-0"
            style={{ background: "radial-gradient(circle at 50% 50%, transparent 10%, var(--surface-1) 76%), linear-gradient(180deg, rgba(7,11,17,.18), rgba(7,11,17,.7))" }}
          />

          {collectionCount > 0 ? (
            <svg aria-hidden="true" viewBox="0 0 100 100" preserveAspectRatio="none" className="pointer-events-none absolute inset-5 z-30 h-[calc(100%-2.5rem)] w-[calc(100%-2.5rem)] overflow-visible">
              <rect x="0" y="0" width="100" height="100" rx="2" fill="none" stroke="var(--border)" vectorEffect="non-scaling-stroke" />
              <polyline points={zigzagPoints} fill="none" stroke="var(--accent-border)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
            </svg>
          ) : null}

          <div className="absolute inset-5 z-20">
            {collections.map((collection, index) => {
              const active = index === activeIndex;
              const geometry = seriesTriangles[index];

              return (
                <Link
                  key={collection.slug}
                  href={`/${locale}/collections/${collection.slug}`}
                  prefetch={false}
                  onMouseEnter={() => setActiveIndex(index)}
                  onFocus={() => setActiveIndex(index)}
                  aria-label={`${collection.name}: ${collection.tagline[locale]}`}
                  className="group/series absolute inset-0 focus-visible:outline-none"
                  style={{
                    clipPath: geometry.clipPath,
                    background: active ? "rgba(204,145,78,.11)" : "transparent",
                  }}
                >
                  <span
                    aria-hidden="true"
                    className={`pointer-events-none absolute -translate-y-1/2 whitespace-nowrap text-[clamp(2.6rem,5.5vw,5.5rem)] font-medium uppercase leading-none tracking-[-.08em] transition-opacity duration-500 ${geometry.side === "right" ? "right-[4%] text-right" : geometry.side === "left" ? "left-[4%] text-left" : "left-1/2 -translate-x-1/2 text-center"} ${active ? "opacity-[.1]" : "opacity-[.035]"}`}
                    style={{ top: `${geometry.labelY}%`, color: "var(--fg-primary)" }}
                  >
                    {collection.name}
                  </span>
                  <span
                    className={`absolute z-10 flex w-[44%] -translate-x-1/2 -translate-y-1/2 items-center gap-2 transition-all duration-300 md:gap-3 ${geometry.side === "right" ? "text-right" : geometry.side === "left" ? "text-left" : "text-center"} ${active ? "scale-[1.04]" : "opacity-70 group-hover/series:opacity-100"}`}
                    style={{
                      left: `${geometry.labelX}%`,
                      top: `${geometry.labelY}%`,
                      color: active ? "var(--fg-primary)" : "var(--fg-secondary)",
                    }}
                  >
                    <span className="font-mono text-[8px] tracking-[.2em]" style={{ color: active ? "var(--ember-bright)" : "var(--fg-muted)" }}>
                      {String(index + 1).padStart(2, "0")}
                    </span>
                    <span className="min-w-0 flex-1">
                      <span className="block truncate text-sm font-medium tracking-[-.02em] md:text-base">{collection.name}</span>
                      <span className={`mt-1 hidden truncate font-mono text-[7px] uppercase tracking-[.14em] sm:block ${active ? "opacity-70" : "opacity-0"}`}>
                        {collection.tagline[locale]}
                      </span>
                    </span>
                    <ArrowRight size={13} className={`shrink-0 transition-transform ${active ? "translate-x-1" : "-translate-x-1 opacity-40"}`} />
                  </span>
                </Link>
              );
            })}
          </div>
        </div>
      </m.div>
    </section>
  );
}
