"use client";

import { getImageProps } from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";

import { about, heroSlides, site, type HeroSlide } from "@/data/site";

const SLIDE_MS = 6500;

/**
 * Portrait and landscape crops ship separately, as on the source site.
 *
 * Rendering two <Image> elements and hiding one with CSS still downloads both,
 * so the srcsets are handed to a <picture> instead — the browser resolves the
 * media query before it fetches, and only one crop is ever requested.
 */
function SlideImage({
  slide,
  priority,
  animate,
}: {
  slide: HeroSlide;
  priority: boolean;
  animate: boolean;
}) {
  const common = {
    alt: "",
    fill: true,
    sizes: "100vw",
    priority,
    placeholder: "blur" as const,
  };

  const { props: desktop } = getImageProps({ ...common, src: slide.desktop, quality: 82 });
  const { props: mobile } = getImageProps({ ...common, src: slide.mobile, quality: 72 });

  return (
    <picture>
      <source media="(min-width: 768px)" srcSet={desktop.srcSet} sizes={desktop.sizes} />
      <source media="(max-width: 767px)" srcSet={mobile.srcSet} sizes={mobile.sizes} />
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        {...mobile}
        alt=""
        className={`object-cover ${animate ? "animate-slow-zoom" : ""}`}
      />
    </picture>
  );
}

export function Hero() {
  const [active, setActive] = useState(0);
  const timer = useRef<ReturnType<typeof setInterval> | null>(null);

  const startAutoplay = useCallback(() => {
    if (timer.current) clearInterval(timer.current);
    timer.current = setInterval(
      () => setActive((i) => (i + 1) % heroSlides.length),
      SLIDE_MS,
    );
  }, []);

  useEffect(() => {
    startAutoplay();
    return () => {
      if (timer.current) clearInterval(timer.current);
    };
  }, [startAutoplay]);

  const goTo = (index: number) => {
    setActive(index);
    startAutoplay(); // restart the clock so a manual pick gets its full dwell time
  };

  return (
    <section className="relative h-[100svh] min-h-[600px] w-full overflow-hidden bg-ink">
      {heroSlides.map((slide, i) => (
        <div
          key={slide.id}
          aria-hidden={i !== active}
          className={`absolute inset-0 transition-opacity duration-[1400ms] ease-out-soft ${
            i === active ? "opacity-100" : "opacity-0"
          }`}
        >
          <SlideImage slide={slide} priority={i === 0} animate={i === active} />
        </div>
      ))}

      {/* Legibility scrim: heavier at the edges, light across the image itself. */}
      <div className="absolute inset-0 bg-gradient-to-b from-black/65 via-black/25 to-black/80" />
      <div className="absolute inset-0 bg-gradient-to-l from-black/45 to-transparent" />

      <div className="relative z-10 mx-auto flex h-full max-w-[1400px] flex-col justify-center px-5 lg:px-10">
        <div className="max-w-2xl">
          <p className="kicker mb-7 animate-fade-up">
            <span className="latin">SINCE 1379</span>
          </p>

          <h1
            className="animate-fade-up text-[1.975rem] leading-[1.35] font-extrabold text-white sm:text-[3.125rem] lg:text-[3.625rem]"
            style={{ animationDelay: "120ms" }}
          >
            {site.name}
          </h1>

          <p
            className="mt-5 animate-fade-up text-xl font-light text-white/85 sm:text-2xl lg:text-3xl"
            style={{ animationDelay: "260ms" }}
          >
            {site.tagline}
          </p>

          <div
            className="mt-10 flex animate-fade-up flex-wrap items-center gap-4"
            style={{ animationDelay: "400ms" }}
          >
            <Link
              href="/aboutus"
              className="group inline-flex items-center gap-3 rounded-full bg-gold px-8 py-3.5 text-white transition-colors duration-300 hover:bg-white hover:text-ink"
            >
              {about.cta}
              <svg
                viewBox="0 0 24 24"
                fill="none"
                aria-hidden="true"
                className="h-4 w-4 transition-transform duration-300 group-hover:-translate-x-1"
              >
                <path d="M19 12H5m0 0 6-6m-6 6 6 6" stroke="currentColor" strokeWidth="1.6" />
              </svg>
            </Link>

            <Link
              href="/portfolios"
              className="rounded-full border border-white/35 px-8 py-3.5 text-white transition-colors duration-300 hover:border-white hover:bg-white/10"
            >
              مشاهده پروژه‌ها
            </Link>
          </div>
        </div>
      </div>

      {/* Slide picker */}
      <div className="absolute bottom-10 z-10 flex w-full justify-center gap-3 px-5 lg:bottom-12 lg:left-10 lg:w-auto lg:justify-start">
        {heroSlides.map((slide, i) => (
          <button
            key={slide.id}
            type="button"
            onClick={() => goTo(i)}
            aria-label={`اسلاید ${i + 1}`}
            aria-current={i === active}
            className="group h-8 py-3.5"
          >
            <span
              className={`block h-px transition-all duration-500 ease-out-soft ${
                i === active ? "w-14 bg-gold" : "w-7 bg-white/45 group-hover:bg-white"
              }`}
            />
          </button>
        ))}
      </div>

      <span className="latin absolute bottom-11 left-1/2 z-10 hidden -translate-x-1/2 text-[0.65rem] tracking-[0.42em] text-white/55 lg:block">
        SCROLL
      </span>
    </section>
  );
}
