"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { DayNightSwitch } from "./DayNightSwitch";
import { LanguageTransitionButton } from "./LanguageTransitionButton";
import { useLanguage } from "./LanguageContext";
import * as T from "@/lib/themeTokens";

const defaultCityLinks = [
  { nameEn: "Riyadh", nameAr: "الرياض", href: "/riyadhProjects" },
  { nameEn: "Jeddah", nameAr: "جدة", href: "/jeddahProjects" },
  { nameEn: "Makkah", nameAr: "مكة", href: "/makkahProjects" },
];

export type ProjectCategory = "landmark" | "mall" | "education" | "health" | "garden" | "mosque";
type PlaceCategory = ProjectCategory | "laundry";
type ProjectCity = "Riyadh" | "Jeddah" | "Makkah";
type ProjectSegment = "residential" | "commercial";

interface NearbyPlace {
  id: string;
  nameEn: string;
  nameAr: string;
  category: PlaceCategory;
  x: number;
  y: number;
}

const categories: {
  id: ProjectCategory;
  en: string;
  ar: string;
  icon: string;
  color: string;
}[] = [
  { id: "landmark", en: "Landmarks", ar: "معالم", icon: "⌖", color: "#d8ad70" },
  { id: "mall", en: "Malls", ar: "مراكز تجارية", icon: "▣", color: "#d7a45e" },
  { id: "education", en: "Education", ar: "تعليم", icon: "◇", color: "#5b9bdb" },
  { id: "health", en: "Health", ar: "صحة", icon: "♡", color: "#df655f" },
  { id: "garden", en: "Garden", ar: "حدائق", icon: "♧", color: "#68a76b" },
  { id: "mosque", en: "Mosque", ar: "مساجد", icon: "⌂", color: "#c9a477" },
];

const projectImages: Record<ProjectCategory, string> = {
  landmark: "/project-images/landmark.jpg",
  mall: "/project-images/mall.jpg",
  education: "/project-images/education.jpg",
  health: "/project-images/health.jpg",
  garden: "/project-images/garden.jpg",
  mosque: "/project-images/mosque.jpg",
};

const markerSpots = [
  { x: 31, y: 29 },
  { x: 47, y: 22 },
  { x: 43, y: 45 },
  { x: 66, y: 37 },
  { x: 58, y: 59 },
  { x: 28, y: 63 },
  { x: 75, y: 68 },
  { x: 80, y: 30 },
];

const nearbyPlacesByCity: Record<ProjectCity, NearbyPlace[]> = {
  Riyadh: [
    { id: "riyadh-kafd", nameEn: "King Abdullah Financial District", nameAr: "مركز الملك عبدالله المالي", category: "landmark", x: 74, y: 17 },
    { id: "riyadh-kingdom-centre", nameEn: "Kingdom Centre", nameAr: "مركز المملكة", category: "landmark", x: 17, y: 38 },
    { id: "riyadh-park", nameEn: "Riyadh Park", nameAr: "الرياض بارك", category: "mall", x: 85, y: 47 },
    { id: "riyadh-boulevard", nameEn: "Boulevard City", nameAr: "بوليفارد سيتي", category: "mall", x: 16, y: 73 },
    { id: "riyadh-university", nameEn: "Princess Nourah University", nameAr: "جامعة الأميرة نورة", category: "education", x: 84, y: 81 },
    { id: "riyadh-hospital", nameEn: "King Faisal Specialist Hospital", nameAr: "مستشفى الملك فيصل التخصصي", category: "health", x: 13, y: 54 },
    { id: "riyadh-mosque", nameEn: "King Khalid Grand Mosque", nameAr: "جامع الملك خالد الكبير", category: "mosque", x: 19, y: 19 },
    { id: "riyadh-park-garden", nameEn: "King Abdullah Park", nameAr: "حديقة الملك عبدالله", category: "garden", x: 87, y: 64 },
    { id: "riyadh-laundry", nameEn: "Neighborhood Laundry", nameAr: "مغسلة الحي", category: "laundry", x: 51, y: 85 },
  ],
  Jeddah: [
    { id: "jeddah-corniche", nameEn: "Jeddah Corniche", nameAr: "كورنيش جدة", category: "landmark", x: 75, y: 17 },
    { id: "jeddah-fountain", nameEn: "King Fahd Fountain", nameAr: "نافورة الملك فهد", category: "landmark", x: 16, y: 38 },
    { id: "jeddah-mall", nameEn: "Red Sea Mall", nameAr: "رد سي مول", category: "mall", x: 85, y: 47 },
    { id: "jeddah-historic", nameEn: "Historic Jeddah", nameAr: "جدة التاريخية", category: "mall", x: 16, y: 73 },
    { id: "jeddah-university", nameEn: "University of Jeddah", nameAr: "جامعة جدة", category: "education", x: 84, y: 81 },
    { id: "jeddah-hospital", nameEn: "King Fahd Hospital", nameAr: "مستشفى الملك فهد", category: "health", x: 13, y: 54 },
    { id: "jeddah-mosque", nameEn: "Al Rahma Mosque", nameAr: "مسجد الرحمة", category: "mosque", x: 19, y: 19 },
    { id: "jeddah-park", nameEn: "Jeddah Waterfront Park", nameAr: "حديقة الواجهة البحرية", category: "garden", x: 87, y: 64 },
    { id: "jeddah-laundry", nameEn: "Al Hamra Laundry", nameAr: "مغسلة الحمراء", category: "laundry", x: 51, y: 85 },
  ],
  Makkah: [
    { id: "makkah-haram", nameEn: "Al Masjid Al Haram", nameAr: "المسجد الحرام", category: "mosque", x: 74, y: 17 },
    { id: "makkah-clock-tower", nameEn: "Makkah Clock Tower", nameAr: "برج ساعة مكة", category: "landmark", x: 17, y: 38 },
    { id: "makkah-mall", nameEn: "Makkah Mall", nameAr: "مكة مول", category: "mall", x: 85, y: 47 },
    { id: "makkah-jabal-omar", nameEn: "Jabal Omar", nameAr: "جبل عمر", category: "landmark", x: 16, y: 73 },
    { id: "makkah-university", nameEn: "Umm Al-Qura University", nameAr: "جامعة أم القرى", category: "education", x: 84, y: 81 },
    { id: "makkah-hospital", nameEn: "King Abdullah Medical City", nameAr: "مدينة الملك عبدالله الطبية", category: "health", x: 13, y: 54 },
    { id: "makkah-mosque", nameEn: "Masjid Aisha (Al-Taneem)", nameAr: "مسجد عائشة (التنعيم)", category: "mosque", x: 19, y: 19 },
    { id: "makkah-park", nameEn: "Al Naseem Park", nameAr: "حديقة النسيم", category: "garden", x: 87, y: 64 },
    { id: "makkah-laundry", nameEn: "Al Aziziyah Laundry", nameAr: "مغسلة العزيزية", category: "laundry", x: 51, y: 85 },
  ],
};

