'use client';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger
} from '@/components/ui/collapsible';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarProvider,
  SidebarRail,
  SidebarTrigger
} from '@/components/ui/sidebar';
import { navItems } from '@/constants/data';
import {
  AlertTriangle,
  Bell,
  Calendar,
  ChevronRight,
  CircleDollarSign,
  CircleHelp,
  Clock,
  FileText,
  GalleryVerticalEnd,
  Landmark,
  LogOut,
  Percent,
  Phone,
  Tag,
  Trash,
  MessageCircleQuestion,
  ScrollText,
  Menu,
  Home,
  LayoutDashboard,
  ShoppingCart,
  MenuSquare,
  Wallet,
  Star,
  Image,
  CalendarCheck2,
  Utensils,
  ListChecks,
  Store,
  BadgeDollarSign,
  Monitor,
  ClipboardList,
  ShoppingBasket,
  Truck
} from 'lucide-react';
import Link from 'next/link';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import * as React from 'react';
import { Icons } from '../icons';
import { Button } from '../ui/button';
import { useGlobalContext } from '@/context/Provider';
import { ScrollArea } from '../ui/scroll-area';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import SidebarModal from '../rightSidebar/page';
import ProfileImg from '../../assets/images/profileimg.png';
import CurrencyDialog from './CurrencyDialog';
import { useBreadcrumbs } from '@/hooks/use-breadcrumbs';
import LogoutDialog from '../ui/logoutModal';
import moment from 'moment';
import { Switch } from '../ui/switch';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';

export const company = {
  name: 'Acme Inc',
  logo: GalleryVerticalEnd,
  plan: 'Enterprise'
};

const pageSts: any = {
  ongoing: 'Ongoing',
  pending: 'Requested',
  prepared: 'Accepted',
  ready: 'Ready',
  picked: 'Picked',
  delivered: 'Completed',
  scheduled: 'Scheduled',
  cancelled: 'Cancelled'
};

const subSts: any = {
  request: 'Request',
  pause: 'Pause',
  cancelled: 'Cancelled'
};

const pageTyp: any = {
  today: 'Today',
  week: 'This week',
  month: 'This month',
  year: 'This Year'
};

