"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import type { HomeBanner } from "@/lib/api";

type Slide = {
  imgDesktop: string;
  imgMobile: string;
  alt: string;
  tone: "beige" | "light" | "dark";
  eyebrow: string;
  titleHtml: string;
  subHtml: string;
  cta: string;
  href: string;
};

// Fallback slides — used only when the admin /home API returns no banners,
// so the hero never renders empty. Kept identical to the launch design.
const base = "/images/portal/banners/";
const FALLBACK_SLIDES: Slide[] = [
  { imgDesktop: base + "avalon-care-desktop.webp", imgMobile: base + "avalon-care-mobile.webp", alt: "Avalon Care moisturising skincare collection", tone: "beige", eyebrow: "Featured brand · Dermatology", titleHtml: "Avalon&nbsp;Care,<br><em>for skin that needs more.</em>", subHtml: "Dermatological moisturisers — anti-wrinkle, dryness repair and emollient care.", cta: "Shop Avalon", href: "/portal/brand/avalon-pharma" },
  { imgDesktop: base + "celestetic-splash-desktop.webp", imgMobile: base + "celestetic-splash-mobile.webp", alt: "Celestetic Ultimate Protect and C Perfect serums", tone: "light", eyebrow: "Featured brand · Cosmeceuticals", titleHtml: "Celestetic.<br><em>Science-led skincare.</em>", subHtml: "Belgian cosmeceuticals — high-concentration actives and daily SPF protection.", cta: "Shop Celestetic", href: "/portal/brand/celestetic" },
  { imgDesktop: base + "mg-deodorant-desktop.webp", imgMobile: base + "mg-deodorant-mobile.webp", alt: "Maria Galland 940 Secret de Beauté refreshing deodorant", tone: "dark", eyebrow: "Maria Galland Paris", titleHtml: "The secret of<br><em>everyday beauty.</em>", subHtml: "940 Secret de Beauté — refreshing deodorant, Parisian luxury care.", cta: "Shop Maria Galland", href: "/portal/brand/maria-galland" },
  { imgDesktop: base + "mg-hydra-desktop.webp", imgMobile: base + "mg-hydra-mobile.webp", alt: "Maria Galland Hydra'Global serum and cream", tone: "beige", eyebrow: "Maria Galland Paris", titleHtml: "Hydra&rsquo;Global.<br><em>Deep, lasting hydration.</em>", subHtml: "The 240 serum &amp; 260 cream — a professional French hydration ritual.", cta: "Shop Maria Galland", href: "/portal/brand/maria-galland" },
  { imgDesktop: base + "piuma-oral-desktop.webp", imgMobile: base + "piuma-oral-mobile.webp", alt: "Piuma toothpaste and toothbrush oral-care set", tone: "light", eyebrow: "Piuma · Oral care", titleHtml: "Piuma.<br><em>A brighter daily ritual.</em>", subHtml: "Gentle toothpaste and brushes — Italian design for everyday oral care.", cta: "Shop Piuma", href: "/portal/brand/piuma" },
  { imgDesktop: base + "celestetic-foamer-desktop.webp", imgMobile: base + "celestetic-foamer-mobile.webp", alt: "Celestetic Pure Foamer cleansing mousse", tone: "light", eyebrow: "Celestetic · Cleansers", titleHtml: "Pure Foamer.<br><em>A fresh start.</em>", subHtml: "Purifying cleansing mousse with vitamin B3, B5 and hyaluronic acid.", cta: "Shop Celestetic", href: "/portal/brand/celestetic" },
  { imgDesktop: base + "piuma-trio-desktop.webp", imgMobile: base + "piuma-trio-mobile.webp", alt: "Piuma toothpaste trio", tone: "light", eyebrow: "Piuma · Oral care", titleHtml: "Fresh and clean,<br><em>every single day.</em>", subHtml: "The Piuma toothpaste trio — clean, considered oral care.", cta: "Shop Piuma", href: "/portal/brand/piuma" },
  { imgDesktop: base + "viva-wellness-desktop.webp", imgMobile: base + "viva-wellness-mobile.webp", alt: "Viva Nutraceuticals wellness supplement collection", tone: "beige", eyebrow: "Viva Nutraceuticals · Wellness", titleHtml: "Wellness,<br><em>from the inside out.</em>", subHtml: "Premium supplements for immunity, beauty, joints and healthy ageing.", cta: "Shop Viva", href: "/portal/brand/viva-nutraceuticals" },
];