const routeScale = {
  mapWidthKm: 30,
  mapHeightKm: 20,
  streetDistanceFactor: 1.25,
  averageDrivingSpeedKmh: 32,
};

export interface ProjectItem {
  id: string;
  nameEn: string;
  nameAr: string;
  typeEn: string;
  typeAr: string;
  statusEn: string;
  statusAr: string;
  locationEn: string;
  locationAr: string;
  descriptionEn: string;
  descriptionAr: string;
  category: ProjectCategory;
  x?: number;
  y?: number;
  image?: string;
}

interface ProjectMapExplorerProps {
  cityNameEn: string;
  cityNameAr: string;
  regionEn: string;
  regionAr: string;
  dayImage: string;
  nightImage?: string;
  projects: ProjectItem[];
  cityLinks?: { nameEn: string; nameAr: string; href: string }[];
}

function projectSegment(project: ProjectItem): ProjectSegment {
  return project.category === "landmark" || project.category === "mall"
    ? "commercial"
    : "residential";
}

function ProjectArtwork({ category, image }: { category: ProjectCategory; image?: string }) {
  return (
    <img
      src={image || projectImages[category]}
      alt=""
      aria-hidden="true"
      loading="lazy"
      style={{
        display: "block",
        width: "100%",
        height: "100%",
        objectFit: "cover",
        filter: "brightness(.86) saturate(.88)",
      }}
    />
  );
}

function PlaceIcon({ category, active }: { category: PlaceCategory; active: boolean }) {
  const accent = active ? T.ACCENT_LIGHT : "rgba(216,173,112,.34)";
  const detail = active ? T.ACCENT_LIGHT : "rgba(225,213,193,.72)";

  return (
    <svg
      width="27"
      height="27"
      viewBox="0 0 40 40"
      fill="none"
      aria-hidden="true"
      style={{ display: "block", filter: "drop-shadow(0 2px 4px rgba(0,0,0,.8))" }}
    >
      <rect x="3" y="3" width="34" height="34" rx="10" fill={active ? "rgba(30,27,24,.9)" : "rgba(30,27,24,.58)"} stroke={accent} strokeWidth="1.3" />
      {category === "mosque" && (
        <>
          <path d="M8 32V15h4v17m16 0V15h4v17M15 32V20a5 5 0 0 1 10 0v12Z" fill="#65533d" stroke={detail} strokeWidth="1.4" />
          <path d="M7 15h6m14 0h6M14 20h12M20 6v4m-2-2h4M7 33h26" stroke={detail} strokeWidth="1.4" strokeLinecap="round" />
          <path d="M18 32v-6a2 2 0 0 1 4 0v6" stroke={detail} strokeWidth="1.3" />
        </>
      )}
      {category === "health" && (
        <>
          <path d="M9 33V11h22v22Z" fill="#51483c" stroke={detail} strokeWidth="1.4" />
          <path d="M17 7h6v4h-6zM18 15h4m-2-2v4" stroke={detail} strokeWidth="1.5" strokeLinecap="round" />
          <path d="M13 22h2m4 0h2m4 0h2m-14 5h2m4 0h2m4 0h2" stroke={detail} strokeWidth="1.6" strokeLinecap="round" />
          <path d="M18 33v-4h4v4" stroke={detail} strokeWidth="1.3" />
        </>
      )}
      {category === "laundry" && (
        <>
          <path d="M9 8h22v25H9z" fill="#51483c" stroke={detail} strokeWidth="1.4" />
          <path d="M9 13h22M13 10.5h.1m3 0h.1" stroke={detail} strokeWidth="1.4" strokeLinecap="round" />
          <circle cx="20" cy="23" r="6" stroke={detail} strokeWidth="1.5" />
          <path d="M17 24c1.5 2 4.5 2 6 0" stroke={detail} strokeWidth="1.2" strokeLinecap="round" />
        </>
      )}
      {category === "mall" && (
        <>
          <path d="M9 17h22v16H9z" fill="#51483c" stroke={detail} strokeWidth="1.4" />
          <path d="m8 17 3-7h18l3 7M8 17a3 3 0 0 0 6 0 3 3 0 0 0 6 0 3 3 0 0 0 6 0 3 3 0 0 0 6 0" stroke={detail} strokeWidth="1.3" strokeLinejoin="round" />
          <path d="M17 25h6v8h-6zM12 22h2m12 0h2" stroke={detail} strokeWidth="1.3" />
        </>
      )}
      {category === "education" && (
        <>
          <path d="m7 16 13-9 13 9v17H7z" fill="#51483c" stroke={detail} strokeWidth="1.4" strokeLinejoin="round" />
          <path d="M12 20h3m5 0h3m5 0h1m-17 5h3m5 0h3m5 0h1m-14 8v-5h6v5" stroke={detail} strokeWidth="1.3" strokeLinecap="round" />
        </>
      )}
      {category === "garden" && (
        <>
          <path d="M20 8v24m-5 0h10" stroke={detail} strokeWidth="1.8" strokeLinecap="round" />
          <path d="M20 7c-5-5-12 0-9 6-5 1-5 9 1 10-1 6 6 8 8 3 2 5 9 3 8-3 6-1 6-9 1-10 3-6-4-11-9-6Z" fill="#4c5940" stroke={detail} strokeWidth="1.3" strokeLinejoin="round" />
        </>
      )}
      {category === "landmark" && (
        <>
          <path d="M11 33V15l9-8 9 8v18Z" fill="#51483c" stroke={detail} strokeWidth="1.4" strokeLinejoin="round" />
          <path d="M20 7V4m-5 14h2m6 0h2m-10 5h2m6 0h2m-10 5h2m6 0h2m-5-14v19" stroke={detail} strokeWidth="1.3" strokeLinecap="round" />
        </>
      )}
    </svg>
  );
}

