"use client";

import Link from "next/link";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { FeaturedGuides } from "@/components/guides/featured-guides";
import { BlogCard } from "@/components/blogs/blog-card";
import { apiRequest, apiUrl, shouldBypassImageOptimization } from "@/lib/api";
import {
  fetchWebsiteLocations,
  getWebsiteLocationLabel,
  getWebsiteLocationValue,
  type WebsiteLocation,
} from "@/lib/website-locations";
import { fetchWebsiteBlogs, mapWebsiteBlogToBlog } from "@/lib/website-blogs";
import {
  fetchWebsiteSkills,
  getWebsiteSkillImage,
  getWebsiteSkillLabel,
  getWebsiteSkillValue,
  type WebsiteSkill,
} from "@/lib/website-skills";
import { useLanguage } from "@/lib/i18n";
import { type Blog } from "@/lib/types";
import {
  Mountain,
  Users,
  Award,
  Shield,
  MapPin,
  ArrowRight,
  ChevronLeft,
  ChevronRight,
  Search,
  Star,
  CheckCircle2,
  Compass,
  Map,
  Newspaper,
} from "lucide-react";

const statDefinitions = [
  { label: "home.verifiedGuides", icon: Users },
  { label: "home.districtsCovered", icon: MapPin },
  { label: "home.happyTourists", icon: Star },
  { label: "home.publishedBlogs", icon: Newspaper },
] as const;

type StatLabel = (typeof statDefinitions)[number]["label"];

type HomeStat = {
  label: StatLabel;
  value: string;
  icon: (typeof statDefinitions)[number]["icon"];
};

type WebsiteCountsResponse = {
  data?: Record<string, unknown>;
} & Record<string, unknown>;

const features = [
  {
    icon: Shield,
    title: "home.governmentVerified",
    description: "home.governmentVerifiedDesc",
  },
  {
    icon: Award,
    title: "home.certifiedSpecialists",
    description: "home.certifiedSpecialistsDesc",
  },
  {
    icon: CheckCircle2,
    title: "home.qualityGuaranteed",
    description: "home.qualityGuaranteedDesc",
  },
  {
    icon: Map,
    title: "home.marketingPromotion",
    description: "home.marketingPromotionDesc",
  },
  {
    icon: Star,
    title: "home.increasedVisibility",
    description: "home.increasedVisibilityDesc",
  },
  {
    icon: Shield,
    title: "home.legalCompliance",
    description: "home.legalComplianceDesc",
  },
] as const;

const heroSlides = [
  { src: "/banner.jpg", alt: "Uttarakhand mountain tourism banner" },
  { src: "/banner-0.jpg", alt: "Uttarakhand mountain tourism banner" },
  { src: "/banner-1.jpg", alt: "Uttarakhand mountain tourism banner" },
  { src: "/banner-2.jpg", alt: "Uttarakhand adventure tourism banner" },
];

function parseStatValue(value: string) {
  const trimmedValue = value.trim();
  const match = trimmedValue.match(/^([\d,]+)(.*)$/);

  return {
    target: match ? Number(match[1].replace(/,/g, "")) : 0,
    suffix: match?.[2] || "",
    isNumeric: Boolean(match),
  };
}

function getCountValue(data: Record<string, unknown>, keys: string[]) {
  const countValues = flattenCountValues(data);
  const normalizedKeys = keys.map(normalizeCountKey);

  for (const key of normalizedKeys) {
    const value = countValues[key];

    if (value !== undefined) {
      return value;
    }
  }

  for (const key of keys) {
    const value = data[key];

    if (typeof value === "number" && Number.isFinite(value)) {
      return value;
    }

    if (typeof value === "string" && value.trim()) {
      const parsed = Number(value);

      if (Number.isFinite(parsed)) {
        return parsed;
      }

      return value;
    }
  }

  return undefined;
}

function normalizeCountKey(value: string) {
  return value.replace(/[^a-z0-9]/gi, "").toLowerCase();
}

function flattenCountValues(
  value: unknown,
  prefix = "",
  output: Record<string, number | string> = {},
) {
  if (typeof value === "number" && Number.isFinite(value)) {
    output[normalizeCountKey(prefix)] = value;
    return output;
  }

  if (typeof value === "string" && value.trim()) {
    const parsed = Number(value);
    output[normalizeCountKey(prefix)] = Number.isFinite(parsed)
      ? parsed
      : value;
    return output;
  }

  if (Array.isArray(value)) {
    output[normalizeCountKey(prefix)] = value.length;
    return output;
  }

  if (!value || typeof value !== "object") {
    return output;
  }

  Object.entries(value).forEach(([key, nestedValue]) => {
    flattenCountValues(
      nestedValue,
      prefix ? `${prefix}_${key}` : key,
      output,
    );
  });

  return output;
}

