'use client';

import React, { useCallback, useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { AnimatePresence, motion, useReducedMotion } from 'motion/react';
import api from '@/lib/api';

export type HeroStat = {
  value: string;
  label: string;
};

export type HeroSlide = {
  id: number | string;
  badge?: string | null;
  title: string;
  subtitle?: string | null;
  primary_button_text?: string | null;
  primary_button_link?: string | null;
  secondary_button_text?: string | null;
  secondary_button_link?: string | null;
  stats?: HeroStat[] | null;
  image?: string | null;
  image_large?: string | null;
  image_medium?: string | null;
};

const AUTOPLAY_MS = 7000;

const FALLBACK_SLIDES: HeroSlide[] = [
  {
    id: 'fallback-1',
    badge: 'When a Girl Learns',
    title: 'The World Rises',
    subtitle:
      'Unlocking potential, transforming communities. SSEOA creates educational opportunities for girls and women in remote regions of Afghanistan.',
    primary_button_text: 'Donate Now',
    primary_button_link: '/donate',
    secondary_button_text: 'Learn More',
    secondary_button_link: '/about-us',
    image: '/images/hero/slider-1.webp',
    stats: [
      { value: '2,000+', label: 'Education Support' },
      { value: '1,500+', label: 'Kankor Preparation' },
      { value: '1,200+', label: 'Early Childhood Development' },
    ],
  },
  {
    id: 'fallback-2',
    badge: 'Every Educated Girl',
    title: 'Plants a Seed of Change',
    subtitle:
      'Building leaders through learning — Community-Based Education, ECD, and classrooms where schools cannot reach.',
    primary_button_text: 'Our Programs',
    primary_button_link: '/programs/education',
    secondary_button_text: 'Read Stories',
    secondary_button_link: '/blog?category=story',
    image: '/images/hero/slider-2.webp',
    stats: [
      { value: '3,130', label: 'CBE Students' },
      { value: '1,800+', label: 'Vocational & Literacy' },
      { value: '1,017', label: 'Teachers Recruited' },
    ],
  },
  {
    id: 'fallback-3',
    badge: 'From Classrooms to Communities',
    title: 'She Transforms All',
    subtitle:
      'Empowering girls is empowering generations. Livelihood skills, literacy, and education that help families thrive.',
    primary_button_text: 'Get Involved',
    primary_button_link: '/#get-involved',
    secondary_button_text: 'What We Do',
    secondary_button_link: '/#what-we-do',
    image: '/images/hero/slider-3.webp',
    stats: [
      { value: '105,081', label: 'Girls Reached' },
      { value: '1,445', label: 'Women in Literacy' },
      { value: '10', label: 'Provinces' },
    ],
  },
];

const STAT_ICONS = [
  <path
    key="cap"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth={1.75}
    d="M4.26 10.146a60.44 60.44 0 00-.491 6.347A48.628 48.628 0 0112 20.904a48.628 48.628 0 018.232-4.41 60.46 60.46 0 00-.491-6.347m-15.482 0a50.57 50.57 0 00-2.658-.813A59.906 59.906 0 0112 3.493a59.903 59.903 0 0110.399 5.84c-.896.248-1.783.52-2.658.814m-15.482 0A50.697 50.697 0 0112 13.489a50.702 50.702 0 017.74-3.342M6.75 15a.75.75 0 100-1.5.75.75 0 000 1.5zm0 0v-3.675A55.378 55.378 0 0112 8.443m-7.007 11.55A5.981 5.981 0 006.75 15.75v-1.5"
  />,
  <path
    key="book"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth={1.75}
    d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25"
  />,
  <path
    key="users"
    strokeLinecap="round"
    strokeLinejoin="round"
    strokeWidth={1.75}
    d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z"
  />,
];

function isExternalLink(href: string) {
  return /^https?:\/\//i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:');
}

function HeroCtaLink({ href, children }: { href: string; children: React.ReactNode }) {
  if (isExternalLink(href)) {
    return (
      <a href={href} target="_blank" rel="noopener noreferrer">
        {children}
      </a>
    );
  }

  return <Link href={href}>{children}</Link>;
}

function slideImage(slide?: HeroSlide | null) {
  return (
    slide?.image_large ||
    slide?.image_medium ||
    slide?.image ||
    '/images/hero/slider-1.webp'
  );
}

function SlidePhoto({
  src,
  alt,
  priority = false,
  className = 'object-cover object-center',
}: {
  src: string;
  alt: string;
  priority?: boolean;
  className?: string;
}) {
  if (src.startsWith('http')) {
    // eslint-disable-next-line @next/next/no-img-element
    return <img src={src} alt={alt} className={`absolute inset-0 h-full w-full ${className}`} />;
  }

  return (
    <Image
      src={src}
      alt={alt}
      fill
      priority={priority}
      className={className}
      sizes="(max-width: 1024px) 100vw, 70vw"
      quality={90}
    />
  );
}

function HighlightTitle({ title }: { title: string }) {
  const words = title.trim().split(/\s+/);
  const last = words.pop() ?? title;
  const rest = words.join(' ');

  return (
    <h1 className="text-[1.85rem] font-black leading-[1.08] tracking-tight sm:text-4xl md:text-5xl lg:text-[3.25rem]">
      {rest ? <span className="block text-white">{rest}</span> : null}
      <span className="text-primary-500">{last}</span>
    </h1>
  );
}

function SideCard({
  slide,
  icon,
  align,
  reduceMotion,
  onClick,
}: {
  slide: HeroSlide;
  icon: React.ReactNode;
  align: 'left' | 'right';
  reduceMotion: boolean | null;
  onClick: () => void;
}) {
  const fromX = align === 'left' ? -36 : 36;

  return (
    <motion.button
      type="button"
      onClick={onClick}
      aria-label={`Go to slide: ${slide.title}`}
      initial={reduceMotion ? false : { opacity: 0.45, x: fromX, scale: 0.96 }}
      animate={{ opacity: 1, x: 0, scale: 1 }}
      whileHover={reduceMotion ? undefined : { scale: 1.04, y: -6 }}
      whileTap={reduceMotion ? undefined : { scale: 0.98 }}
      transition={{ type: 'spring', stiffness: 260, damping: 28 }}
      className={`absolute top-[12%] z-0 hidden h-[76%] w-[13%] overflow-hidden rounded-[1.35rem] border border-white/10 text-left shadow-[0_18px_50px_rgba(0,0,0,0.4)] lg:block xl:w-[12%] ${
        align === 'left' ? 'left-0 origin-right' : 'right-0 origin-left'
      }`}
    >
      <motion.div
        className="absolute inset-0"
        animate={reduceMotion ? undefined : { scale: [1, 1.06] }}
        transition={{ duration: 10, repeat: Infinity, repeatType: 'reverse', ease: 'linear' }}
      >
        <SlidePhoto src={slideImage(slide)} alt="" />
      </motion.div>
      <div className="absolute inset-0 bg-navy-900/50" />
      <div className="absolute inset-0 bg-gradient-to-t from-navy-900 via-navy-900/25 to-transparent" />
      <span className="absolute left-3 top-3 flex h-8 w-8 items-center justify-center rounded-full border border-primary-500/70 text-primary-500">
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
          {icon}
        </svg>
      </span>
      <div className="absolute inset-x-3 bottom-4">
        <p className="line-clamp-3 text-[0.7rem] font-black leading-tight text-white xl:text-xs">{slide.title}</p>
        <span className="mt-3 inline-flex h-7 w-7 items-center justify-center rounded-full bg-white/10 text-white">
          <svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d={align === 'left' ? 'M15 19l-7-7 7-7' : 'M9 5l7 7-7 7'}
            />
          </svg>
        </span>
      </div>
    </motion.button>
  );
}

/**
 * Centered coverflow hero — navy canvas, yellow-bordered active card,
 * peeking neighbours, stats dock, and numbered progress rail.
 */
export const Hero: React.FC = () => {
  const reduceMotion = useReducedMotion();
  const [slides, setSlides] = useState<HeroSlide[]>(FALLBACK_SLIDES);
  const [loading, setLoading] = useState(true);
  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(1);
  const [userPaused, setUserPaused] = useState(false);
  const [hoverPaused, setHoverPaused] = useState(false);
  const [progressKey, setProgressKey] = useState(0);

  const paused = userPaused || hoverPaused;

  useEffect(() => {
    let cancelled = false;

    const loadSlides = async () => {
      try {
        setLoading(true);
        const response: unknown = await api.getHeroSlides({ status: 'active' });

        let data: HeroSlide[] = [];
        if (Array.isArray(response)) {
          data = response as HeroSlide[];
        } else if (
          response &&
          typeof response === 'object' &&
          'data' in response &&
          Array.isArray((response as { data: unknown }).data)
        ) {
          data = (response as { data: HeroSlide[] }).data;
        }

        if (!cancelled && data.length > 0) {
          setSlides(data);
          setIndex(0);
          setProgressKey((key) => key + 1);
        }
      } catch (error) {
        console.error('Error fetching hero slides:', error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    loadSlides();
    return () => {
      cancelled = true;
    };
  }, []);

  const slideCount = slides.length;
  const activeSlide = slides[index] ?? slides[0];
  const prevSlide = slides[(index - 1 + slideCount) % slideCount];
  const nextSlide = slides[(index + 1) % slideCount];
  const stats = Array.isArray(activeSlide?.stats) ? activeSlide.stats : [];

  const goTo = useCallback(
    (nextIndex: number) => {
      if (slideCount <= 1) return;
      const normalized = ((nextIndex % slideCount) + slideCount) % slideCount;
      let dir = normalized > index ? 1 : -1;
      if (index === slideCount - 1 && normalized === 0) dir = 1;
      if (index === 0 && normalized === slideCount - 1) dir = -1;
      setDirection(dir);
      setIndex(normalized);
      setProgressKey((key) => key + 1);
    },
    [index, slideCount]
  );

  const goNext = useCallback(() => goTo(index + 1), [goTo, index]);
  const goPrev = useCallback(() => goTo(index - 1), [goTo, index]);

  useEffect(() => {
    if (paused || reduceMotion || slideCount <= 1 || loading) return;
    const timer = window.setTimeout(goNext, AUTOPLAY_MS);
    return () => window.clearTimeout(timer);
  }, [goNext, index, loading, paused, progressKey, reduceMotion, slideCount]);

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'ArrowRight') goNext();
      if (event.key === 'ArrowLeft') goPrev();
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [goNext, goPrev]);

  return (
    <section
      id="home"
      className="hero-section relative flex flex-col overflow-hidden bg-navy-900"
      aria-roledescription="carousel"
      aria-label="Homepage hero"
    >
      <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(251,205,8,0.08),transparent_42%)]" />

      <div className="relative z-10 flex min-h-0 flex-1 flex-col justify-center px-2 pb-3 pt-[5rem] sm:px-4 lg:px-5">
        <div className="relative mx-auto w-full max-w-[96rem]">
          <div className="relative mx-auto h-[min(42rem,calc(100svh-10.25rem))] min-h-[24rem] w-full sm:min-h-[28rem]">
            {slideCount > 1 && prevSlide ? (
              <SideCard
                key={`side-prev-${prevSlide.id}`}
                slide={prevSlide}
                align="left"
                icon={STAT_ICONS[0]}
                reduceMotion={reduceMotion}
                onClick={() => goTo(index - 1)}
              />
            ) : null}

            {slideCount > 1 && nextSlide ? (
              <SideCard
                key={`side-next-${nextSlide.id}`}
                slide={nextSlide}
                align="right"
                icon={STAT_ICONS[2]}
                reduceMotion={reduceMotion}
                onClick={() => goTo(index + 1)}
              />
            ) : null}

            <motion.div
              className="hero-center-card relative z-10 mx-auto h-full w-full overflow-hidden rounded-[1.6rem] border-2 border-primary-500 sm:rounded-[2rem] lg:w-[82%] xl:w-[84%]"
              onMouseEnter={() => setHoverPaused(true)}
              onMouseLeave={() => setHoverPaused(false)}
              initial={false}
              animate={reduceMotion ? undefined : { boxShadow: '0 28px 80px rgba(0,0,0,0.5), 0 0 0 1px rgba(251,205,8,0.28)' }}
            >
              <AnimatePresence initial={false} custom={direction} mode="sync">
                <motion.div
                  key={activeSlide?.id ?? index}
                  className="absolute inset-0"
                  custom={direction}
                  initial={{
                    opacity: reduceMotion ? 1 : 0,
                    x: reduceMotion ? 0 : direction * 72,
                    scale: reduceMotion ? 1 : 1.06,
                  }}
                  animate={{ opacity: 1, x: 0, scale: 1 }}
                  exit={{
                    opacity: 0,
                    x: reduceMotion ? 0 : direction * -56,
                    scale: reduceMotion ? 1 : 1.03,
                  }}
                  transition={{ duration: reduceMotion ? 0.15 : 0.7, ease: [0.22, 1, 0.36, 1] }}
                >
                  <motion.div
                    className="absolute inset-0"
                    animate={reduceMotion ? undefined : { scale: [1, 1.08] }}
                    transition={{ duration: AUTOPLAY_MS / 1000, ease: 'linear' }}
                  >
                    <SlidePhoto
                      src={slideImage(activeSlide)}
                      alt={activeSlide?.title || 'SSEOA hero'}
                      priority={index === 0}
                    />
                  </motion.div>
                  <div className="absolute inset-0 bg-gradient-to-r from-navy-900/90 via-navy-900/48 to-navy-900/8" />
                  <div className="absolute inset-0 bg-gradient-to-t from-navy-900/65 via-transparent to-navy-900/15" />
                </motion.div>
              </AnimatePresence>

              <div className="relative z-10 flex h-full flex-col justify-between p-5 sm:p-8 lg:p-12">
                <AnimatePresence mode="wait" custom={direction}>
                  <motion.div
                    key={`copy-${activeSlide?.id ?? index}`}
                    custom={direction}
                    initial={{ opacity: 0, y: reduceMotion ? 0 : 22, x: reduceMotion ? 0 : direction * 18 }}
                    animate={{ opacity: 1, y: 0, x: 0 }}
                    exit={{ opacity: 0, y: reduceMotion ? 0 : -14, x: reduceMotion ? 0 : direction * -12 }}
                    transition={{ duration: reduceMotion ? 0.15 : 0.5, ease: [0.22, 1, 0.36, 1] }}
                    className="max-w-2xl"
                    aria-live="polite"
                  >
                    {activeSlide?.badge ? (
                      <span className="inline-flex rounded-full bg-primary-500 px-3.5 py-1 text-[0.7rem] font-bold uppercase tracking-[0.14em] text-navy-900">
                        {activeSlide.badge}
                      </span>
                    ) : null}

                    <div className="mt-4 sm:mt-5">
                      <HighlightTitle title={activeSlide?.title || ''} />
                    </div>

                    {activeSlide?.subtitle ? (
                      <p className="mt-4 max-w-md text-sm leading-relaxed text-white/85 sm:text-base">
                        {activeSlide.subtitle}
                      </p>
                    ) : null}

                    {(activeSlide?.primary_button_text || activeSlide?.secondary_button_text) && (
                      <div className="mt-6 flex flex-wrap items-center gap-3">
                        {activeSlide.primary_button_text && activeSlide.primary_button_link ? (
                          <HeroCtaLink href={activeSlide.primary_button_link}>
                            <span className="inline-flex items-center gap-2 rounded-full bg-primary-500 px-5 py-2.5 text-sm font-bold text-navy-900 shadow-lg transition-transform duration-300 hover:-translate-y-0.5 hover:bg-primary-400">
                              {activeSlide.primary_button_text}
                              <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.25} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                              </svg>
                            </span>
                          </HeroCtaLink>
                        ) : null}

                        {activeSlide.secondary_button_text && activeSlide.secondary_button_link ? (
                          <HeroCtaLink href={activeSlide.secondary_button_link}>
                            <span className="inline-flex items-center rounded-full border border-white/70 px-5 py-2.5 text-sm font-bold text-white transition-colors hover:bg-white hover:text-navy-900">
                              {activeSlide.secondary_button_text}
                            </span>
                          </HeroCtaLink>
                        ) : null}
                      </div>
                    )}
                  </motion.div>
                </AnimatePresence>

                <div className="mt-6 flex items-end justify-between gap-4">
                  {stats.length > 0 ? (
                    <div className="flex max-w-[min(100%,36rem)] flex-wrap items-center gap-x-5 gap-y-3 rounded-2xl bg-navy-900/70 px-4 py-3 backdrop-blur-md sm:gap-x-7 sm:px-5">
                      {stats.slice(0, 3).map((stat, statIndex) => (
                        <div key={`${stat.label}-${stat.value}`} className="flex min-w-0 items-center gap-2.5">
                          <span className="flex h-8 w-8 shrink-0 items-center justify-center text-primary-500">
                            <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                              {STAT_ICONS[statIndex % STAT_ICONS.length]}
                            </svg>
                          </span>
                          <div className="min-w-0">
                            <div className="text-sm font-black text-primary-500 sm:text-base">{stat.value}</div>
                            <div className="truncate text-[0.65rem] font-medium text-white/80 sm:text-xs">
                              {stat.label}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <span />
                  )}

                  {slideCount > 1 ? (
                    <div className="flex shrink-0 items-center gap-2">
                      <button
                        type="button"
                        onClick={goPrev}
                        aria-label="Previous slide"
                        className="flex h-10 w-10 items-center justify-center rounded-full border border-white/25 bg-navy-900/70 text-white backdrop-blur-md transition-colors hover:bg-white hover:text-navy-900"
                      >
                        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                        </svg>
                      </button>
                      <button
                        type="button"
                        onClick={goNext}
                        aria-label="Next slide"
                        className="flex h-10 w-10 items-center justify-center rounded-full bg-primary-500 text-navy-900 transition-colors hover:bg-primary-400"
                      >
                        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                        </svg>
                      </button>
                    </div>
                  ) : null}
                </div>
              </div>
            </motion.div>
          </div>
        </div>

        {slideCount > 1 ? (
          <div className="mx-auto mt-4 flex w-full max-w-6xl items-center justify-between gap-4 rounded-full bg-white/5 px-4 py-2.5 backdrop-blur-md sm:mt-5 sm:px-6">
            <div className="flex min-w-0 flex-1 items-center gap-4 overflow-x-auto sm:gap-8" role="tablist" aria-label="Hero slides">
              {slides.map((slide, slideIndex) => {
                const isActive = slideIndex === index;
                const number = String(slideIndex + 1).padStart(2, '0');
                return (
                  <button
                    key={slide.id}
                    type="button"
                    role="tab"
                    aria-selected={isActive}
                    onClick={() => goTo(slideIndex)}
                    className={`flex shrink-0 items-center gap-3 text-left transition-colors ${
                      isActive ? 'text-primary-500' : 'text-white/45 hover:text-white/80'
                    }`}
                  >
                    <span className="text-xs font-bold tabular-nums sm:text-sm">{number}</span>
                    {isActive ? <span className="hidden h-px w-8 bg-primary-500 sm:block" /> : null}
                    <span className={`max-w-[10rem] truncate text-xs font-semibold sm:max-w-none sm:text-sm ${isActive ? '' : 'hidden md:inline'}`}>
                      {slide.title}
                    </span>
                    {isActive && !reduceMotion ? (
                      <span className="relative ml-1 hidden h-0.5 w-10 overflow-hidden rounded-full bg-white/15 sm:block">
                        <span
                          key={progressKey}
                          className="absolute inset-y-0 left-0 origin-left rounded-full bg-primary-500"
                          style={{
                            animation: `hero-progress ${AUTOPLAY_MS}ms linear forwards`,
                            animationPlayState: paused ? 'paused' : 'running',
                          }}
                        />
                      </span>
                    ) : null}
                  </button>
                );
              })}
            </div>

            <div className="flex shrink-0 items-center gap-3">
              <div className="hidden items-center gap-1.5 sm:flex">
                {slides.map((slide, slideIndex) => (
                  <button
                    key={`dot-${slide.id}`}
                    type="button"
                    aria-label={`Go to slide ${slideIndex + 1}`}
                    onClick={() => goTo(slideIndex)}
                    className={`h-2 rounded-full transition-all ${
                      slideIndex === index ? 'w-5 bg-primary-500' : 'w-2 bg-white/30 hover:bg-white/60'
                    }`}
                  />
                ))}
              </div>
              <button
                type="button"
                onClick={() => setUserPaused((value) => !value)}
                aria-pressed={userPaused}
                aria-label={userPaused ? 'Play slideshow' : 'Pause slideshow'}
                className="flex h-9 w-9 items-center justify-center rounded-full border border-white/20 text-white/80 transition-colors hover:border-primary-500 hover:text-primary-500"
              >
                {userPaused ? (
                  <svg className="h-3.5 w-3.5" fill="currentColor" viewBox="0 0 24 24" aria-hidden>
                    <path d="M8 5v14l11-7z" />
                  </svg>
                ) : (
                  <svg className="h-3.5 w-3.5" fill="currentColor" viewBox="0 0 24 24" aria-hidden>
                    <path d="M6 5h4v14H6zm8 0h4v14h-4z" />
                  </svg>
                )}
              </button>
            </div>
          </div>
        ) : null}
      </div>
    </section>
  );
};
