"use client";

import Image, { type StaticImageData } from "next/image";
import { useCallback, useEffect, useState } from "react";
import { useTranslations, useLocale } from "next-intl";
import { ArrowRight } from "lucide-react";
import heroTherapistClient from "@/public/images/hero-therapist-client.jpg";
import heroIndividual from "@/public/images/hero-individual-selfscreen.jpg";
import heroPractitioner from "@/public/images/hero-practitioner-report.jpg";
import { Link } from "@/i18n/navigation";
import { isAuthenticated, getUserDataCookie } from "@/lib/cookies";
import { RoleType } from "@/lib/enums/RoleType";

const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';

const HERO_SLIDE_INTERVAL = 5000;

interface HeroSlide {
  src: StaticImageData;
  alt: string;
}

const slides: HeroSlide[] = [
  {
    src: heroTherapistClient,
    alt: "Therapist and client reviewing a MBHS behavioral health results graph together on a laptop",
  },
  {
    src: heroPractitioner,
    alt: "Therapist reviewing a client's MBHS screening report on a laptop before a session",
  },
  {
    src: heroIndividual,
    alt: "Person at home completing an MBHS self-screening and viewing their results on a tablet",
  },
];

export default function Hero() {
  const t = useTranslations("hero");
  const locale = useLocale();

  const pills = [t("pills.screening"), t("pills.reports"), t("pills.progress")];

  // Right-panel carousel: auto-rotating MBHS scenes (client request)
  const [currentSlide, setCurrentSlide] = useState(0);
  const [isPaused, setIsPaused] = useState(false);

  // CTA label defaults to the public trial prompt for SSR/first paint, then
  // adapts to the visitor's role after mount (avoids a hydration mismatch,
  // since auth state lives in a client-only cookie).
  const [ctaLabel, setCtaLabel] = useState(() => t("cta"));

  useEffect(() => {
    // Auth/role live in a client-only cookie, so the label must be synced
    // after mount to avoid an SSR hydration mismatch — intentional setState.
    if (!isAuthenticated()) return;
    const role = getUserDataCookie()?.role;
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setCtaLabel(role === RoleType.INDIVIDUALS ? t("ctaNewScreening") : t("ctaDashboard"));
  }, [t]);

  const goToSlide = useCallback((index: number) => {
    setCurrentSlide(index);
  }, []);

  useEffect(() => {
    if (isPaused) return;
    // Respect users who prefer reduced motion — no auto-advance
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % slides.length);
    }, HERO_SLIDE_INTERVAL);
    return () => clearInterval(timer);
  }, [isPaused]);

  // Handle Start Screening button click with role-based redirect
  const handleStartScreening = (e: React.MouseEvent) => {
    // Check if user is logged in
    if (isAuthenticated()) {
      e.preventDefault();
      const userData = getUserDataCookie();
      const role = userData?.role;

      // Build locale-aware path
      const buildPath = (path: string) => `${basePath}/${locale}${path}`;

      // Redirect based on role
      if (role === RoleType.ADMIN) {
        window.location.href = buildPath("/admin");
      } else if (role === RoleType.PRACTITIONERS) {
        window.location.href = buildPath("/practitioner");
      } else if (role === RoleType.INDIVIDUALS) {
        // For individuals, go directly to new screening
        window.location.href = buildPath("/individual/screening/new");
      } else {
        // Fallback to signup for unknown roles
        window.location.href = buildPath("/signup");
      }
    }
    // If not authenticated, let the default Link behavior navigate to /signup
  };

  return (
    <section className="relative w-full grid grid-cols-1 lg:grid-cols-2 lg:min-h-screen">
      {/* Left panel: copy, insight pills, CTA */}
      <div className="flex items-center bg-[#2e8ebe] px-6 sm:px-10 lg:px-16 py-16 lg:py-0">
        <div className="max-w-xl w-full">
          <p className="inline-block bg-white rounded-md px-3 py-1.5 text-[#135A87] font-bold text-sm sm:text-base tracking-wide mb-4 font-sans">
            {t("fullName")}
          </p>
          <h1 className="text-white leading-[1.1] mb-8 font-sans">
            <span className="block text-4xl sm:text-5xl font-normal">
              {t("titleLead")}
            </span>
            <span className="block text-4xl sm:text-5xl font-extrabold">
              {t("titleHighlight")}
            </span>
            <span className="block text-4xl sm:text-5xl font-normal">
              {t("titleTail")}
            </span>
          </h1>

          <ul className="space-y-3 mb-8 max-w-md">
            {pills.map((pill) => (
              <li
                key={pill}
                className="flex items-center gap-3 bg-white rounded-lg px-4 py-3 shadow-sm"
              >
                <ArrowRight className="h-4 w-4 shrink-0 text-[#1F80C3]" />
                <span className="text-sm font-medium text-gray-900">{pill}</span>
              </li>
            ))}
          </ul>

          <Link
            href="/signup"
            onClick={handleStartScreening}
            className="inline-flex items-center px-6 py-3 bg-white hover:bg-white/90 text-[#1F80C3] text-sm font-semibold rounded-lg transition"
          >
            {ctaLabel}
          </Link>
          <p className="mt-4 max-w-md text-white/80 text-[13px] leading-relaxed font-sans">
            {t("trialNote")}
          </p>
        </div>
      </div>

      {/* Right panel: auto-rotating carousel of MBHS scenes */}
      <div
        className="relative w-full h-64 sm:h-96 lg:h-auto overflow-hidden"
        onMouseEnter={() => setIsPaused(true)}
        onMouseLeave={() => setIsPaused(false)}
        onFocusCapture={() => setIsPaused(true)}
        onBlurCapture={() => setIsPaused(false)}
      >
        {slides.map((slide, index) => (
          <div
            key={slide.alt}
            className={`absolute inset-0 transition-opacity duration-700 ease-in-out ${
              index === currentSlide ? "opacity-100" : "opacity-0"
            }`}
            aria-hidden={index !== currentSlide}
          >
            <Image
              src={slide.src}
              alt={slide.alt}
              fill
              priority={index === 0}
              sizes="(min-width: 1024px) 50vw, 100vw"
              className="object-cover object-[center_20%]"
            />
          </div>
        ))}

        {/* Pagination dots */}
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-2">
          {slides.map((slide, index) => (
            <button
              key={slide.alt}
              type="button"
              onClick={() => goToSlide(index)}
              aria-label={`Show slide ${index + 1} of ${slides.length}`}
              aria-current={index === currentSlide}
              className={`h-2.5 rounded-full transition-all duration-300 ${
                index === currentSlide
                  ? "w-6 bg-white"
                  : "w-2.5 bg-white/60 hover:bg-white/90"
              }`}
            />
          ))}
        </div>
      </div>
    </section>
  );
}