function formatCountValue(value: unknown, fallback: string) {
  if (value === undefined || value === null || value === "") {
    return fallback;
  }

  if (typeof value === "string") {
    return value;
  }

  return String(value);
}

function normalizeWebsiteCounts(result: WebsiteCountsResponse): HomeStat[] {
  const responseData =
    result.data && typeof result.data === "object" ? result.data : result;
  const nestedCounts =
    "counts" in responseData && typeof responseData.counts === "object"
      ? responseData.counts
      : responseData;
  const data = nestedCounts as Record<string, unknown>;

  return statDefinitions.map((stat) => {
    const value =
      stat.label === "home.verifiedGuides"
        ? getCountValue(data, [
            "verified_guides",
            "verifiedGuides",
            "verified_guides_count",
            "verifiedGuidesCount",
            "approved_guides",
            "approvedGuides",
            "approved_guides_count",
            "approvedGuidesCount",
            "total_guides",
            "totalGuides",
            "total_guides_count",
            "totalGuidesCount",
            "guide_count",
            "guideCount",
            "guides_count",
            "guidesCount",
            "guides",
            "guide",
            "users",
            "user_count",
            "userCount",
            "users_count",
            "usersCount",
          ])
        : stat.label === "home.districtsCovered"
          ? getCountValue(data, [
              "districts_covered",
              "districtsCovered",
              "total_locations",
              "totalLocations",
              "total_locations_count",
              "totalLocationsCount",
              "location_count",
              "locationCount",
              "locations_count",
              "locationsCount",
              "locations",
              "location",
              "total_districts",
              "totalDistricts",
              "total_districts_count",
              "totalDistrictsCount",
              "district_count",
              "districtCount",
              "districts_count",
              "districtsCount",
              "districts",
              "district",
            ])
          : stat.label === "home.happyTourists"
            ? getCountValue(data, [
                "happy_tourists",
                "happyTourists",
                "happy_tourists_count",
                "happyTouristsCount",
                "total_tourists",
                "totalTourists",
                "total_tourists_count",
                "totalTouristsCount",
                "tourist_count",
                "touristCount",
                "tourists_count",
                "touristsCount",
                "tourists",
                "tourist",
                "total_reviews",
                "totalReviews",
                "total_reviews_count",
                "totalReviewsCount",
                "review_count",
                "reviewCount",
                "reviews_count",
                "reviewsCount",
                "guide_reviews",
                "guideReviews",
                "guide_reviews_count",
                "guideReviewsCount",
                "reviews",
                "review",
              ])
            : getCountValue(data, [
                "published_blogs",
                "publishedBlogs",
                "published_blogs_count",
                "publishedBlogsCount",
                "approved_blogs",
                "approvedBlogs",
                "approved_blogs_count",
                "approvedBlogsCount",
                "blog_count",
                "blogCount",
                "blogs_count",
                "blogsCount",
                "blogs",
                "blog",
              ]);

    return {
      ...stat,
      value: formatCountValue(value, "0"),
    };
  });
}

async function fetchWebsiteCounts() {
  const response = await apiRequest(apiUrl("/website/counts"), {
    headers: {
      Accept: "application/json",
    },
  });

  if (!response.ok) {
    throw new Error("Counts request failed.");
  }

  return normalizeWebsiteCounts(
    (await response.json()) as WebsiteCountsResponse,
  );
}

function AnimatedStatValue({ value }: { value: string }) {
  const ref = useRef<HTMLDivElement | null>(null);
  const [hasStarted, setHasStarted] = useState(false);
  const [displayValue, setDisplayValue] = useState(0);
  const { target, suffix, isNumeric } = parseStatValue(value);

  useEffect(() => {
    setDisplayValue(0);
    setHasStarted(false);
  }, [value]);

  useEffect(() => {
    const element = ref.current;
    if (!element || hasStarted) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setHasStarted(true);
          observer.disconnect();
        }
      },
      { threshold: 0.35 },
    );

    observer.observe(element);

    return () => observer.disconnect();
  }, [hasStarted]);

  useEffect(() => {
    if (!hasStarted || !isNumeric) return;

    let animationFrame = 0;
    const duration = 1200;
    const startedAt = performance.now();

    const tick = (now: number) => {
      const progress = Math.min((now - startedAt) / duration, 1);
      const easedProgress = 1 - Math.pow(1 - progress, 3);

      setDisplayValue(Math.round(target * easedProgress));

      if (progress < 1) {
        animationFrame = requestAnimationFrame(tick);
      }
    };

    animationFrame = requestAnimationFrame(tick);

    return () => cancelAnimationFrame(animationFrame);
  }, [hasStarted, isNumeric, target]);

  return (
    <div
      ref={ref}
      className="mb-0.5 text-2xl font-bold text-foreground lg:text-3xl"
    >
      {isNumeric ? (
        <>
          {displayValue.toLocaleString("en-IN")}
          {suffix}
        </>
      ) : (
        value
      )}
    </div>
  );
}

