"use client";

import React, { useState, useRef, useEffect, useMemo } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  PROPERTIES_DATA,
  DEVELOPMENTS_DATA,
  HOUSE_PLANS_DATA,
  VIRTUAL_TOURS_DATA,
  AGENTS_DATA,
  PROFESSIONAL_AGENTS,
  ARTICLES_DATA,
  Property
} from "@/data/portalData";
import { getProperties, getPublicLocationsDetailed, PublicLocation, fetchPublicBanners, PublicBanner, normalizeProperty } from "@/services/propertyService";
import PropertyCard from "@/components/PropertyCard";
import TourModal from "@/components/TourModal";
import AgentContactModal from "@/components/AgentContactModal";
import {
  Search,
  Compass,
  Building2,
  Layers,
  Sparkles,
  TrendingUp,
  ShieldCheck,
  ArrowRight,
  Eye,
  Hammer,
  Award,
  Star,
  PhoneCall,
  CheckCircle2,
  ChevronRight,
  ChevronLeft,
  ChevronDown,
  SlidersHorizontal,
  Check,
  Filter,
  MapPin
} from "lucide-react";

interface AreaSpotlight {
  id: string;
  name: string;
  queryParam: string;
  tagline: string;
  propertyCount: string;
  image: string;
  highlightBadge: string;
  popularTypes: string[];
}

const AREA_METADATA_PRESETS: Record<string, Partial<AreaSpotlight>> = {
  "colombo 3": {
    tagline: "Marine Drive & Sea View Penthouses",
    image: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "High Capital Growth",
    popularTypes: ["Luxury Apartments", "Seafront Condos"]
  },
  "colombo 7": {
    tagline: "Prestigious Mansions & Diplomatic Enclaves",
    image: "https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Prime Trophy Assets",
    popularTypes: ["Bespoke Villas", "Sky Duplexes"]
  },
  "colombo": {
    tagline: "Metropolitan Financial District & City Living",
    image: "https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Financial Capital",
    popularTypes: ["Commercial Plots", "Penthouses"]
  },
  "piliyandala": {
    tagline: "Serene Lakefront & Suburban Living",
    image: "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Popular Family Hub",
    popularTypes: ["Modern 2-Storey", "Gated Residencies"]
  },
  "malabe": {
    tagline: "Horizon Road & Modern Architecture",
    image: "https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Fastest Appreciating",
    popularTypes: ["Architect Villas", "Residential Plots"]
  },
  "athurugiriya": {
    tagline: "Expressway Access & Peaceful Neighborhoods",
    image: "https://images.unsplash.com/photo-1600585154526-990dced4db0d?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Top Value for Money",
    popularTypes: ["Single-Storey Homes", "Brand New Builds"]
  },
  "battaramulla": {
    tagline: "Parliament View & International Schools",
    image: "https://images.unsplash.com/photo-1500382017468-9049fed747ef?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Diplomatic Sector",
    popularTypes: ["Rooftop Mansions", "Commercial Plots"]
  },
  "pelawatte": {
    tagline: "Overseas School Sector & Lush Residencies",
    image: "https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Expat Preferred",
    popularTypes: ["Luxury Houses", "Architect Villas"]
  },
  "galle": {
    tagline: "Rumassala Cliff & Unawatuna Beachfronts",
    image: "https://images.unsplash.com/photo-1613977257363-707ba9348227?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "12.8% Annual Rental Yield",
    popularTypes: ["Oceanfront Villas", "Colonial Estates"]
  },
  "bentota": {
    tagline: "Golden Mile Beachfronts & Riverfronts",
    image: "https://images.unsplash.com/photo-1540555700478-4be289fbecef?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Resort Living",
    popularTypes: ["Beachfront Villas", "Riverfront Plots"]
  },
  "kandy": {
    tagline: "Scenic Hillside Estates & Mountain Views",
    image: "https://images.unsplash.com/photo-1596178065887-1198b6148b2b?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Hill Capital",
    popularTypes: ["Hill View Homes", "Tea Estates"]
  },
  "nuwara eliya": {
    tagline: "Little England & Cool Climate Tea Manors",
    image: "https://images.unsplash.com/photo-1544644181-1484b3fdfc62?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Highland Retreat",
    popularTypes: ["Colonial Cottages", "Tea Plantations"]
  },
  "thalawathugoda": {
    tagline: "Gated Residencies & Walking Tracks",
    image: "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Prime Suburb",
    popularTypes: ["Modern 2-Storey", "Custom Villas"]
  },
  "hokandara": {
    tagline: "Private Gated Living & Lush Gardens",
    image: "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=800&q=80",
    highlightBadge: "Eco Luxury Living",
    popularTypes: ["Custom Garden Villas", "Bare Lands"]
  }
};

const CATEGORY_OPTIONS = [
  "All categories",
  "Sell",
  "Rent",
  "House",
  "Apartment",
  "Land",
  "Commercial Property"
];

const INITIAL_LOCATION_OPTIONS = [
  "All locations",
  "Colombo",
  "Colombo 3 (Kollupitiya)",
  "Colombo 7 (Cinnamon Gardens)",
  "Battaramulla",
  "Pelawatte",
  "Athurugiriya",
  "Galle Fort",
  "Bentota",
  "Kandy",
  "Nuwara Eliya"
];

const AGENT_OPTIONS = [
  "All agents",
  ...PROFESSIONAL_AGENTS.map((a) => a.name)
];

