import { useState, useEffect, useMemo, useCallback } from "react"
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
} from "@/components/ui/sidebar"
import { useSidebar } from "@/components/ui/sidebar-context"
import { SafeRender } from "./components/ui/settings-ui"
import {
  LayoutGrid,
  Send,
  Crown,
  Settings,
  Zap,
  Target,
  Mail,
  Globe,
  Fingerprint,
  PencilLine,
  Lock,
  Route,
  ShieldCheck,
  Code,
  History as HistoryIcon,
  BookOpen,
  ChevronDown,
  Search,
  ExternalLink,
  Brackets,
  FileText,
  ShieldBan,
  MessagesSquare,
  ShoppingCart,
  Plus,
  Users as UsersIcon
} from "lucide-react"
import type { WawpDashboardData } from './types'

interface AppSidebarProps {
  data: WawpDashboardData
}

const SENDER_SECTIONS = ['whatsapp-web-sender', 'meta-api-sender', 'firebase-sender', 'smtp-sender'];
const GENERAL_SETTINGS_SECTIONS = ['account', 'system_info', 'country-code', 'authentication-pages', 'google_recaptcha', 'abandoned_carts_settings'];
const MESSAGING_TOOLS_SECTIONS = ['block-manager', 'email_templates', 'activity_hub'];

const prefetchSection = (section: string) => {
  switch (section) {
    case 'dashboard': import('./Dashboard'); break;
    case 'activity_hub': import('./ActivityLogs'); break;
    case 'system_info': import('./SystemInfo'); break;
    case 'account': import('./Connector'); break;
    case 'notifications': import('./NotificationsBuilder'); break;
    case 'email_templates': import('./EmailTemplates'); break;
    case 'campaigns': import('./Campaigns'); break;
    case 'chat_widget': import('./ChatWidget'); break;
    case 'country-code': import('./PhoneFieldSettings'); break;
    case 'google_recaptcha': import('./GoogleRecaptchaSettings'); break;
    case 'authentication-pages': import('./AuthenticationPagesSettings'); break;
    case 'checkout-verification': import('./CheckoutVerificationSettings'); break;
    case 'registration-form': import('./RegistrationFormSettings'); break;
    case 'passwordless-login': import('./PasswordlessLoginSettings'); break;
    case 'abandoned_carts_settings': import('./AbandonedCartSettings'); break;
    case 'abandoned_carts': import('./AbandonedCartSessions'); break;
    case 'senders': import('./Senders'); break;
    case 'whatsapp-web-sender': import('./WhatsAppWebSender'); break;
    case 'meta-api-sender': import('./MetaAPISender'); break;
    case 'firebase-sender': import('./FirebaseSender'); break;
    case 'smtp-sender': import('./SMTPSender'); break;
    case 'block-manager': import('./BlockManager'); break;
  }
};

const NavItem = ({ section, icon: Icon, iconPath, remixIcon, label, external = false, badge = null, search, isActive, adminUrl, handleNavClick, plusSection }: { section: string, icon?: React.ComponentType<{ className?: string }>, iconPath?: string, remixIcon?: string, label: string, external?: boolean, badge?: React.ReactNode, search: string, isActive: (section: string) => boolean, adminUrl: (section: string) => string, handleNavClick: (e: React.MouseEvent, section: string, external: boolean) => void, plusSection?: string }) => {
  if (search && !label.toLowerCase().includes(search.toLowerCase())) return null
  const active = isActive(section)
  return (
    <SidebarMenuItem>
      <SidebarMenuButton
        asChild
        isActive={active}
        tooltip={label}
        className={`transition-all duration-200 h-9 px-3 rounded-md group/nav-item !shadow-none ${active ? 'bg-white/10 !text-white font-semibold shadow-sm' : '!text-white/60 hover:!text-white hover:bg-white/5'}`}
        onMouseEnter={() => !external && prefetchSection(section)}
      >
        <div className="flex items-center gap-3 relative !text-inherit w-full">
          <a href={external ? section : adminUrl(section)} target={external ? "_blank" : "_self"} rel={external ? "noopener noreferrer" : ""} className="flex-1 flex items-center gap-3 !text-inherit truncate focus:outline-none" onClick={(e) => handleNavClick(e, section, external)}>
            {active && <div className="absolute -left-3 top-1/2 -translate-y-1/2 w-0.5 h-6 bg-emerald-400 rounded-r-full" />}
            {iconPath ? (
              <img src={iconPath} className={`size-4 shrink-0 transition-opacity ${active ? 'opacity-100' : 'opacity-60 group-hover/nav-item:opacity-100'}`} alt="" />
            ) : remixIcon ? (
              <i className={`${remixIcon} text-[18px] shrink-0 transition-colors ${active ? 'text-emerald-400' : 'text-white/60 group-hover/nav-item:text-white'}`} />
            ) : Icon && (
              <Icon className={`size-4 shrink-0 transition-colors ${active ? '!text-emerald-400' : 'group-hover/nav-item:!text-white'}`} />
            )}
            <span className="truncate text-[13px] !text-inherit group-data-[collapsible=icon]:hidden"><SafeRender content={label} /></span>
          </a>
          
          {plusSection && (
            <button 
              className="shrink-0 size-5 flex items-center justify-center text-white/40 hover:text-white hover:bg-white/10 rounded-[4px] transition-all group-data-[collapsible=icon]:hidden"
              onClick={(e) => { e.preventDefault(); e.stopPropagation(); handleNavClick(e, plusSection, false); }}
              title="Create New"
            >
              <Plus className="size-3.5" strokeWidth={2.5} />
            </button>
          )}

          {badge && <span className="ml-auto group-data-[collapsible=icon]:hidden"><SafeRender content={badge} /></span>}
          {external && <ExternalLink className="size-3 opacity-30 group-hover/nav-item:opacity-100 group-data-[collapsible=icon]:hidden" />}
        </div>
      </SidebarMenuButton>
    </SidebarMenuItem>
  )
}

