import { useState, useEffect, useCallback } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { Layout, Menu, Dropdown, Button, Typography, Drawer, Grid, theme, Tooltip, Modal, Badge } from 'antd';
import {
  DashboardOutlined,
  SendOutlined,
  IdcardOutlined,
  MailOutlined,
  MessageOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  SettingOutlined,
  LogoutOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MenuOutlined,
  ScissorOutlined,
  CalendarOutlined,
  ScheduleOutlined,
  FileTextOutlined,
  NotificationOutlined,
  BookOutlined,
  GlobalOutlined,
  CodeOutlined,
  DatabaseOutlined,
  ApiOutlined,
  BranchesOutlined,
  CloudServerOutlined,
  QrcodeOutlined,
  PlaySquareOutlined,
  FolderOutlined,
  HistoryOutlined,
  LineChartOutlined,
  BarChartOutlined,
  SoundOutlined,
  EditOutlined,
  OrderedListOutlined,
  DollarOutlined,
  ShoppingOutlined,
  HeartOutlined,
  CrownOutlined,
  PictureOutlined,
  LockOutlined,
  PhoneOutlined,
  TagOutlined,
  SearchOutlined,
  ContactsOutlined,
  VideoCameraOutlined,
  ApartmentOutlined,
  SafetyOutlined,
  StarFilled,
  StarOutlined,
  TrophyOutlined,
  FlagOutlined,
  UserAddOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { hasAnyRole } from '@/utils/roles';
import type { PageHeaderConfig, AppOutletContext, User } from '@/types/api';
import {
  INFLUENCE_ROLES,
  BROADCAST_ROLES,
  CONTENT_ROLES,
  MAP_ROLES,
  SCHEDULING_ROLES,
  MEDIA_ROLES,
  PAYMENTS_ROLES,
  SOCIAL_ROLES,
  POLLS_ROLES,
  ANALYTICS_ROLES,
} from '@/types/api';
import { buildHomeUrl, resolveNavUrl } from '@/lib/service-url';
import type { NavItem } from '@/types/api';
import {
  DEFAULT_NAV_ITEMS,
  ICON_MAP,
  mergeNavDefaults,
  filterNavItems,
  buildFeatureFlags,
  applyAdminOverrides,
} from '@/lib/nav-defaults';
import { useCommandPaletteStore } from '@/stores/command-palette.store';
import { useFavoritesStore } from '@/stores/favorites.store';
import { useTourStore } from '@/stores/tour.store';
import { AdminTour } from './tour/AdminTour';
import { TourHub } from './tour/TourHub';
import { TourTriggerButton } from './tour/TourTriggerButton';
import { resolveValidFavorites, collectLeafKeys } from '@/utils/menu-items';
import RocketChatWidget from './chat/RocketChatWidget';

// Re-export for backward compatibility
export type { PageHeaderConfig, AppOutletContext };

/** Wrap a leaf menu item's label with a favorite star toggle */
function FavoriteLabel({ label, itemKey }: { label: React.ReactNode; itemKey: string }) {
  const { isFavorite, toggleFavorite } = useFavoritesStore();
  const starred = isFavorite(itemKey);
  return (
    <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
      <span
        className={`favorite-star${starred ? ' favorite-star--active' : ''}`}
        onClick={(e) => { e.stopPropagation(); toggleFavorite(itemKey); }}
        style={{ fontSize: 12, lineHeight: 1, cursor: 'pointer', flexShrink: 0 }}
      >
        {starred ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined style={{ color: 'rgba(255,255,255,0.45)' }} />}
      </span>
    </span>
  );
}

/** Recursively walk menu items, wrapping leaf labels with FavoriteLabel stars */
function addStarsToMenuItems(items: MenuProps['items'], leafKeys: Set<string>): MenuProps['items'] {
  if (!items) return items;
  return items.map(item => {
    if (!item) return item;
    if ('children' in item && item.children) {
      return { ...item, children: addStarsToMenuItems(item.children as MenuProps['items'], leafKeys) } as typeof item;
    }
    if ('key' in item && 'label' in item && item.key && leafKeys.has(item.key as string)) {
      return { ...item, label: <FavoriteLabel label={item.label} itemKey={item.key as string} /> } as typeof item;
    }
    return item;
  });
}

const { Header, Sider, Content } = Layout;
const { Text } = Typography;
const { useBreakpoint } = Grid;

/** Admin icon overrides: some icons differ in the admin header context */
const ADMIN_ICON_OVERRIDES: Record<string, React.ReactNode> = {
  SendOutlined: <SoundOutlined />,
  PlayCircleOutlined: <PlaySquareOutlined />,
};

function buildMenuItems(settings: import('@/types/api').SiteSettings | null, user: User | null, badges?: { pendingResponses?: number; pendingEmails?: number; pendingCampaignReview?: number; pendingComments?: number }): MenuProps['items'] {
  const isSuperAdmin = hasAnyRole(user, ['SUPER_ADMIN']);
  const can = (roles: import('@/types/api').UserRole[]) => hasAnyRole(user, roles);

  const items: MenuProps['items'] = [
    {
      key: '/app',
      icon: <DashboardOutlined />,
      label: 'Dashboard',
    },
  ];

  // People & Access submenu — Users visible to any admin, social sub-items gated by SOCIAL_ROLES
  {
    const communityChildren: MenuProps['items'] = [];
    if (settings?.enablePeople) {
      communityChildren.push({ key: '/app/people', icon: <ContactsOutlined />, label: 'People' });
    }
    communityChildren.push({ key: '/app/users', icon: <TeamOutlined />, label: 'Users' });
    if (settings?.enableSocial && can(SOCIAL_ROLES)) {
      communityChildren.push(
        { key: '/app/social', icon: <HeartOutlined />, label: 'Social Dashboard' },
        { key: '/app/social/graph', icon: <ApartmentOutlined />, label: 'Social Graph' },
        { key: '/app/social/moderation', icon: <SafetyOutlined />, label: 'Social Moderation' },
        { key: '/app/social/referrals', icon: <UserAddOutlined />, label: 'Referrals' },
        { key: '/app/social/spotlights', icon: <StarOutlined />, label: 'Spotlights' },
        { key: '/app/social/challenges', icon: <FlagOutlined />, label: 'Challenges' },
      );
    }
    items.push({
      key: 'community-submenu',
      icon: <ContactsOutlined />,
      label: 'People & Access',
      children: communityChildren,
    });
  }

  if (settings?.enableInfluence !== false && can(INFLUENCE_ROLES)) {
    items.push({
      key: 'influence-submenu',
      icon: <SendOutlined />,
      label: 'Advocacy',
      children: [
        { key: '/app/campaigns', icon: <SendOutlined />, label: 'Campaigns' },
        { key: '/app/campaign-moderation', icon: <FileTextOutlined />, label: badges?.pendingCampaignReview ? <Badge count={badges.pendingCampaignReview} size="small" offset={[8, 0]}>Campaign Review</Badge> : 'Campaign Review' },
        { key: '/app/representatives', icon: <IdcardOutlined />, label: 'Representatives' },
        { key: '/app/email-queue', icon: <MailOutlined />, label: badges?.pendingEmails ? <Badge count={badges.pendingEmails} size="small" offset={[8, 0]}>Outgoing Emails</Badge> : 'Outgoing Emails' },
        { key: '/app/responses', icon: <MessageOutlined />, label: badges?.pendingResponses ? <Badge count={badges.pendingResponses} size="small" offset={[8, 0]}>Responses</Badge> : 'Responses' },
        { key: '/app/influence/action-campaigns', icon: <TrophyOutlined />, label: 'Action Campaigns' },
        { key: '/app/influence/effectiveness', icon: <LineChartOutlined />, label: 'Effectiveness' },
        { key: '/app/influence/stories', icon: <TrophyOutlined />, label: 'Impact Stories' },
        ...(settings?.enablePetitions !== false ? [
          { key: '/app/influence/petitions', icon: <FileTextOutlined />, label: 'Petitions' },
          { key: '/app/influence/petitions/moderation', icon: <FileTextOutlined />, label: 'Petition Review' },
        ] : []),
        ...(settings?.enablePolls !== false && can(POLLS_ROLES) ? [{ key: '/app/influence/straw-polls', icon: <BarChartOutlined />, label: 'Straw Polls' }] : []),
      ],
    });
  }

  if (settings?.enableNewsletter !== false && can(BROADCAST_ROLES)) {
    const broadcastChildren: MenuProps['items'] = [
      { key: '/app/listmonk', icon: <MailOutlined />, label: 'Newsletter' },
      { key: '/app/email-templates', icon: <FileTextOutlined />, label: 'Email Templates' },
    ];
    if (settings?.enableChat) {
      broadcastChildren.push({ key: '/app/services/rocketchat', icon: <MessageOutlined />, label: 'Team Chat' });
    }
    if (settings?.enableSms || isSuperAdmin) {
      broadcastChildren.push(
        { key: '/app/sms/setup', icon: <SettingOutlined />, label: 'SMS Setup' },
      );
    }
    if (settings?.enableSms) {
      broadcastChildren.push(
        { key: '/app/sms', icon: <PhoneOutlined />, label: 'SMS Dashboard' },
        { key: '/app/sms/contacts', icon: <TeamOutlined />, label: 'SMS Contacts' },
        { key: '/app/sms/campaigns', icon: <SendOutlined />, label: 'SMS Campaigns' },
        { key: '/app/sms/conversations', icon: <MessageOutlined />, label: 'SMS Threads' },
        { key: '/app/sms/templates', icon: <FileTextOutlined />, label: 'SMS Templates' },
      );
    }
    items.push({
      key: 'broadcast-submenu',
      icon: <NotificationOutlined />,
      label: 'Broadcast',
      children: broadcastChildren,
    });
  }

  // Web submenu — conditionally include Landing Pages
  if (can(CONTENT_ROLES)) {
    const webChildren: MenuProps['items'] = [];
    if (settings?.enableLandingPages !== false) {
      webChildren.push({ key: '/app/pages', icon: <FileTextOutlined />, label: 'Landing Pages' });
    }
    webChildren.push({ key: '/app/navigation', icon: <GlobalOutlined />, label: 'Navigation' });
    webChildren.push({ key: '/app/docs', icon: <BookOutlined />, label: 'Documentation' });
    webChildren.push({ key: '/app/docs/analytics', icon: <BarChartOutlined />, label: 'Analytics' });
    webChildren.push({ key: '/app/docs/comments', icon: <MessageOutlined />, label: badges?.pendingComments ? <Badge count={badges.pendingComments} size="small" offset={[8, 0]}>Comments</Badge> : 'Comments' });
    webChildren.push({ key: '/app/docs/metadata', icon: <DatabaseOutlined />, label: 'Metadata' });
    webChildren.push({ key: '/app/docs/settings', icon: <SettingOutlined />, label: 'Docs Settings' });
    webChildren.push({ key: '/app/code', icon: <CodeOutlined />, label: 'Code Editor' });
    items.push({
      key: 'web-submenu',
      icon: <GlobalOutlined />,
      label: 'Web',
      children: webChildren,
    });
  }

  if (settings?.enableMap !== false && can(MAP_ROLES)) {
    items.push({
      key: 'map-submenu',
      icon: <EnvironmentOutlined />,
      label: 'Map',
      children: [
        { key: '/app/map', icon: <EnvironmentOutlined />, label: 'Locations' },
        { key: '/app/map/data-quality', icon: <BarChartOutlined />, label: 'Data Quality' },
        { key: '/app/map/cuts', icon: <ScissorOutlined />, label: 'Areas' },
        { key: '/app/map/canvass', icon: <TeamOutlined />, label: 'Canvassing' },
        { key: '/app/map/settings', icon: <SettingOutlined />, label: 'Settings' },
      ],
    });
  }

  // Scheduling submenu — visible if relevant features are enabled AND user has SCHEDULING_ROLES
  if (can(SCHEDULING_ROLES) && (settings?.enableMap !== false || settings?.enableMeetingPlanner || settings?.enableTicketedEvents || settings?.enableMeet || settings?.enableEvents)) {
    const schedulingChildren: any[] = [];
    if (settings?.enableMap !== false) {
      schedulingChildren.push({ key: '/app/map/shifts', icon: <ScheduleOutlined />, label: 'Shifts' });
    }
    if (settings?.enableMeetingPlanner) {
      schedulingChildren.push({ key: '/app/meeting-planner', icon: <ScheduleOutlined />, label: 'Meeting Planner' });
      schedulingChildren.push({ key: '/app/meetings/agendas', icon: <FileTextOutlined />, label: 'Agendas' });
      schedulingChildren.push({ key: '/app/meetings/action-items', icon: <OrderedListOutlined />, label: 'Action Items' });
    }
    if (settings?.enableTicketedEvents) {
      schedulingChildren.push({ key: '/app/events', icon: <TagOutlined />, label: 'Events' });
    }
    if (settings?.enableMeet) {
      schedulingChildren.push({ key: '/app/services/jitsi', icon: <VideoCameraOutlined />, label: 'Video Meet' });
    }
    if (settings?.enableEvents) {
      schedulingChildren.push({ key: '/app/services/gancio', icon: <GlobalOutlined />, label: 'Gancio' });
    }
    // Always add Calendar as the last item in scheduling
    schedulingChildren.push({ key: '/app/scheduling/calendar', icon: <CalendarOutlined />, label: 'Calendar' });
    if (schedulingChildren.length > 0) {
      items.push({
        key: 'scheduling-submenu',
        icon: <ScheduleOutlined />,
        label: 'Scheduling',
        children: schedulingChildren,
      });
    }
  }

  if (settings?.enableMediaFeatures !== false && can(MEDIA_ROLES)) {
    items.push({
      key: 'media-submenu',
      icon: <PlaySquareOutlined />,
      label: 'Media',
      children: [
        { key: '/app/media/library', icon: <FolderOutlined />, label: 'Library' },
        { key: '/app/media/analytics', icon: <BarChartOutlined />, label: 'Analytics' },
        { key: '/app/media/curated', icon: <OrderedListOutlined />, label: 'Curated' },
        { key: '/app/media/moderation', icon: <MessageOutlined />, label: 'Moderation' },
        { key: '/app/media/jobs', icon: <HistoryOutlined />, label: 'Processing Jobs' },
      ],
    });
  }

  if (settings?.enablePayments && can(PAYMENTS_ROLES)) {
    items.push({
      key: 'payments-submenu',
      icon: <DollarOutlined />,
      label: 'Payments',
      children: [
        { key: '/app/payments', icon: <DashboardOutlined />, label: 'Dashboard' },
        { key: '/app/payments/plans', icon: <TagOutlined />, label: 'Plans' },
        { key: '/app/payments/subscribers', icon: <CrownOutlined />, label: 'Subscribers' },
        { key: '/app/payments/products', icon: <ShoppingOutlined />, label: 'Products' },
        { key: '/app/payments/donation-pages', icon: <HeartOutlined />, label: 'Donation Pages' },
        { key: '/app/payments/donations', icon: <DollarOutlined />, label: 'Donation Orders' },
        { key: '/app/payments/ads', icon: <PictureOutlined />, label: 'Gallery Ads' },
        { key: '/app/payments/ads/analytics', icon: <BarChartOutlined />, label: 'Ad Analytics' },
        { key: '/app/payments/settings', icon: <SettingOutlined />, label: 'Settings' },
      ],
    });
  }

  if (isSuperAdmin) {
  if (settings?.enableAnalytics !== false && can(ANALYTICS_ROLES)) {
    items.push({
      key: 'analytics-submenu',
      icon: <BarChartOutlined />,
      label: 'Analytics',
      children: [
        { key: '/app/analytics', icon: <DashboardOutlined />, label: 'Overview' },
        { key: '/app/analytics/geo', icon: <GlobalOutlined />, label: 'Geography' },
        { key: '/app/analytics/content', icon: <FileTextOutlined />, label: 'Content' },
        { key: '/app/analytics/users', icon: <TeamOutlined />, label: 'Users' },
      ],
    });
  }

    items.push({
      key: 'services-submenu',
      icon: <CloudServerOutlined />,
      label: 'Services',
      children: [
        { type: 'group', label: 'Infrastructure', children: [
          { key: '/app/tunnel', icon: <CloudServerOutlined />, label: 'Tunnel' },
          { key: '/app/control-panel', icon: <ApiOutlined />, label: 'Control Panel' },
          { key: '/app/observability', icon: <LineChartOutlined />, label: 'Monitoring' },
          { key: '/app/services/nocodb', icon: <DatabaseOutlined />, label: 'Database' },
          { key: '/app/services/vaultwarden', icon: <LockOutlined />, label: 'Vault' },
          { key: '/app/services/mailhog', icon: <MailOutlined />, label: 'MailHog' },
        ]},
        { type: 'group', label: 'Tools', children: [
          { key: '/app/services/n8n', icon: <ApiOutlined />, label: 'Workflows' },
          { key: '/app/services/gitea', icon: <BranchesOutlined />, label: 'Git' },
          { key: '/app/services/gitea/setup', icon: <SettingOutlined />, label: 'Gitea Setup' },
          { key: '/app/services/excalidraw', icon: <EditOutlined />, label: 'Whiteboard' },
          { key: '/app/services/miniqr', icon: <QrcodeOutlined />, label: 'QR Codes' },
        ]},
      ],
    });
  }

  if (isSuperAdmin) {
    items.push(
      {
        key: '/app/settings',
        icon: <SettingOutlined />,
        label: 'Settings',
      },
    );
  }

  return items;
}

export default function AppLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [pageHeader, setPageHeader] = useState<PageHeaderConfig | null>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const { user, logout } = useAuthStore();
  const { settings } = useSettingsStore();
  const { token } = theme.useToken();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const [badgeCounts, setBadgeCounts] = useState<{ pendingResponses: number; pendingEmails: number; pendingCampaignReview: number; pendingComments: number }>({ pendingResponses: 0, pendingEmails: 0, pendingCampaignReview: 0, pendingComments: 0 });

  const fetchBadges = useCallback(() => {
    api.get('/dashboard/summary').then(({ data }) => {
      setBadgeCounts({
        pendingResponses: data?.responses?.pending ?? 0,
        pendingEmails: data?.emails?.queued ?? 0,
        pendingCampaignReview: data?.campaignModeration?.pendingReview ?? 0,
        pendingComments: data?.docsComments?.pending ?? 0,
      });
    }).catch(() => {});
  }, []);

  useEffect(() => {
    fetchBadges();
    const interval = setInterval(fetchBadges, 120_000);
    return () => clearInterval(interval);
  }, [fetchBadges]);

  const baseMenuItems = buildMenuItems(settings, user, badgeCounts);
  const { favorites } = useFavoritesStore();

  // Build final menu: resolve favorites, add stars, prepend favorites section
  const menuItems = (() => {
    const leafKeys = collectLeafKeys(baseMenuItems);
    const starredItems = addStarsToMenuItems(baseMenuItems, leafKeys);

    // Resolve favorites against current menu (handles feature-flag changes)
    const validFavorites = resolveValidFavorites(baseMenuItems, favorites);
    if (validFavorites.length === 0) return starredItems;

    const favSection: NonNullable<MenuProps['items']> = [
      {
        type: 'group' as const,
        label: 'Favorites',
        children: validFavorites.map(fav => ({
          key: `fav:${fav.key}`,
          icon: fav.icon,
          label: fav.label,
        })),
      },
      { type: 'divider' as const },
    ];
    return [...favSection, ...(starredItems || [])];
  })();

  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    // Strip 'fav:' prefix from favorites section items
    const route = key.startsWith('fav:') ? key.slice(4) : key;
    navigate(route);
    if (isMobile) setDrawerOpen(false);
  };

  const handleLogout = () => {
    Modal.confirm({
      title: 'Log out?',
      icon: <LogoutOutlined />,
      okText: 'Log out',
      okType: 'danger',
      onOk: async () => {
        await logout();
        navigate('/login', { replace: true });
      },
    });
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'tour',
      icon: <QuestionCircleOutlined />,
      label: 'Learning Tours',
      onClick: () => {
        useTourStore.getState().openHub();
      },
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: 'Logout',
      onClick: handleLogout,
    },
  ];

  // Match the current path to a menu key (supports submenus and item groups)
  const selectedKey = (() => {
    const path = location.pathname;
    // Exact match first
    if (path === '/app') return '/app';
    // Check all items including children and group grandchildren — longest match wins
    let best = '';
    const checkKey = (k: string) => {
      if (k.startsWith('/') && (path === k || path.startsWith(k + '/'))) {
        if (k.length > best.length) best = k;
      }
    };
    for (const item of menuItems || []) {
      if (!item || !('key' in item)) continue;
      if ('children' in item && item.children) {
        for (const child of item.children) {
          if (!child) continue;
          // Handle item groups (type: 'group') — check their nested children
          if ('type' in child && child.type === 'group' && 'children' in child && child.children) {
            for (const grandchild of child.children) {
              if (!grandchild || !('key' in grandchild)) continue;
              checkKey(grandchild.key as string);
            }
          } else if ('key' in child) {
            checkKey(child.key as string);
          }
        }
      }
      const k = item.key?.toString() || '';
      if (k !== '/app') checkKey(k);
    }
    return best || '/app';
  })();

  // Also highlight the corresponding favorite item if present
  const selectedKeys = favorites.includes(selectedKey)
    ? [selectedKey, `fav:${selectedKey}`]
    : [selectedKey];

  // Derive which submenus should be open based on active route
  const defaultOpenKeys = (() => {
    const path = location.pathname;
    const keys: string[] = [];
    for (const item of menuItems || []) {
      if (!item || !('children' in item) || !item.children) continue;
      let found = false;
      for (const child of item.children) {
        if (found) break;
        if (!child) continue;
        // Handle item groups (type: 'group') — check their nested children
        if ('type' in child && child.type === 'group' && 'children' in child && child.children) {
          for (const grandchild of child.children) {
            if (!grandchild || !('key' in grandchild)) continue;
            const k = grandchild.key as string;
            if (path === k || path.startsWith(k + '/')) {
              keys.push(item.key as string);
              found = true;
              break;
            }
          }
        } else if ('key' in child) {
          const k = child.key as string;
          if (path === k || path.startsWith(k + '/')) {
            keys.push(item.key as string);
            found = true;
          }
        }
      }
    }
    return keys;
  })();

  const fullBleed = pageHeader?.fullBleed === true;

  const logoUrl = settings?.organizationLogoUrl;
  const showLogo = logoUrl && !(collapsed && !isMobile);

  const sidebarMenu = (
    <>
      <div
        style={{
          height: 64,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: '#fff',
          fontWeight: 600,
          fontSize: collapsed && !isMobile ? 14 : 16,
          borderBottom: '1px solid rgba(255,255,255,0.1)',
          padding: '0 8px',
          gap: 8,
        }}
      >
        {showLogo ? (
          <img
            src={logoUrl}
            alt={settings?.organizationName ?? 'Logo'}
            style={{ maxHeight: 36, maxWidth: collapsed && !isMobile ? 48 : 160, objectFit: 'contain' }}
          />
        ) : (
          collapsed && !isMobile
            ? (settings?.organizationShortName ?? 'CML')
            : (settings?.organizationName ?? 'Changemaker Lite')
        )}
      </div>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKeys}
        defaultOpenKeys={defaultOpenKeys}
        items={menuItems}
        onClick={handleMenuClick}
      />
    </>
  );

  return (
    <>
    <style>{`
      .favorite-star { opacity: 0; transition: opacity 0.15s; }
      .favorite-star--active { opacity: 1; }
      .ant-menu-item:hover .favorite-star { opacity: 1; }
    `}</style>
    <Layout style={{ minHeight: '100vh' }}>
      {isMobile ? (
        <Drawer
          placement="left"
          open={drawerOpen}
          onClose={() => setDrawerOpen(false)}
          width={256}
          styles={{ body: { padding: 0, background: '#001529' }, header: { display: 'none' } }}
        >
          {sidebarMenu}
        </Drawer>
      ) : (
        <Sider
          trigger={null}
          collapsible
          collapsed={collapsed}
          data-tour="sidebar"
          style={{ overflow: 'auto', height: '100vh', position: 'sticky', top: 0, left: 0 }}
        >
          {sidebarMenu}
        </Sider>
      )}
      <Layout>
        <Header
          style={{
            padding: '0 16px',
            background: 'transparent',
            display: 'flex',
            alignItems: 'center',
            gap: 2,
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
          }}
        >
          <Button
            type="text"
            icon={
              isMobile
                ? <MenuOutlined />
                : collapsed
                  ? <MenuUnfoldOutlined />
                  : <MenuFoldOutlined />
            }
            onClick={() => (isMobile ? setDrawerOpen(true) : setCollapsed(!collapsed))}
          />
          {pageHeader?.title && (
            <Text strong style={{ fontSize: 16, whiteSpace: 'nowrap' }}>
              {pageHeader.title}
            </Text>
          )}
          <div style={{ flex: 1 }} />
          <Tooltip title={navigator.platform?.toLowerCase().includes('mac') ? 'Search (⌘K)' : 'Search (Ctrl+K)'}>
            <Button
              type="text"
              icon={<SearchOutlined />}
              data-tour="search-button"
              onClick={() => useCommandPaletteStore.getState().open()}
            />
          </Tooltip>
          {pageHeader?.actions}
          {!isMobile && (() => {
            const merged = mergeNavDefaults(settings?.navConfig?.items ?? DEFAULT_NAV_ITEMS);
            const withOverrides = applyAdminOverrides(merged);
            const flags = buildFeatureFlags(settings);
            const filtered = filterNavItems(withOverrides, flags);

            const getIcon = (iconName: string) => ADMIN_ICON_OVERRIDES[iconName] ?? ICON_MAP[iconName] ?? <GlobalOutlined />;
            const handleItemClick = (item: NavItem) => {
              if (item.path.startsWith('$')) {
                window.open(resolveNavUrl(item.path), '_blank', 'noopener,noreferrer');
              } else if (item.external && item.id === 'home') {
                window.open(buildHomeUrl(), '_blank', 'noopener,noreferrer');
              } else if (item.external) {
                // Only open http/https URLs to prevent javascript: URI injection
                if (item.path.startsWith('http://') || item.path.startsWith('https://')) {
                  window.open(item.path, '_blank', 'noopener,noreferrer');
                }
              } else {
                navigate(item.path);
              }
            };

            return filtered.map(item => {
              if (item.type === 'group' && item.children) {
                return (
                  <Dropdown
                    key={item.id}
                    menu={{
                      items: item.children.map(child => ({
                        key: child.id,
                        icon: getIcon(child.icon),
                        label: child.label,
                        onClick: () => handleItemClick(child),
                      })),
                    }}
                    placement="bottomRight"
                  >
                    <Button type="text" size="small" icon={getIcon(item.icon)}>
                      {!collapsed && item.label}
                    </Button>
                  </Dropdown>
                );
              }
              return (
                <Tooltip key={item.id} title={item.label}>
                  <Button
                    type="text"
                    size="small"
                    icon={getIcon(item.icon)}
                    onClick={() => handleItemClick(item)}
                  >
                    {!collapsed && item.label}
                  </Button>
                </Tooltip>
              );
            });
          })()}
          {/* Volunteer Portal button — always visible for quick switching */}
          {!isMobile && (
            <Tooltip title="Switch to Volunteer Portal">
              <Button
                type="text"
                size="small"
                icon={<TeamOutlined />}
                onClick={() => navigate('/volunteer')}
              >
                {!collapsed && 'Volunteer'}
              </Button>
            </Tooltip>
          )}
          <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
            <Button type="text" icon={<UserOutlined />} data-tour="user-menu">
              {!isMobile && !collapsed && (
                <Text style={{ marginLeft: 8 }}>
                  {user?.name || user?.email || 'User'}
                </Text>
              )}
            </Button>
          </Dropdown>
        </Header>
        <Content
          id="app-content-area"
          style={{
            margin: fullBleed ? 0 : (isMobile ? 12 : 24),
            padding: fullBleed ? 0 : (isMobile ? 16 : 24),
            background: 'transparent',
            borderRadius: fullBleed ? 0 : token.borderRadiusLG,
            minHeight: 280,
            overflow: fullBleed ? 'hidden' : undefined,
            position: 'relative',
          }}
        >
          <Outlet context={{ setPageHeader } satisfies AppOutletContext} />
        </Content>
      </Layout>
    </Layout>
    <AdminTour />
    <TourHub />
    <TourTriggerButton />
    <RocketChatWidget />
    </>
  );
}