export default function HomePage() {
  const router = useRouter();

  // Search Filter States (Using Theme Colors)
  const [selectedCategory, setSelectedCategory] = useState("All categories");
  const [selectedLocation, setSelectedLocation] = useState("All locations");
  const [locationSearch, setLocationSearch] = useState("");
  const [maxPrice, setMaxPrice] = useState("");
  const [minPrice, setMinPrice] = useState("");
  const [selectedAgent, setSelectedAgent] = useState("All agents");

  // Dropdown open states
  const [isCategoryOpen, setIsCategoryOpen] = useState(false);
  const [isLocationOpen, setIsLocationOpen] = useState(false);
  const [isFilterPopoverOpen, setIsFilterPopoverOpen] = useState(false);
  const [isAgentDropdownOpen, setIsAgentDropdownOpen] = useState(false);

  // Refs for click outside
  const categoryRef = useRef<HTMLDivElement>(null);
  const locationRef = useRef<HTMLDivElement>(null);
  const filterRef = useRef<HTMLDivElement>(null);

  // Close dropdowns on outside click
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (categoryRef.current && !categoryRef.current.contains(event.target as Node)) {
        setIsCategoryOpen(false);
      }
      if (locationRef.current && !locationRef.current.contains(event.target as Node)) {
        setIsLocationOpen(false);
      }
      if (filterRef.current && !filterRef.current.contains(event.target as Node)) {
        setIsFilterPopoverOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Dynamic Locations & Popular Areas from Backend API
  const [locationOptions, setLocationOptions] = useState<string[]>(INITIAL_LOCATION_OPTIONS);
  const [locationChips, setLocationChips] = useState<string[]>([
    "All Areas", "Colombo 3", "Colombo 7", "Battaramulla", "Pelawatte", "Athurugiriya", "Galle", "Kandy", "Nuwara Eliya"
  ]);
  const [popularAreas, setPopularAreas] = useState<AreaSpotlight[]>([]);
  const [isLoadingAreas, setIsLoadingAreas] = useState(true);

  // Dynamic Backend Hero Banners & Slider State
  const [banners, setBanners] = useState<PublicBanner[]>([]);
  const [activeBannerIndex, setActiveBannerIndex] = useState(0);

  // Auto-rotate hero banners
  useEffect(() => {
    if (banners.length <= 1) return;
    const timer = setInterval(() => {
      setActiveBannerIndex((prev) => (prev + 1) % banners.length);
    }, 7500);
    return () => clearInterval(timer);
  }, [banners.length]);

  // Filter locations by input
  const filteredLocations = locationOptions.filter((loc) =>
    loc.toLowerCase().includes(locationSearch.toLowerCase())
  );

  // Tour modal state
  const [activeTourProperty, setActiveTourProperty] = useState<Property | null>(null);
  const [isTourModalOpen, setIsTourModalOpen] = useState(false);
  const [selectedContactAgent, setSelectedContactAgent] = useState<any | null>(null);

  const handleOpenTour = (property: Property) => {
    setActiveTourProperty(property);
    setIsTourModalOpen(true);
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const params = new URLSearchParams();
    if (selectedCategory !== "All categories") params.set("category", selectedCategory);
    if (selectedLocation !== "All locations") params.set("city", selectedLocation);
    if (maxPrice) params.set("maxPrice", maxPrice);
    if (minPrice) params.set("minPrice", minPrice);
    if (selectedAgent !== "All agents") params.set("agent", selectedAgent);

    router.push(`/properties?${params.toString()}`);
  };

  const [allProperties, setAllProperties] = useState<Property[]>([]);
  const [homeCategoryFilter, setHomeCategoryFilter] = useState("All categories");
  const [isLoadingFeatured, setIsLoadingFeatured] = useState(true);

  useEffect(() => {
    let isMounted = true;
    setIsLoadingFeatured(true);
    setIsLoadingAreas(true);

    // 1. Fetch properties for home showcase
    getProperties().then((items) => {
      if (isMounted) {
        setAllProperties(items || []);
        setIsLoadingFeatured(false);
      }
    }).catch(() => {
      if (isMounted) {
        setAllProperties([]);
        setIsLoadingFeatured(false);
      }
    });

    // 2. Fetch backend hero banners
    fetchPublicBanners().then((loadedBanners) => {
      if (isMounted && loadedBanners && loadedBanners.length > 0) {
        setBanners(loadedBanners);
      }
    }).catch((err) => {
      console.warn("Could not load hero banners:", err);
    });

    // 3. Fetch detailed locations
    getPublicLocationsDetailed().then((locs) => {
      if (isMounted) {
        if (locs && locs.length > 0) {
          setLocationOptions(["All locations", ...locs.map((l) => l.name)]);
          setLocationChips(["All Areas", ...locs.map((l) => l.name)]);

          const fallbackImages = [
            "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1600585154526-990dced4db0d?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1500382017468-9049fed747ef?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1613977257363-707ba9348227?auto=format&fit=crop&w=800&q=80",
            "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=800&q=80"
          ];

          const mapped: AreaSpotlight[] = locs.map((loc, idx) => {
            const key = (loc.name || "").toLowerCase();
            const matchedEntry = Object.entries(AREA_METADATA_PRESETS).find(([k]) => key.includes(k));
            const preset = matchedEntry ? matchedEntry[1] : {};

            const count = loc.properties_count ?? 0;
            const countStr = count > 0 ? `${count} Active ${count === 1 ? "Listing" : "Listings"}` : "Prime Location";

            return {
              id: String(loc.id || idx),
              name: loc.name,
              queryParam: loc.name,
              tagline: preset.tagline || ((loc as any).description ? (loc as any).description.slice(0, 55) : "Prime Residential & Investment Opportunities"),
              propertyCount: countStr,
              image: preset.image || fallbackImages[idx % fallbackImages.length],
              highlightBadge: preset.highlightBadge || (loc.type === "City" ? "Urban Center" : "High Growth Area"),
              popularTypes: preset.popularTypes || ["Luxury Houses", "Residential Plots"]
            };
          });

          setPopularAreas(mapped);
        }
        setIsLoadingAreas(false);
      }
    }).catch(() => {
      if (isMounted) setIsLoadingAreas(false);
    });

    return () => {
      isMounted = false;
    };
  }, []);

  const currentBanner = banners[activeBannerIndex];

  const displayedHomeProperties = useMemo(() => {
    if (homeCategoryFilter === "All categories") {
      const featured = allProperties.filter((p) => p.featured);
      return featured.length > 0 ? featured : allProperties.slice(0, 6);
    }
    const cat = homeCategoryFilter.toLowerCase();
    return allProperties.filter((item) => {
      const rawItem = item as any;
      const itemCat = typeof rawItem.category === "object" && rawItem.category !== null 
        ? (rawItem.category.name || "").toLowerCase() 
        : (rawItem.category || "").toLowerCase();
      const itemType = (rawItem.type || "").toLowerCase();
      const itemStatus = (rawItem.status || "").toLowerCase();

      if (cat === "sell" || cat === "for sale" || cat === "sale") {
        return !itemStatus.includes("rent") && !itemType.includes("rent") && !itemCat.includes("rent");
      } else if (cat === "rent" || cat === "for rent") {
        return itemStatus.includes("rent") || itemType.includes("rent") || itemCat.includes("rent");
      } else if (cat === "house") {
        return itemCat.includes("house") || itemCat.includes("villa") || itemCat.includes("bungalow") || itemType.includes("house");
      } else if (cat === "apartment") {
        return itemCat.includes("apartment") || itemCat.includes("penthouse") || itemCat.includes("condo") || itemType.includes("apartment");
      } else if (cat === "land") {
        return itemCat.includes("land") || itemCat.includes("estate") || itemType.includes("land");
      } else if (cat === "commercial property" || cat === "commercial") {
        return itemCat.includes("commercial") || itemType.includes("commercial");
      }
      return itemCat === cat || itemType === cat;
    });
  }, [allProperties, homeCategoryFilter]);

  return (
    <div className="min-h-screen">

      {/* ------------------------------------------------------------- */}
      {/* HERO SECTION WITH DYNAMIC BACKEND BANNERS & SLIDER */}
      {/* ------------------------------------------------------------- */}
      <section className="relative text-white pt-16 pb-44 md:pb-52 overflow-hidden">

        {/* Dynamic Backend Banner Background Slider with Responsive 3-View Videos & Fallback Posters */}
        {banners.length > 0 ? (
          <div className="absolute inset-0 -z-10 overflow-hidden">
            {banners.map((b, idx) => {
              const isVideo = b.media_type === "video" || Boolean(b.video_desktop || b.video_mobile || b.video_url);
              const poster = b.image_desktop || b.image_tablet || b.image_mobile || b.image_url;
              const isCurrent = idx === activeBannerIndex;

              return (
                <div
                  key={b.id || idx}
                  className={`absolute inset-0 transition-opacity duration-1000 ease-in-out ${
                    isCurrent ? "opacity-100 scale-100" : "opacity-0 scale-105 pointer-events-none"
                  } transition-transform duration-7000`}
                >
                  {isVideo && (b.video_desktop || b.video_tablet || b.video_mobile || b.video_url) ? (
                    <div className="w-full h-full relative">
                      <video
                        key={`hero-vid-${b.id}-${idx}`}
                        className="w-full h-full object-cover object-center"
                        autoPlay
                        muted
                        loop
                        playsInline
                        poster={poster}
                      >
                        {b.video_desktop && <source media="(min-width: 1024px)" src={b.video_desktop} type="video/mp4" />}
                        {b.video_tablet && <source media="(min-width: 640px)" src={b.video_tablet} type="video/mp4" />}
                        <source src={b.video_mobile || b.video_desktop || b.video_url} type="video/mp4" />
                      </video>
                    </div>
                  ) : (
                    <picture className="w-full h-full">
                      {b.image_desktop && <source media="(min-width: 1024px)" srcSet={b.image_desktop} />}
                      {b.image_tablet && <source media="(min-width: 640px)" srcSet={b.image_tablet} />}
                      <img
                        src={b.image_mobile || b.image_desktop || b.image_url}
                        alt={b.title || "DreamHomes Real Estate"}
                        className="w-full h-full object-cover object-center"
                      />
                    </picture>
                  )}
                </div>
              );
            })}
            {/* Cinematic Gradient Overlays to guarantee high legibility */}
            <div className="absolute inset-0 bg-gradient-to-t from-[#0A0A0A] via-[#0A0A0A]/70 to-[#0A0A0A]/50" />
            <div className="absolute inset-0 bg-gradient-to-r from-[#0A0A0A]/80 via-transparent to-[#0A0A0A]/80" />
          </div>
        ) : (
          <>
            {/* Clean Luxury Gradient Background */}
            <div className="absolute inset-0 bg-gradient-to-b from-[#0A0A0A] via-[#0A0A0A] to-[#121214] -z-10" />
            <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(230,161,0,0.15),transparent_50%)] pointer-events-none -z-10" />
            <div className="absolute top-20 -left-24 w-96 h-96 bg-[#059669]/20 rounded-full blur-3xl pointer-events-none -z-10" />
          </>
        )}

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-20 pt-28 sm:pt-44 md:pt-60">

          {/* Banner Slide Indicator Dots and Arrows (when > 1 banner) */}
          {banners.length > 1 && (
            <div className="flex items-center justify-center gap-3 mt-6">
              <button
                type="button"
                onClick={() => setActiveBannerIndex((prev) => (prev === 0 ? banners.length - 1 : prev - 1))}
                className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/25 border border-white/20 flex items-center justify-center text-white backdrop-blur-sm transition-all"
                title="Previous Slide"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>

              <div className="flex items-center gap-1.5">
                {banners.map((_, idx) => (
                  <button
                    key={idx}
                    type="button"
                    onClick={() => setActiveBannerIndex(idx)}
                    className={`h-2 rounded-full transition-all ${
                      idx === activeBannerIndex ? "w-8 bg-[#4223de]" : "w-2 bg-white/30 hover:bg-white/60"
                    }`}
                    title={`Slide ${idx + 1}`}
                  />
                ))}
              </div>

              <button
                type="button"
                onClick={() => setActiveBannerIndex((prev) => (prev + 1) % banners.length)}
                className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/25 border border-white/20 flex items-center justify-center text-white backdrop-blur-sm transition-all"
                title="Next Slide"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* ------------------------------------------------------------- */}
          {/* HOME SEARCH BAR WITH CRISP BORDERS & CLEAN SELECTS */}
          {/* ------------------------------------------------------------- */}
          <div className="mt-12 max-w-5xl mx-auto relative z-30">
            <form
              onSubmit={handleSearchSubmit}
              className="bg-[#0f0f11] p-2.5 sm:p-3 rounded-2xl sm:rounded-3xl border border-[#FFE259]/30 shadow-[0px_25px_60px_rgba(0,0,0,0.6)] flex flex-col md:flex-row items-stretch md:items-center gap-2.5"
            >

              {/* 1. Category Dropdown */}
              <div className="relative flex-1" ref={categoryRef}>
                <button
                  type="button"
                  onClick={() => {
                    setIsCategoryOpen(!isCategoryOpen);
                    setIsLocationOpen(false);
                    setIsFilterPopoverOpen(false);
                  }}
                  className="w-full bg-[#121214] hover:bg-[#18181b] border border-zinc-800 focus:border-[#FFE259] text-left px-4 py-3.5 rounded-xl text-xs sm:text-sm font-semibold text-white flex items-center justify-between transition-all cursor-pointer"
                >
                  <span className="truncate">{selectedCategory}</span>
                  <ChevronDown className="w-4 h-4 text-[#FFE259] shrink-0 ml-2" />
                </button>

                {isCategoryOpen && (
                  <div className="absolute top-full left-0 mt-2 w-64 bg-[#0e0e10] border border-[#FFE259]/40 rounded-2xl shadow-2xl overflow-hidden z-50 p-2 space-y-1 animate-in fade-in zoom-in-95 duration-150">
                    {CATEGORY_OPTIONS.map((cat) => (
                      <button
                        key={cat}
                        type="button"
                        onClick={() => {
                          setSelectedCategory(cat);
                          setIsCategoryOpen(false);
                        }}
                        className={`w-full text-left px-4 py-2.5 text-xs font-semibold rounded-xl flex items-center gap-2.5 transition-all cursor-pointer ${selectedCategory === cat
                          ? "bg-[#FFE259] text-black font-bold shadow-md"
                          : "text-[#FFE259] hover:text-white hover:bg-white/10"
                          }`}
                      >
                        {selectedCategory === cat ? (
                          <Check className="w-4 h-4 shrink-0 text-black stroke-[3]" />
                        ) : (
                          <span className="w-4" />
                        )}
                        <span>{cat}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* 2. Locations Dropdown with Search */}
              <div className="relative flex-1" ref={locationRef}>
                <button
                  type="button"
                  onClick={() => {
                    setIsLocationOpen(!isLocationOpen);
                    setIsCategoryOpen(false);
                    setIsFilterPopoverOpen(false);
                  }}
                  className="w-full bg-[#121214] hover:bg-[#18181b] border border-white/10 focus:border-[#059669] text-left px-4 py-3.5 rounded-xl text-xs sm:text-sm font-semibold text-white flex items-center justify-between transition-all"
                >
                  <span className="truncate">{selectedLocation}</span>
                  <ChevronDown className="w-4 h-4 text-slate-400 shrink-0 ml-2" />
                </button>

                {isLocationOpen && (
                  <div className="absolute top-full left-0 mt-2 w-64 bg-[#121214] border border-white/15 rounded-xl shadow-2xl z-50 p-2.5 animate-in fade-in zoom-in-95 duration-150">
                    {/* Location Search Input */}
                    <div className="relative mb-2">
                      <Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-2.5" />
                      <input
                        type="text"
                        value={locationSearch}
                        onChange={(e) => setLocationSearch(e.target.value)}
                        placeholder="Search locations..."
                        className="w-full bg-[#0f0f11] border border-white/10 text-xs text-white pl-8 pr-3 py-2 rounded-lg focus:outline-none focus:border-[#059669]"
                        autoFocus
                      />
                    </div>

                    {/* Scrollable list */}
                    <div className="max-h-48 overflow-y-auto space-y-0.5 scrollbar-thin pr-1">
                      {filteredLocations.map((loc) => (
                        <button
                          key={loc}
                          type="button"
                          onClick={() => {
                            setSelectedLocation(loc);
                            setIsLocationOpen(false);
                            setLocationSearch("");
                          }}
                          className={`w-full text-left px-3 py-2 text-xs font-semibold rounded-lg flex items-center justify-between transition-colors ${selectedLocation === loc
                            ? "bg-[#059669] text-white font-bold"
                            : "text-slate-300 hover:text-white hover:bg-white/10"
                            }`}
                        >
                          <span className="truncate">{loc}</span>
                          {selectedLocation === loc && <Check className="w-3.5 h-3.5 text-white" />}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* 3. Advanced Filter Popover */}
              <div className="relative" ref={filterRef}>
                <button
                  type="button"
                  onClick={() => {
                    setIsFilterPopoverOpen(!isFilterPopoverOpen);
                    setIsCategoryOpen(false);
                    setIsLocationOpen(false);
                  }}
                  className="bg-[#121214] hover:bg-[#18181b] border border-white/10 focus:border-[#059669] text-slate-300 hover:text-white px-4 py-3.5 rounded-xl text-xs sm:text-sm font-semibold flex items-center gap-2 transition-all"
                >
                  <SlidersHorizontal className="w-4 h-4 text-[#059669]" />
                  <span>Filters</span>
                </button>

                {isFilterPopoverOpen && (
                  <div className="absolute top-full right-0 mt-2 w-72 sm:w-80 bg-[#121214] border border-white/15 rounded-2xl shadow-2xl z-50 p-5 space-y-4 animate-in fade-in zoom-in-95 duration-150">
                    <div className="flex items-center justify-between border-b border-white/10 pb-3">
                      <h4 className="text-sm font-bold text-white flex items-center gap-1.5">
                        <Sparkles className="w-3.5 h-3.5 text-[#059669]" />
                        <span>Filter Criteria</span>
                      </h4>
                      <button
                        type="button"
                        onClick={() => {
                          setMinPrice("");
                          setMaxPrice("");
                          setSelectedAgent("All agents");
                        }}
                        className="text-[11px] text-slate-400 hover:text-white"
                      >
                        Clear
                      </button>
                    </div>

                    <div>
                      <label className="block text-[11px] font-bold text-slate-400 uppercase tracking-wider mb-1.5">
                        Price Range (LKR Millions)
                      </label>
                      <div className="grid grid-cols-2 gap-2">
                        <input
                          type="number"
                          placeholder="Min (e.g. 20)"
                          value={minPrice}
                          onChange={(e) => setMinPrice(e.target.value)}
                          className="w-full bg-[#0f0f11] border border-white/10 text-xs text-white px-3 py-2 rounded-lg focus:outline-none focus:border-[#059669]"
                        />
                        <input
                          type="number"
                          placeholder="Max (e.g. 150)"
                          value={maxPrice}
                          onChange={(e) => setMaxPrice(e.target.value)}
                          className="w-full bg-[#0f0f11] border border-white/10 text-xs text-white px-3 py-2 rounded-lg focus:outline-none focus:border-[#059669]"
                        />
                      </div>
                    </div>

                    <div>
                      <label className="block text-[11px] font-bold text-slate-400 uppercase tracking-wider mb-1.5">
                        Assigned Agent
                      </label>
                      <select
                        value={selectedAgent}
                        onChange={(e) => setSelectedAgent(e.target.value)}
                        className="w-full bg-[#0f0f11] border border-white/10 text-xs text-white px-3 py-2 rounded-lg focus:outline-none focus:border-[#059669]"
                      >
                        {AGENT_OPTIONS.map((agent) => (
                          <option key={agent} value={agent} className="bg-[#121214]">
                            {agent}
                          </option>
                        ))}
                      </select>
                    </div>

                    <button
                      type="button"
                      onClick={() => setIsFilterPopoverOpen(false)}
                      className="w-full bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold py-2 rounded-lg transition-colors"
                    >
                      Apply Filters
                    </button>
                  </div>
                )}
              </div>

              {/* 4. Search Submit Button */}
              <div>
                <button
                  type="submit"
                  className="w-full md:w-auto bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs sm:text-sm px-6 py-3.5 rounded-xl shadow-lg shadow-[#059669]/30 transition-all flex items-center justify-center gap-2 shrink-0 cursor-pointer"
                >
                  <Search className="w-4 h-4 text-white stroke-[2.5]" />
                  <span>Search</span>
                </button>
              </div>

            </form>
          </div>

        </div>
      </section>

      {/* ------------------------------------------------------------- */}
      {/* FEATURED PROPERTIES SECTION WITH CATEGORY FILTER BUTTONS */}
      {/* ------------------------------------------------------------- */}
      <section className="py-20 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex flex-col md:flex-row md:items-end justify-between mb-8 gap-4">
          <div>
            <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-[#0A0A0A] text-[#FFE259] border border-[#FFA726]/40 mb-3">
              <Award className="w-3.5 h-3.5 text-[#FFE259]" /> Signature Portfolios
            </div>
            <h2 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight font-display-lg">
              Featured Properties for <span className="text-[#FFE259]">Sale &amp; Rent</span>
            </h2>
            <p className="text-slate-400 text-sm mt-2 max-w-xl">
              Whether you&apos;re searching for houses for sale in Thalawathugoda, land for sale in new developing areas, or apartments in Colombo, our experienced team is here to guide you.
            </p>
          </div>
          <Link
            href={`/properties${homeCategoryFilter !== "All categories" ? `?category=${encodeURIComponent(homeCategoryFilter)}` : ""}`}
            className="inline-flex items-center gap-2 text-sm font-bold text-[#FFE259] hover:text-white transition-all"
          >
            <span>Explore All Properties Across Colombo &amp; Beyond</span>
            <ChevronRight className="w-4 h-4" />
          </Link>
        </div>

        {/* Golden Category Filter Buttons Bar Above Properties */}
        <div className="flex items-center gap-2.5 overflow-x-auto pb-4 mb-8 scrollbar-none">
          {CATEGORY_OPTIONS.map((cat) => {
            const isSelected = homeCategoryFilter === cat;
            return (
              <button
                key={cat}
                type="button"
                onClick={() => setHomeCategoryFilter(cat)}
                className={`px-5 py-2.5 rounded-full text-xs font-extrabold transition-all whitespace-nowrap cursor-pointer flex items-center gap-1.5 shadow-sm ${isSelected
                    ? "bg-[#FFE259] text-black shadow-md border border-[#FFE259] scale-[1.02]"
                    : "bg-[#0e0e10] text-[#FFE259] border border-[#FFE259]/40 hover:bg-[#18181b] hover:border-[#FFE259]"
                  }`}
              >
                <span>{cat}</span>
              </button>
            );
          })}
        </div>

        {isLoadingFeatured ? (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {[1, 2, 3].map((n) => (
              <div key={n} className="bg-[#0e0e10] rounded-3xl overflow-hidden border border-zinc-800 p-6 animate-pulse space-y-4 shadow-xl">
                <div className="aspect-[16/10] bg-zinc-800 rounded-2xl w-full" />
                <div className="h-4 bg-zinc-800 rounded w-1/3" />
                <div className="h-6 bg-zinc-800 rounded w-3/4" />
                <div className="h-10 bg-zinc-800 rounded-xl w-full" />
              </div>
            ))}
          </div>
        ) : displayedHomeProperties.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {displayedHomeProperties.map((prop: Property) => (
              <PropertyCard
                key={prop.id}
                property={prop}
                onOpenTourModal={handleOpenTour}
              />
            ))}
          </div>
        ) : (
          <div className="bg-[#0e0e10] border border-[#FFE259]/30 rounded-3xl p-12 text-center text-white space-y-3">
            <h3 className="text-lg font-bold text-white font-display-lg mb-1">
              No {homeCategoryFilter} Properties Found
            </h3>
            <p className="text-xs text-slate-400 max-w-sm mx-auto">
              We are currently onboarding new {homeCategoryFilter.toLowerCase()} listings across Colombo district.
            </p>
            <button
              onClick={() => setHomeCategoryFilter("All categories")}
              className="mt-3 px-5 py-2.5 rounded-full bg-[#FFE259] text-black font-bold text-xs shadow-md cursor-pointer"
            >
              View All Categories
            </button>
          </div>
        )}
      </section>

      {/* ------------------------------------------------------------- */}
      {/* THALAWATHUGODA & HIGH GROWTH EMERGING AREAS */}
      {/* ------------------------------------------------------------- */}
      <section className="py-20 bg-[#0A0A0A] text-white relative overflow-hidden">
        {/* Subtle Background Elements */}
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_bottom_left,rgba(230,161,0,0.1),transparent_50%)] pointer-events-none" />
        <div className="absolute top-0 right-0 w-96 h-96 bg-[#059669]/10 rounded-full blur-3xl pointer-events-none" />

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">

          {/* Section Header */}
          <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-6">
            <div className="space-y-3 max-w-2xl">
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#121214] text-xs font-bold text-[#FFE259] border border-[#FFA726]/40">
                <MapPin className="w-3.5 h-3.5 text-[#FFE259]" />
                <span>Thalawathugoda &amp; Emerging Suburbs</span>
              </div>
              <h2 className="text-3xl sm:text-4xl md:text-5xl font-extrabold tracking-tight font-display-lg text-white">
                Browse By <span className="text-[#FFE259]">Area</span>
              </h2>
              <p className="text-slate-300 text-sm sm:text-base leading-relaxed">
                Thalawathugoda has emerged as one of Sri Lanka&apos;s most sought-after locations for real estate, offering a blend of suburban tranquillity and urban convenience. Explore exclusive listings across Thalawathugoda, Pelawatta, Kaduwela, Kottawa, Athurugiriya, Pannipitiya, and Boralesgamuwa.
              </p>
            </div>

            <Link
              href="/properties"
              className="inline-flex items-center gap-2 text-xs font-bold text-[#FFE259] hover:text-white bg-white/10 hover:bg-white/20 border border-[#FFE259]/30 px-5 py-3 rounded-full transition-all shrink-0 self-start md:self-auto"
            >
              <span>View All {locationOptions.length > 1 ? `${locationOptions.length - 1}+` : "24+"} Locations</span>
              <ChevronRight className="w-4 h-4 text-[#FFE259]" />
            </Link>
          </div>

          {/* Auto-Running Left-to-Right Marquee for Location Names (Pauses on Hover) */}
          <div className="relative mb-10 overflow-hidden group py-2">
            {/* Left & Right Subtle Edge Gradient Fades */}
            <div className="pointer-events-none absolute inset-y-0 left-0 w-16 sm:w-24 bg-gradient-to-r from-[#0A0A0A] to-transparent z-10" />
            <div className="pointer-events-none absolute inset-y-0 right-0 w-16 sm:w-24 bg-gradient-to-l from-[#0A0A0A] to-transparent z-10" />

            <div className="flex animate-marquee-ltr gap-3 items-center">
              {/* Render duplicated list for continuous seamless infinite loop */}
              {[...locationChips, ...locationChips].map((loc, idx) => {
                const query = loc === "All Areas" ? "/properties" : `/properties?location=${encodeURIComponent(loc)}`;
                return (
                  <Link
                    key={`${loc}-${idx}`}
                    href={query}
                    className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs font-bold bg-white/5 hover:bg-[#059669] border border-white/10 hover:border-[#059669] text-slate-200 hover:text-white transition-all whitespace-nowrap shadow-sm hover:scale-105"
                  >
                    <MapPin className="w-3 h-3 text-[#FFE259] shrink-0" />
                    <span>{loc}</span>
                  </Link>
                );
              })}
            </div>
          </div>

          {/* Areas Showcase Grid */}
          {isLoadingAreas ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {[1, 2, 3, 4].map((n) => (
                <div key={n} className="rounded-3xl aspect-[4/5] sm:aspect-[3/4] bg-white/5 border border-white/10 p-6 animate-pulse flex flex-col justify-between">
                  <div className="flex justify-between">
                    <div className="h-4 bg-white/20 rounded w-20" />
                    <div className="h-4 bg-white/20 rounded w-16" />
                  </div>
                  <div className="space-y-2">
                    <div className="h-5 bg-white/20 rounded w-3/4" />
                    <div className="h-3 bg-white/10 rounded w-full" />
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {popularAreas.slice(0, 8).map((area) => (
                <Link
                  key={area.id}
                  href={`/properties?location=${encodeURIComponent(area.queryParam)}`}
                  className="group relative rounded-3xl overflow-hidden aspect-[4/5] sm:aspect-[3/4] border border-white/10 shadow-xl hover:border-[#FFA726] transition-all duration-500 flex flex-col justify-between p-6"
                >
                  {/* Background Image with Zoom */}
                  <div className="absolute inset-0 z-0">
                    <img
                      src={area.image}
                      alt={area.name}
                      className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 opacity-80 group-hover:opacity-90"
                    />
                    {/* Dark Gradient Overlay */}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/95 via-black/50 to-black/20 group-hover:from-black/90 transition-colors" />
                  </div>

                  {/* Top Badge & Count */}
                  <div className="relative z-10 flex items-center justify-between gap-2">
                    <span className="px-2.5 py-1 rounded-full text-[10px] font-extrabold bg-[#0A0A0A]/80 backdrop-blur-md text-[#FFE259] border border-[#FFA726]/40">
                      {area.highlightBadge}
                    </span>
                    <span className="px-2.5 py-1 rounded-full text-[10px] font-bold bg-[#059669] text-white shadow-md">
                      {area.propertyCount}
                    </span>
                  </div>

                  {/* Bottom Content */}
                  <div className="relative z-10 space-y-2">
                    <div className="flex items-center gap-1.5 text-xs text-[#FFE259] font-semibold">
                      <MapPin className="w-3.5 h-3.5 text-[#FFE259]" />
                      <span>Western &amp; Southern Province</span>
                    </div>

                    <h3 className="text-xl font-extrabold text-white font-headline-md leading-tight group-hover:text-[#FFE259] transition-colors">
                      {area.name}
                    </h3>

                    <p className="text-slate-300 text-xs line-clamp-1">
                      {area.tagline}
                    </p>

                    {/* Popular Types Chips */}
                    <div className="flex flex-wrap gap-1.5 pt-2">
                      {area.popularTypes.map((type) => (
                        <span
                          key={type}
                          className="text-[10px] font-medium px-2 py-0.5 rounded-md bg-white/10 text-slate-200"
                        >
                          {type}
                        </span>
                      ))}
                    </div>

                    {/* Hover Action Link */}
                    <div className="pt-2 flex items-center justify-between text-xs font-bold text-white group-hover:text-[#FFE259] transition-colors border-t border-white/15">
                      <span>Explore Listings</span>
                      <span className="w-7 h-7 rounded-full bg-white/10 group-hover:bg-[#059669] flex items-center justify-center transition-all group-hover:translate-x-1">
                        <ChevronRight className="w-4 h-4 text-white" />
                      </span>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          )}

          {/* Bottom Area Advisory Banner */}
          <div className="mt-12 bg-white/5 border border-white/10 rounded-3xl p-6 sm:p-8 flex flex-col md:flex-row items-center justify-between gap-6">
            <div className="space-y-1 text-center md:text-left">
              <h4 className="text-lg font-bold text-white">Looking for land or property in another town in Sri Lanka?</h4>
              <p className="text-xs sm:text-sm text-slate-300">
                We cover Kandy, Kurunegala, Negombo, Gampaha, Dehiwala, Rajagiriya, and 50+ regional hubs.
              </p>
            </div>
            <Link
              href="/properties"
              className="bg-[#059669] hover:bg-[#047857] text-white text-xs font-extrabold px-6 py-3.5 rounded-full shadow-lg shadow-[#059669]/30 transition-all whitespace-nowrap shrink-0"
            >
              Search All Locations
            </Link>
          </div>

        </div>
      </section>

      {/* ------------------------------------------------------------- */}
      {/* CUSTOM CONSTRUCTION & ARCHITECTURAL SERVICES (COMMENTED OUT) */}
      {/* ------------------------------------------------------------- */}
      {/*
      <section className="py-20 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="bg-gradient-to-br from-[#0e0e10] to-[#18181b] text-white rounded-3xl p-8 sm:p-12 shadow-2xl relative overflow-hidden">
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-center">
            <div className="lg:col-span-7 space-y-6">
              <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-white/10 text-[#a7f3d0]">
                <Hammer className="w-3.5 h-3.5 text-[#ecfdf5]" /> Turnkey Architectural Solutions
              </div>
              <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight font-display-lg leading-tight">
                Build Your Architectural Dream Home on Your Land
              </h2>
              <p className="text-slate-300 text-sm leading-relaxed">
                From conceptual 3D BIM designs and municipal approvals to turnkey luxury construction at locked BOQ pricing—supervised by certified structural engineers.
              </p>

              <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 pt-2">
                <div className="bg-white/5 border border-white/10 rounded-2xl p-4">
                  <span className="text-xl font-bold text-[#a7f3d0] block font-display-lg">LKR 19,500</span>
                  <span className="text-[11px] text-slate-300">Premium Cost / SqFt</span>
                </div>
                <div className="bg-white/5 border border-white/10 rounded-2xl p-4">
                  <span className="text-xl font-bold text-[#a7f3d0] block font-display-lg">10-14 Mo.</span>
                  <span className="text-[11px] text-slate-300">Guaranteed Handover</span>
                </div>
                <div className="bg-white/5 border border-white/10 rounded-2xl p-4 col-span-2 sm:col-span-1">
                  <span className="text-xl font-bold text-[#a7f3d0] block font-display-lg">10-Year</span>
                  <span className="text-[11px] text-slate-300">Structural Warranty</span>
                </div>
              </div>

              <div className="pt-2 flex flex-wrap gap-4">
                <Link
                  href="/construction"
                  className="bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs px-6 py-3.5 rounded-full shadow-lg shadow-[#059669]/20 transition-all"
                >
                  Estimate Build Budget
                </Link>
                <Link
                  href="/house-plans"
                  className="bg-white/10 hover:bg-white/20 text-white font-bold text-xs px-6 py-3.5 rounded-full transition-all"
                >
                  Browse 2D/3D House Plans
                </Link>
              </div>
            </div>

            <div className="lg:col-span-5 grid grid-cols-2 gap-4">
              <img
                src="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=600&q=80"
                alt="Architecture"
                className="w-full h-44 object-cover rounded-2xl border border-white/10 shadow-lg"
              />
              <img
                src="https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?auto=format&fit=crop&w=600&q=80"
                alt="Modern Villa"
                className="w-full h-44 object-cover rounded-2xl border border-white/10 shadow-lg mt-6"
              />
            </div>
          </div>
        </div>
      </section>
      */}

      {/* ------------------------------------------------------------- */}
      {/* WHY CHOOSE DREAM HOMES & OUR PROFESSIONAL AGENTS */}
      {/* ------------------------------------------------------------- */}
      <section className="py-20 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center max-w-3xl mx-auto mb-14 space-y-3">
          <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-[#0A0A0A] text-[#FFE259] border border-[#FFA726]/40">
            <ShieldCheck className="w-3.5 h-3.5 text-[#FFE259]" /> Local Market Mastery
          </div>
          <h2 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight font-display-lg">
            Why Choose Dream Homes for Real Estate in <span className="text-[#FFE259]">Sri Lanka?</span>
          </h2>
          <p className="text-slate-600 text-sm sm:text-base leading-relaxed">
            At Dream Homes Real Estate (PVT) Ltd, we combine local market knowledge with a disciplined, friendly, and efficient approach. Our talented agents understand the nuances of real estate in Sri Lanka—from pricing trends in Thalawathugoda and Malabe to legal requirements for property transfer.
          </p>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {PROFESSIONAL_AGENTS.map((agent) => (
            <div
              key={agent.id}
              className="bg-[#0e0e10] rounded-3xl p-6 border border-[#FFE259]/30 shadow-xl hover:border-[#FFE259]/60 hover:shadow-2xl transition-all text-center flex flex-col justify-between text-white"
            >
              <div>
                <img
                  src={agent.avatar}
                  alt={agent.name}
                  className="w-24 h-24 rounded-full object-cover mx-auto mb-4 border-4 border-[#FFE259]/40 shadow-md"
                />
                <h4 className="text-base font-bold text-white">{agent.name}</h4>
                <p className="text-xs text-[#FFE259] font-semibold mt-0.5">{agent.role}</p>
                <p className="text-[11px] text-slate-400 mt-1">{agent.division}</p>

                <p className="mt-3 text-xs text-slate-400 line-clamp-2 italic border-l-2 border-[#FFE259]/40 pl-2 text-left">
                  {agent.bio}
                </p>

                <div className="mt-4 p-2.5 bg-[#18181b] border border-zinc-800 rounded-2xl text-xs text-slate-300 font-medium">
                  <span>{agent.propertiesCount} Represented Properties</span>
                </div>
              </div>

              <div className="mt-6 pt-4 border-t border-zinc-800 flex flex-col gap-2">
                <button
                  type="button"
                  onClick={() => setSelectedContactAgent(agent)}
                  className="w-full bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold py-2.5 rounded-full flex items-center justify-center gap-1.5 shadow-md shadow-[#059669]/20 transition-all cursor-pointer"
                >
                  <span>Contact Agent</span>
                </button>
                <Link
                  href={`/agents/${agent.slug}`}
                  className="text-xs font-bold text-slate-300 hover:text-[#FFE259] transition-colors py-1"
                >
                  View Profile &amp; Listings &rarr;
                </Link>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Tour Modal Provider */}
      <TourModal
        property={activeTourProperty}
        isOpen={isTourModalOpen}
        onClose={() => setIsTourModalOpen(false)}
      />

      {/* Agent Contact Modal Provider */}
      {selectedContactAgent && (
        <AgentContactModal
          isOpen={!!selectedContactAgent}
          onClose={() => setSelectedContactAgent(null)}
          agent={selectedContactAgent}
        />
      )}

    </div>
  );
}