const SubItem = ({ section, icon: Icon, iconPath, remixIcon, label, badge = null, search, isActive, adminUrl, handleNavClick, plusSection }: { section: string, icon?: React.ComponentType<{ className?: string }>, iconPath?: string, remixIcon?: string, label: string, badge?: React.ReactNode, search: string, isActive: (section: string) => boolean, adminUrl: (section: string) => string, handleNavClick: (e: React.MouseEvent, section: string, external: boolean) => void, plusSection?: string }) => {
  if (search && !label.toLowerCase().includes(search.toLowerCase())) return null
  const active = isActive(section)
  return (
    <SidebarMenuSubItem>
      <SidebarMenuSubButton 
        asChild 
        isActive={active} 
        className={`relative !text-white/60 hover:!text-white hover:bg-white/10 rounded-md px-2 h-8 transition-all group/sub-item ${active ? '!text-white font-bold bg-white/10 ring-1 ring-white/10' : ''}`}
        onMouseEnter={() => prefetchSection(section)}
      >
        <div className="flex items-center gap-2.5 w-full">
          <a href={adminUrl(section)} onClick={(e) => handleNavClick(e, section, false)} className="flex-1 flex items-center gap-2.5 !text-inherit truncate focus:outline-none">
            {active && <div className="absolute -left-[18px] top-1/2 -translate-y-1/2 w-0.5 h-4 bg-emerald-400 rounded-r-full" />}
            {iconPath ? (
              <img src={iconPath} className={`size-3.5 shrink-0 transition-opacity ${active ? 'opacity-100' : 'opacity-60 group-hover/sub-item:opacity-100'}`} alt="" />
            ) : remixIcon ? (
              <i className={`${remixIcon} text-[14px] shrink-0 transition-colors ${active ? 'text-emerald-400' : 'text-white/30 group-hover/sub-item:text-white'}`} />
            ) : Icon && (
              <Icon className={`size-3.5 shrink-0 transition-colors ${active ? '!text-emerald-400' : 'text-white/30 group-hover/sub-item:!text-white'}`} />
            )}
            <span className="truncate text-[12px]"><SafeRender content={label} /></span>
          </a>

          {plusSection && (
            <button 
              className="shrink-0 size-5 flex items-center justify-center text-white/40 hover:text-white hover:bg-white/10 rounded-[4px] transition-all"
              onClick={(e) => { e.preventDefault(); e.stopPropagation(); handleNavClick(e, plusSection, false); }}
              title="Create New"
            >
              <Plus className="size-3" strokeWidth={3} />
            </button>
          )}

          {badge && <span className="ml-auto group-data-[collapsible=icon]:hidden"><SafeRender content={badge} /></span>}
        </div>
      </SidebarMenuSubButton>
    </SidebarMenuSubItem>
  )
}

