import { useState, useEffect, useMemo } from "react"
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  useSidebar,
} from "./components/ui/sidebar"
import { SafeRender } from "./components/ui/settings-ui"
import {
  LayoutGrid,
  Send,
  Crown,
  Settings,
  MessageCircle,
  Zap,
  Target,
  Mail,
  Globe,
  Fingerprint,
  PencilLine,
  Lock,
  Route,
  ShieldCheck,
  Code,
  Flag,
  History,
  BookOpen,
  Bell,
  ChevronDown,
  Search,
  ExternalLink,
  Tv,
  Brackets,
  FileText,
  ShieldBan,
  MessagesSquare,
  ShoppingCart,
  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 = ['connector', 'system_info', 'settings', 'authentication-pages', 'google_recaptcha'];
const MESSAGING_TOOLS_SECTIONS = ['block-manager', 'email_templates', 'activity_hub'];
const ABANDONED_CARTS_SECTIONS = ['abandoned_carts', 'abandoned_carts_notifications', 'abandoned_carts_settings'];

const NavItem = ({ section, icon: Icon, label, external = false, badge = null, search, isActive, adminUrl, handleNavClick }: { section: string, icon: React.ComponentType<{ className?: 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 }) => {
  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 !shadow-none ${active ? 'bg-white/10 !text-white font-semibold shadow-sm' : '!text-white/60 hover:!text-white hover:bg-white/5'}`}
      >
        <a href={external ? section : adminUrl(section)} target={external ? "_blank" : "_self"} rel={external ? "noopener noreferrer" : ""} className="flex items-center gap-3 relative !text-inherit" 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" />}
          <Icon className={`size-4 shrink-0 transition-colors ${active ? '!text-emerald-400' : 'group-hover:!text-white'}`} />
          <span className="flex-1 truncate text-[13px] !text-inherit group-data-[collapsible=icon]:hidden"><SafeRender content={label} /></span>
          {badge && <span className="ml-auto group-data-[collapsible=icon]:hidden"><SafeRender content={badge} /></span>}
          {external && <ExternalLink className="size-3 opacity-30 group-hover:opacity-100 group-data-[collapsible=icon]:hidden" />}
        </a>
      </SidebarMenuButton>
    </SidebarMenuItem>
  )
}

const SubItem = ({ section, icon: Icon, label, badge = null, search, isActive, adminUrl, handleNavClick }: { section: string, icon: React.ComponentType<{ className?: 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 }) => {
  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 ${active ? '!text-white font-bold bg-white/10 ring-1 ring-white/10' : ''}`}>
        <a href={adminUrl(section)} onClick={(e) => handleNavClick(e, section, false)} className="flex items-center gap-2.5 w-full">
          {active && <div className="absolute -left-[18px] top-1/2 -translate-y-1/2 w-0.5 h-4 bg-emerald-400 rounded-r-full" />}
          <Icon className={`size-3.5 shrink-0 transition-colors ${active ? '!text-emerald-400' : 'text-white/30 group-hover:!text-white'}`} />
          <span className="truncate flex-1"><SafeRender content={label} /></span>
          {badge && <span className="ml-auto group-data-[collapsible=icon]:hidden"><SafeRender content={badge} /></span>}
        </a>
      </SidebarMenuSubButton>
    </SidebarMenuSubItem>
  )
}

