"use client";

import React, { useState, useEffect, useRef } from "react";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import Logo from "../../../public/images/header-logo.svg";
import SliverArrow from "../../../public/images/response-arrow.svg";
import PhoneIcon from "../../../public/images/phone.svg";
import ChevronDown from "../../../public/images/chevron-down.svg";
import HamburgerIcon from "../../../public/images/hamburger.svg";
import CloseDarkIcon from "../../../public/images/close-dark.svg";
import { HeaderProps, MainMenuItem } from "@/types/header";
import BookAnAppointmentModal from "@/components/CommonComponent/BookAppointmentModal";

export default function Header({ data }: HeaderProps) {
  const pathname = usePathname();
  const router = useRouter();
  const headerRef = useRef<HTMLDivElement>(null);

  // States
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [activeSubmenu, setActiveSubmenu] = useState<string | null>(null);
  const [isDesktopHamburgerOpen, setIsDesktopHamburgerOpen] = useState(false);
  const [wasDropdownOpen, setWasDropdownOpen] = useState(false);

  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [activeMobileCategory, setActiveMobileCategory] = useState<string | null>(null);
  const [mobileExpandedSubmenus, setMobileExpandedSubmenus] = useState<string[]>([]);
  const [activeLang, setActiveLang] = useState<"FR" | "EN">("FR");

  // Read initial language from cookie with default to French ("fr")
  useEffect(() => {
    try {
      const matches = document.cookie.match(/(?:^|; )lang=([^;]*)/);
      const cookieLang = matches ? matches[1] : null;

      if (cookieLang === "en") {
        setActiveLang("EN");
      } else {
        setActiveLang("FR");
        if (!cookieLang) {
          document.cookie = "lang=fr; path=/; max-age=31536000; SameSite=Lax";
        }
      }
    } catch (e) {
      setActiveLang("FR");
    }
  }, []);

  const handleLangChange = (lang: "FR" | "EN") => {
    setActiveLang(lang);
    document.cookie = `lang=${lang.toLowerCase()}; path=/; max-age=31536000; SameSite=Lax`;
    if (typeof window !== "undefined") {
      window.dispatchEvent(new Event("languageChange"));
    }
    router.refresh();
  };

  // Verify that data structure exists, otherwise return null
  if (!data || !data.header_data) {
    return null;
  }

  const { header_data, main_menu = [], secondary_menu = [] } = data;

  const logoSrc = header_data.logo
    ? header_data.logo.replace(/^http:\/\//, "https://")
    : Logo;
  const rawTelNumber = header_data.tel_url || header_data.contact;
  const telHref = rawTelNumber.trim().toLowerCase().startsWith("tel:")
    ? rawTelNumber.trim()
    : `tel:${rawTelNumber.replace(/\s+/g, "")}`;
  const telLogo = header_data.tel_logo
    ? header_data.tel_logo.replace(/^http:\/\//, "https://")
    : PhoneIcon;

  // Book appointment CTA
  const bookAppointmentCta = secondary_menu.find((item) => {
    const title = (item.title || "").toLowerCase();
    const url = (item.url || "").toLowerCase();
    return (
      title.includes("book") ||
      title.includes("appointment") ||
      title.includes("rendez-vous") ||
      title.includes("rdv") ||
      url.includes("book") ||
      url.includes("appointment") ||
      url.includes("rendez-vous")
    );
  }) || secondary_menu[0] || {
    title: activeLang === "FR" ? "Prendre rendez-vous" : "Book appointment",
    url: "/book-appointment",
    target: ""
  };

  // Hamburger items
  const hamburgerItems = secondary_menu.filter((item) => item !== bookAppointmentCta);

  const activeCategoryItem = main_menu.find((item) => item.title === activeMobileCategory);

  // Toggle category dropdown on click
  const handleDropdownClick = (label: string) => {
    if (activeDropdown === label) {
      setActiveDropdown(null);
      setActiveSubmenu(null);
      setWasDropdownOpen(false);
    } else {
      setWasDropdownOpen(activeDropdown !== null);
      setActiveDropdown(label);
      setActiveSubmenu(null);
      setIsDesktopHamburgerOpen(false);
    }
  };

  // Close all menus and drawers
  const closeAllMenus = () => {
    setActiveDropdown(null);
    setActiveSubmenu(null);
    setIsDesktopHamburgerOpen(false);
    setIsMobileMenuOpen(false);
    setActiveMobileCategory(null);
    setMobileExpandedSubmenus([]);
    setWasDropdownOpen(false);
  };

  // Click outside and escape handler
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (headerRef.current && !headerRef.current.contains(event.target as Node)) {
        setActiveDropdown(null);
        setActiveSubmenu(null);
        setIsDesktopHamburgerOpen(false);
        setWasDropdownOpen(false);
      }
    };

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        closeAllMenus();
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleEscape);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, []);

  // Scroll lock effect for mobile menu
  useEffect(() => {
    if (isMobileMenuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [isMobileMenuOpen]);

  // Blur handler for tabbing accessibility
  const handleContainerBlur = (e: React.FocusEvent) => {
    if (!e.currentTarget.contains(e.relatedTarget)) {
      setActiveDropdown(null);
      setActiveSubmenu(null);
      setIsDesktopHamburgerOpen(false);
      setWasDropdownOpen(false);
    }
  };

  // Helper: check if route is active
  const isLinkActive = (href?: string) => {
    if (!href) return false;
    return pathname === href;
  };

  const isCategoryActive = (item: MainMenuItem) => {
    if (isLinkActive(item.url)) return true;
    if (item.children) {
      return item.children.some((child) => {
        if (isLinkActive(child.url)) return true;
        if (child.children) {
          return child.children.some((subChild) => isLinkActive(subChild.url));
        }
        return false;
      });
    }
    return false;
  };

  // Helper: check if mobile category is active based on path
  const isMobileCategoryActive = (categoryLabel: string) => {
    const item = main_menu.find(i => i.title === categoryLabel);
    if (item) return isCategoryActive(item);

    // Check hamburger items/secondary menu
    const hamItem = hamburgerItems.find(i => i.title === categoryLabel);
    if (hamItem) return pathname === hamItem.url;

    return false;
  };

  // Toggle mobile accordion submenus
  const toggleMobileSubmenu = (label: string) => {
    setMobileExpandedSubmenus((prev) =>
      prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
    );
  };

  return (
    <header
      ref={headerRef}
      onBlur={handleContainerBlur}
      className="sticky top-0 z-50 w-full bg-white backdrop-white-md border-b border-[#E5E9ED] "
    >
      <div className="container">
        <div className="flex items-center justify-between py-5">

          {/* Logo */}
          <Link
            href="/"
            onClick={closeAllMenus}
            className="flex items-center"
          >
            <div className="w-[103px] md:w-[130px] relative">
              <Image
                src={logoSrc}
                width={130}
                height={40}
                alt="Oculus Cliniques Logo"
                style={{ width: '100%', height: 'auto' }}
                priority
              />
            </div>
          </Link>

          {/* Desktop Navigation */}
          <nav aria-label="Main Navigation" className="hidden nav:flex items-center">
            <ul className="flex items-center gap-2 xl:gap-4 2xl:gap-6">
              {main_menu.map((item) => {
                const hasChildren = !!item.children && item.children.length > 0;
                const isActive = isCategoryActive(item);
                const isOpen = activeDropdown === item.title;

                return (
                  <li key={item.title} className="relative">
                    {hasChildren ? (
                      <button
                        type="button"
                        onClick={() => handleDropdownClick(item.title)}
                        aria-expanded={isOpen}
                        aria-haspopup="true"
                        aria-controls={`dropdown-${item.title.toLowerCase().replace(/\s+/g, "-")}`}
                        className={`flex items-center gap-1.5 text-[16px] font-medium transition-colors duration-200 cursor-pointer rounded-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5] focus-visible:outline-offset-2 ${isOpen || isActive
                          ? "text-[#1718F5]"
                          : "text-[#334D72] hover:text-[#00204F]"
                          }`}
                      >
                        {item.title}
                        <Image
                          src={ChevronDown}
                          width={20}
                          height={20}
                          alt="arrow"
                          className={` shrink-0 transition-transform duration-300 ${isOpen ? "rotate-180" : ""}`}
                        />
                      </button>
                    ) : (
                      <Link
                        href={item.url || "#"}
                        onClick={closeAllMenus}
                        className={`block  text-[16px] font-medium transition-colors duration-200 rounded-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5] focus-visible:outline-offset-2 ${isActive
                          ? "text-[#1718F5]"
                          : "text-[#334D72] hover:text-[#00204F]"
                          }`}
                      >
                        {item.title}
                      </Link>
                    )}

                    {/* Desktop Hover Category Dropdowns */}
                    {hasChildren && (
                      <div
                        id={`dropdown-${item.title.toLowerCase().replace(/\s+/g, "-")}`}
                        className={`absolute top-full left-1/2 -translate-x-1/2 mt-2 w-64 bg-white border border-slate-100 shadow-xl rounded-2xl py-3 origin-top ${wasDropdownOpen ? "transition-none" : "transition-all duration-200"
                          } ${isOpen
                            ? "opacity-100 translate-y-0 scale-100 visible"
                            : "opacity-0 -translate-y-2 scale-95 invisible pointer-events-none"
                          }`}
                      >
                        <ul className="flex flex-col gap-0.5">
                          {item.children?.map((subItem) => {
                            const hasSubChildren = !!subItem.children && subItem.children.length > 0;
                            const isSubActive = isLinkActive(subItem.url) ||
                              (subItem.children?.some(c => isLinkActive(c.url)) ?? false);
                            const isSubmenuOpen = activeSubmenu === subItem.title;

                            return (
                              <li
                                key={subItem.title}
                                className="relative px-2"
                                onMouseEnter={() =>
                                  hasSubChildren
                                    ? setActiveSubmenu(subItem.title)
                                    : setActiveSubmenu(null)
                                }
                              >
                                {hasSubChildren ? (
                                  <>
                                    <Link
                                      href={subItem.url || "#"}
                                      onClick={closeAllMenus}
                                      aria-expanded={isSubmenuOpen}
                                      className={`w-full flex items-center justify-between py-2.5 px-3.5 rounded-xl text-[15px] font-semibold text-left transition-colors duration-200 cursor-pointer ${isSubmenuOpen || isSubActive
                                        ? "bg-[#EEF2FF] text-[#1718F5]"
                                        : "text-[#334D72] hover:bg-slate-50 hover:text-[#00204F]"
                                        }`}
                                    >
                                      <span>{subItem.title}</span>
                                      <Image
                                        src={SliverArrow}
                                        width={14}
                                        height={14}
                                        alt="arrow"
                                        className="w-4 h-4 shrink-0 opacity-60"
                                      />
                                    </Link>

                                    {/* Secondary Dropdown Panels */}
                                    <div
                                      className={`absolute left-full top-0 ml-1.5 w-64 bg-white border border-slate-100 shadow-xl rounded-2xl py-3 transition-all duration-200 origin-left ${isSubmenuOpen
                                        ? "opacity-100 translate-x-0 scale-100 visible"
                                        : "opacity-0 -translate-x-2 scale-95 invisible pointer-events-none"
                                        }`}
                                    >
                                      <ul className="flex flex-col gap-0.5">
                                        {subItem.children?.map((subSubItem) => {
                                          const isSubSubActive = isLinkActive(subSubItem.url);

                                          return (
                                            <li key={subSubItem.title} className="px-2">
                                              <Link
                                                href={subSubItem.url}
                                                onClick={closeAllMenus}
                                                className={`block py-2.5 px-3.5 rounded-xl text-[14px] font-semibold transition-colors duration-200 ${isSubSubActive
                                                  ? "bg-[#EEF2FF] text-[#1718F5]"
                                                  : "text-[#334D72] hover:bg-slate-50 hover:text-[#00204F]"
                                                  }`}
                                              >
                                                {subSubItem.title}
                                              </Link>
                                            </li>
                                          );
                                        })}
                                      </ul>
                                    </div>
                                  </>
                                ) : (
                                  <Link
                                    href={subItem.url || "#"}
                                    onClick={closeAllMenus}
                                    className={`block py-2.5 px-3.5 rounded-xl text-[15px] font-semibold transition-colors duration-200 ${isSubActive
                                      ? "bg-[#EEF2FF] text-[#1718F5]"
                                      : "text-[#334D72] hover:bg-slate-50 hover:text-[#00204F]"
                                      }`}
                                  >
                                    {subItem.title}
                                  </Link>
                                )}
                              </li>
                            );
                          })}
                        </ul>
                      </div>
                    )}
                  </li>
                );
              })}
            </ul>
          </nav>

          {/* Right Section widgets and Hamburger button */}
          <div className="flex items-center">

            {/* Phone Widget / Call Icon (Mobile Only) */}
            <Link
              href={telHref}
              className="nav:hidden flex items-center p-1 mr-2 text-[#334D72] hover:text-[#1718F5] transition-colors font-medium rounded-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5]"
            >
              <Image src={telLogo} width={32} height={32} alt="phone" className="shrink-0" />
            </Link>

            {/* Language Switcher */}
            <div className="flex items-center border border-[#E5E9F0] rounded-[8px] p-[3px] mr-3 md:mr-6 bg-white select-none">
              <button
                onClick={() => handleLangChange("FR")}
                className={`px-2 py-1 text-[14px] font-medium rounded-[6px] transition-all duration-300 cursor-pointer ${activeLang === "FR"
                  ? "bg-[#334D72] text-white shadow-sm"
                  : "text-[#334D72]"
                  }`}
              >
                FR
              </button>
              <button
                onClick={() => handleLangChange("EN")}
                className={`px-2 py-1 text-[14px] font-medium rounded-[6px] transition-all duration-300 cursor-pointer ${activeLang === "EN"
                  ? "bg-[#334D72] text-white shadow-sm"
                  : "text-[#334D72]"
                  }`}
              >
                EN
              </button>
            </div>

            {/* Book Appointment CTA */}
            {/* <Link
              href={bookAppointmentCta.url}
              className="hidden nav:inline-flex items-center justify-center px-5 py-2.5 mr-3 rounded-[8px] bg-[#1718F5] hover:bg-[#0004ff] text-white font-bold text-[16px] transition-all focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5] focus-visible:outline-offset-2 cursor-pointer shadow-md hover:shadow-lg"
            >
              {bookAppointmentCta.title}
            </Link> */}
            <div className="hidden min-[1240px]:block">
              <BookAnAppointmentModal
                buttonBgClass="bg-[#1718FF] !px-4 !py-2"
                buttonTextClass="text-[#fff]"
                buttonText={bookAppointmentCta.title}
                className="mr-3"
              />
            </div>

            {/* Desktop Hamburger (Visible on lg screens only) */}
            <div className="relative hidden nav:block">
              <button
                onClick={() => {
                  setIsDesktopHamburgerOpen(!isDesktopHamburgerOpen);
                  setActiveDropdown(null);
                  setActiveSubmenu(null);
                }}
                aria-expanded={isDesktopHamburgerOpen}
                aria-label="Toggle extra menu"
                className="flex items-center justify-center w-10 h-10 rounded-full border border-slate-200  text-[#1718F5] transition-all bg-white cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5]"
              >
                <Image
                  src={isDesktopHamburgerOpen ? CloseDarkIcon : HamburgerIcon}
                  width={22}
                  height={22}
                  alt="menu"
                  className="w-5 h-5 shrink-0"
                />
              </button>

              {/* Desktop Hamburger Dropdown Menu (Figma Image 1) */}
              {isDesktopHamburgerOpen && (
                <div
                  className="absolute right-0 top-full mt-2 w-56 bg-white border border-slate-100 shadow-xl rounded-2xl py-3 z-50 transition-all duration-200"
                >
                  <ul className="flex flex-col gap-0.5">
                    {hamburgerItems.map((hamburgerItem) => {
                      const isHamActive = isLinkActive(hamburgerItem.url);
                      return (
                        <li key={hamburgerItem.title} className="px-2">
                          <Link
                            href={hamburgerItem.url}
                            onClick={closeAllMenus}
                            className={`block py-2.5 px-4 rounded-xl font-semibold text-[15px] transition-colors duration-200 ${isHamActive
                              ? "bg-[#EEF2FF] text-[#1718F5]"
                              : "text-[#334D72] hover:bg-slate-50 hover:text-[#00204F]"
                              }`}
                          >
                            {hamburgerItem.title}
                          </Link>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              )}
            </div>

            {/* Mobile Hamburger (Visible on mobile/tablet only) */}
            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              aria-expanded={isMobileMenuOpen}
              aria-label="Toggle mobile navigation menu"
              className="flex nav:hidden items-center justify-center w-10 h-10 rounded-full border border-[#CCD2DC] text-[#1718F5] bg-white cursor-pointer  transition-all focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5]"
            >
              <Image
                src={isMobileMenuOpen ? CloseDarkIcon : HamburgerIcon}
                width={22}
                height={22}
                alt="menu"
                className="w-5 h-5 shrink-0"
              />
            </button>

          </div>

        </div>
      </div>

      {/* Mobile Drawer Backdrop Overlay */}
      {isMobileMenuOpen && (
        <div
          className="fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-xs transition-opacity duration-300 nav:hidden"
          onClick={closeAllMenus}
          aria-hidden="true"
        />
      )}

      {/* Mobile Slide-in Drawer (Figma Images 2, 3, 4) */}
      <aside
        className={`fixed inset-y-0 right-0 z-50 w-full h-dvh bg-white shadow-2xl pt-4 pb-10 px-5 flex flex-col justify-between transition-transform duration-300 ease-in-out transform nav:hidden overflow-x-hidden ${isMobileMenuOpen ? "translate-x-0" : "translate-x-full"
          }`}
        aria-label="Mobile Navigation"
      >
        {/* Header Row (Fixed size) */}
        <div className="flex-none flex items-center justify-between border-b border-slate-100 pb-2 mb-7">
          <Link href="/" onClick={closeAllMenus} className="outline-none">
            <div className="w-[120px] relative">
              <Image
                src={logoSrc}
                width={150}
                height={47}
                alt="Oculus Cliniques Logo"
                className="object-contain"
                style={{ width: '100%', height: 'auto' }}
              />
            </div>
          </Link>
          <button
            onClick={closeAllMenus}
            aria-label="Close menu"
            className="w-10 h-10 flex items-center justify-center rounded-full border border-slate-200 text-[#1718F5] transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#1718F5]"
          >
            <Image
              src={CloseDarkIcon}
              width={22}
              height={22}
              alt="close"
              className="w-5 h-5 shrink-0"
            />
          </button>
        </div>

        {/* Drill-down Navigation Body (Scrollable container) */}
        <div className="flex-1 overflow-hidden min-h-0 select-none">
          <div
            className="flex w-[200%] h-full transition-transform duration-300 ease-in-out"
            style={{
              transform: activeMobileCategory
                ? "translate3d(-50%, 0, 0)"
                : "translate3d(0, 0, 0)",
            }}
          >
            {/* Primary Mobile Menu Pane (Figma Image 2) - shrink-0 to prevent compression */}
            <div className="w-1/2 shrink-0 h-full overflow-y-auto pr-1 flex flex-col">
              <ul className="flex flex-col gap-1">
                {main_menu.map((item) => {
                  const hasChildren = !!item.children && item.children.length > 0;
                  if (hasChildren) {
                    return (
                      <li key={item.title} className="border-b border-[#E5E9ED]">
                        <button
                          type="button"
                          onClick={() => setActiveMobileCategory(item.title)}
                          className={`w-full flex items-center justify-between py-3 transition-colors cursor-pointer ${activeMobileCategory === item.title || isMobileCategoryActive(item.title)
                            ? "text-[#1718F5]"
                            : "text-[#00204F] hover:text-[#1718F5]"
                            }`}
                        >
                          <span className="text-[16px] text-[#00204F] font-medium">{item.title}</span>
                          <Image src={SliverArrow} width={20} height={20} alt="arrow" />
                        </button>
                      </li>
                    );
                  } else {
                    return (
                      <li key={item.title} className="border-b border-[#E5E9ED]">
                        <Link
                          href={item.url || "#"}
                          onClick={closeAllMenus}
                          className={`block py-3 text-[16px] font-medium transition-colors ${isMobileCategoryActive(item.title) ? "text-[#1718F5]" : "text-[#00204F] hover:text-[#1718F5]"
                            }`}
                        >
                          {item.title}
                        </Link>
                      </li>
                    );
                  }
                })}

                {hamburgerItems.map((item) => (
                  <li key={item.title} className="border-b border-[#E5E9ED]">
                    <Link
                      href={item.url || "#"}
                      onClick={closeAllMenus}
                      className={`block py-3 text-[16px] font-medium transition-colors ${isMobileCategoryActive(item.title) ? "text-[#1718F5]" : "text-[#00204F] hover:text-[#1718F5]"
                        }`}
                    >
                      {item.title}
                    </Link>
                  </li>
                ))}
              </ul>
            </div>

            {/* Secondary Submenu Pane (Figma Image 3 & 4) - shrink-0 to prevent compression */}
            <div className="w-1/2 shrink-0 h-full overflow-y-auto pr-1 flex flex-col">

              {/* Back Button */}
              <button
                type="button"
                onClick={() => setActiveMobileCategory(null)}
                className="flex items-center gap-2 py-2 text-[18px] font-bold text-[#00204F]  transition-colors focus-visible:outline-none cursor-pointer"
              >
                <Image
                  src={SliverArrow}
                  width={20}
                  height={20}
                  alt="back"
                  className="w-5 h-5 shrink-0 rotate-180 opacity-60"
                />
                {activeMobileCategory}
              </button>

              {/* Sub-menu Content Container */}
              <div className="bg-[#F8FAFC] rounded-[24px] p-4.5 flex flex-col mt-4">
                {activeCategoryItem?.children && (
                  <ul className="flex flex-col">
                    {activeCategoryItem.children.map((subItem, index, arr) => {
                      const hasSubChildren = !!subItem.children && subItem.children.length > 0;
                      const uniqueKey = `${activeMobileCategory}-${subItem.title}`;
                      const isExpanded = mobileExpandedSubmenus.includes(uniqueKey);

                      if (hasSubChildren) {
                        return (
                          <li
                            key={subItem.title}
                            className={index !== arr.length - 1 ? "border-b border-slate-200/60" : ""}
                          >
                            <div
                              className={`w-full flex items-center justify-between py-3.5 px-1 text-[15px] font-bold transition-colors ${isExpanded || subItem.children?.some(c => isLinkActive(c.url))
                                ? "text-[#1718F5]"
                                : "text-[#334D72]"
                                }`}
                            >
                              <Link
                                href={subItem.url || "#"}
                                onClick={closeAllMenus}
                                className="hover:text-[#1718F5] grow text-left"
                              >
                                {subItem.title}
                              </Link>
                              <button
                                type="button"
                                onClick={() => toggleMobileSubmenu(uniqueKey)}
                                aria-expanded={isExpanded}
                                aria-label={`Toggle ${subItem.title} submenu`}
                                className="cursor-pointer p-1 -mr-1"
                              >
                                <Image
                                  src={ChevronDown}
                                  width={14}
                                  height={14}
                                  alt="arrow"
                                  className={`w-4 h-4 shrink-0 opacity-60 transition-transform duration-300 ${isExpanded ? "rotate-180" : ""
                                    }`}
                                />
                              </button>
                            </div>
                            <div
                              className={`overflow-hidden transition-all duration-300 ${isExpanded ? "max-h-[300px] opacity-100 mt-1 mb-2" : "max-h-0 opacity-0"
                                }`}
                            >
                              <ul className="pl-4 border-l border-slate-200 flex flex-col gap-1.5">
                                {subItem.children?.map((subSubItem) => (
                                  <li key={subSubItem.title}>
                                    <Link
                                      href={subSubItem.url || "#"}
                                      onClick={closeAllMenus}
                                      className={`block py-1.5 text-[14px] font-semibold transition-colors ${isLinkActive(subSubItem.url)
                                        ? "text-[#1718F5]"
                                        : "text-slate-500 hover:text-[#1718F5]"
                                        }`}
                                    >
                                      {subSubItem.title}
                                    </Link>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          </li>
                        );
                      } else {
                        return (
                          <li
                            key={subItem.title}
                            className={index !== arr.length - 1 ? "border-b border-slate-200/60" : ""}
                          >
                            <Link
                              href={subItem.url || "#"}
                              onClick={closeAllMenus}
                              className={`block py-3.5 px-1 text-[15px] font-bold transition-colors ${isLinkActive(subItem.url)
                                ? "text-[#1718F5]"
                                : "text-[#334D72] hover:text-[#1718F5]"
                                }`}
                            >
                              {subItem.title}
                            </Link>
                          </li>
                        );
                      }
                    })}
                  </ul>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Drawer Footer (Persistent Call Widget + CTA Button - Fixed size) */}
        <div className="flex-none  flex flex-col gap-4">

          {/* Phone call widget */}
          {/* <Link
            href={telUrl}
            className="flex items-center justify-center gap-3 py-2 px-1 text-[#334D72] hover:text-[#1718F5] transition-colors"
          >
            <Image src={telLogo} width={30} height={30} alt="phone" className="shrink-0" />
            <span className="text-[16px] font-medium leading-none text-[#334D72]">
              <strong className="text-[#00204F] font-bold">{contactNumber}</strong>
            </span>
          </Link> */}

          {/* Book Appointment Full-Width modal*/}
          <BookAnAppointmentModal
            buttonBgClass="bg-[#1718FF]"
            buttonTextClass="text-[#fff]"
            buttonText={bookAppointmentCta.title}
            className="mr-3 justify-center"
          />
        </div>

      </aside>
    </header>
  );
}