const AppSidebar: React.FC<AppSidebarProps> = ({ data }) => {
  const { sidebarData, i18n, global } = data
  const { planName, issuesCount, enabledSections } = sidebarData
  const isGuest = data.isGuest;
  const enabledSenders = useMemo(() => {
    const defaults = { email: 1, wa: 1, meta: 1, firebase: 1, block: 1 };
    return { ...defaults, ...(sidebarData.enabledSenders || {}) };
  }, [sidebarData.enabledSenders]);
  const domainStatus = data?.domainStatus || (window as unknown as { wawpDashboardData: { domainStatus: string } }).wawpDashboardData?.domainStatus;
  const isRestricted = domainStatus && domainStatus !== 'active';


  const [search, setSearch] = useState("")
  const [localEnabledSections, setLocalEnabledSections] = useState(enabledSections)
  const [localEnabledSenders, setLocalEnabledSenders] = useState(() => {
    // Merge with defaults to ensure Free features (WA, Block) don't disappear on transient server errors
    const defaults = { email: 0, wa: 1, meta: 0, firebase: 0, block: 1 };
    return { ...defaults, ...enabledSenders };
  })
  const { state, setOpenMobile } = useSidebar()

  const isEnabled = (val: unknown) => {
    if (val && typeof val === 'object' && 'enabled' in val) {
      const obj = val as { enabled: string | number | boolean };
      return Number(obj.enabled) === 1 || obj.enabled === true;
    }
    return Number(val) === 1 || val === true;
  };

  // Deep comparison to prevent unnecessary resets
  const [prevEnabledSectionsStr, setPrevEnabledSectionsStr] = useState(JSON.stringify(enabledSections));
  const currentEnabledSectionsStr = JSON.stringify(enabledSections);
  if (currentEnabledSectionsStr !== prevEnabledSectionsStr) {
    setPrevEnabledSectionsStr(currentEnabledSectionsStr);
    setLocalEnabledSections(enabledSections);
  }

  const [prevEnabledSendersStr, setPrevEnabledSendersStr] = useState(JSON.stringify(enabledSenders));
  const currentEnabledSendersStr = JSON.stringify(enabledSenders);
  if (currentEnabledSendersStr !== prevEnabledSendersStr) {
    setPrevEnabledSendersStr(currentEnabledSendersStr);
    const defaults = { email: 0, wa: 1, meta: 0, firebase: 0, block: 1 };
    setLocalEnabledSenders({ ...defaults, ...enabledSenders });
  }

  const isSenderSection = SENDER_SECTIONS.includes(global.section) || global.section === 'senders';
  const isGeneralSection = GENERAL_SETTINGS_SECTIONS.includes(global.section);
  const isMessagingSection = MESSAGING_TOOLS_SECTIONS.includes(global.section);

  const [isSendersOpen, setIsSendersOpen] = useState(isSenderSection)
  const [isGeneralOpen, setIsGeneralOpen] = useState(isGeneralSection)
  const [isMessagingOpen, setIsMessagingOpen] = useState(isMessagingSection)
  const [isResourcesOpen, setIsResourcesOpen] = useState(false)

  // Pre-calculate visibility for search
  const isMatch = useCallback((text: string) => !search || text.toLowerCase().includes(search.toLowerCase()), [search]);

  const subItems = useMemo(() => ({
    general: [
      { section: 'account', label: i18n.subscription || 'Subscription', enabled: !!sidebarData.isProPluginActive },
      { section: 'system_info', label: i18n.systemInfo || 'System Status', enabled: isEnabled(localEnabledSections.systemInfo) },
      { section: 'country-code', label: 'Country Code', enabled: isEnabled(localEnabledSections.countryCode) },
      { section: 'authentication-pages', label: i18n.authPages || 'Auth Pages', enabled: isEnabled(localEnabledSections.customPages) },
      { section: 'google_recaptcha', label: i18n.recaptcha || 'Google reCAPTCHA', enabled: isEnabled(localEnabledSections.recaptcha) },
      { section: 'abandoned_carts_settings', label: 'ACart Settings', enabled: isEnabled(localEnabledSections.abandonedCarts) }
    ],
    senders: [
      { section: 'whatsapp-web-sender', label: i18n.waWeb || 'WhatsApp Web Authentication', enabled: true },
      { section: 'meta-api-sender', label: i18n.metaApi || 'Meta API', enabled: !!sidebarData.isProPluginActive && isEnabled(localEnabledSenders.meta) },
      { section: 'smtp-sender', label: i18n.smtpServer || 'Email Magic Link Login', enabled: isEnabled(localEnabledSenders.email) },
      { section: 'firebase-sender', label: i18n.firebaseOtp || 'Firebase SMS Authentication', enabled: !!sidebarData.isProPluginActive && isEnabled(localEnabledSenders.firebase) }
    ],
    messaging: [
      { section: 'block-manager', label: i18n.blockManager || 'Block Manager', enabled: isEnabled(localEnabledSenders.block) },
      { section: 'email_templates', label: i18n.emailTemplates || 'Email Templates', enabled: isEnabled(localEnabledSections.emailTemplates) },
      { section: 'activity_hub', label: i18n.activityHub || "Activity Hub", enabled: !!sidebarData.isProPluginActive && isEnabled(localEnabledSections.activityHub) }
    ],
    resources: [
      { section: '', label: i18n.shortcodes || "Wawp Shortcodes", enabled: true },
      { section: '', label: i18n.documentation || 'Documentation', enabled: true },
      { section: '', label: i18n.placeholders || 'Placeholders', enabled: true },
      { section: '', label: i18n.community || 'Community', enabled: true }
    ]
  }), [i18n, localEnabledSections, localEnabledSenders, sidebarData.isProPluginActive]);

  const visibility = useMemo(() => {
    const checkGroup = (group: keyof typeof subItems, groupLabel: string) => {
      const groupItems = subItems[group] as { label: string; enabled: boolean; section?: string }[];
      const activeSubs = groupItems.filter(s => s.enabled);
      const matchingSubs = activeSubs.filter(s => isMatch(s.label));

      const groupMatches = isMatch(groupLabel);

      return {
        show: activeSubs.length > 0 && (matchingSubs.length > 0 || groupMatches),
        hasMatchingSub: matchingSubs.length > 0,
        matchingSubs: matchingSubs.map(s => s.section || s.label)
      };
    };

      return {
        general: checkGroup('general', i18n.generalSettings || 'General Settings'),
        senders: checkGroup('senders', i18n.senderSettings || 'Sender Settings'),
        messaging: checkGroup('messaging', i18n.messagingTools || 'Messaging Tools'),
        resources: checkGroup('resources', i18n.resources || 'Resources'),
        dashboard: isMatch(i18n.dashboard || 'Dashboard'),
        userJourney: isMatch('User Journey') && isEnabled(localEnabledSections.abandonedCarts),
        chatWidget: isMatch(i18n.whatsappChat || 'WhatsApp Chat') && isEnabled(localEnabledSections.chatWidget),
        notifications: isMatch(i18n.automatedNotif || 'Automated Notif') && isEnabled(localEnabledSections.notifications),
        campaigns: isMatch(i18n.bulkCampaigns || 'Bulk Campaigns') && isEnabled(localEnabledSections.campaigns),
        otpLogin: isMatch(i18n.passwordlessLogin || 'Passwordless Login') && isEnabled(localEnabledSections.otpLogin),
        signupOtp: isMatch(i18n.registrationForm || 'Registration Form') && isEnabled(localEnabledSections.signupOtp),
        checkoutOtp: isMatch(i18n.checkoutVerif || 'Checkout Verification') && isEnabled(localEnabledSections.checkoutOtp)
      };
  }, [subItems, i18n, localEnabledSections, isMatch]);

  // Handle auto-opening of parent groups when searching
  useEffect(() => {
    const timer = setTimeout(() => {
      if (search) {
        if (visibility.general.hasMatchingSub) setIsGeneralOpen(true);
        if (visibility.senders.hasMatchingSub) setIsSendersOpen(true);
        if (visibility.messaging.hasMatchingSub) setIsMessagingOpen(true);
        if (visibility.resources.hasMatchingSub) setIsResourcesOpen(true);
      } else {
        // Reset to default active state when search is cleared
        setIsGeneralOpen(isGeneralSection);
        setIsSendersOpen(isSenderSection);
        setIsMessagingOpen(isMessagingSection);
        setIsResourcesOpen(false);
      }
    }, 0);
    return () => clearTimeout(timer);
  }, [search, visibility, isGeneralSection, isSenderSection, isMessagingSection]);

  const [prevSection, setPrevSection] = useState(global.section);
  if (global.section !== prevSection) {
    setPrevSection(global.section);
    if (!search) {
      if (isSenderSection) {
        setIsSendersOpen(true); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false);
      } else if (isGeneralSection || global.section === 'account') {
        setIsGeneralOpen(true); setIsSendersOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false);
      } else if (isMessagingSection) {
        setIsMessagingOpen(true); setIsSendersOpen(false); setIsGeneralOpen(false); setIsResourcesOpen(false);
      } else {
        setIsSendersOpen(false); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false);
      }
    }
  }

  useEffect(() => {
    const handleSenderUpdate = (e: Event) => {
      const detail = (e as CustomEvent).detail;
      if (detail) {
        setLocalEnabledSenders((prev: Record<string, number>) => {
          const newState = { ...prev, ...detail };
          return newState;
        })
      }
    }
    const handleSectionUpdate = (e: Event) => {
      const detail = (e as CustomEvent).detail;
      if (detail) {
        setLocalEnabledSections((prev: Record<string, unknown>) => {
          const newState = { ...prev, ...detail };
          return newState;
        })
      }
    }
    window.addEventListener('wawp-senders-updated', handleSenderUpdate)
    window.addEventListener('wawp-sections-updated', handleSectionUpdate)
    return () => {
      window.removeEventListener('wawp-senders-updated', handleSenderUpdate)
      window.removeEventListener('wawp-sections-updated', handleSectionUpdate)
    }
  }, []); // Only run once on mount

  useEffect(() => {
    const timer = setTimeout(() => {
      const activeElement = document.querySelector('[data-active="true"]');
      const scrollContainer = document.querySelector('[data-sidebar="content"]');
      if (activeElement && scrollContainer) {
        const containerRect = scrollContainer.getBoundingClientRect();
        const elementRect = activeElement.getBoundingClientRect();
        const relativeTop = elementRect.top - containerRect.top;
        const targetScrollTop = (scrollContainer.scrollTop + relativeTop) - (containerRect.height / 2) + (elementRect.height / 2);
        scrollContainer.scrollTo({ top: targetScrollTop, behavior: 'smooth' });
      }
    }, 150);
    return () => clearTimeout(timer);
  }, [global.section]);

  const adminUrl = (section: string) => `${window.location.pathname}?page=wawp&wawp_section=${section}`
  const isActive = (section: string) => global.section === section

  const handleNavClick = (e: React.MouseEvent, section: string, external: boolean) => {
    if (external) return;
    e.preventDefault();
    const newUrl = adminUrl(section);
    window.history.pushState({ section }, "", newUrl);
    window.dispatchEvent(new CustomEvent('wawp-navigate', { detail: section }));
    window.scrollTo({ top: 0, behavior: 'smooth' });
    setOpenMobile(false);
  };

  const navProps = { search, isActive, adminUrl, handleNavClick };

  return (
    <Sidebar collapsible="icon" className="border-sidebar-border bg-sidebar z-[100]">
      <SidebarHeader className="p-4 pt-6 group-data-[collapsible=icon]:p-0 group-data-[collapsible=icon]:pt-3">
        <div className="flex items-center justify-between px-2 mb-4 group-data-[collapsible=icon]:mb-0 group-data-[collapsible=icon]:px-0 group-data-[collapsible=icon]:justify-center">
          <div className="flex items-center gap-3 group-data-[collapsible=icon]:gap-0">
            {state === "expanded" ? (
              <img src={`${global.pluginUrl}assets/img/wawp-logo.svg`} alt="Wawp Logo" className="h-8 w-auto transition-all duration-300" />
            ) : (
              <svg className="h-7 w-7 text-white" xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 240 240" fill="none">
                <path d="M70 0C75.5228 0 80 4.47715 80 10V30H160V10C160 4.47715 164.477 0 170 0H190C195.523 0 200 4.47715 200 10V30C222.091 30 240 47.9086 240 70V170C240 192.091 222.091 210 200 210H170C170 210 140 240 120 240C100 240 70 210 70 210H40C17.9086 210 0 192.091 0 170V70C0 47.9086 17.9086 30 40 30V10C40 4.47715 44.4772 0 50 0H70ZM40 50C28.9543 50 20 58.9543 20 70V170C20 181.046 28.9543 190 40 190H200C211.046 190 220 181.046 220 170V70C220 58.9543 211.046 50 200 50H40Z" fill="currentColor"></path>
                <path d="M140 100C140 94.4772 144.477 90 150 90H170C175.523 90 180 94.4772 180 100V140C180 145.523 175.523 150 170 150H150C144.477 150 140 145.523 140 140V100Z" fill="currentColor"></path>
                <path d="M60 100C60 94.4772 64.4772 90 70 90H90C95.5228 90 100 94.4772 100 100V140C100 145.523 95.5228 150 90 150H70C64.4772 150 60 145.523 60 140V100Z" fill="currentColor"></path>
              </svg>
            )}
          </div>
          <a
            href="https://wawp.net"
            target="_blank"
            rel="noreferrer"
            className="size-6 rounded-full border border-white/5 flex items-center justify-center group-data-[collapsible=icon]:hidden hover:bg-white/5 hover:border-white/10 transition-all cursor-pointer group"
          >
            <Globe className="size-3.5 text-white/20 group-hover:text-white/60 transition-colors" />
          </a>
        </div>
        <div className="px-1 group-data-[collapsible=icon]:hidden">
          <div className="relative group flex items-center">
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 size-3.5 text-slate-400 group-focus-within:text-emerald-500 transition-all duration-200 z-10 pointer-events-none" />
            <input
              type="text"
              placeholder={i18n.search || "Search..."}
              style={{ paddingLeft: '42px', paddingRight: '56px' }}
              className="w-full rounded-lg bg-white border border-slate-200 py-1.5 text-[12px] text-slate-700 placeholder:text-slate-400 outline-none focus:border-emerald-500/50 focus:ring-4 focus:ring-emerald-500/5 transition-all font-medium shadow-sm"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1 px-1.5 py-0.5 bg-slate-50 border border-slate-200 rounded text-[9px] font-bold text-slate-400 group-focus-within:text-slate-500 transition-colors pointer-events-none z-10">
              <span className="opacity-70">{navigator.platform.toUpperCase().indexOf('MAC') >= 0 ? '⌘' : 'Ctrl'}</span>
              <span>K</span>
            </div>
          </div>
        </div>
      </SidebarHeader>

      <SidebarContent className="px-2 group-data-[collapsible=icon]:px-0">
        <>
            <SidebarGroup className="group-data-[collapsible=icon]:px-0">

              {(visibility.dashboard || visibility.userJourney || visibility.general.show || visibility.senders.show || visibility.messaging.show) && (
                <SidebarGroupLabel className="text-[10px] font-bold uppercase tracking-widest text-white/20 px-3 mb-1 group-data-[collapsible=icon]:hidden">{i18n.general || 'General'}</SidebarGroupLabel>
              )}
              <SidebarGroupContent>
                <SidebarMenu className="gap-0.5 group-data-[collapsible=icon]:items-center">
                  {/* Dashboard */}
                  {visibility.dashboard && <NavItem {...navProps} section="dashboard" icon={LayoutGrid} label={i18n.dashboard || 'Dashboard'} />}

                  {/* User Journey */}
                  {visibility.userJourney && <NavItem {...navProps} section="abandoned_carts" icon={ShoppingCart} label="User Journey" />}

                  {/* General Settings */}
                  {visibility.general.show && (
                    <SidebarMenuItem>
                      <SidebarMenuButton
                        isActive={isGeneralSection}
                        className={`transition-all duration-200 h-9 px-3 rounded-md group !shadow-none ${isGeneralSection ? 'bg-white/10 !text-white font-semibold' : '!text-white/60 hover:!text-white hover:bg-white/5'}`}
                        onClick={() => {
                          const next = !isGeneralOpen; setIsGeneralOpen(next);
                          if (next) { setIsSendersOpen(false); setIsMessagingOpen(false); }
                        }}
                      >
                        <div className="flex items-center gap-3 relative flex-1">
                          <Settings className={`size-4 shrink-0 transition-colors ${isGeneralSection ? '!text-emerald-400' : 'group-hover:!text-white'}`} />
                          <span className="flex-1 truncate text-[13px] !text-inherit">{i18n.generalSettings || 'General Settings'}</span>
                          <div className="size-4 flex items-center justify-center">
                            <ChevronDown className={`size-3.5 transition-transform duration-200 ${isGeneralOpen ? '' : '-rotate-90'}`} />
                          </div>
                        </div>
                      </SidebarMenuButton>
                      {isGeneralOpen && (
                        <SidebarMenuSub className="border-white/10 pr-0 mr-0 mt-0.5">
                          {sidebarData.isProPluginActive && <SubItem {...navProps} section="account" icon={Crown} label={i18n.subscription || 'Subscription'} badge={!isRestricted && <span className="rounded-[4px] px-1.5 py-0.5 text-[10px] font-bold bg-amber-500 text-white">{planName ? planName.replace(/\(?lifetime\)?/gi, '').replace(/\(\s*\)/g, '').trim() || planName : 'Free'}</span>} />}
                          {isEnabled(localEnabledSections.systemInfo) && <SubItem {...navProps} section="system_info" icon={Settings} label={i18n.systemInfo || 'System Status'} badge={issuesCount > 0 ? <span className="rounded-[4px] px-1.5 py-0.5 text-[9px] font-bold bg-rose-500/20 text-rose-200 border border-rose-500/30">{issuesCount}</span> : null} />}
                          {isEnabled(localEnabledSections.countryCode) && <SubItem {...navProps} section="country-code" icon={Globe} label="Country Code" />}
                          {isEnabled(localEnabledSections.customPages) && <SubItem {...navProps} section="authentication-pages" icon={Route} label={i18n.authPages || 'Auth Pages'} />}
                          {isEnabled(localEnabledSections.recaptcha) && <SubItem {...navProps} section="google_recaptcha" icon={ShieldCheck} label={i18n.recaptcha || 'Google reCAPTCHA'} />}
                          {!isGuest && isEnabled(localEnabledSections.abandonedCarts) && <SubItem {...navProps} section="abandoned_carts_settings" icon={Settings} label="ACart Settings" />}
                        </SidebarMenuSub>
                      )}
                    </SidebarMenuItem>
                  )}

                  {/* Sender Settings */}
                  {visibility.senders.show && (
                    <SidebarMenuItem>
                      <SidebarMenuButton
                        isActive={isActive('senders') || isSenderSection}
                        className={`transition-all duration-200 h-9 px-3 rounded-md group !shadow-none ${isActive('senders') || isSenderSection ? 'bg-white/10 !text-white font-semibold' : '!text-white/60 hover:!text-white hover:bg-white/5'}`}
                        onClick={(e) => {
                          handleNavClick(e, 'senders', false);
                          setIsSendersOpen(true); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false);
                        }}
                      >
                        <div className="flex items-center gap-3 relative flex-1">
                          <Send className={`size-4 shrink-0 transition-colors ${isActive('senders') || isSenderSection ? '!text-emerald-400' : 'group-hover:!text-white'}`} />
                          <span className="flex-1 truncate text-[13px] !text-inherit">{i18n.senderSettings || 'Sender Settings'}</span>
                          <button
                            onClick={(e) => { e.preventDefault(); e.stopPropagation(); const next = !isSendersOpen; setIsSendersOpen(next); if (next) { setIsGeneralOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false); } }}
                            className="size-4 flex items-center justify-center hover:bg-white/10 rounded-sm transition-colors"
                          >
                            <ChevronDown className={`size-3.5 transition-transform duration-200 ${isSendersOpen ? '' : '-rotate-90'}`} />
                          </button>
                        </div>
                      </SidebarMenuButton>
                      {isSendersOpen && (
                        <SidebarMenuSub className="border-white/10 pr-0 mr-0 mt-0.5">
                          <SubItem {...navProps} section="whatsapp-web-sender" iconPath={`${global.pluginUrl}assets/img/senders/whatsapp.svg`} label={i18n.waWeb || 'WhatsApp Web'} />
                          {sidebarData.isProPluginActive && isEnabled(localEnabledSenders.meta) && <SubItem {...navProps} section="meta-api-sender" iconPath={`${global.pluginUrl}assets/img/senders/meta.svg`} label={i18n.metaApi || 'Meta API'} />}
                          {isEnabled(localEnabledSenders.email) && <SubItem {...navProps} section="smtp-sender" iconPath={`${global.pluginUrl}assets/img/senders/gmail.svg`} label={i18n.smtpServer || 'SMTP Server'} />}
                          {sidebarData.isProPluginActive && isEnabled(localEnabledSenders.firebase) && <SubItem {...navProps} section="firebase-sender" iconPath={`${global.pluginUrl}assets/img/senders/firebase.svg`} label={i18n.firebaseOtp || 'Firebase OTP'} />}
                        </SidebarMenuSub>
                      )}
                    </SidebarMenuItem>
                  )}

                  {/* Messaging Tools */}
                  {visibility.messaging.show && (
                    <SidebarMenuItem>
                      <SidebarMenuButton
                        isActive={isMessagingSection}
                        className={`transition-all duration-200 h-9 px-3 rounded-md group !shadow-none ${isMessagingSection ? 'bg-white/10 !text-white font-semibold' : '!text-white/60 hover:!text-white hover:bg-white/5'}`}
                        onClick={() => {
                          const next = !isMessagingOpen; setIsMessagingOpen(next);
                          if (next) { setIsSendersOpen(false); setIsGeneralOpen(false); }
                        }}
                      >
                        <div className="flex items-center gap-3 relative flex-1">
                          <MessagesSquare className={`size-4 shrink-0 transition-colors ${isMessagingSection ? '!text-emerald-400' : 'group-hover:!text-white'}`} />
                          <span className="flex-1 truncate text-[13px] !text-inherit">{i18n.messagingTools || 'Messaging Tools'}</span>
                          <div className="size-4 flex items-center justify-center">
                            <ChevronDown className={`size-3.5 transition-transform duration-200 ${isMessagingOpen ? '' : '-rotate-90'}`} />
                          </div>
                        </div>
                      </SidebarMenuButton>
                      {isMessagingOpen && (
                        <SidebarMenuSub className="border-white/10 pr-0 mr-0 mt-0.5">
                          {isEnabled(localEnabledSenders.block) && <SubItem {...navProps} section="block-manager" icon={ShieldBan} label={i18n.blockManager || 'Block Manager'} />}
                          {isEnabled(localEnabledSections.emailTemplates) && <SubItem {...navProps} section="email_templates" icon={Mail} label={i18n.emailTemplates || 'Email Templates'} plusSection="email_templates&action=create" />}
                          {sidebarData.isProPluginActive && isEnabled(localEnabledSections.activityHub) && <SubItem {...navProps} section="activity_hub" icon={HistoryIcon} label={i18n.activityHub || "Activity Hub"} />}
                        </SidebarMenuSub>
                      )}
                    </SidebarMenuItem>
                  )}

                  {/* Abandoned Carts Group Removed - items moved to top-level and general settings */}
                </SidebarMenu>
              </SidebarGroupContent>
            </SidebarGroup>

            {/* ENGAGEMENT */}
            {(visibility.chatWidget || visibility.notifications || visibility.campaigns) && (
              <SidebarGroup className="mt-2 text-start group-data-[collapsible=icon]:px-0">
                <SidebarGroupLabel className="text-[10px] font-bold uppercase tracking-widest text-white/20 px-3 mb-1 group-data-[collapsible=icon]:hidden">{i18n.engagement || 'Engagement'}</SidebarGroupLabel>
                <SidebarGroupContent>
                  <SidebarMenu className="gap-0.5 group-data-[collapsible=icon]:items-center">
                    {visibility.chatWidget && <NavItem {...navProps} section="chat_widget" remixIcon="ri-whatsapp-fill" label={i18n.whatsappChat || 'WhatsApp Chat'} />}
                    {visibility.notifications && <NavItem {...navProps} section="notifications" icon={Zap} label={i18n.automatedNotif || 'Automated Notif'} />}
                    {visibility.campaigns && <NavItem {...navProps} section="campaigns" icon={Target} label={i18n.bulkCampaigns || 'Bulk Campaigns'} plusSection="campaigns_new" />}
                  </SidebarMenu>
                </SidebarGroupContent>
              </SidebarGroup>
            )}

            {/* AUTHENTICATIONS */}
            {(visibility.otpLogin || visibility.signupOtp || visibility.checkoutOtp) && (
              <SidebarGroup className="mt-2 text-start group-data-[collapsible=icon]:px-0">
                <SidebarGroupLabel className="text-[10px] font-bold uppercase tracking-widest text-white/20 px-3 mb-1 group-data-[collapsible=icon]:hidden">{i18n.authentications || 'Authentications'}</SidebarGroupLabel>
                <SidebarGroupContent>
                  <SidebarMenu className="gap-0.5 group-data-[collapsible=icon]:items-center">
                    {visibility.otpLogin && <NavItem {...navProps} section="passwordless-login" icon={Fingerprint} label={i18n.passwordlessLogin || 'Passwordless Login'} />}
                    {visibility.signupOtp && <NavItem {...navProps} section="registration-form" icon={PencilLine} label={i18n.registrationForm || 'Registration Form'} />}
                    {visibility.checkoutOtp && <NavItem {...navProps} section="checkout-verification" icon={Lock} label={i18n.checkoutVerif || 'Checkout Verification'} />}
                  </SidebarMenu>
                </SidebarGroupContent>
              </SidebarGroup>
            )}

            {/* RESOURCES */}
            {visibility.resources.show && (
              <SidebarGroup className="mt-2 text-start group-data-[collapsible=icon]:px-0">
                <SidebarGroupLabel className="text-[10px] font-bold uppercase tracking-widest text-white/20 px-3 mb-1 group-data-[collapsible=icon]:hidden">{i18n.resources || 'Resources'}</SidebarGroupLabel>
                <SidebarGroupContent>
                  <SidebarMenu className="gap-0.5 group-data-[collapsible=icon]:items-center">
                    <SidebarMenuItem>
                      <SidebarMenuButton asChild className="relative !text-white/70 hover:!text-white hover:bg-white/5 rounded-md px-3 transition-all duration-200 group/btn h-10 border border-transparent">
                        <div className="flex items-center w-full gap-2.5">
                          <div className="p-1.5 rounded-md bg-emerald-500/10 text-emerald-400 group-hover/btn:bg-emerald-500/20 transition-colors"><BookOpen className="size-4" /></div>
                          <span className="flex-1 truncate text-[13px] !text-inherit">{i18n.resources || 'Resources'}</span>
                          <button onClick={(e) => { e.preventDefault(); e.stopPropagation(); setIsResourcesOpen(!isResourcesOpen); }} className="size-4 flex items-center justify-center hover:bg-white/5 rounded-sm transition-colors">
                            <ChevronDown className={`size-3.5 transition-transform duration-200 ${isResourcesOpen ? '' : '-rotate-90'}`} />
                          </button>
                        </div>
                      </SidebarMenuButton>
                      {isResourcesOpen && (
                        <SidebarMenuSub className="border-white/10 pr-0 mr-0">
                          {isMatch(i18n.shortcodes || "Wawp Shortcodes") && <SidebarMenuSubItem><SidebarMenuSubButton asChild className="relative !text-white/60 hover:!text-white hover:bg-white/5 rounded-md px-2"><a href="https://help.wawp.net/en_US/wawp-shortcodes/" target="_blank" rel="noopener noreferrer"><Code className="size-3.5 mr-2" />{i18n.shortcodes || "Wawp Shortcodes"}</a></SidebarMenuSubButton></SidebarMenuSubItem>}
                          {isMatch(i18n.documentation || 'Documentation') && <SidebarMenuSubItem><SidebarMenuSubButton asChild className="relative !text-white/60 hover:!text-white hover:bg-white/5 rounded-md px-2"><a href="https://help.wawp.net/en_US/" target="_blank" rel="noopener noreferrer"><FileText className="size-3.5 mr-2" />{i18n.documentation || 'Documentation'}</a></SidebarMenuSubButton></SidebarMenuSubItem>}
                          {isMatch(i18n.placeholders || 'Placeholders') && <SidebarMenuSubItem><SidebarMenuSubButton asChild className="relative !text-white/60 hover:!text-white hover:bg-white/5 rounded-md px-2"><a href="https://help.wawp.net/en_US/wawp-shortcodes-list/" target="_blank" rel="noopener noreferrer"><Brackets className="size-3.5 mr-2" />{i18n.placeholders || 'Placeholders'}</a></SidebarMenuSubButton></SidebarMenuSubItem>}
                          {isMatch(i18n.community || 'Community') && <SidebarMenuSubItem><SidebarMenuSubButton asChild className="relative !text-white/60 hover:!text-white hover:bg-white/5 rounded-md px-2"><a href="https://www.facebook.com/groups/wawp.net/" target="_blank" rel="noopener noreferrer"><UsersIcon className="size-3.5 mr-2" />{i18n.community || 'Community'}</a></SidebarMenuSubButton></SidebarMenuSubItem>}
                        </SidebarMenuSub>
                      )}
                    </SidebarMenuItem>
                  </SidebarMenu>
                </SidebarGroupContent>
              </SidebarGroup>
            )}
          </>
      </SidebarContent>
    </Sidebar>

  )
}

export default AppSidebar