function stripTags(s: string | null): string {
  return (s || "").replace(/<[^>]*>/g, " ").replace(/&[a-z]+;/gi, " ").replace(/\s+/g, " ").trim();
}

function toSlides(banners?: HomeBanner[]): Slide[] {
  if (!banners || banners.length === 0) return FALLBACK_SLIDES;
  const mapped = banners
    .filter((b) => b.image)
    .map((b): Slide => ({
      imgDesktop: b.image as string,
      imgMobile: b.mobile || (b.image as string),
      alt: stripTags(b.title) || b.eyebrow || "Featured",
      tone: (b.tone === "light" || b.tone === "dark" ? b.tone : "beige"),
      eyebrow: b.eyebrow || "",
      titleHtml: b.title || "",
      subHtml: b.subtitle || "",
      cta: b.cta || "Shop now",
      href: b.link || "/portal",
    }));
  return mapped.length ? mapped : FALLBACK_SLIDES;
}

export default function PortalHero({ banners }: { banners?: HomeBanner[] }) {
  const SLIDES = toSlides(banners);
  const [active, setActive] = useState(0);
  const timer = useRef<ReturnType<typeof setInterval> | null>(null);
  const n = SLIDES.length;

  useEffect(() => {
    const start = () => {
      stop();
      timer.current = setInterval(() => setActive((i) => (i + 1) % n), 5500);
    };
    const stop = () => { if (timer.current) clearInterval(timer.current); };
    start();
    return stop;
  }, [n]);

  const go = (i: number) => {
    setActive(i);
    if (timer.current) clearInterval(timer.current);
    timer.current = setInterval(() => setActive((x) => (x + 1) % n), 5500);
  };

  return (
    <section className="pb-hero pb-hero--banners" data-hero>
      <div className="pb-hero-slides">
        {SLIDES.map((s, i) => (
          <div
            key={s.imgDesktop + i}
            className={`pb-hero-slide pb-hero-slide--${s.tone}${i === active ? " is-active" : ""}`}
            aria-hidden={i !== active}
          >
            <div className="pb-hero-media">
              <picture>
                <source media="(max-width: 900px)" srcSet={s.imgMobile} />
                <img src={s.imgDesktop} alt={s.alt} width={2160} height={720} loading={i === 0 ? "eager" : "lazy"} decoding="async" />
              </picture>
              <span className="pb-hero-scrim" />
            </div>
            <div className="pb-shell pb-hero-in">
              <div className="pb-hero-copy">
                {s.eyebrow ? <span className="pb-eyebrow pb-eyebrow--line">{s.eyebrow}</span> : null}
                <h1 className="pb-hero-title" dangerouslySetInnerHTML={{ __html: s.titleHtml }} />
                {s.subHtml ? <p className="pb-hero-sub" dangerouslySetInnerHTML={{ __html: s.subHtml }} /> : null}
                <div className="pb-hero-cta">
                  <Link href={s.href} className="pb-btn pb-btn--primary">
                    {s.cta}
                    <svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" /></svg>
                  </Link>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className="pb-hero-dots" role="group" aria-label="Featured banners">
        {SLIDES.map((s, i) => (
          <button
            key={s.imgDesktop + i}
            type="button"
            className={i === active ? "is-active" : ""}
            aria-label={`Show banner ${i + 1}`}
            aria-pressed={i === active}
            onClick={() => go(i)}
          />
        ))}
      </div>
    </section>
  );
}