export default function AppSidebar({
  children
}: {
  children: React.ReactNode;
}) {
  const items = useBreadcrumbs();
  const [currencyModal, setcurrencyModal] = React.useState(false);
  const [logoutModal, setLogoutModal] = React.useState(false);
  const [mounted, setMounted] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const pageStatus = searchParams.get('status');
  const pageType = searchParams.get('type');
  const [selectedOption, setSelectedOption] = React.useState<any>(null);
  const [showVerificationModal, setShowVerificationModal] = React.useState(false);

  const { userInfo, setUserInfo, activeModal, setActiveModal, Toast, getProfile, statusCounts, setStatusCounts } = useGlobalContext();
  const [localStatusCounts, setLocalStatusCounts] = React.useState<any>(null);

  React.useEffect(() => {
    const handler = (e: any) => {
      if (e.detail) {
        setLocalStatusCounts(e.detail);
      }
    };
    window.addEventListener('statusCountsUpdated', handler);
    return () => window.removeEventListener('statusCountsUpdated', handler);
  }, []);

  const activeCounts = statusCounts || localStatusCounts;

  const fetchStatusCounts = React.useCallback(async () => {
    if (!userInfo?.restaurant_id?._id) return;
    try {
      const res = await apis.Orders.get(
        new URLSearchParams({
          restaurant_id: userInfo.restaurant_id._id,
          page: '1',
          limit: '1'
        }).toString()
      );
      if (res?.status_counts) {
        setStatusCounts?.(res.status_counts);
        setLocalStatusCounts(res.status_counts);
      }
    } catch (err) {
      console.error('Error fetching status counts:', err);
    }
  }, [userInfo?.restaurant_id?._id, setStatusCounts]);

  React.useEffect(() => {
    if (userInfo?.restaurant_id?._id && pathname?.startsWith('/orders')) {
      fetchStatusCounts();
    }
  }, [userInfo?.restaurant_id?._id, pathname, fetchStatusCounts]);

  const getOrderTabCount = (label: string) => {
    if (!activeCounts) return null;
    const l = label.toLowerCase();
    if (l === 'ongoing') return activeCounts.ongoing_count ?? null;
    if (l === 'completed' || l === 'delivered') return activeCounts.delivered ?? null;
    if (l === 'requested' || l === 'pending') return activeCounts.pending ?? null;
    if (l === 'accepted' || l === 'prepared' || l === 'preparing') return activeCounts.prepared ?? null;
    if (l === 'ready') return activeCounts.ready ?? null;
    if (l === 'picked') return activeCounts.picked_up ?? null;
    if (l === 'scheduled') return activeCounts.scheduled ?? null;
    if (l === 'cancelled') return activeCounts.cancelled ?? null;
    return null;
  };

  const rawType = userInfo?.restaurant_id?.type || 'grocery';
  const typeLabel = rawType === 'food' ? 'Grocery' : rawType.charAt(0).toUpperCase() + rawType.slice(1);

  const getDisplayTitle = (title: string) => {
    if (!title) return '';
    if (title === 'Grocery POS' || title === 'Point of Sale' || title.endsWith(' POS')) return 'POS';
    if (title === 'Grocery POS Order List' || title === 'POS Order List' || title.endsWith(' POS Order List')) return 'POS Order List';
    if (title === 'Grocery') return typeLabel;
    if (title.startsWith('Grocery ')) {
      return title.replace('Grocery', typeLabel);
    }
    return title;
  };
  const [resOpen, setResOpen] = React.useState<boolean>(true);
  const desktopScrollAreaRef = React.useRef<HTMLDivElement>(null);
  const mobileScrollAreaRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    setMounted(true);
  }, []);

  React.useEffect(() => {
    if (mounted) {
      const restoreScroll = (ref: React.RefObject<HTMLDivElement>, key: string) => {
        if (!ref.current) return;

        const viewport = ref.current.querySelector('[data-radix-scroll-area-viewport]');
        if (viewport instanceof HTMLElement) {
          // Restore saved position
          const savedPos = sessionStorage.getItem(key);
          if (savedPos) {
            viewport.scrollTop = parseInt(savedPos, 10);
          }

          // Ensure active item is visible if it's the first mount of this session/page
          const activeItem = ref.current.querySelector('[data-active="true"]');
          if (activeItem instanceof HTMLElement) {
            activeItem.scrollIntoView({ block: 'nearest' });
          }

          const handleScroll = (e: Event) => {
            const target = e.target as HTMLElement;
            sessionStorage.setItem(key, target.scrollTop.toString());
          };

          viewport.addEventListener('scroll', handleScroll);
          return () => viewport.removeEventListener('scroll', handleScroll);
        }
      };

      const cleanupDesktop = restoreScroll(desktopScrollAreaRef, 'sidebar-desktop-scroll');
      const cleanupMobile = restoreScroll(mobileScrollAreaRef, 'sidebar-mobile-scroll');

      return () => {
        cleanupDesktop?.();
        cleanupMobile?.();
      };
    }
  }, [mounted, pathname]);

  React.useEffect(() => {
    if (userInfo?.restaurant_id?.is_restaurant_verified === false) {
      setResOpen(false);
    } else {
      setResOpen(userInfo?.restaurant_id?.status === 'online' ? true : false);
    }
  }, [userInfo]);

  React.useEffect(() => {
    if (pageType) {
      setSelectedOption(pageTyp?.[pageType]);
    } else if (pageStatus) {
      const displayStatus = subSts?.[pageStatus] || pageSts?.[pageStatus];
      setSelectedOption(displayStatus);
    }
  }, [pageStatus, pageType]);

  if (!mounted) {
    return null;
  }

  function cleanUrl(url: string) {
    if (!url) return '';
    const clean = url.split('?')[0];
    const idRegex = /\/[a-f0-9]{24}(\/|$)/;
    const idMatch = clean.match(idRegex);

    if (idMatch) {
      return clean.substring(0, idMatch.index);
    }
    if (clean.includes('generate')) {
      const pageIndex = clean.indexOf('/generate');
      return clean.substring(0, pageIndex);
    }

    const pageIndex = clean.indexOf('/page');
    if (pageIndex !== -1) {
      return clean.substring(0, pageIndex);
    }

    return clean;
  }

  const lastItemTitle = items?.[0]?.title;

  const filterOptions: { [key: string]: string[] } = {
    Earning: ['Today', 'This week', 'This month'],
    Orders: [
      'Ongoing',
      // 'Requested',
      // 'Scheduled',
      // 'Accepted',
      // 'Ready',
      // 'Picked',
      'Completed',
      // 'Cancelled'
    ],
    Subscriptions: ['Request', 'Pause', 'Cancelled']
  };

  const activeTitle =
    lastItemTitle && filterOptions[lastItemTitle] ? lastItemTitle : null;

  const handleFilterClick = (filter: string) => {
    setSelectedOption(filter);
    const orderRoutes: Record<string, string> = {
      Ongoing: '/orders/ongoing?status=ongoing&page=1&limit=15',
      Requested: '/orders/requested?status=pending&page=1&limit=15',
      Accepted: '/orders/prepared?status=prepared&page=1&limit=15',
      Scheduled: '/orders/scheduled?status=scheduled&page=1&limit=15',
      Ready: '/orders/ready?status=ready&page=1&limit=15',
      Picked: '/orders/picked?status=picked_up&page=1&limit=15',
      Delivered: '/orders/delivered?status=delivered&page=1&limit=15',
      Completed: '/orders/delivered?status=delivered&page=1&limit=15',
      Cancelled: '/orders/cancelled?status=cancelled&page=1&limit=15'
    };
    const subscriberRoutes: Record<string, string> = {
      Request: '/subscriptions/request?status=request&page=1&limit=15',
      Pause: '/subscriptions/pause?status=pause&page=1&limit=15',
      Cancelled: '/subscriptions/cancelled?status=cancelled&page=1&limit=15'
    };

    const earningRoutes: Record<string, string> = {
      Today: '/earning?type=today&page=1&limit=10',
      'This week': '/earning?type=week&page=1&limit=10',
      'This month': '/earning?type=month&page=1&limit=10',
      'This Year': '/earning?type=year&page=1&limit=10'
    };

    const route =
      orderRoutes[filter] || earningRoutes[filter] || subscriberRoutes[filter];

    if (route) {
      router.push(route);
      setMobileOpen(false);
    }
  };

  const sidebarIcons: Record<string, React.ReactElement> = {
    Dashboard: <LayoutDashboard size={20} />,
    Home: <Home size={20} />,
    Notification: <Bell size={20} />,
    Orders: <ShoppingCart size={20} />,
    Menu: <MenuSquare size={20} />,
    Earning: <Wallet size={20} />,
    'Vendor Wallet': <Landmark size={20} />,
    Reviews: <Star size={20} />,
    Drivers: <Truck size={20} />,
    Banner: <Image size={20} />,
    'Snap and Order': <MessageCircleQuestion size={20} />,
    'Customer Queries': <MessageCircleQuestion size={20} />,
    Documents: <FileText size={20} />,
    'Dineout Bookings': <CalendarCheck2 size={20} />,
    Catering: <Utensils size={20} />,
    'Catering List': <ListChecks size={20} />,
    'Catering Menu': <Store size={20} />,
    'Auto-Renew Orders': <BadgeDollarSign size={20} />,
    'Point of Sale': <Monitor size={20} />,
    'POS Order List': <ClipboardList size={20} />,
    Grocery: <ShoppingBasket size={20} />,
    'Grocery Category': <ListChecks size={20} />,
    'Category Requests': <MessageCircleQuestion size={20} />,
    'Grocery POS': <Monitor size={20} />,
    'Grocery POS Order List': <ClipboardList size={20} />,
  };


  const toggleRes = async (type: any) => {
    if (userInfo?.restaurant_id?.is_restaurant_verified === false) {
      setShowVerificationModal(true);
      setResOpen(false);
      return;
    }
    try {
      const params = new URLSearchParams({
        status: type ? 'online' : 'offline',
        restaurant_id: userInfo?.restaurant_id?._id
      });

      const apiRes = await apis.Auth.resUpdate(params.toString());
      setResOpen(type);
      if (setUserInfo) {
        setUserInfo((prev: any) => {
          if (!prev) return prev;
          return {
            ...prev,
            restaurant_id: {
              ...prev.restaurant_id,
              status: type ? 'online' : 'offline'
            }
          };
        });
      }
      if (getProfile) {
        getProfile();
      }
      if (typeof window !== 'undefined') {
        window.dispatchEvent(
          new CustomEvent('vendorStatusChanged', {
            detail: { status: type ? 'online' : 'offline' }
          })
        );
      }
    } catch (error) {
      Toast.error(error);
    }
  };

  // Render navigation menu items
  const renderNavItems = () => {
    return navItems
      .filter((item) => {
        if (item.title === 'Auto-Renew Orders') {
          return (
            userInfo?.restaurant_id?.restaurant_type === 'home-cooked-meal'
          );
        }
        if (['Catering Menu', 'Catering List', 'Catering'].includes(item.title)) {
          return userInfo?.restaurant_id?.catering_services === true;
        }
        if (userInfo?.restaurant_id?.type === 'food') {
          return !['Grocery', 'Grocery Category', 'Category Requests', 'Grocery POS', 'Grocery POS Order List', 'Snap and Order', 'Customer Queries'].includes(item.title);
        } else {
          return !['Menu', 'Dineout Bookings', 'Point of Sale', 'POS Order List'].includes(item.title);
        }
        return true;
      })
      .map((item) => {
        const path = pathname?.split('/');
        const isActiveParent =
          pathname === item?.url ||
          item?.items?.some(
            (subItem) => cleanUrl(pathname) === cleanUrl(subItem?.url)
          );

        if (item?.items && item?.items?.length > 0) {
          return (
            <Collapsible
              key={item.title}
              asChild
              defaultOpen={isActiveParent}
              className="group/collapsible"
            >
              <SidebarMenuItem>
                <CollapsibleTrigger asChild>
                  <SidebarMenuButton
                    tooltip={getDisplayTitle(item.title)}
                    isActive={isActiveParent}
                  >
                    <span>{getDisplayTitle(item?.title)}</span>
                    <ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
                  </SidebarMenuButton>
                </CollapsibleTrigger>
                <CollapsibleContent>
                  <SidebarMenuSub className="pl-0">
                    {item.items?.map((subItem) => (
                      <SidebarMenuSubItem key={subItem.title}>
                        <SidebarMenuSubButton
                          className="pl-0"
                          asChild
                          isActive={
                            cleanUrl(pathname) === cleanUrl(subItem.url)
                          }
                        >
                          <Link
                            href={subItem.url}
                            onClick={() => setMobileOpen(false)}
                          >
                            <span>
                              <Icons.Minus />
                            </span>
                            <span>{getDisplayTitle(subItem.title)}</span>
                          </Link>
                        </SidebarMenuSubButton>
                      </SidebarMenuSubItem>
                    ))}
                  </SidebarMenuSub>
                </CollapsibleContent>
              </SidebarMenuItem>
            </Collapsible>
          );
        } else if (item.isSidebar) {
          return (
            <SidebarMenuItem key={item.title}>
              <SidebarMenuButton
                asChild
                tooltip={getDisplayTitle(item.title)}
                isActive={cleanUrl(pathname) === cleanUrl(item.url)}
              >
                <div
                  onClick={() => {
                    setActiveModal(item.url);
                    setMobileOpen(false);
                  }}
                  style={{ cursor: 'pointer' }}
                >
                  {sidebarIcons?.[item.title]}
                  <span>{getDisplayTitle(item.title)}</span>
                </div>
              </SidebarMenuButton>
            </SidebarMenuItem>
          );
        } else {
          return (
            <SidebarMenuItem key={item.title}>
              <SidebarMenuButton
                asChild
                tooltip={getDisplayTitle(item.title)}
                isActive={
                  item.title === 'Point of Sale'
                    ? pathname === '/point-of-sale'
                    : item.title === 'POS Order List'
                      ? pathname.startsWith('/pos-order-list')
                      : item.title === 'Earning'
                        ? pathname.startsWith('/earning')
                        : !!(
                          path?.[1] &&
                          item.url.split('?')[0].split('/')[1] === path[1]
                        )
                }
              >
                <Link href={item.url} onClick={() => setMobileOpen(false)}>
                  {sidebarIcons?.[item.title]}
                  <span>{getDisplayTitle(item.title)}</span>
                </Link>
              </SidebarMenuButton>
            </SidebarMenuItem>
          );
        }
      });
  };

  // Render profile dropdown menu items
  const renderProfileDropdown = (isMobile: boolean = false) => {
    const iconSize = isMobile ? 14 : 15;
    const boxSize = isMobile ? 'h-6 w-6' : 'h-[24px] w-[24px]';

    return (
      <>
        <DropdownMenuItem onClick={() => setActiveModal('profile')}>
          <div className="flex w-full flex-row gap-3 md:gap-4">
            <div className="flex items-center justify-center flex-shrink-0">
              {userInfo?.image ? (
                <img
                  src={BUCKET_ROOT + userInfo?.image}
                  className="h-10 w-10 rounded-full object-cover"
                  alt="Profile"
                />
              ) : (
                <img
                  src={ProfileImg.src}
                  className="h-10 w-10 rounded-full object-cover"
                  alt="Profile"
                />
              )}
            </div>
            <div className="flex flex-col items-start justify-center min-w-0 flex-1">
              <span className="text-sm font-semibold text-[#2a2a2a] truncate w-full">
                {userInfo?.restaurant_id?.restaurant_name}
              </span>
              <span className="text-xs font-medium text-[#999999] truncate w-full">
                {userInfo?.email}
              </span>
              <span className="flex flex-row items-center gap-1 md:gap-2 text-xs font-normal text-[#121212] mt-1">
                Edit Profile <ChevronRight size={isMobile ? 12 : 15} />
              </span>
            </div>
          </div>
        </DropdownMenuItem>

        <DropdownMenuItem onClick={() => setActiveModal('bankDetails')}>
          <div
            className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
          >
            <Landmark size={iconSize} color="white" />
          </div>
          <span className="ml-2 text-sm font-normal">Bank Details</span>
        </DropdownMenuItem>

        <DropdownMenuItem onClick={() => setActiveModal('accountDelete')}>
          <div
            className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
          >
            <Trash size={iconSize} color="white" />
          </div>
          <span className="ml-2 text-sm font-normal">Delete Account</span>
        </DropdownMenuItem>

        <DropdownMenuItem onClick={() => setActiveModal('timings')}>
          <div
            className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
          >
            <Clock size={iconSize} color="white" />
          </div>
          <span className="ml-2 text-sm font-normal">Timing</span>
        </DropdownMenuItem>

        {userInfo?.restaurant_id?.type === 'food' && (
          <DropdownMenuItem onClick={() => setActiveModal('dineout')}>
            <div
              className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
            >
              <Clock size={iconSize} color="white" />
            </div>
            <span className="ml-2 text-sm font-normal">DineOut Timing</span>
          </DropdownMenuItem>
        )}

        <DropdownMenuItem onClick={() => setActiveModal('support')}>
          <div
            className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
          >
            <CircleHelp size={iconSize} color="white" />
          </div>
          <span className="ml-2 text-sm font-normal">Support</span>
        </DropdownMenuItem>

        {/* {userInfo?.restaurant_id?.type === 'food' && (
          <DropdownMenuItem onClick={() => setActiveModal('discount')}>
            <div
              className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
            >
              <Percent size={iconSize} color="white" />
            </div>
            <span className="ml-2 text-sm font-normal">Discount</span>
          </DropdownMenuItem>
        )} */}

        <DropdownMenuItem>
          <Link
            href={'https://readyeats.henceforthsolutions.com/terms'}
            target="_blank"
            className="flex flex-row w-full"
          >
            <div
              className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
            >
              <FileText size={iconSize} color="white" />
            </div>
            <span className="ml-2 text-sm font-normal">Terms of Service</span>
          </Link>
        </DropdownMenuItem>

        <DropdownMenuItem>
          <Link
            href={'https://readyeats.henceforthsolutions.com/about'}
            target="_blank"
            className="flex flex-row w-full"
          >
            <div
              className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
            >
              <FileText size={iconSize} color="white" />
            </div>
            <span className="ml-2 text-sm font-normal">About us</span>
          </Link>
        </DropdownMenuItem>

        <DropdownMenuItem>
          <Link
            href={'https://readyeats.henceforthsolutions.com/vendor_policy'}
            target="_blank"
            className="flex flex-row w-full"
          >
            <div
              className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
            >
              <FileText size={iconSize} color="white" />
            </div>
            <span className="ml-2 text-sm font-normal">Privacy policy</span>
          </Link>
        </DropdownMenuItem>

        <DropdownMenuItem onClick={() => setActiveModal('faq')}>
          <div
            className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
          >
            <MessageCircleQuestion size={iconSize} color="white" />
          </div>
          <span className="ml-2 text-sm font-normal">FAQ</span>
        </DropdownMenuItem>

        <DropdownMenuSeparator />

        <DropdownMenuItem onClick={() => setLogoutModal(true)}>
          <div
            className={`flex ${boxSize} items-center justify-center rounded-md bg-[var(--orange-500)]`}
          >
            <LogOut size={iconSize} color="white" />
          </div>
          <span className="ml-2 text-sm font-normal">Log out</span>
        </DropdownMenuItem>
      </>
    );
  };

  return (
    <>
      <SidebarProvider className="sidebar-layout">
        {/* ========== MOBILE LAYOUT ========== */}
        <div className="md:hidden w-full flex flex-col h-screen">
          {/* Mobile Header */}
          <header className="sticky top-0 z-50 bg-white border-b px-4 py-3 flex-shrink-0">
            <div className="flex items-center justify-between mb-3">
              {/* Mobile Menu Toggle */}
              <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
                <SheetTrigger asChild>
                  <Button variant="outline" size="icon" className="h-9 w-9">
                    <Menu className="h-5 w-5" />
                  </Button>
                </SheetTrigger>
                <SheetContent side="left" className="w-[280px] p-0">
                  <div className="flex h-full w-full flex-col bg-sidebar">
                    {/* Mobile Sidebar Header */}
                    <SidebarHeader>
                      <div className="border-b-2 border-gray-200 pb-4">
                        <Link href={'/dashboard'}>
                          <span className="text-xl font-bold text-[#1C1D22]">
                            {userInfo?.restaurant_id?.restaurant_name}
                          </span>
                        </Link>
                      </div>
                    </SidebarHeader>

                    {/* Mobile Sidebar Content */}
                    <ScrollArea
                      ref={mobileScrollAreaRef}
                      className={
                        userInfo?.current_plan?.plan_name
                          ? `h-[calc(100vh-200px)]`
                          : `h-[calc(100vh-150px)]`
                      }
                    >
                      <SidebarContent className="overflow-x-hidden">
                        <SidebarGroup>
                          <SidebarMenu>{renderNavItems()}</SidebarMenu>
                        </SidebarGroup>
                      </SidebarContent>
                    </ScrollArea>
                  </div>
                </SheetContent>
              </Sheet>

              {/* Mobile Restaurant Name */}
              <h1 className="text-base font-semibold text-[#1C1D22] truncate flex-1 mx-3">
                {userInfo?.restaurant_id?.restaurant_name}
              </h1>

              {/* Mobile Profile Dropdown */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <button className="h-9 w-9 rounded-full flex-shrink-0 overflow-hidden">
                    {userInfo?.image ? (
                      <img
                        src={BUCKET_ROOT + userInfo?.image}
                        className="h-9 w-9 rounded-full object-cover"
                        alt="Profile"
                      />
                    ) : (
                      <img
                        src={ProfileImg.src}
                        className="h-9 w-9 rounded-full object-cover"
                        alt="Profile"
                      />
                    )}
                  </button>
                </DropdownMenuTrigger>
                <DropdownMenuContent
                  className="w-72 bg-white p-3 font-semibold"
                  align="end"
                >
                  {renderProfileDropdown(true)}
                </DropdownMenuContent>
              </DropdownMenu>
            </div>

            {/* Mobile Welcome and Date */}
            <div className="flex items-center justify-between text-xs mb-2">
              <span className="font-semibold text-[#1C1D22] truncate flex-1">
                Welcome, {userInfo?.name} 👋
              </span>
              <div className="flex items-center gap-1 text-[#999999] ml-2 flex-shrink-0">
                <Calendar size={14} />
                <span className="whitespace-nowrap">
                  {moment().format('D MMM YY')}
                </span>
              </div>
            </div>

            {/* Mobile Restaurant Status Toggle */}
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-medium">
                <span className={resOpen ? 'text-green-500' : 'text-red-500'}>
                  Vendor is {resOpen ? 'open' : 'closed'}
                </span>
              </span>
              <Switch
                checked={resOpen}
                onCheckedChange={() => toggleRes(!resOpen)}
                className="scale-90"
              />
            </div>

            {/* Mobile Filter Tabs */}
            {activeTitle && (
              <div className="flex gap-1 overflow-x-auto pb-1 -mx-4 px-4 no-scrollbar">
                {filterOptions[activeTitle].map((label) => {
                  const count = activeTitle === 'Orders' ? getOrderTabCount(label) : null;
                  return (
                    <button
                      key={label}
                      className={`px-3 py-1.5 text-xs font-semibold whitespace-nowrap rounded-md transition-colors inline-flex items-center gap-1.5 ${label === selectedOption
                        ? 'text-[#1C1D22] bg-gray-100'
                        : 'text-[#999999]'
                        }`}
                      onClick={() => handleFilterClick(label)}
                    >
                      <span>{label}</span>
                      {count !== null && count !== undefined && (
                        <span
                          className="text-[10px] px-1.5 py-0.5 rounded-full font-bold leading-none text-white shadow-sm"
                          style={{ backgroundColor: 'var(--primary-brand)', color: '#ffffff' }}
                        >
                          {count}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            )}
          </header>

          {/* Mobile Content */}
          <div className="flex-1 overflow-auto bg-gray-100">{children}</div>
        </div>

        {/* ========== DESKTOP LAYOUT ========== */}
        <div className="hidden md:flex w-full h-screen overflow-hidden">
          {/* Desktop Sidebar */}
          <Sidebar collapsible="icon">
            <SidebarHeader>
              <div className="border-common flex items-center justify-center gap-6 border-b-2 pb-6 text-sidebar-primary-foreground">
                <div className="group-data-[collapsible=icon]:hidden">
                  <Link href={'/dashboard'}>
                    <span className="text-[30px] font-[700] text-[#1C1D22]">
                      {userInfo?.restaurant_id?.restaurant_name}
                    </span>
                  </Link>
                </div>
                <Button
                  type="button"
                  variant="outline"
                  className="h-[36px] w-[36px] rounded-full bg-[#1C1D2214] p-0"
                >
                  <SidebarTrigger className="" />
                </Button>
              </div>
            </SidebarHeader>

            <ScrollArea
              ref={desktopScrollAreaRef}
              className={
                userInfo?.current_plan?.plan_name
                  ? `h-[calc(100vh-328px)]`
                  : `h-[calc(100vh-200px)]`
              }
            >
              <SidebarContent className="overflow-x-hidden">
                <SidebarGroup>
                  <SidebarMenu>{renderNavItems()}</SidebarMenu>
                </SidebarGroup>
              </SidebarContent>
            </ScrollArea>

            <SidebarRail />
          </Sidebar>

          {/* Desktop Main Content Area */}
          <SidebarInset className="flex h-full max-h-[100vh] min-h-0 w-full flex-col overflow-hidden">
            {/* Desktop Header */}
            <header className="header flex shrink-0 flex-col items-center justify-between gap-1 px-5 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12">
              <div className="mt-1 flex w-full flex-row justify-between">
                <div className="flex items-center gap-2">
                  <span className="text-[20px] font-[700] text-[#1C1D22]">
                    Welcome back, {userInfo?.name} 👋
                  </span>
                </div>

                <div className="flex flex-col">
                  <div className="flex flex-row items-center gap-2">
                    {/* Date Card */}
                    <div className="profile-card-1 flex h-11 flex-row items-center gap-4 rounded-lg bg-white px-3">
                      <div className="flex items-center justify-center gap-1">
                        <Calendar size={18} />
                        <p className="text-[16px] font-medium text-[#999999]">
                          {moment().format('D MMMM YYYY')}
                        </p>
                      </div>
                    </div>

                    {/* Desktop Profile Dropdown */}
                    <div className="profile-card flex h-11 flex-row items-center gap-2 md:gap-4">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <button className="h-[40px] w-[40px] rounded-full cursor-pointer overflow-hidden">
                            {userInfo?.image ? (
                              <img
                                src={BUCKET_ROOT + userInfo?.image}
                                className="h-[40px] w-[40px] rounded-full object-cover"
                                alt="Profile"
                              />
                            ) : (
                              <img
                                src={ProfileImg.src}
                                className="h-[40px] w-[40px] rounded-full object-cover"
                                alt="Profile"
                              />
                            )}
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent className="relative right-4 bg-white p-3 font-semibold">
                          {renderProfileDropdown(false)}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>

                  {/* Desktop Restaurant Status */}
                  <div className="mt-1 flex justify-end gap-1">
                    <span
                      className={`${resOpen ? 'text-green-400' : 'text-red-500'}`}
                    >
                      Vendor is {resOpen ? 'open.' : 'closed.'}
                    </span>
                    <Switch
                      checked={resOpen}
                      onCheckedChange={() => toggleRes(!resOpen)}
                    />
                  </div>
                </div>
              </div>

              {/* Desktop Filter Tabs */}
              {activeTitle ? (
                <div className="flex w-full items-start justify-start gap-2">
                  {filterOptions[activeTitle].map((label) => {
                    const count = activeTitle === 'Orders' ? getOrderTabCount(label) : null;
                    return (
                      <span
                        key={label}
                        className={`cursor-pointer p-2 text-[16px] font-[600] inline-flex items-center gap-1.5 ${label === selectedOption
                          ? 'text-[#1C1D22]'
                          : 'text-[#999999]'
                          }`}
                        style={
                          label === selectedOption
                            ? { borderBottom: '2px solid #333' }
                            : {}
                        }
                        onClick={() => handleFilterClick(label)}
                      >
                        <span>{label}</span>
                        {count !== null && count !== undefined && (
                          <span
                            className="text-[11px] px-2 py-0.5 rounded-full font-bold leading-none text-white shadow-sm"
                            style={{ backgroundColor: 'var(--primary-brand)', color: '#ffffff' }}
                          >
                            {count}
                          </span>
                        )}
                      </span>
                    );
                  })}
                </div>
              ) : (
                <div className="flex w-full items-start justify-start gap-2">
                  <span
                    className="p-2 text-[16px] font-[600] text-[#1C1D22]"
                    style={{ borderBottom: '2px solid #333' }}
                  >
                    {getDisplayTitle(lastItemTitle)}
                  </span>
                </div>
              )}
            </header>

            {/* Desktop Page Content */}
            <div className="flex-1 min-h-0 w-full overflow-y-auto bg-gray-100">
              {children}
            </div>
          </SidebarInset>
        </div>

        {/* ========== MODALS (Shared between mobile and desktop) ========== */}
        {activeModal && (
          <SidebarModal
            type={activeModal}
            onClose={() => setActiveModal('')}
          />
        )}

        {logoutModal && (
          <LogoutDialog
            isOpen={logoutModal}
            onClose={() => setLogoutModal(false)}
          />
        )}

        {showVerificationModal && (
          <Dialog open={showVerificationModal} onOpenChange={setShowVerificationModal}>
            <DialogContent className="max-w-[400px] p-0 border-0 bg-white rounded-[24px] shadow-2xl overflow-hidden focus:outline-none">
              <div className="relative pt-10 pb-8 px-6 flex flex-col items-center text-center">
                <div className="relative mb-6">
                  <div className="absolute inset-0 bg-[var(--orange-100)] rounded-full animate-ping opacity-20" style={{ animationDuration: '3s' }}></div>
                  <div className="absolute inset-[-4px] bg-[var(--orange-50)] rounded-full opacity-50"></div>
                  <div className="relative flex items-center justify-center w-20 h-20 bg-white rounded-full shadow-xl shadow-[var(--orange-100)]/50">
                    <AlertTriangle className="w-10 h-10 text-[var(--primary-brand)]" strokeWidth={1.5} />
                  </div>
                </div>

                <div className="space-y-3">
                  <h2 className="text-[24px] font-bold text-gray-900 leading-tight">
                    Verification Pending
                  </h2>
                  <p className="text-[15px] font-medium text-gray-400/80 leading-relaxed px-4">
                    Your store is not verified by admin yet. It will remain closed until approval is completed.
                  </p>
                </div>

                <div className="flex flex-col w-full gap-3 mt-10">
                  <button
                    className="w-full py-4 text-[16px] font-bold text-white bg-[var(--primary-brand)] rounded-2xl shadow-lg shadow-[var(--orange-100)] hover:opacity-90 active:scale-[0.98] transition-all duration-200"
                    onClick={() => setShowVerificationModal(false)}
                  >
                    Okay
                  </button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        )}
      </SidebarProvider>

      {/* Add this CSS to your global styles */}
      <style jsx global>{`
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
      `}</style>
    </>
  );
}