type TypingHeroLine = {
  text: string;
  className?: string;
};

function TypingHeroTitle({
  lines,
  className,
}: {
  lines: TypingHeroLine[];
  className: string;
}) {
  const [visibleCharacters, setVisibleCharacters] = useState(0);
  const [isDeleting, setIsDeleting] = useState(false);
  const totalCharacters = lines.reduce(
    (total, line) => total + line.text.length,
    0,
  );
  const lineSignature = lines.map((line) => line.text).join("|");

  useEffect(() => {
    setVisibleCharacters(0);
    setIsDeleting(false);
  }, [lineSignature]);

  useEffect(() => {
    const isComplete = visibleCharacters === totalCharacters;
    const isEmpty = visibleCharacters === 0;
    const delay = isComplete
      ? 1400
      : isEmpty && isDeleting
        ? 350
        : isDeleting
          ? 36
          : 68;

    const timer = window.setTimeout(() => {
      if (isComplete && !isDeleting) {
        setIsDeleting(true);
        return;
      }

      if (isEmpty && isDeleting) {
        setIsDeleting(false);
        return;
      }

      setVisibleCharacters((current) => current + (isDeleting ? -1 : 1));
    }, delay);

    return () => window.clearTimeout(timer);
  }, [isDeleting, totalCharacters, visibleCharacters]);

  let consumedCharacters = 0;
  const cursorLineIndex = lines.findIndex((line) => {
    const lineEnd = consumedCharacters + line.text.length;
    const isCursorHere =
      visibleCharacters <= lineEnd || line === lines[lines.length - 1];
    consumedCharacters = lineEnd;
    return isCursorHere;
  });
  let renderedCharacters = visibleCharacters;

  return (
    <h1
      className={className}
      aria-label={lines.map((line) => line.text).join(" ")}
    >
      {lines.map((line, index) => {
        const visibleText = line.text.slice(0, Math.max(0, renderedCharacters));
        renderedCharacters -= line.text.length;

        return (
          <span
            key={`${line.text}-${index}`}
            className={`block min-h-[1.05em] ${line.className || ""}`}
          >
            {visibleText}
            {cursorLineIndex === index && (
              <span className="ml-1 inline-block animate-pulse text-[var(--theme-primary)]">
                _
              </span>
            )}
          </span>
        );
      })}
    </h1>
  );
}

