import { useState, useEffect } from "react";
import { useLanguage } from "../contexts/LanguageContext";
import { useListPublishedRequests } from "@workspace/api-client-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { OpportunityCard } from "../components/OpportunityCard";
import { Reveal } from "../components/Reveal";
import { CountUp } from "../components/CountUp";
import { Link } from "wouter";
import { Pause, Play, Leaf, HandHeart, Users, Wallet } from "lucide-react";
import zakatBanner from "@assets/zakatbanarWEB_1780682994527.png";
import dawriBanner from "@assets/dawribanarWEB_1780682998494.png";
import waqfBanner from "@assets/waqfbanerWEB_1780683002610.png";
import giftBanner from "@assets/giftbanarWEB_1780683006569.png";
import ayahArt from "@assets/ahseno-ayah_(1)_1780685571353.svg";
import statsBg from "@assets/snapil-vertical-bg_1780692460644.svg";

const HERO_BANNERS = [zakatBanner, dawriBanner, waqfBanner, giftBanner];

function Ornament({ className = "" }: { className?: string }) {
  return (
    <svg
      width="56"
      height="20"
      viewBox="0 0 56 20"
      fill="none"
      aria-hidden="true"
      className={`text-primary/30 ${className}`}
    >
      <path
        d="M2 10c6-7 12-7 18 0 6 7 12 7 18 0 4-4.6 8-5.6 12-3"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        fill="none"
      />
      <circle cx="20" cy="10" r="2.2" fill="currentColor" />
      <circle cx="50" cy="6.5" r="1.6" fill="currentColor" />
    </svg>
  );
}

export default function Home() {
  const { t, language } = useLanguage();
  const { data: published, isLoading: pubLoading } = useListPublishedRequests();
  const [slide, setSlide] = useState(0);
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    if (reduce || paused) return;
    const id = setInterval(() => {
      setSlide((s) => (s + 1) % HERO_BANNERS.length);
    }, 5000);
    return () => clearInterval(id);
  }, [paused]);

  const featured = published || [];

  return (
    <>
      {/* Hero — auto-rotating banner carousel */}
      <section
        className="relative w-full overflow-hidden bg-muted"
        aria-roledescription="carousel"
        aria-label={t.home.heroBrowse}
      >
        <div className="relative h-[220px] sm:h-[320px] md:h-[420px] lg:h-[480px]">
          {HERO_BANNERS.map((src, i) => (
            <img
              key={i}
              src={src}
              alt=""
              aria-hidden="true"
              loading={i === 0 ? "eager" : "lazy"}
              className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-700 ease-in-out ${
                i === slide ? "opacity-100" : "opacity-0"
              }`}
            />
          ))}

          {/* bottom scrim keeps the CTA + dots readable over any banner */}
          <div className="pointer-events-none absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/45 to-transparent" />

          <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-4 p-4 md:p-8">
            <Link href="/opportunities" className="pointer-events-auto">
              <Button
                size="lg"
                className="bg-white text-primary hover:bg-white/90 font-bold px-7 shadow-lg"
                data-testid="button-heroBrowse"
              >
                {t.home.heroBrowse}
              </Button>
            </Link>

            <div className="pointer-events-auto flex items-center gap-3 rounded-full bg-black/25 px-3 py-2 backdrop-blur-sm">
              <button
                type="button"
                onClick={() => setPaused((p) => !p)}
                aria-label={paused ? t.common.play : t.common.pause}
                aria-pressed={paused}
                data-testid="button-hero-toggle"
                className="flex h-5 w-5 items-center justify-center text-white/90 transition-colors hover:text-white"
              >
                {paused ? <Play className="h-3.5 w-3.5" /> : <Pause className="h-3.5 w-3.5" />}
              </button>
              <div className="flex items-center gap-2">
                {HERO_BANNERS.map((_, i) => (
                  <button
                    key={i}
                    type="button"
                    onClick={() => setSlide(i)}
                    aria-label={`${t.home.heroBrowse} ${i + 1}`}
                    aria-current={i === slide}
                    data-testid={`dot-hero-${i}`}
                    className={`h-2.5 rounded-full transition-all duration-300 ${
                      i === slide ? "w-7 bg-white" : "w-2.5 bg-white/50 hover:bg-white/80"
                    }`}
                  />
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Ayah banner */}
      <section className="bg-white py-10">
        <div className="container mx-auto px-4 flex items-center justify-center gap-5 sm:gap-8">
          <Ornament className="hidden sm:block shrink-0" />
          <img
            src={ayahArt}
            alt="وأحسنوا إن الله يحب المحسنين"
            className="h-7 sm:h-9 md:h-10 w-auto brightness-0"
            data-testid="img-ayah"
          />
          <Ornament className="hidden sm:block shrink-0 -scale-x-100" />
        </div>
      </section>

      <div className="container mx-auto px-4 py-12">
        {/* Featured Opportunities */}
        <section className="mb-16">
          {pubLoading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[1, 2, 3].map((i) => <Skeleton key={i} className="h-96 w-full" />)}
            </div>
          ) : featured.length === 0 ? (
            <div className="col-span-full text-center py-12 text-muted-foreground bg-muted/20 rounded-xl border border-dashed">
              {t.opportunities.noOpportunities}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {featured.slice(0, 6).map((request, i) => (
                <Reveal key={request.id} delay={(i % 3) * 0.08} className="h-full">
                  <OpportunityCard request={request} />
                </Reveal>
              ))}
            </div>
          )}
        </section>

        {/* Impact Statistics */}
        <section className="relative overflow-hidden mb-12 py-8">
          <img
            src={statsBg}
            alt=""
            aria-hidden="true"
            className="pointer-events-none select-none absolute top-0 left-0 h-full w-auto opacity-70"
          />
          <div className="relative z-10">
            <div className="text-center mb-8">
              <div className="flex items-center justify-center gap-2 mb-2">
                <Leaf className="w-6 h-6 text-primary" aria-hidden="true" />
                <h2 className="text-2xl font-bold text-[#14573A]">{t.home.stats.title}</h2>
              </div>
              <p className="text-sm text-muted-foreground max-w-xl mx-auto">
                {t.home.stats.subtitle}
              </p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {[
                {
                  Icon: Wallet,
                  value: t.home.stats.totalValue,
                  label: t.home.stats.totalLabel,
                },
                {
                  Icon: Users,
                  value: t.home.stats.beneficiariesValue,
                  label: t.home.stats.beneficiariesLabel,
                },
                {
                  Icon: HandHeart,
                  value: t.home.stats.donationsValue,
                  label: t.home.stats.donationsLabel,
                },
              ].map(({ Icon, value, label }, i) => (
                <Reveal key={label} delay={i * 0.08} className="h-full">
                  <Card className="border-none shadow-md h-full rounded-2xl">
                    <CardContent className="p-8 text-center">
                      <Icon className="w-9 h-9 text-primary mx-auto mb-4" aria-hidden="true" />
                      <div className="text-3xl font-bold text-[#14573A] mb-3" data-testid={`stat-value-${i}`}>
                        <CountUp key={`${language}-${value}`} value={value} />
                      </div>
                      <div className="text-sm text-muted-foreground font-medium">{label}</div>
                    </CardContent>
                  </Card>
                </Reveal>
              ))}
            </div>
          </div>
        </section>
      </div>
    </>
  );
}