export function ProjectMapExplorer({
  cityNameEn,
  cityNameAr,
  regionEn,
  regionAr,
  dayImage,
  nightImage,
  projects,
  cityLinks = defaultCityLinks,
}: ProjectMapExplorerProps) {
  const router = useRouter();
  const { isArabic } = useLanguage();
  const [isNight, setIsNight] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [cityMenuOpen, setCityMenuOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [segment, setSegment] = useState<"all" | ProjectSegment>("all");
  const [category, setCategory] = useState<ProjectCategory | null>(null);
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);
  const [selectedPlaceId, setSelectedPlaceId] = useState<string | null>(null);
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [favorites, setFavorites] = useState<string[]>([]);
  const cityMenuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!cityMenuOpen) return;

    const closeOnOutsideClick = (event: PointerEvent) => {
      if (event.target instanceof Node && !cityMenuRef.current?.contains(event.target)) {
        setCityMenuOpen(false);
      }
    };
    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") setCityMenuOpen(false);
    };

    document.addEventListener("pointerdown", closeOnOutsideClick);
    document.addEventListener("keydown", closeOnEscape);
    return () => {
      document.removeEventListener("pointerdown", closeOnOutsideClick);
      document.removeEventListener("keydown", closeOnEscape);
    };
  }, [cityMenuOpen]);

  useEffect(() => {
    setSearch("");
    setSegment("all");
    setCategory(null);
    setSelectedProjectId(null);
    setSelectedPlaceId(null);
    setDetailsOpen(false);
  }, [cityNameEn]);

  const background = isNight && nightImage ? nightImage : dayImage;
  const visibleProjects = projects.filter((project) => {
    const query = search.trim().toLocaleLowerCase();
    const matchesSearch =
      !query ||
      [project.nameEn, project.nameAr, project.typeEn, project.typeAr, project.locationEn, project.locationAr]
        .join(" ")
        .toLocaleLowerCase()
        .includes(query);
    const matchesSegment = segment === "all" || projectSegment(project) === segment;
    const matchesCategory = category === null || project.category === category;
    return matchesSearch && matchesSegment && matchesCategory;
  });
  const selectedProject =
    visibleProjects.find((project) => project.id === selectedProjectId) ?? null;
  const nearbyPlaces = nearbyPlacesByCity[cityNameEn as ProjectCity] ?? [];
  const selectedPlace = nearbyPlaces.find((place) => place.id === selectedPlaceId) ?? null;
  const selectedProjectIndex = selectedProject ? projects.indexOf(selectedProject) : -1;
  const routeOrigin = selectedProject && selectedProjectIndex >= 0
    ? {
        x: selectedProject.x ?? markerSpots[selectedProjectIndex % markerSpots.length].x,
        y: selectedProject.y ?? markerSpots[selectedProjectIndex % markerSpots.length].y,
      }
    : null;
  const routeEstimate =
    routeOrigin && selectedPlace
      ? (() => {
          const dx = ((selectedPlace.x - routeOrigin.x) / 100) * routeScale.mapWidthKm;
          const dy = ((selectedPlace.y - routeOrigin.y) / 100) * routeScale.mapHeightKm;
          const distanceKm = Math.hypot(dx, dy) * routeScale.streetDistanceFactor;
          return {
            distanceKm,
            durationMinutes: Math.max(
              1,
              Math.round((distanceKm / routeScale.averageDrivingSpeedKmh) * 60),
            ),
            midpointX: (routeOrigin.x + selectedPlace.x) / 2,
            midpointY: Math.min(
              90,
              Math.max(
                10,
                (routeOrigin.y + selectedPlace.y) / 2 + (selectedPlace.y < 50 ? 12 : -12),
              ),
            ),
            bendX: (routeOrigin.x + selectedPlace.x) / 2 + 4,
            bendY: (routeOrigin.y + selectedPlace.y) / 2 - 3,
          };
        })()
      : null;
  const residentialCount = projects.filter((project) => projectSegment(project) === "residential").length;
  const commercialCount = projects.filter((project) => projectSegment(project) === "commercial").length;
  const currentCity =
    cityLinks.find((city) => city.nameEn === cityNameEn) ??
    cityLinks[0] ??
    defaultCityLinks[0];

  const selectProject = (project: ProjectItem) => {
    setSelectedProjectId(project.id);
    setSelectedPlaceId(null);
    setDetailsOpen(false);
  };

  return (
    <div
      style={{
        position: "relative",
        display: "flex",
        width: "100vw",
        height: "100vh",
        overflow: "hidden",
        background: "#0b0f14",
        color: T.TEXT,
        fontFamily: isArabic ? "var(--font-arabic)" : "var(--font-sans)",
      }}
    >
      <aside
        aria-label={isArabic ? "قائمة المشاريع" : "Project list"}
        aria-hidden={!sidebarOpen}
        style={{
          position: "relative",
          zIndex: 5,
          display: "flex",
          flexDirection: "column",
          flex: sidebarOpen ? "0 0 clamp(230px, 24vw, 280px)" : "0 0 0px",
          minWidth: 0,
          height: "100%",
          padding: sidebarOpen ? 11 : 0,
          overflow: "hidden",
          visibility: sidebarOpen ? "visible" : "hidden",
          opacity: sidebarOpen ? 1 : 0,
          direction: isArabic ? "rtl" : "ltr",
          background: "linear-gradient(155deg, rgba(89,78,66,.94), rgba(42,39,36,.94))",
          backdropFilter: "blur(24px) saturate(125%)",
          WebkitBackdropFilter: "blur(24px) saturate(125%)",
          borderRight: isArabic ? 0 : `1px solid ${T.GLASS_BORDER}`,
          borderLeft: isArabic ? `1px solid ${T.GLASS_BORDER}` : 0,
          boxShadow: isArabic
            ? "-14px 0 42px rgba(0,0,0,.35)"
            : "14px 0 42px rgba(0,0,0,.35)",
          transition: "flex-basis .25s ease, padding .25s ease, opacity .2s ease, visibility .25s",
        }}
      >
        <button
          type="button"
          onClick={() => setSidebarOpen(false)}
          aria-label={isArabic ? "إغلاق قائمة المشاريع" : "Close project list"}
          title={isArabic ? "إغلاق القائمة" : "Close list"}
          style={{
            position: "absolute",
            top: "50%",
            [isArabic ? "left" : "right"]: -1,
            zIndex: 8,
            display: "grid",
            placeItems: "center",
            width: 25,
            height: 42,
            padding: 0,
            transform: "translateY(-50%)",
            border: `1px solid ${T.GLASS_BORDER}`,
            borderLeft: isArabic ? 0 : undefined,
            borderRight: isArabic ? undefined : 0,
            borderRadius: isArabic ? "0 10px 10px 0" : "10px 0 0 10px",
            background: T.GLASS_LABEL,
            color: T.ACCENT_LIGHT,
            boxShadow: T.SHADOW_CARD,
            cursor: "pointer",
          }}
        >
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
            <path d="m15 18-6-6 6-6" />
          </svg>
        </button>
        <div
          ref={cityMenuRef}
          style={{
            position: "relative",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            gap: 8,
            marginBottom: 10,
          }}
        >
          <h1
            style={{
              minWidth: 0,
              margin: 0,
              color: T.TEXT,
              fontSize: 14,
              fontFamily: "var(--font-display)",
              fontWeight: 500,
              letterSpacing: ".035em",
              textTransform: "uppercase",
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
          >
            {isArabic ? `مشاريع ${cityNameAr}` : `${cityNameEn} Projects`}
          </h1>
          <button
            type="button"
            aria-label={isArabic ? "اختر المدينة" : "Select city"}
            aria-haspopup="listbox"
            aria-expanded={cityMenuOpen}
            aria-controls="project-city-options"
            onClick={() => setCityMenuOpen((open) => !open)}
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 7,
              width: 75,
              minHeight: 32,
              flexShrink: 0,
              padding: "6px 10px",
              borderRadius: 9,
              border: `1px solid ${cityMenuOpen ? T.GLASS_BORDER_ACTIVE : T.GLASS_BORDER}`,
              background: cityMenuOpen ? T.GLASS_CONTROL_ACTIVE : T.GLASS_LABEL,
              color: T.TEXT,
              fontFamily: "var(--font-display)",
              fontSize: 10,
              cursor: "pointer",
            }}
          >
            <span>{isArabic ? currentCity.nameAr : currentCity.nameEn}</span>
            <svg
              width="11"
              height="11"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              aria-hidden="true"
              style={{
                flexShrink: 0,
                transform: cityMenuOpen ? "rotate(180deg)" : "none",
                transition: "transform .18s ease",
              }}
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </button>
          {cityMenuOpen && (
            <div
              id="project-city-options"
              role="listbox"
              aria-label={isArabic ? "المدن المتاحة" : "Available cities"}
              style={{
                position: "absolute",
                top: "calc(100% + 6px)",
                [isArabic ? "left" : "right"]: 0,
                zIndex: 10,
                width: 112,
                padding: 4,
                borderRadius: 11,
                border: `1px solid ${T.GLASS_BORDER}`,
                background: "linear-gradient(155deg, rgba(66,59,51,.98), rgba(31,29,27,.98))",
                backdropFilter: T.GLASS_BLUR,
                WebkitBackdropFilter: T.GLASS_BLUR,
                boxShadow: T.SHADOW_PANEL,
              }}
            >
              {cityLinks.map((city) => {
                const active = city.href === currentCity.href;
                return (
                  <button
                    key={city.href}
                    type="button"
                    role="option"
                    aria-selected={active}
                    onClick={() => {
                      setCityMenuOpen(false);
                      if (!active) router.push(city.href);
                    }}
                    style={{
                      width: "100%",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      gap: 8,
                      padding: "8px 9px",
                      border: `1px solid ${active ? T.GLASS_BORDER_SOFT : "transparent"}`,
                      borderRadius: 7,
                      background: active ? T.GLASS_CONTROL_ACTIVE : "transparent",
                      color: active ? T.ACCENT_LIGHT : T.TEXT_SOFT,
                      fontFamily: "inherit",
                      fontSize: 10,
                      textAlign: isArabic ? "right" : "left",
                      cursor: "pointer",
                    }}
                  >
                    {isArabic ? city.nameAr : city.nameEn}
                    {active && <span aria-hidden="true">✓</span>}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        <div style={{ display: "flex", gap: 6, marginBottom: 9 }}>
          <label
            style={{
              display: "flex",
              flex: 1,
              alignItems: "center",
              gap: 7,
              minWidth: 0,
              height: 33,
              padding: "0 9px",
              borderRadius: 9,
              border: `1px solid ${T.GLASS_BORDER_SOFT}`,
              background: "rgba(25,24,23,.28)",
              color: T.TEXT_MUTED,
            }}
          >
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
              <circle cx="11" cy="11" r="7" />
              <path d="m20 20-4-4" />
            </svg>
            <input
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              placeholder={isArabic ? "ابحث عن مشروع" : "Search projects"}
              style={{
                width: "100%",
                minWidth: 0,
                border: 0,
                outline: 0,
                background: "transparent",
                color: T.TEXT,
                fontSize: 11,
                fontFamily: "inherit",
              }}
            />
          </label>
          <button
            type="button"
            onClick={() => setFiltersOpen((open) => !open)}
            aria-label={isArabic ? "تصفية المشاريع" : "Filter projects"}
            aria-expanded={filtersOpen}
            style={{
              width: 34,
              height: 33,
              flexShrink: 0,
              display: "grid",
              placeItems: "center",
              borderRadius: 9,
              border: `1px solid ${filtersOpen ? T.GLASS_BORDER_ACTIVE : T.GLASS_BORDER}`,
              background: filtersOpen ? T.GLASS_CONTROL_ACTIVE : T.GLASS_LABEL,
              color: T.ACCENT_LIGHT,
              cursor: "pointer",
            }}
          >
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
              <path d="M4 7h9M17 7h3M4 17h3M11 17h9" />
              <circle cx="15" cy="7" r="2" />
              <circle cx="9" cy="17" r="2" />
            </svg>
          </button>
        </div>

        <div style={{ display: "flex", gap: 5, marginBottom: 9 }}>
          {([
            ["all", isArabic ? "الكل" : "ALL", projects.length],
            ["residential", isArabic ? "سكني" : "RESIDENTIAL", residentialCount],
            ["commercial", isArabic ? "تجاري" : "COMMERCIAL", commercialCount],
          ] as const).map(([value, label, count]) => {
            const active = segment === value;
            return (
              <button
                key={value}
                type="button"
                onClick={() => setSegment(value)}
                aria-pressed={active}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 4,
                  minWidth: 0,
                  padding: "5px 7px",
                  borderRadius: 8,
                  border: `1px solid ${active ? T.GLASS_BORDER_ACTIVE : T.GLASS_BORDER_SOFT}`,
                  background: active ? T.GLASS_CONTROL_ACTIVE : "rgba(20,19,18,.24)",
                  color: active ? T.ACCENT_LIGHT : T.TEXT_MUTED,
                  fontSize: 8,
                  fontFamily: "var(--font-display)",
                  whiteSpace: "nowrap",
                  cursor: "pointer",
                }}
              >
                {label}
                <span style={{ opacity: 0.65 }}>{String(count).padStart(2, "0")}</span>
              </button>
            );
          })}
        </div>

        {filtersOpen && (
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 5,
              marginBottom: 8,
              padding: 7,
              borderRadius: 11,
              border: `1px solid ${T.GLASS_BORDER_SOFT}`,
              background: "rgba(24,22,20,.48)",
            }}
          >
            <button
              type="button"
              onClick={() => setCategory(null)}
              aria-pressed={category === null}
              style={{
                gridColumn: "1 / -1",
                padding: "6px 8px",
                borderRadius: 7,
                border: `1px solid ${category === null ? T.GLASS_BORDER_ACTIVE : "transparent"}`,
                background: category === null ? T.GLASS_CONTROL_ACTIVE : "transparent",
                color: T.TEXT,
                textAlign: "left",
                fontSize: 10,
                cursor: "pointer",
              }}
            >
              {isArabic ? "كل أنواع المواقع" : "ALL LOCATIONS"}
            </button>
            {categories.map((item) => {
              const active = category === item.id;
              return (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => setCategory(active ? null : item.id)}
                  aria-pressed={active}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 5,
                    minWidth: 0,
                    padding: "6px 5px",
                    borderRadius: 7,
                    border: `1px solid ${active ? T.GLASS_BORDER_ACTIVE : "transparent"}`,
                    background: active ? T.GLASS_CONTROL_ACTIVE : "transparent",
                    color: active ? T.ACCENT_LIGHT : T.TEXT_SOFT,
                    textAlign: "left",
                    fontSize: 9,
                    cursor: "pointer",
                  }}
                >
                  <span style={{ color: item.color, fontSize: 13 }}>{item.icon}</span>
                  <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {isArabic ? item.ar : item.en}
                  </span>
                </button>
              );
            })}
          </div>
        )}

        <div style={{ display: "flex", flex: 1, flexDirection: "column", minHeight: 0 }}>
          <div
            className="project-list-scroll"
            style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: "1px 2px 6px" }}
          >
            {visibleProjects.map((project) => {
              const active = selectedProjectId === project.id;
              const projectCategory = categories.find((item) => item.id === project.category);
              return (
                <button
                  key={project.id}
                  type="button"
                  onClick={() => selectProject(project)}
                  aria-pressed={active}
                  style={{
                    width: "100%",
                    minHeight: 72,
                    display: "flex",
                    alignItems: "center",
                    gap: 9,
                    marginBottom: 8,
                    padding: 7,
                    borderRadius: 12,
                    border: `1px solid ${active ? T.GLASS_BORDER_ACTIVE : T.GLASS_BORDER_FAINT}`,
                    background: active
                      ? "linear-gradient(135deg, rgba(216,173,112,.25), rgba(38,35,32,.88))"
                      : "linear-gradient(135deg, rgba(74,67,59,.76), rgba(35,33,31,.88))",
                    boxShadow: active ? T.SHADOW_GOLD_GLOW : T.SHADOW_CARD,
                    color: T.TEXT,
                    textAlign: isArabic ? "right" : "left",
                    cursor: "pointer",
                    overflow: "hidden",
                  }}
                >
                  <div style={{ width: 62, height: 58, flex: "0 0 62px", overflow: "hidden", borderRadius: 7 }}>
                    <ProjectArtwork category={project.category} image={project.image} />
                  </div>
                  <span style={{ minWidth: 0, flex: 1, overflow: "hidden" }}>
                    <strong
                      style={{
                        display: "block",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                        fontFamily: "var(--font-display)",
                        fontSize: 10,
                        fontWeight: 500,
                        textTransform: "uppercase",
                      }}
                    >
                      {isArabic ? project.nameAr : project.nameEn}
                    </strong>
                    <span
                      style={{
                        display: "block",
                        marginTop: 4,
                        overflow: "hidden",
                        color: projectCategory?.color ?? T.ACCENT_LIGHT,
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                        fontSize: 8,
                        textTransform: "uppercase",
                      }}
                    >
                      {isArabic ? project.typeAr : project.typeEn}
                    </span>
                    <span
                      style={{
                        display: "block",
                        marginTop: 5,
                        overflow: "hidden",
                        color: T.TEXT_MUTED,
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                        fontSize: 8,
                      }}
                    >
                      ◉ {isArabic ? project.locationAr : project.locationEn}
                    </span>
                  </span>
                </button>
              );
            })}
            {visibleProjects.length === 0 && (
              <p style={{ padding: 10, color: T.TEXT_MUTED, fontSize: 11, textAlign: "center" }}>
                {isArabic ? "لا توجد مواقع مطابقة" : "No matching locations"}
              </p>
            )}
          </div>
        </div>
      </aside>

      {!sidebarOpen && (
        <button
          type="button"
          onClick={() => setSidebarOpen(true)}
          aria-label={isArabic ? "فتح قائمة المشاريع" : "Open project list"}
          title={isArabic ? "فتح القائمة" : "Open list"}
          style={{
            position: "absolute",
            top: "50%",
            [isArabic ? "right" : "left"]: 0,
            zIndex: 8,
            display: "grid",
            placeItems: "center",
            width: 32,
            height: 46,
            padding: 0,
            transform: "translateY(-50%)",
            border: `1px solid ${T.GLASS_BORDER}`,
            borderLeft: isArabic ? undefined : 0,
            borderRight: isArabic ? 0 : undefined,
            borderRadius: isArabic ? "10px 0 0 10px" : "0 10px 10px 0",
            background: T.GLASS_LABEL,
            color: T.ACCENT_LIGHT,
            boxShadow: T.SHADOW_CARD,
            cursor: "pointer",
          }}
        >
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
            <path d="m9 18 6-6-6-6" />
          </svg>
        </button>
      )}

      <main
        aria-label={isArabic ? `خريطة ${cityNameAr}` : `${cityNameEn} map`}
        style={{
          position: "relative",
          flex: 1,
          minWidth: 0,
          height: "100%",
          overflow: "hidden",
          background: "#25221f",
        }}
      >
        <div
          aria-hidden="true"
          style={{
            position: "absolute",
            inset: 0,
            backgroundImage: `url(${background})`,
            backgroundSize: background.startsWith("/uploads/") ? "100% 100%" : "cover",
            backgroundPosition: "center",
            filter: isNight ? "brightness(.56) contrast(1.13) saturate(.72)" : "brightness(.78) contrast(1.03) saturate(.9)",
            transition: "filter .35s ease, background-image .35s ease",
          }}
        />
        <div
          aria-hidden="true"
          style={{
            position: "absolute",
            inset: 0,
            pointerEvents: "none",
            background: "linear-gradient(135deg, rgba(32,27,22,.12), rgba(27,25,24,.4))",
          }}
        />

        <div
          style={{
            position: "absolute",
            top: 20,
            right: isArabic ? "auto" : 20,
            left: isArabic ? 20 : "auto",
            zIndex: 7,
            display: "flex",
            alignItems: "center",
            gap: 8,
            direction: isArabic ? "rtl" : "ltr",
            paddingLeft: isArabic ? 46 : 0,
            paddingRight: isArabic ? 0 : 46,
          }}
        >
          <DayNightSwitch isNight={isNight} onToggle={setIsNight} size="sm" />
          <LanguageTransitionButton position="static" top={0} right={0} />
          <Link
            href="/admin"
            aria-label={isArabic ? "فتح لوحة التحكم" : "Open dashboard"}
            title={isArabic ? "لوحة التحكم" : "Dashboard"}
            style={{
              display: "grid",
              placeItems: "center",
              width: 36,
              height: 36,
              borderRadius: 9,
              border: `1px solid ${T.GLASS_BORDER}`,
              background: T.GLASS_LABEL,
              color: T.ACCENT_LIGHT,
              textDecoration: "none",
              boxShadow: T.SHADOW_CARD,
            }}
          >
            ⚙
          </Link>
          <Link
            href="/"
            aria-label={isArabic ? "العودة إلى الخريطة الرئيسية" : "Back to main map"}
            style={{
              position: "absolute",
              top: 0,
              right: isArabic ? "auto" : 0,
              left: isArabic ? 0 : "auto",
              display: "grid",
              placeItems: "center",
              width: 38,
              height: 38,
              borderRadius: 10,
              border: `1px solid ${T.GLASS_BORDER}`,
              background: T.GLASS_LABEL,
              color: T.TEXT,
              textDecoration: "none",
              boxShadow: T.SHADOW_CARD,
            }}
          >
            →
          </Link>
        </div>

        {routeEstimate && routeOrigin && selectedPlace && (
          <>
            <svg
              aria-hidden="true"
              viewBox="0 0 100 100"
              preserveAspectRatio="none"
              style={{
                position: "absolute",
                inset: 0,
                zIndex: 1,
                width: "100%",
                height: "100%",
                overflow: "visible",
                pointerEvents: "none",
              }}
            >
              <path
                d={`M ${routeOrigin.x} ${routeOrigin.y} Q ${routeEstimate.bendX} ${routeEstimate.bendY} ${selectedPlace.x} ${selectedPlace.y}`}
                fill="none"
                stroke="rgba(13,16,19,.9)"
                strokeWidth="1.2"
                strokeLinecap="round"
              />
              <path
                d={`M ${routeOrigin.x} ${routeOrigin.y} Q ${routeEstimate.bendX} ${routeEstimate.bendY} ${selectedPlace.x} ${selectedPlace.y}`}
                fill="none"
                stroke={T.ACCENT_LIGHT}
                strokeWidth=".48"
                strokeDasharray="1.1 .65"
                strokeLinecap="round"
                style={{ filter: "drop-shadow(0 0 2px rgba(239,207,152,.8))" }}
              />
              <circle cx={routeOrigin.x} cy={routeOrigin.y} r=".8" fill={T.ACCENT_LIGHT} />
              <circle cx={selectedPlace.x} cy={selectedPlace.y} r=".8" fill={T.ACCENT_LIGHT} />
            </svg>
            <div
              role="status"
              aria-label={isArabic ? "وقت الوصول التقديري بالسيارة" : "Estimated driving time"}
              style={{
                position: "absolute",
                left: `${routeEstimate.midpointX}%`,
                top: `${routeEstimate.midpointY}%`,
                zIndex: 5,
                display: "flex",
                alignItems: "center",
                gap: 8,
                padding: "7px 10px",
                transform: "translate(-50%, -50%)",
                border: `1px solid ${T.GLASS_BORDER}`,
                borderRadius: 10,
                background: "rgba(31,29,27,.88)",
                backdropFilter: "blur(12px)",
                boxShadow: T.SHADOW_PANEL,
                direction: "ltr",
                whiteSpace: "nowrap",
              }}
            >
              <svg width="23" height="18" viewBox="0 0 24 18" fill="none" aria-hidden="true">
                <path d="M4 10 5.7 5.7A2.5 2.5 0 0 1 8 4h8a2.5 2.5 0 0 1 2.3 1.7L20 10v4H4v-4Z" stroke={T.ACCENT_LIGHT} strokeWidth="1.5" />
                <path d="M3 9h18M7 14v2m10-2v2" stroke={T.ACCENT_LIGHT} strokeWidth="1.5" strokeLinecap="round" />
                <circle cx="7" cy="12" r="1" fill={T.ACCENT_LIGHT} />
                <circle cx="17" cy="12" r="1" fill={T.ACCENT_LIGHT} />
              </svg>
              <span style={{ display: "grid", gap: 2 }}>
                <strong style={{ color: T.TEXT, fontSize: 11, fontWeight: 600 }}>
                  {routeEstimate.distanceKm.toFixed(1)} km | {routeEstimate.durationMinutes}{" "}
                  {isArabic ? "دقيقة" : "min"}
                </strong>
                <span style={{ color: T.TEXT_MUTED, fontSize: 8 }}>
                  {isArabic ? "تقديري · بالسيارة" : "Approx. · by car"}
                </span>
              </span>
              <button
                type="button"
                onClick={() => setSelectedPlaceId(null)}
                aria-label={isArabic ? "مسح المسار" : "Clear route"}
                style={{
                  display: "grid",
                  placeItems: "center",
                  width: 20,
                  height: 20,
                  padding: 0,
                  border: 0,
                  borderRadius: 6,
                  background: "rgba(255,255,255,.08)",
                  color: T.TEXT_SOFT,
                  fontSize: 14,
                  cursor: "pointer",
                }}
              >
                ×
              </button>
            </div>
          </>
        )}

        {visibleProjects.map((project) => {
          const index = projects.indexOf(project);
          const spot = {
            x: project.x ?? markerSpots[index % markerSpots.length].x,
            y: project.y ?? markerSpots[index % markerSpots.length].y,
          };
          const active = selectedProjectId === project.id;
          const labelOnLeft = spot.x > 65;
          return (
            <button
              key={project.id}
              type="button"
              onClick={() => selectProject(project)}
              aria-label={isArabic ? `عرض ${project.nameAr}` : `Show ${project.nameEn}`}
              aria-pressed={active}
              style={{
                position: "absolute",
                left: `${spot.x}%`,
                top: `${spot.y}%`,
                zIndex: active ? 3 : 2,
                display: "block",
                width: 25,
                height: 31,
                padding: 0,
                border: 0,
                background: "transparent",
                transform: "translate(-50%, -100%)",
                color: T.TEXT,
                cursor: "pointer",
                overflow: "visible",
              }}
            >
              <svg width="25" height="31" viewBox="0 0 25 31" aria-hidden="true" style={{ display: "block", filter: "drop-shadow(0 3px 4px rgba(0,0,0,.65))" }}>
                <path d="M12.5 30S1 17.6 1 11.6a11.5 11.5 0 1 1 23 0C24 17.6 12.5 30 12.5 30Z" fill={active ? "#f0ca89" : "#c9a16a"} stroke="#fff1d2" strokeWidth="1.5" />
                <circle cx="12.5" cy="11.5" r="4" fill="#574433" stroke="#fff1d2" strokeWidth="1.5" />
              </svg>
              <span
                style={{
                  position: "absolute",
                  top: "50%",
                  left: labelOnLeft ? "auto" : 30,
                  right: labelOnLeft ? 30 : "auto",
                  transform: "translateY(-50%)",
                  maxWidth: 150,
                  width: "max-content",
                  overflow: "hidden",
                  padding: "4px 8px",
                  border: `1px solid ${active ? T.GLASS_BORDER_ACTIVE : T.GLASS_BORDER_SOFT}`,
                  borderRadius: 6,
                  background: "rgba(46,41,36,.9)",
                  boxShadow: "0 3px 8px rgba(0,0,0,.35)",
                  fontFamily: "var(--font-display)",
                  fontSize: 9,
                  textOverflow: "ellipsis",
                }}
              >
                {isArabic ? project.nameAr : project.nameEn}
              </span>
            </button>
          );
        })}

        {nearbyPlaces.map((place) => {
            const active = selectedPlaceId === place.id;
            return (
              <button
                key={place.id}
                type="button"
                onClick={() => {
                  if (selectedProject) setSelectedPlaceId(place.id);
                }}
                aria-disabled={!selectedProject}
                aria-label={
                  !selectedProject
                    ? isArabic
                      ? `اختر مشروعاً أولاً لرسم طريق إلى ${place.nameAr}`
                      : `Select a project first to route to ${place.nameEn}`
                    : isArabic
                      ? `احسب الطريق إلى ${place.nameAr}`
                      : `Route to ${place.nameEn}`
                }
                aria-pressed={active}
                title={
                  !selectedProject
                    ? isArabic
                      ? `اختر مشروعاً أولاً · ${place.nameAr}`
                      : `Select a project first · ${place.nameEn}`
                    : isArabic
                      ? place.nameAr
                      : place.nameEn
                }
                style={{
                  position: "absolute",
                  left: `${place.x}%`,
                  top: `${place.y}%`,
                  zIndex: active ? 5 : 1,
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  gap: 1,
                  maxWidth: 138,
                  padding: 0,
                  border: 0,
                  background: "transparent",
                  transform: "translate(-50%, -50%)",
                  color: T.TEXT,
                  opacity: active ? 1 : 0.76,
                  cursor: selectedProject ? "pointer" : "default",
                  whiteSpace: "nowrap",
                  transition: "opacity .18s ease",
                }}
              >
                <PlaceIcon category={place.category} active={active} />
                <span
                  style={{
                    maxWidth: 138,
                    overflow: "hidden",
                    padding: "1px 3px",
                    borderRadius: 4,
                    background: active ? "rgba(31,29,27,.72)" : "transparent",
                    color: active ? T.ACCENT_LIGHT : "rgba(244,240,234,.72)",
                    fontFamily: isArabic ? "var(--font-arabic)" : "var(--font-display)",
                    fontSize: 8,
                    fontWeight: active ? 600 : 500,
                    lineHeight: 1.15,
                    textOverflow: "ellipsis",
                    textAlign: "center",
                    textShadow: "0 1px 4px rgba(0,0,0,.95)",
                    direction: isArabic ? "rtl" : "ltr",
                  }}
                >
                  {isArabic ? place.nameAr : place.nameEn}
                </span>
              </button>
            );
        })}

        {selectedProject && !selectedPlace && (
          <section
            className="scrollbar-hidden"
            aria-label={isArabic ? "تفاصيل الموقع" : "Location details"}
            style={{
              position: "absolute",
              zIndex: 6,
              left: "50%",
              top: "54%",
              width: "min(225px, calc(100% - 24px))",
              maxHeight: "calc(100% - 120px)",
              overflowY: "auto",
              transform: "translate(-50%, -50%)",
              padding: 9,
              borderRadius: 16,
              border: `1px solid ${T.GLASS_BORDER}`,
              background: "linear-gradient(145deg, rgba(83,76,67,.96), rgba(37,35,33,.97))",
              backdropFilter: "blur(20px) saturate(120%)",
              WebkitBackdropFilter: "blur(20px) saturate(120%)",
              boxShadow: "0 18px 48px rgba(0,0,0,.48)",
            }}
          >
            <div style={{ position: "relative", height: 108, overflow: "hidden", borderRadius: 10 }}>
              <ProjectArtwork category={selectedProject.category} image={selectedProject.image} />
              <button
                type="button"
                onClick={() => {
                  setSelectedProjectId(null);
                  setSelectedPlaceId(null);
                  setDetailsOpen(false);
                }}
                aria-label={isArabic ? "إغلاق بطاقة الموقع" : "Close location card"}
                style={{
                  position: "absolute",
                  top: 7,
                  left: 7,
                  width: 24,
                  height: 24,
                  border: 0,
                  borderRadius: 7,
                  background: "rgba(225,236,241,.82)",
                  color: "#34383b",
                  cursor: "pointer",
                }}
              >
                ×
              </button>
              <button
                type="button"
                onClick={() =>
                  setFavorites((current) =>
                    current.includes(selectedProject.id)
                      ? current.filter((id) => id !== selectedProject.id)
                      : [...current, selectedProject.id],
                  )
                }
                aria-label={isArabic ? "حفظ الموقع" : "Save location"}
                aria-pressed={favorites.includes(selectedProject.id)}
                style={{
                  position: "absolute",
                  top: 7,
                  right: 7,
                  width: 25,
                  height: 25,
                  border: 0,
                  borderRadius: 8,
                  background: "rgba(225,236,241,.82)",
                  color: favorites.includes(selectedProject.id) ? "#c95b55" : "#59616a",
                  cursor: "pointer",
                }}
              >
                {favorites.includes(selectedProject.id) ? "♥" : "♡"}
              </button>
            </div>
            <div style={{ padding: "8px 3px 1px", direction: isArabic ? "rtl" : "ltr" }}>
              <strong
                style={{
                  display: "block",
                  color: T.TEXT,
                  fontFamily: "var(--font-display)",
                  fontSize: 12,
                  fontWeight: 600,
                  textTransform: "uppercase",
                }}
              >
                {isArabic ? selectedProject.nameAr : selectedProject.nameEn}
              </strong>
              <span style={{ display: "block", marginTop: 4, color: T.ACCENT_LIGHT, fontSize: 9, textTransform: "uppercase" }}>
                {isArabic ? selectedProject.typeAr : selectedProject.typeEn}
              </span>
              <span style={{ display: "block", marginTop: 5, color: T.TEXT_MUTED, fontSize: 9 }}>
                ◉ {isArabic ? selectedProject.locationAr : selectedProject.locationEn}
              </span>
              {detailsOpen && (
                <p style={{ margin: "9px 0 0", color: T.TEXT_SOFT, fontSize: 10, lineHeight: 1.6 }}>
                  {isArabic ? selectedProject.descriptionAr : selectedProject.descriptionEn}
                </p>
              )}
              <button
                type="button"
                onClick={() => setDetailsOpen((open) => !open)}
                style={{
                  width: "100%",
                  display: "flex",
                  justifyContent: "space-between",
                  marginTop: 8,
                  padding: "7px 9px",
                  border: `1px solid ${T.GLASS_BORDER_SOFT}`,
                  borderRadius: 8,
                  background: "rgba(32,30,28,.32)",
                  color: T.ACCENT_LIGHT,
                  fontFamily: "var(--font-display)",
                  fontSize: 9,
                  textAlign: "left",
                  cursor: "pointer",
                }}
              >
                <span>
                  {detailsOpen
                    ? isArabic
                      ? "إخفاء التفاصيل"
                      : "CLOSE DETAILS"
                    : isArabic
                      ? "عرض المشروع"
                      : "OPEN PROJECT"}
                </span>
                <span>{detailsOpen ? "↑" : "→"}</span>
              </button>
            </div>
          </section>
        )}

      </main>
    </div>
  );
}