export default function HomePage() {
  const { language, t } = useLanguage();
  const [activeSlide, setActiveSlide] = useState(0);
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [skills, setSkills] = useState<WebsiteSkill[]>([]);
  const [locations, setLocations] = useState<WebsiteLocation[]>([]);
  const [stats, setStats] = useState<HomeStat[]>(
    statDefinitions.map((stat) => ({ ...stat, value: "0" })),
  );
  const [activeLocationIndex, setActiveLocationIndex] = useState(0);

  useEffect(() => {
    const timer = window.setInterval(() => {
      setActiveSlide((current) => (current + 1) % heroSlides.length);
    }, 5500);

    return () => window.clearInterval(timer);
  }, []);

  useEffect(() => {
    let isMounted = true;

    async function loadWebsiteCounts() {
      try {
        const websiteStats = await fetchWebsiteCounts();

        if (isMounted) {
          setStats(websiteStats);
        }
      } catch {
        if (isMounted) {
          setStats(statDefinitions.map((stat) => ({ ...stat, value: "0" })));
        }
      }
    }

    loadWebsiteCounts();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    async function loadLatestBlogs() {
      try {
        const latestBlogs = await fetchWebsiteBlogs({ sort_by: "latest" });

        if (isMounted) {
          setBlogs(latestBlogs.map(mapWebsiteBlogToBlog).slice(0, 8));
        }
      } catch {
        if (isMounted) {
          setBlogs([]);
        }
      }
    }

    loadLatestBlogs();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    async function loadLocations() {
      try {
        const websiteLocations = await fetchWebsiteLocations();

        if (isMounted) {
          setLocations(websiteLocations.slice(0, 5));
          setActiveLocationIndex(0);
        }
      } catch {
        if (isMounted) {
          setLocations([]);
        }
      }
    }

    loadLocations();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    if (locations.length <= 1) {
      return;
    }

    const timer = window.setInterval(() => {
      setActiveLocationIndex((current) => (current + 1) % locations.length);
    }, 3000);

    return () => window.clearInterval(timer);
  }, [locations.length]);

  useEffect(() => {
    let isMounted = true;

    async function loadSkills() {
      try {
        const websiteSkills = await fetchWebsiteSkills();

        if (isMounted) {
          setSkills(websiteSkills.slice(0, 6));
        }
      } catch {
        if (isMounted) {
          setSkills([]);
        }
      }
    }

    loadSkills();

    return () => {
      isMounted = false;
    };
  }, []);

  const goToPreviousSlide = () => {
    setActiveSlide(
      (current) => (current - 1 + heroSlides.length) % heroSlides.length,
    );
  };

  const goToNextSlide = () => {
    setActiveSlide((current) => (current + 1) % heroSlides.length);
  };
  const carouselLocations = locations.length
    ? [...locations, ...locations, ...locations]
    : [];
  const carouselBaseIndex = locations.length;

  return (
    <div className="flex flex-col">
      {/* Hero Section - Full Width Image Banner */}
      <section className="relative flex min-h-screen items-center overflow-hidden pt-20">
        <div className="absolute inset-0">
          {heroSlides.map((slide, index) => (
            <Image
              key={slide.src}
              src={slide.src}
              alt={slide.alt}
              fill
              priority={index === 0}
              loading={index === 0 ? "eager" : "lazy"}
              sizes="100vw"
              data-parallax="0.04"
              className={`object-cover transition-opacity duration-1000 ease-out ${
                activeSlide === index ? "opacity-100" : "opacity-0"
              }`}
            />
          ))}
          <div className="absolute inset-0 bg-[linear-gradient(90deg,rgba(255,255,255,0.96)_0%,rgba(255,255,255,0.82)_26%,rgba(255,255,255,0.34)_48%,rgba(255,255,255,0.04)_68%,transparent_100%)]" />
          <div className="absolute bottom-0 left-0 top-0 w-[58%] bg-[radial-gradient(ellipse_at_22%_50%,rgba(255,255,255,0.96)_0%,rgba(255,255,255,0.72)_40%,rgba(255,255,255,0)_72%)]" />
          <div className="absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-background/35 via-background/10 to-transparent" />
        </div>

        <button
          type="button"
          aria-label={t("home.previousSlide")}
          onClick={goToPreviousSlide}
          className="absolute left-4 top-1/2 z-20 hidden h-14 w-14 -translate-y-1/2 items-center justify-center rounded-full border border-[#b4c5c7]/70 bg-[#b4c5c7]/15 text-[#cdd8d9] shadow-xl backdrop-blur-md transition-all hover:bg-[#9fb4b7]/25 md:flex"
        >
          <ChevronLeft className="h-7 w-7" />
        </button>
        <button
          type="button"
          aria-label={t("home.nextSlide")}
          onClick={goToNextSlide}
          className="absolute right-4 top-1/2 z-20 hidden h-14 w-14 -translate-y-1/2 items-center justify-center rounded-full border border-[#b4c5c7]/70 bg-[#b4c5c7]/15 text-[#cdd8d9] shadow-xl backdrop-blur-md transition-all hover:bg-[#9fb4b7]/25 md:flex"
        >
          <ChevronRight className="h-7 w-7" />
        </button>

        <div className="relative z-10 mx-auto w-full max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="max-w-3xl">
            <div className="mb-6 inline-flex items-center gap-2 rounded-full border border-[var(--theme-secondary)]/25 bg-[var(--theme-surface-strong)]/80 px-4 py-2 text-sm font-medium text-[var(--theme-emphasis-text)] shadow-sm backdrop-blur-md">
              <Map className="h-4 w-4 text-[var(--theme-secondary)]" />
              {t("home.officialPlatform")}
            </div>

            <TypingHeroTitle
              className={`mb-7 font-black tracking-tight text-foreground ${
                language === "hi"
                  ? "space-y-1 text-[3.15rem] leading-[1.18] sm:text-[4.1rem] lg:text-[4.85rem] xl:text-[5.4rem]"
                  : "text-4xl leading-[1.05] sm:text-5xl lg:text-6xl xl:text-7xl"
              }`}
              lines={[
                {
                  text: t("home.heroDiscover"),
                },
                {
                  text: t("home.heroDevBhoomi"),
                  className: "block text-[var(--theme-primary)]",
                },
                {
                  text: t("home.heroWithGuides"),
                  className: `block font-semibold text-muted-foreground ${
                    language === "hi"
                      ? "text-[2.55rem] leading-[1.2] sm:text-[3.25rem] lg:text-[3.85rem] xl:text-[4.25rem]"
                      : "text-4xl sm:text-5xl lg:text-6xl"
                  }`,
                },
              ]}
            />

            <p className="mb-10 max-w-2xl text-lg leading-8 text-foreground/75 sm:text-xl">
              {t("home.heroDescription")}
            </p>

            <div className="flex flex-wrap gap-4">
              <Link href="/guides">
                <Button
                  size="lg"
                  className="h-14 rounded-full bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] px-8 text-base text-white shadow-xl shadow-[var(--theme-secondary)]/25"
                >
                  <Search className="mr-2 h-5 w-5" />
                  {t("home.findGuide")}
                </Button>
              </Link>
              <Link href="/auth/register">
                <Button
                  size="lg"
                  variant="outline"
                  className="h-14 rounded-full border border-border/70 bg-white/80 px-8 text-base text-foreground shadow-md backdrop-blur-md hover:bg-white hover:text-[var(--theme-accent)]"
                >
                  {t("common.becomeGuide")}
                  <ArrowRight className="ml-2 h-5 w-5" />
                </Button>
              </Link>
            </div>

            <div className="mt-10 flex flex-wrap items-center gap-x-8 gap-y-3 text-sm text-foreground/70">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="h-5 w-5 text-green-600" />
                <span>{t("home.govtVerified")}</span>
              </div>
              <div className="flex items-center gap-2">
                <Shield className="h-5 w-5 text-[var(--theme-secondary)]" />
                <span>{t("home.secureBooking")}</span>
              </div>
              <div className="flex items-center gap-2">
                <Star className="h-5 w-5 text-[var(--theme-accent)]" />
                <span>{t("home.rating")}</span>
              </div>
            </div>
          </div>
        </div>

        <div className="absolute bottom-9 left-1/2 z-20 flex -translate-x-1/2 items-center gap-3">
          {heroSlides.map((slide, index) => (
            <button
              key={slide.src}
              type="button"
              aria-label={`${t("home.goToSlide")} ${index + 1}`}
              onClick={() => setActiveSlide(index)}
              className={`h-2.5 rounded-full transition-all ${
                activeSlide === index
                  ? "w-12 bg-[var(--theme-secondary)]"
                  : "w-2.5 bg-foreground/25 hover:bg-foreground/40"
              }`}
            />
          ))}
        </div>

        <button
          type="button"
          onClick={() =>
            window.scrollBy({
              top: Math.round(window.innerHeight * 0.82),
              behavior: "smooth",
            })
          }
          className="absolute bottom-8 right-8 z-20 hidden items-center gap-3 rounded-full px-3 py-2 text-sm font-medium text-foreground/65 transition-colors hover:text-[var(--theme-primary)] md:flex"
        >
          <span>{t("home.scrollExplore")}</span>
          <span className="relative h-10 w-6 rounded-full border border-foreground/30">
            <span className="absolute left-1/2 top-2 h-2 w-1 -translate-x-1/2 rounded-full bg-[var(--theme-secondary)]" />
          </span>
        </button>
      </section>

      {/* Stats Section */}
      <section className="relative overflow-hidden bg-[var(--theme-surface-soft)] py-8 lg:py-10">
        <div className="relative mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
          <div className="mx-auto mb-7 max-w-2xl text-center">
            <h2 className="text-3xl font-black tracking-tight text-[var(--theme-primary)] lg:text-4xl">
              {t("home.statsTitle")}
            </h2>
            <p className="mt-2 text-sm leading-6 text-muted-foreground lg:text-base">
              {t("home.statsDescription")}
            </p>
          </div>
          <div className="grid grid-cols-2 gap-4 lg:grid-cols-4 lg:gap-5">
            {stats.map((stat) => (
              <Card
                key={stat.label}
                className="group relative overflow-hidden border-[var(--theme-border-soft)] bg-[var(--theme-surface)] py-0 shadow-sm hover:border-[var(--theme-secondary)]/30 hover:shadow-lg hover:shadow-[var(--theme-secondary)]/10"
              >
                <CardContent className="p-4 text-center lg:p-5">
                  <div className="mb-3 inline-flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-[var(--theme-secondary)]/10 to-[var(--theme-accent)]/10 transition-transform group-hover:scale-110">
                    <stat.icon className="h-5 w-5 text-[var(--theme-primary)]" />
                  </div>
                  <AnimatedStatValue value={stat.value} />
                  <div className="text-xs text-muted-foreground lg:text-sm">
                    {t(stat.label)}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Featured Guides */}
      <section className="relative overflow-hidden py-10 lg:py-12">
        <SectionBackdrop src="/background-2.jpg" />
        <div className="container mx-auto px-4 relative z-10">
          <div className="mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
            <div>
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-primary)] text-sm font-medium mb-4">
                <Users className="h-4 w-4" />
                {t("home.topRated")}
              </div>
              <h2 className="text-3xl lg:text-4xl font-black tracking-tight text-foreground mb-3">
                {t("home.featuredGuides")}
              </h2>
              <p className="text-muted-foreground text-lg">
                {t("home.featuredGuidesDescription")}
              </p>
            </div>
            <Link href="/guides">
              <Button
                variant="outline"
                className="rounded-full px-6 h-11 gap-2"
              >
                {t("home.viewAllGuides")}
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
          </div>
          <FeaturedGuides />
        </div>
      </section>

      {/* Explore by Destination - Map Cards */}
      <section className="relative overflow-hidden bg-[var(--theme-surface-soft)] py-12 lg:py-14">
        <div className="absolute inset-0 flex items-center justify-center opacity-75">
          <Image
            src="/map-background.png"
            alt=""
            fill
            sizes="100vw"
            className="scale-110 object-contain object-center"
          />
        </div>
        <div className="absolute inset-0 bg-[linear-gradient(180deg,var(--theme-surface)_0%,color-mix(in_srgb,var(--theme-surface-strong)_78%,white)_52%,var(--theme-surface-soft)_100%)]/85" />
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_42%,color-mix(in_srgb,var(--theme-secondary)_12%,transparent),transparent_34%)]" />
        <div className="container relative z-10 mx-auto px-4">
          <div className="mb-9 text-center">
            <p className="mb-2 text-sm font-semibold uppercase tracking-wide text-[var(--theme-secondary)]">
              {t("home.findBestDestination")}
            </p>
            <h2 className="mb-3 text-3xl font-black tracking-tight text-foreground lg:text-4xl">
              {t("home.exploreLocation")}
            </h2>
            <p className="mx-auto max-w-2xl text-base text-muted-foreground">
              {t("home.locationDescription")}
            </p>
          </div>
          {locations.length > 0 && (
            <div className="mx-auto max-w-6xl overflow-hidden px-1 py-3">
              <div
                className="flex [--location-center-offset:0%] [--location-slide-width:100%] sm:[--location-center-offset:25%] sm:[--location-slide-width:50%] lg:[--location-center-offset:40%] lg:[--location-slide-width:20%]"
                style={{
                  transform: `translateX(calc(var(--location-center-offset) - ${
                    carouselBaseIndex + activeLocationIndex
                  } * var(--location-slide-width)))`,
                  transition: "transform 700ms cubic-bezier(0.22, 1, 0.36, 1)",
                }}
              >
                {carouselLocations.map((location, index) => {
                  const locationLabel = getWebsiteLocationLabel(
                    location,
                    language,
                  );
                  const locationQueryLabel = getWebsiteLocationLabel(location);
                  const locationValue = getWebsiteLocationValue(location);
                  const normalizedIndex =
                    locations.length > 0 ? index % locations.length : 0;
                  const isActive = normalizedIndex === activeLocationIndex;

                  return (
                    <div
                      key={`${locationValue}-${index}`}
                      className="shrink-0 basis-full px-2 sm:basis-1/2 lg:basis-1/5"
                    >
                      <Link
                        href={`/guides?district=${encodeURIComponent(
                          locationQueryLabel,
                        )}`}
                        className="group block"
                      >
                        <Card
                          className={`relative aspect-square overflow-hidden border-0 py-0 shadow-sm transition-all duration-300 group-hover:-translate-y-2 group-hover:shadow-xl ${
                            isActive
                              ? "scale-[1.03] bg-gradient-to-br from-[var(--theme-secondary)] to-[var(--theme-accent)] text-white shadow-lg shadow-[var(--theme-secondary)]/25"
                              : "bg-white/95 text-foreground shadow-black/5"
                          }`}
                        >
                          <CardContent className="flex h-full flex-col items-center justify-center p-5 text-center">
                            <div
                              className={`mb-4 flex h-14 w-14 items-center justify-center rounded-xl transition-transform duration-300 group-hover:scale-110 ${
                                isActive
                                  ? "bg-white/15"
                                  : "bg-gradient-to-br from-[var(--theme-secondary)]/10 to-[var(--theme-accent)]/10"
                              }`}
                            >
                              <MapPin
                                className={`h-7 w-7 ${
                                  isActive
                                    ? "text-white"
                                    : "text-[var(--theme-secondary)]"
                                }`}
                              />
                            </div>
                            <p className="text-base font-bold">
                              {locationLabel}
                            </p>
                          </CardContent>
                        </Card>
                      </Link>
                    </div>
                  );
                })}
              </div>

              {locations.length > 1 && (
                <div className="mt-5 flex justify-center gap-2">
                  {locations.map((location, index) => (
                    <button
                      key={getWebsiteLocationValue(location)}
                      type="button"
                      aria-label={`Show ${getWebsiteLocationLabel(
                        location,
                        language,
                      )}`}
                      className={`h-2 rounded-full transition-all ${
                        index === activeLocationIndex
                          ? "w-8 bg-[var(--theme-primary)]"
                          : "w-2 bg-[var(--theme-border)] hover:bg-[var(--theme-secondary)]/50"
                      }`}
                      onClick={() => setActiveLocationIndex(index)}
                    />
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </section>

      {/* Expertise Areas - Image Cards */}
      <section className="relative overflow-hidden py-10 lg:py-12">
        <SectionBackdrop src="/background-3.jpg" />
        <div className="container mx-auto px-4 relative z-10">
          <div className="mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
            <div className="text-center md:text-left">
              <div className="mb-4 inline-flex items-center gap-2 rounded-full bg-[var(--theme-surface-strong)] px-3 py-1 text-sm font-medium text-[var(--theme-primary)]">
                <Compass className="h-4 w-4" />
                {t("home.experiences")}
              </div>
              <h2 className="mb-3 text-3xl font-black tracking-tight text-foreground lg:text-4xl">
                {t("home.exploreExperience")}
              </h2>
              <p className="mx-auto max-w-2xl text-lg text-muted-foreground md:mx-0">
                {t("home.experienceDescription")}
              </p>
            </div>
            <Link href="/experiences">
              <Button
                variant="outline"
                className="h-11 rounded-full px-6 font-bold"
              >
                {t("common.viewAll")}
                <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </Link>
          </div>
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {skills.map((skill) => {
              const skillLabel = getWebsiteSkillLabel(skill, language);
              const skillQueryLabel = getWebsiteSkillLabel(skill);
              const skillValue = getWebsiteSkillValue(skill);
              const skillImage = getWebsiteSkillImage(
                skill,
                "/placeholder.png",
              );

              return (
                <Link
                  key={skillValue}
                  href={`/guides?expertise=${encodeURIComponent(skillQueryLabel)}`}
                >
                  <Card className="group overflow-hidden cursor-pointer border-0 py-0 gap-0 shadow-lg hover:shadow-2xl transition-all duration-500 hover:-translate-y-2">
                    <CardContent className="p-0 relative aspect-[4/3] image-zoom">
                      <Image
                        src={skillImage}
                        alt={skillLabel}
                        fill
                        sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
                        className="object-cover transition-transform duration-700 group-hover:scale-110"
                        unoptimized={shouldBypassImageOptimization(skillImage)}
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />
                      <div className="absolute bottom-0 left-0 right-0 p-6">
                        <h3 className="text-xl font-bold text-white mb-1">
                          {skillLabel}
                        </h3>
                        <p className="text-sm text-white/70 flex items-center gap-2">
                          <span>{t("home.exploreAction")}</span>
                          <ArrowRight className="h-4 w-4 group-hover:translate-x-1 transition-transform" />
                        </p>
                      </div>
                    </CardContent>
                  </Card>
                </Link>
              );
            })}
          </div>
        </div>
      </section>

      {/* Why Choose Us - Feature Grid */}
      <section
        id="about-us"
        className="relative overflow-hidden bg-white py-10 lg:py-12"
      >
        <div className="container relative z-10 mx-auto px-4">
          <div className="mx-auto max-w-6xl">
            <div className="mb-6 text-center">
              <div className="mb-3 inline-flex items-center gap-2 rounded-full bg-[var(--theme-highlight)] px-3 py-1 text-sm font-medium text-[var(--theme-primary)] shadow-sm">
                <Award className="h-4 w-4" />
                {t("home.whyUs")}
              </div>
              <h2 className="text-3xl font-black tracking-tight text-foreground lg:text-4xl">
                {t("home.whyChoose")}
              </h2>
              <p className="mx-auto mt-3 max-w-2xl text-base leading-7 text-muted-foreground">
                {t("home.whyDescription")}
              </p>
            </div>

            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 lg:gap-7">
              {features.map((feature) => (
                <div
                  key={feature.title}
                  className="group flex gap-4 rounded-md border border-[var(--theme-border-soft)] bg-[var(--theme-surface-soft)] p-5 shadow-sm transition-all duration-300 hover:-translate-y-1 hover:border-[var(--theme-secondary)]/35 hover:shadow-lg"
                >
                  <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-[var(--theme-secondary)] to-[var(--theme-accent)] shadow-md shadow-[var(--theme-secondary)]/20">
                    <feature.icon className="h-5 w-5 text-white" />
                  </div>
                  <div>
                    <h3 className="mb-1 text-base font-bold text-foreground">
                      {t(feature.title)}
                    </h3>
                    <p className="text-sm leading-6 text-muted-foreground">
                      {t(feature.description)}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Latest Blog Posts */}
      {blogs.length > 0 && (
        <section className="relative overflow-hidden py-10 lg:py-12">
          <SectionBackdrop src="/background-1.jpg" />
          <div className="container mx-auto px-4 relative z-10">
            <div className="mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
              <div>
                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[var(--theme-surface-strong)] text-[var(--theme-primary)] text-sm font-medium mb-4">
                  <Map className="h-4 w-4" />
                  {t("common.blog")}
                </div>
                <h2 className="text-3xl lg:text-4xl font-black tracking-tight text-foreground mb-3">
                  {t("home.travelInsights")}
                </h2>
                <p className="text-muted-foreground text-lg">
                  {t("home.travelInsightsDesc")}
                </p>
              </div>
              <Link href="/blogs">
                <Button
                  variant="outline"
                  className="rounded-full px-6 h-11 gap-2"
                >
                  {t("home.viewAllPosts")}
                  <ArrowRight className="h-4 w-4" />
                </Button>
              </Link>
            </div>
            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
              {blogs.map((blog) => (
                <BlogCard key={blog.id} blog={blog} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* CTA Section - Modern Gradient */}
      <section className="relative pb-28 pt-14 lg:pb-32 lg:pt-16">
        <div className="container mx-auto px-4">
          <div className="relative mx-auto max-w-6xl overflow-hidden rounded-[2rem] bg-gradient-to-br from-[var(--theme-secondary)] to-[var(--theme-accent)] hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)] px-6 py-16 text-center shadow-[0_28px_80px_rgba(15,35,58,0.18)] md:rounded-[2.5rem] md:px-10 lg:py-20">
            <div className="absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdHRlcm4gaWQ9ImdyaWQiIHdpZHRoPSI2MCIgaGVpZ2h0PSI2MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHBhdGggZD0iTSAxMCAwIEwgMCAwIDAgMTAiIGZpbGw9Im5vbmUiIHN0cm9rZT0icmdiYSgyNTUsMjU1LDI1NSwwLjEyKSIgc3Ryb2tlLXdpZHRoPSIxIi8+PC9wYXR0ZXJuPjwvZGVmcz48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJ1cmwoI2dyaWQpIi8+PC9zdmc+')] opacity-20" />
            <div className="absolute -left-24 top-10 h-64 w-64 rounded-full bg-white/10 blur-3xl" />
            <div className="absolute -bottom-28 right-10 h-72 w-72 rounded-full bg-[var(--theme-secondary)]/10 blur-3xl" />
            <div className="relative mx-auto max-w-3xl">
              <div className="mb-8 inline-flex h-16 w-16 items-center justify-center rounded-2xl bg-white/10 backdrop-blur-sm">
                <Mountain className="h-8 w-8 text-white" />
              </div>
              <h2 className="mb-6 text-balance text-3xl font-black tracking-tight text-white md:text-4xl lg:text-5xl">
                {t("home.readyExplore")}
              </h2>
              <p className="mx-auto mb-10 max-w-2xl text-lg leading-relaxed text-white/80">
                {t("home.readyExploreDesc")}
              </p>
              <div className="flex flex-wrap justify-center gap-4">
                <Link href="/guides">
                  <Button
                    size="lg"
                    className="h-14 rounded-full bg-white px-8 text-base text-[#0d2d42] shadow-xl hover:bg-white/90"
                  >
                    <Search className="mr-2 h-5 w-5" />
                    {t("home.findYourGuide")}
                  </Button>
                </Link>
                <Link href="/auth/register">
                  <Button
                    size="lg"
                    variant="outline"
                    className="h-14 rounded-full border-2 border-white/30 bg-transparent px-8 text-base text-white hover:bg-white/10 hover:text-white"
                  >
                    {t("home.joinGuide")}
                    <ArrowRight className="ml-2 h-5 w-5" />
                  </Button>
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function SectionBackdrop({
  src: _src,
  className = "",
}: {
  src: string;
  className?: string;
}) {
  return (
    <div
      aria-hidden="true"
      className={`pointer-events-none absolute inset-0 z-0 ${className}`}
    >
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_20%_20%,color-mix(in srgb, var(--theme-secondary) 14%, transparent),transparent_32%),radial-gradient(circle_at_80%_30%,rgba(14,116,144,0.12),transparent_30%)]" />
      <div className="absolute inset-0 bg-background/72" />
    </div>
  );
}
