"use client";

import { useEffect, useRef, useState } from "react";
import { SectionIcon } from "./icons";
import type { GalleryCoverflowData } from "./GalleryCoverflow.schema";

const NAV_LABELS = {
  ar: { prev: "السابق", next: "التالي", first: "٠١" },
  en: { prev: "Previous", next: "Next", first: "01" },
} as const;

function detectLocale(): "ar" | "en" {
  if (typeof document === "undefined") return "ar";
  return document.documentElement.lang === "en" ? "en" : "ar";
}

export function GalleryCoverflow({ data }: { data: GalleryCoverflowData }) {
  const rootRef = useRef<HTMLDivElement | null>(null);
  const [locale, setLocale] = useState<"ar" | "en">("ar");
  useEffect(() => setLocale(detectLocale()), []);
  const labels = NAV_LABELS[locale];

  useEffect(() => {
    let swiperInstance: { destroy: (a: boolean, b: boolean) => void } | null = null;
    let lightbox: { destroy: () => void } | null = null;

    (async () => {
      const [SwiperModule, modulesPkg, glightboxModule] = await Promise.all([
        import("swiper"),
        import("swiper/modules"),
        import("glightbox"),
      ]);
      const Swiper = (SwiperModule as { default: unknown }).default as new (
        el: HTMLElement,
        opts: Record<string, unknown>,
      ) => { destroy: (a: boolean, b: boolean) => void };
      const { EffectCoverflow, Autoplay, Navigation, Keyboard } = modulesPkg as unknown as {
        EffectCoverflow: unknown;
        Autoplay: unknown;
        Navigation: unknown;
        Keyboard: unknown;
      };

      const el = rootRef.current?.querySelector<HTMLElement>(".gal-swiper");
      if (!el) return;

      swiperInstance = new Swiper(el, {
        modules: [EffectCoverflow, Autoplay, Navigation, Keyboard],
        effect: "coverflow",
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: "auto",
        loop: true,
        speed: 700,
        coverflowEffect: { rotate: 22, stretch: -30, depth: 320, modifier: 1, slideShadows: false },
        autoplay: { delay: 3800, disableOnInteraction: false, pauseOnMouseEnter: true },
        navigation: { nextEl: ".gal-next", prevEl: ".gal-prev" },
        keyboard: { enabled: true },
      });

      const GLightboxFactory = (glightboxModule as { default: (opts: Record<string, unknown>) => { destroy: () => void } }).default;
      lightbox = GLightboxFactory({ selector: ".gallery-link", touchNavigation: true, loop: true });
    })();

    return () => {
      swiperInstance?.destroy(true, true);
      lightbox?.destroy();
    };
  }, []);

  return (
    <section className="gallery-sec" data-screen-label="04b Gallery" ref={rootRef}>
      <div className="pattern" />
      <div className="wrap" style={{ position: "relative", zIndex: 2 }}>
        <div className="gallery-head">
          <div className="left">
            <div className="label-row">
              {data.eyebrow ? (
                <span className="eyebrow">
                  <span className="pip" />
                  {data.eyebrow}
                </span>
              ) : null}
              {data.total_label ? (
                <span className="index-pill">
                  <span className="num" id="galCurrent">{labels.first}</span>
                  <span>/</span>
                  <span className="total">{data.total_label}</span>
                </span>
              ) : null}
            </div>
            {(data.title_line_1 || data.title_line_2) && (
              <h2>
                {data.title_line_1}
                {data.title_line_2 ? (
                  <>
                    <br />
                    <span dangerouslySetInnerHTML={{ __html: data.title_line_2 }} />
                  </>
                ) : null}
              </h2>
            )}
            {data.subtitle ? <p className="sub">{data.subtitle}</p> : null}
          </div>
        </div>

        <div className="swiper gal-swiper">
          <div className="swiper-wrapper">
            {data.slides.map((slide, i) => (
              <div key={i} className="swiper-slide">
                <a
                  href={slide.src}
                  className="gallery-link"
                  data-type="image"
                  data-gallery="backyard"
                  data-title={slide.caption}
                >
                  <div className="gal-card">
                    <div className="img" style={{ backgroundImage: `url('${slide.src}')` }} />
                    <span className="zoom-hint" aria-hidden="true">
                      <SectionIcon name="zoom-in" size={18} />
                    </span>
                    <span className="num">{slide.num_label}</span>
                    <span className="cat">
                      <span className="dot" />
                      {slide.category}
                    </span>
                    <div className="floor">
                      <div className="eb">{slide.eyebrow}</div>
                      <div className="ttl">
                        {slide.title_line_1}
                        {slide.title_line_2 ? (
                          <>
                            <br />
                            {slide.title_line_2}
                          </>
                        ) : null}
                      </div>
                    </div>
                  </div>
                </a>
              </div>
            ))}
          </div>
        </div>

        <div className="gallery-nav-bottom">
          <button className="gal-btn gal-prev" aria-label={labels.prev} type="button">
            <SectionIcon name="chevron-right" size={20} />
          </button>
          <button className="gal-btn gal-next" aria-label={labels.next} type="button">
            <SectionIcon name="chevron-left" size={20} />
          </button>
        </div>

        {data.marquee_chips.length > 0 ? (
          <div className="gallery-marquee" aria-hidden="true">
            <div className="marquee-track">
              {data.marquee_chips.map((chip, i) => (
                <span key={i} className={`marq-chip${chip.color !== "purple" ? ` ${chip.color}` : ""}`}>
                  <span className="sw" />
                  {chip.label}
                </span>
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </section>
  );
}

// Registration moved to GalleryCoverflow.register.ts — see that file for why.