const AppSidebar: React.FC<AppSidebarProps> = ({ data }) => {
  const { sidebarData, i18n, global } = data
  const { planName, issuesCount, enabledSections } = sidebarData
  const enabledSenders = useMemo(() => sidebarData.enabledSenders || { email: 1, wa: 1, meta: 1, firebase: 1, block: 1 }, [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(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;
  };

  useEffect(() => {
    setLocalEnabledSections(enabledSections);
  }, [enabledSections]);

  useEffect(() => {
    setLocalEnabledSenders(enabledSenders);
  }, [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 isAbandonedSection = ABANDONED_CARTS_SECTIONS.includes(global.section);

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

  const [prevSection, setPrevSection] = useState(global.section);
  if (global.section !== prevSection) {
    setPrevSection(global.section);
    if (isSenderSection) {
      setIsSendersOpen(true); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsAbandonedOpen(false); setIsResourcesOpen(false);
    } else if (isGeneralSection) {
      setIsGeneralOpen(true); setIsSendersOpen(false); setIsMessagingOpen(false); setIsAbandonedOpen(false); setIsResourcesOpen(false);
    } else if (isMessagingSection) {
      setIsMessagingOpen(true); setIsSendersOpen(false); setIsGeneralOpen(false); setIsAbandonedOpen(false); setIsResourcesOpen(false);
    } else if (isAbandonedSection) {
      setIsAbandonedOpen(true); setIsSendersOpen(false); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false);
    } else if (global.section === 'dashboard') {
      setIsSendersOpen(false); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsAbandonedOpen(false); setIsResourcesOpen(false);
    } else {
      setIsSendersOpen(false); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsAbandonedOpen(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 };
          if (Object.values(detail).some(v => isEnabled(v as string | number | boolean))) {
            setIsSendersOpen(true); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsAbandonedOpen(false);
          }
          return newState;
        })
      }
    }
    const handleSectionUpdate = (e: Event) => {
      const detail = (e as CustomEvent).detail;
      if (detail) {
        setLocalEnabledSections((prev: Record<string, unknown>) => {
          const newState = { ...prev, ...detail };
          const generalKeys = ['systemInfo', 'countryCode', 'customPages', 'recaptcha'];
          const messagingKeys = ['emailTemplates', 'activityHub'];
          if (generalKeys.some(k => detail[k] !== undefined && isEnabled(detail[k]))) {
            setIsGeneralOpen(true); setIsSendersOpen(false); setIsMessagingOpen(false); setIsAbandonedOpen(false);
          }
          if (messagingKeys.some(k => detail[k] !== undefined && isEnabled(detail[k]))) {
            setIsMessagingOpen(true); setIsSendersOpen(false); setIsGeneralOpen(false); setIsAbandonedOpen(false);
          }
          if (detail.abandonedCarts !== undefined && isEnabled(detail.abandonedCarts)) {
            setIsAbandonedOpen(true); setIsSendersOpen(false); setIsGeneralOpen(false); setIsMessagingOpen(false);
          }
          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)
    }
  }, []);

  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">
      <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>
          <div className="size-6 rounded-full border border-white/5 flex items-center justify-center group-data-[collapsible=icon]:hidden">
            <Globe className="size-3.5 text-white/20" />
          </div>
        </div>
        <div className="px-1 group-data-[collapsible=icon]:hidden">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-white/20" />
            <input type="text" placeholder={i18n.search} className="w-full rounded-lg bg-white/5 border border-white/5 py-2 pl-10 pr-3 text-xs text-white placeholder-white/20 outline-none focus:border-white/10 focus:bg-white/10 transition-all font-medium" value={search} onChange={(e) => setSearch(e.target.value)} />
          </div>
        </div>
      </SidebarHeader>

      <SidebarContent className="px-2 group-data-[collapsible=icon]:px-0">
        <SidebarGroup className="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.general || 'General'}</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu className="gap-0.5 group-data-[collapsible=icon]:items-center">
              {/* Dashboard */}
              {!isRestricted && <NavItem {...navProps} section="dashboard" icon={LayoutGrid} label={i18n.dashboard || 'Dashboard'} />}

              {/* General Settings */}
              <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); setIsAbandonedOpen(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">
                    <SubItem {...navProps} section="connector" 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}</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="settings" icon={Globe} label={i18n.phoneField || 'Phone Field'} />}
                    {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'} />}
                  </SidebarMenuSub>
                )}
              </SidebarMenuItem>

              {/* Sender Settings */}
              {!isRestricted && (
                <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); setIsAbandonedOpen(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); setIsAbandonedOpen(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">
                      {isEnabled(localEnabledSenders.wa) && <SubItem {...navProps} section="whatsapp-web-sender" icon={MessageCircle} label={i18n.waWeb || 'WhatsApp Web'} />}
                      {isEnabled(localEnabledSenders.meta) && <SubItem {...navProps} section="meta-api-sender" icon={Globe} label={i18n.metaApi || 'Meta API'} />}
                      {isEnabled(localEnabledSenders.email) && <SubItem {...navProps} section="smtp-sender" icon={Mail} label={i18n.smtpServer || 'SMTP Server'} />}
                      {isEnabled(localEnabledSenders.firebase) && <SubItem {...navProps} section="firebase-sender" icon={Zap} label={i18n.firebaseOtp || 'Firebase OTP'} />}
                    </SidebarMenuSub>
                  )}
                </SidebarMenuItem>
              )}

              {/* Messaging Tools */}
              <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); setIsAbandonedOpen(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'} />}
                    {isEnabled(localEnabledSections.activityHub) && <SubItem {...navProps} section="activity_hub" icon={History} label={i18n.activityHub || "Activity Hub"} />}
                  </SidebarMenuSub>
                )}
              </SidebarMenuItem>

              {/* Abandoned Carts */}
              {isEnabled(localEnabledSections.abandonedCarts) && (
                <SidebarMenuItem>
                  <SidebarMenuButton
                    isActive={isAbandonedSection}
                    className={`transition-all duration-200 h-9 px-3 rounded-md group !shadow-none ${isAbandonedSection ? 'bg-white/10 !text-white font-semibold' : '!text-white/60 hover:!text-white hover:bg-white/5'}`}
                    onClick={() => {
                      const next = !isAbandonedOpen; setIsAbandonedOpen(next);
                      if (next) { setIsSendersOpen(false); setIsGeneralOpen(false); setIsMessagingOpen(false); setIsResourcesOpen(false); }
                    }}
                  >
                    <div className="flex items-center gap-3 relative flex-1">
                      <ShoppingCart className={`size-4 shrink-0 transition-colors ${isAbandonedSection ? '!text-emerald-400' : 'group-hover:!text-white'}`} />
                      <span className="flex-1 truncate text-[13px] !text-inherit">{i18n.abandonedCartsTitle || 'Abandoned Carts'}</span>
                      <div className="size-4 flex items-center justify-center">
                        <ChevronDown className={`size-3.5 transition-transform duration-200 ${isAbandonedOpen ? '' : '-rotate-90'}`} />
                      </div>
                    </div>
                  </SidebarMenuButton>
                  {isAbandonedOpen && (
                    <SidebarMenuSub className="border-white/10 pr-0 mr-0 mt-0.5">
                      <SubItem {...navProps} section="abandoned_carts" icon={Flag} label={i18n.sessions || 'Sessions'} />
                      <SubItem {...navProps} section="abandoned_carts_notifications" icon={Bell} label={i18n.reminders || 'Reminders'} />
                      <SubItem {...navProps} section="abandoned_carts_settings" icon={Tv} label={i18n.cartSettings || 'Settings'} />
                    </SidebarMenuSub>
                  )}
                </SidebarMenuItem>
              )}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        {/* ENGAGEMENT */}
        <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">
              {isEnabled(localEnabledSections.chatWidget) && <NavItem {...navProps} section="chat_widget" icon={MessageCircle} label={i18n.whatsappChat || 'WhatsApp Chat'} />}
              {isEnabled(localEnabledSections.notifications) && <NavItem {...navProps} section="notifications" icon={Zap} label={i18n.automatedNotif || 'Automated Notif'} />}
              {isEnabled(localEnabledSections.campaigns) && <NavItem {...navProps} section="campaigns" icon={Target} label={i18n.bulkCampaigns || 'Bulk Campaigns'} />}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        {/* AUTHENTICATIONS */}
        <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">
              {isEnabled(localEnabledSections.otpLogin) && <NavItem {...navProps} section="passwordless-login" icon={Fingerprint} label={i18n.passwordlessLogin || 'Passwordless Login'} />}
              {isEnabled(localEnabledSections.signupOtp) && <NavItem {...navProps} section="registration-form" icon={PencilLine} label={i18n.registrationForm || 'Registration Form'} />}
              {isEnabled(localEnabledSections.checkoutOtp) && <NavItem {...navProps} section="checkout-verification" icon={Lock} label={i18n.checkoutVerif || 'Checkout Verification'} />}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        {/* RESOURCES */}
        <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">
                    <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>
                    <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>
                    <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>
                    <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
