'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useCallback, useEffect, useRef, useState } from 'react';
import {
  AccountBadge,
  AccountSwitcher,
  rememberSwitch,
  useSwitchedToast,
} from '@/components/crm/AccountSwitcher';
import { BrandLogo } from '@/components/crm/BrandLogo';
import { ClientNotificationDelivery } from '@/components/crm/ClientNotificationDelivery';
import { createDrawerFocus } from '@/components/crm/drawerFocus';
import { APP_NAME, CRM_ASSETS } from '@/config/constants';
import { logout, switchBusiness } from '@/features/auth/api.client';
import { forgetAllDrafts } from '@/features/inbox/drafts';
import { signOutExtension } from '@/features/extension/bridge';
import { stopImpersonating } from '@/features/members/api.client';
import { listObjectDefinitions, onObjectDefinitionsChanged } from '@/features/objects/api.client';
import { listObjectLabels, onObjectLabelsChanged } from '@/features/objects/labels';
import { objectListPath } from '@/features/objects/paths';
import { compareSidebarObjects } from '@/features/objects/sidebarOrder';
import { GlobalSearch } from '@/features/search/ui/GlobalSearch';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import type { MeResponse } from '@/types/api';
import { apiGet } from '@/lib/api/client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { canUsePlaybooks } from '@/features/playbooks/access';
import { rememberAppPath } from '@/lib/utils/last-app-path';

function Icon({
  d,
  className = 'icon iconSize-18',
  size = 18,
}: {
  d: string;
  className?: string;
  size?: number;
}) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      focusable={false}
    >
      <path d={d} />
    </svg>
  );
}

const NAV_GROUPS = [
  {
    key: 'crm',
    label: 'CRM',
    icon: 'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75',
    // 13 Nov design sidebar: Contacts, Companies, Deals, then the custom objects (Leads, Tickets,
    // Events; inserted after Deals below), Segments, Inbox, Calls, Meetings, Tasks, Playbooks,
    // Message Templates (HUB-721).
    links: [
      { href: '/contacts', label: 'Contacts' },
      { href: '/companies', label: 'Companies' },
      { href: '/deals', label: 'Deals' },
      { href: '/lists', label: 'Segments' },
      { href: '/inbox', label: 'Inbox' },
      { href: '/calls', label: 'Calls' },
      { href: '/meetings', label: 'Meetings' },
      { href: '/tasks', label: 'Tasks' },
      // 28 Oct design: Playbooks (PB8: hidden without the "Playbooks" permission).
      { href: '/playbooks', label: 'Playbooks' },
      { href: '/templates', label: 'Message Templates' },
    ],
  },
  {
    key: 'sales',
    label: 'Sales',
    icon: 'M4 5h16l-6 7.5V19l-4 1.5v-8z',
    // 13 Nov design (HUB-710): Sales Workspace, Calendar, Target Accounts, Documents, Meeting
    // Scheduler, Sequences, Activity Feed, Forecast, Sales Analytics. Quotes isn't in the
    // design's sidebar but has no other way in, so it stays here after Sales Analytics.
    // MT-6 (D-4, D-19): no Calendar link; /calendar is folded into Meetings' Calendar views.
    links: [
      { href: '/sales-workspace', label: 'Sales Workspace' },
      { href: '/target-accounts', label: 'Target Accounts' },
      { href: '/documents', label: 'Documents' },
      // Go-live bug 907: sales content sits under Sales, not CRM.
      { href: '/snippets', label: 'Snippets' },
      { href: '/meeting-scheduler', label: 'Meeting Scheduler' },
      { href: '/sequences', label: 'Sequences' },
      { href: '/activity-feed', label: 'Activity Feed' },
      { href: '/forecast', label: 'Forecast' },
      { href: '/sales-analytics', label: 'Sales Analytics' },
      { href: '/quotes', label: 'Quotes' },
    ],
  },
  {
    key: 'data',
    label: 'Data Management',
    icon: 'M4 6c0-1.7 3.6-3 8-3s8 1.3 8 3-3.6 3-8 3-8-1.3-8-3M4 6v12c0 1.7 3.6 3 8 3s8-1.3 8-3V6M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3',
    links: [
      { href: '/data-integration', label: 'Data Integration' },
      { href: '/data-model', label: 'Data Model' },
    ],
  },
  {
    key: 'automation',
    label: 'Automation',
    icon: 'M3.5 6a2.5 2.5 0 1 0 5 0a2.5 2.5 0 1 0-5 0M15.5 18a2.5 2.5 0 1 0 5 0a2.5 2.5 0 1 0-5 0M8.5 6H14a3 3 0 0 1 3 3v6.5',
    // The design's Overview and Workflows are views of /workflows: Overview is marked on every
    // tab but Workflows (Analyze and Health too), as the design marks it.
    links: [
      { href: '/workflows', label: 'Overview', exact: true },
      { href: '/workflows?tab=workflows', label: 'Workflows' },
    ],
  },
  {
    key: 'reporting',
    label: 'Reporting',
    icon: 'M4 4v16h16M8 16v-4M12 16V8M16 16v-6',
    links: [
      { href: '/reports/dashboards', label: 'Dashboards' },
      { href: '/reports', label: 'Reports' },
      { href: '/goals', label: 'Goals' },
    ],
  },
] as const;

type NavGroupKey = (typeof NAV_GROUPS)[number]['key'];

/** A sidebar link; `also` are other paths that mark it active (`/objects/event` for `/events`). */
type NavLink = {
  href: string;
  label: string;
  also?: string;
  exact?: boolean;
  /** Custom objects: the singular name, for the Create menu (HUB-746 #5). */
  singular?: string;
};

type NavGroupView = { key: NavGroupKey; label: string; icon: string; links: NavLink[] };

/** The design's order for the custom objects under CRM (Leads, Tickets, Events); any others follow by name. */
export function sortObjectLinks(links: NavLink[]): NavLink[] {
  return [...links].sort((a, b) => compareSidebarObjects(a.label, b.label));
}

/**
 * The one link of a group to highlight: the most specific match, so /reports/dashboards marks
 * Dashboards and not Reports, and /workflows?tab=workflows marks Workflows and not Overview.
 * A link with a query matches its path with those params, or any page under that path.
 */
export function activeNavHref(links: NavLink[], pathname: string, search: string): string | null {
  const params = new URLSearchParams(search);
  const under = (path: string) => pathname === path || pathname.startsWith(`${path}/`);
  let best: { href: string; score: number } | null = null;
  for (const link of links) {
    const [path = link.href, query] = link.href.split('?');
    let score = -1;
    if (query) {
      const want = new URLSearchParams(query);
      const same = [...want].every(([k, v]) => params.get(k) === v);
      if (pathname === path && same) score = path.length + 1000;
      else if (pathname.startsWith(`${path}/`)) score = path.length + 1;
    } else if (link.exact) {
      // The path itself, whatever its query: a link with the matching query still wins.
      if (pathname === path) score = path.length;
    } else if (under(path) || (link.also !== undefined && under(link.also))) {
      score = path.length;
    }
    if (score >= 0 && (!best || score > best.score)) best = { href: link.href, score };
  }
  return best?.href ?? null;
}

/**
 * Pages drawn full screen, without the sidebar and top bar, as HubSpot draws its editors. The page
 * fills the window below any impersonation banner and scrolls its own parts.
 * - The workflow editor `/workflows/[id]` (A-21), not `/workflows/templates` or `/workflows/issues`.
 * - The segment builder `/lists/create` (S-02, D-33).
 */
const BARE_PAGES: readonly RegExp[] = [
  /^\/workflows\/(?!(?:templates|issues)(?:\/|$))[^/]+$/,
  /^\/lists\/create$/,
];

export function isBarePage(pathname: string): boolean {
  return BARE_PAGES.some((page) => page.test(pathname));
}

type NavGroupsProps = {
  groups: NavGroupView[];
  pathname: string;
  openGroups: Record<NavGroupKey, boolean>;
  toggle: (key: NavGroupKey) => void;
};

function NavGroupsWithSearch(props: NavGroupsProps) {
  const search = useSearchParams();
  return <NavGroups {...props} search={search.toString()} />;
}

/**
 * The pop-out of a menu group while the main menu is collapsed to icons: one at a time, for the
 * group pointed at or focused. The style shows it only in the collapsed menu.
 */
function useNavFlyout(pathname: string) {
  const [key, setKey] = useState<string | null>(null);
  const timer = useRef(0);
  const hide = useCallback(() => {
    window.clearTimeout(timer.current);
    setKey(null);
  }, []);
  const show = useCallback((next: string, group: HTMLElement) => {
    window.clearTimeout(timer.current);
    setKey(next);
    // beside its icon, moved up when it would run off the screen
    window.requestAnimationFrame(() => {
      const height = group.querySelector('.nav-group__panel')?.getBoundingClientRect().height ?? 0;
      const top = Math.min(group.getBoundingClientRect().top, window.innerHeight - height - 8);
      group.style.setProperty('--fly-top', `${Math.max(8, top)}px`);
    });
  }, []);
  /** A moment's grace, so the pointer can cross the gap to the pop-out. */
  const hideSoon = useCallback(() => {
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setKey(null), 220);
  }, []);
  useEffect(() => hide(), [pathname, hide]);
  useEffect(() => () => window.clearTimeout(timer.current), []);
  return { key, show, hide, hideSoon };
}

function NavGroups({
  groups,
  pathname,
  openGroups,
  toggle,
  search,
}: NavGroupsProps & { search: string }) {
  const fly = useNavFlyout(pathname);
  return (
    <>
      {groups.map((group) => {
        const active = activeNavHref(group.links, pathname, search);
        const open = openGroups[group.key];
        return (
          <li
            key={group.key}
            className={cn(
              'nav-group',
              fly.key === group.key && 'is-flyout',
              open && 'is-open',
              active && 'has-active',
            )}
            data-nav-group={group.key}
            onMouseEnter={(e) => fly.show(group.key, e.currentTarget)}
            onMouseLeave={fly.hideSoon}
            onFocus={(e) => fly.show(group.key, e.currentTarget)}
            onBlur={(e) => {
              if (!e.currentTarget.contains(e.relatedTarget)) fly.hide();
            }}
            onKeyDown={(e) => {
              if (e.key !== 'Escape') return;
              fly.hide();
            }}
          >
            <button
              type="button"
              className="sidebar__link nav-group__btn"
              aria-expanded={open}
              onClick={() => toggle(group.key)}
            >
              <Icon d={group.icon} />
              <span className="sidebar__text">{group.label}</span>
              <Icon d="m7 10 5 5 5-5" className="icon iconSize-16 nav-group__chev" size={16} />
            </button>
            <div className="nav-group__panel">
              <ul className="nav-group__list">
                {group.links.map((link) => (
                  <li key={link.href}>
                    <Link
                      className={cn('nav-sub', link.href === active && 'is-active')}
                      href={link.href}
                      data-tip={link.label}
                      onClick={fly.hide}
                    >
                      {link.label}
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          </li>
        );
      })}
    </>
  );
}

type OpenMenu = 'create' | 'help' | 'notif' | 'account' | null;

export function AppShell({ me, children }: { me: MeResponse; children: React.ReactNode }) {
  const pathname = usePathname();
  const bare = isBarePage(pathname);
  const homePath = useUserPrefs().homePath;
  const router = useRouter();
  const topbarRef = useRef<HTMLElement>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const sidebarRef = useRef<HTMLElement>(null);
  const [drawerFocus] = useState(() => createDrawerFocus());
  const [openGroups, setOpenGroups] = useState<Record<NavGroupKey, boolean>>({
    crm: true,
    sales: true,
    data: true,
    automation: true,
    reporting: true,
  });
  const [searchOpen, setSearchOpen] = useState(false);
  const [openMenu, setOpenMenu] = useState<OpenMenu>(null);
  // The bell's unread badge and the latest notifications (28 Oct design header).
  const [unread, setUnread] = useState(0);
  const [notes, setNotes] = useState<
    Array<{
      id: string;
      title: string;
      link: string | null;
      readAt: string | null;
      createdAt: string;
    }>
  >([]);
  useEffect(() => {
    let alive = true;
    const load = () =>
      apiGet<{ count: number }>('/notifications/unread-count').then(
        (r) => alive && setUnread(r.count),
        () => {},
      );
    void load();
    const t = window.setInterval(load, 60_000);
    return () => {
      alive = false;
      window.clearInterval(t);
    };
  }, []);
  useEffect(() => {
    if (openMenu !== 'notif') return;
    let alive = true;
    apiGet<{ data: typeof notes }>('/notifications', { params: { limit: 6 } }).then(
      (r) => alive && setNotes(r.data),
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [openMenu]);
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const [switchingBusiness, setSwitchingBusiness] = useState(false);
  const workspaceSync = useRef(false);
  // QA go-live (Tickets 975): the toggle's label follows the menu, whoever collapsed it (button, ⌘B, saved state).
  const [menuCollapsed, setMenuCollapsed] = useState(false);
  useEffect(() => {
    const root = document.documentElement;
    const sync = () => setMenuCollapsed(root.classList.contains('sidebar-collapsed'));
    sync();
    const observer = new MutationObserver(sync);
    observer.observe(root, { attributes: true, attributeFilter: ['class'] });
    return () => observer.disconnect();
  }, []);
  /** The business's custom objects (Events, Leads, Tickets), listed under CRM. */
  const [objectLinks, setObjectLinks] = useState<NavLink[]>([]);
  /** Contacts, Companies and Deals as the business names them (Data Model "Edit object name"). */
  const [builtInNames, setBuiltInNames] = useState<Record<string, string>>({});

  useEffect(() => {
    let alive = true;
    const load = () =>
      listObjectLabels().then(
        (labels) => {
          if (!alive) return;
          setBuiltInNames(
            Object.fromEntries(
              labels.map((l) => [
                `/${{ contact: 'contacts', company: 'companies', deal: 'deals' }[l.objectType]}`,
                l.pluralLabel,
              ]),
            ),
          );
        },
        () => {
          // The default names stay.
        },
      );
    void load();
    const stop = onObjectLabelsChanged(() => void load());
    return () => {
      alive = false;
      stop();
    };
  }, []);

  useEffect(() => {
    let alive = true;
    const load = () =>
      listObjectDefinitions().then(
        (defs) => {
          if (!alive) return;
          setObjectLinks(
            defs
              .map((d) => ({
                href: objectListPath(d.key),
                label: d.pluralLabel,
                singular: d.singularLabel,
                also: `/objects/${encodeURIComponent(d.key)}`,
              }))
              .sort((a, b) => a.label.localeCompare(b.label)),
          );
        },
        () => {
          // The sidebar works without them; the pages are still reachable by URL.
        },
      );
    void load();
    // Objects created, renamed or archived in Settings > Objects show up without a reload.
    const stop = onObjectDefinitionsChanged(() => void load());
    return () => {
      alive = false;
      stop();
    };
  }, []);

  // D-16: the drawer's focus, as the design's `setDrawer`. A page change closes it and leaves
  // focus to the new page; Close, the scrim and Escape put focus back where it was.
  const closeDrawer = useCallback(() => {
    setDrawerOpen(false);
    drawerFocus.forget();
  }, [drawerFocus]);
  const dismissDrawer = useCallback(() => {
    setDrawerOpen(false);
    drawerFocus.restore();
  }, [drawerFocus]);
  const openDrawer = () => {
    drawerFocus.open(document.activeElement as HTMLElement | null, () =>
      sidebarRef.current?.querySelector<HTMLElement>('.sidebar__link'),
    );
    setDrawerOpen(true);
  };
  const closeMenus = useCallback(() => setOpenMenu(null), []);

  useEffect(() => {
    closeDrawer();
    closeMenus();
    setSearchOpen(false);
    rememberAppPath(pathname); // for the Settings "Back" link
  }, [pathname, closeDrawer, closeMenus]);

  useEffect(() => {
    // Set again after the page is drawn, as the first script did (app/layout.tsx): the saved
    // choice, else the computer's setting. A page that React has to draw again (Home, where
    // "Log in as user" lands) loses the attribute, and dark mode turned light (go-live QA).
    let saved: string | null = null;
    try {
      saved = localStorage.getItem('crm-theme');
    } catch {
      // private mode: the computer's setting
    }
    const next =
      saved === 'dark' || saved === 'light'
        ? saved
        : window.matchMedia?.('(prefers-color-scheme: dark)').matches
          ? 'dark'
          : 'light';
    document.documentElement.setAttribute('data-theme', next);
    setTheme(next);
  }, []);

  /* Extension OPEN_CRM links pass ?workspace= so the tab matches the Gmail session. */
  useEffect(() => {
    if (workspaceSync.current) return;
    const params = new URLSearchParams(window.location.search);
    const workspace = params.get('workspace');
    if (!workspace) return;
    const url = new URL(window.location.href);
    url.searchParams.delete('workspace');
    const next = `${url.pathname}${url.search}${url.hash}`;
    if (workspace === me.business.id || workspace === me.business.slug) {
      workspaceSync.current = true;
      router.replace(next);
      return;
    }
    workspaceSync.current = true;
    void switchBusiness(workspace)
      .then(() => {
        window.location.assign(next);
      })
      .catch((err) => {
        workspaceSync.current = false;
        window.alert(errorText(err));
        router.replace(next);
      });
  }, [me.business.id, me.business.slug, router]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'b') {
        e.preventDefault();
        document.documentElement.classList.toggle('sidebar-collapsed');
      }
      if (e.key === 'Escape') {
        closeMenus();
        setSearchOpen(false);
        dismissDrawer();
      }
    };
    const onPointer = (e: MouseEvent) => {
      if (!topbarRef.current?.contains(e.target as Node)) closeMenus();
    };
    window.addEventListener('keydown', onKey);
    window.addEventListener('mousedown', onPointer);
    return () => {
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('mousedown', onPointer);
    };
  }, [dismissDrawer, closeMenus]);

  const toggleTheme = () => {
    const next = theme === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    try {
      localStorage.setItem('crm-theme', next);
    } catch {
      // ignore
    }
    setTheme(next);
    // Left open, the menu covers the page's top-right buttons.
    closeMenus();
  };

  const onLogout = async () => {
    try {
      await signOutExtension();
    } catch {
      // extension may be missing
    }
    try {
      await logout();
    } catch {
      // still leave
    }
    // unsent Inbox replies must not stay for whoever uses this browser next
    forgetAllDrafts();
    router.replace('/login?signed_out=1');
  };

  // GLB3 (go-live Blocker 3): one Exit at a time. A second one sent with the old cookie could
  // answer after the first and clear the admin's new cookie.
  const [exiting, setExiting] = useState(false);
  const onStopImpersonating = async () => {
    if (exiting) return;
    setExiting(true);
    try {
      await stopImpersonating();
      window.location.reload();
    } catch (err) {
      setExiting(false);
      window.alert(errorText(err));
    }
  };

  const onSwitchBusiness = async (business: string, name?: string) => {
    if (business === me.business.id || business === me.business.slug || switchingBusiness) return;
    setSwitchingBusiness(true);
    try {
      await switchBusiness(business);
      if (name) rememberSwitch(name);
      closeMenus();
      // Soft refresh keeps client state from the previous business. Hard-navigate so
      // /me, lists, and shell all remount against the new workspace. Detail URLs
      // (e.g. /companies/:id) are not valid across workspaces — drop to the list.
      const listRoot = pathname.match(
        /^\/(contacts|companies|deals|sequences|workflows|tasks|reports)\/[^/]+/,
      );
      window.location.assign(listRoot ? `/${listRoot[1]}` : pathname || '/contacts');
    } catch (err) {
      window.alert(errorText(err));
      setSwitchingBusiness(false);
    }
  };

  const hasOtherAccounts = me.memberships.some((m) => m.business.id !== me.business.id);
  useSwitchedToast();

  const { hasAvatar, avatarVersion } = useUserPrefs();
  const avatarSrc = hasAvatar
    ? `/api/v1/me/profile/avatar?v=${encodeURIComponent(avatarVersion)}`
    : null;
  const initials = me.user.name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((p) => p[0]?.toUpperCase() ?? '')
    .join('');

  const toggleMenu = (menu: OpenMenu) => {
    setOpenMenu((current) => (current === menu ? null : menu));
  };

  return (
    <div
      className={cn(
        'app',
        bare && 'app--bare',
        drawerOpen && 'drawer-open',
        searchOpen && 'search-open',
      )}
    >
      <ClientNotificationDelivery />
      {drawerOpen ? (
        <div className="scrim" data-drawer-close onClick={dismissDrawer} aria-hidden />
      ) : null}

      <aside
        className="sidebar"
        id="sidebar"
        aria-label="Main navigation"
        data-drawer
        ref={sidebarRef}
      >
        <div className="sidebar__head">
          <Link className="brand sidebar__brand" href={homePath} aria-label={`${APP_NAME} home`}>
            <span className="sidebar__logo">
              <BrandLogo />
            </span>
            <img
              className="sidebar__mark"
              src={`${CRM_ASSETS}/img/crm-icon.svg`}
              alt=""
              width={28}
              height={28}
              aria-hidden
            />
          </Link>
          <button
            type="button"
            className="icon-btn icon-btn--ghost sidebar__close"
            aria-label="Close menu"
            onClick={dismissDrawer}
          >
            <Icon d="M6 6l12 12M18 6 6 18" className="icon iconSize-20" size={20} />
          </button>
          <button
            type="button"
            className="sidebar__toggle"
            aria-expanded={!menuCollapsed}
            aria-controls="sidebar"
            aria-label={menuCollapsed ? 'Expand menu' : 'Collapse menu'}
            title={`${menuCollapsed ? 'Expand' : 'Collapse'} menu (⌘B / Ctrl+B)`}
            onClick={() => document.documentElement.classList.toggle('sidebar-collapsed')}
          >
            <Icon d="m15 18-6-6 6-6" className="icon iconSize-16 sidebar__toggle-icon" size={16} />
          </button>
        </div>

        <nav className="sidebar__nav" data-sidebar-nav>
          <ul className="sidebar__list">
            <li>
              <Link
                className={cn('sidebar__link', pathname === '/home' && 'is-active')}
                href="/home"
                data-tip="Home"
              >
                <Icon d="M3 10.5 12 3l9 7.5M5 9.5V20a1 1 0 0 0 1 1h4v-6h4v6h4a1 1 0 0 0 1-1V9.5" />
                <span className="sidebar__text">Home</span>
              </Link>
            </li>
          </ul>

          <hr className="sidebar__rule" />

          <ul className="sidebar__list">
            {(() => {
              // Data Management shows for everyone (the user's call, 18 Nov 2026): Data
              // Integration for anyone with Import, the Data Model view only without Manage
              // settings.
              const groups: NavGroupView[] = NAV_GROUPS.map((group) => {
                const own: NavLink[] = group.links
                  // PB8: Playbooks only with the "Playbooks" permission.
                  .filter((l) => l.href !== '/playbooks' || canUsePlaybooks(me))
                  .map((l) => ({
                    ...l,
                    label: builtInNames[l.href] ?? l.label,
                  }));
                // The design lists the custom objects (Leads, Tickets, Events) right after Deals.
                const links =
                  group.key === 'crm'
                    ? [...own.slice(0, 3), ...sortObjectLinks(objectLinks), ...own.slice(3)]
                    : own;
                return { key: group.key, label: group.label, icon: group.icon, links };
              });
              const toggle = (key: NavGroupKey) => setOpenGroups((g) => ({ ...g, [key]: !g[key] }));
              const props = { groups, pathname, openGroups, toggle };
              // The Automation links differ only by `?tab=`; reading it needs a Suspense boundary.
              return (
                <Suspense fallback={<NavGroups {...props} search="" />}>
                  <NavGroupsWithSearch {...props} />
                </Suspense>
              );
            })()}
          </ul>
        </nav>
      </aside>

      <div className="app__body">
        <header className="topbar" ref={topbarRef}>
          <button
            type="button"
            className="icon-btn topbar__menu crm-w-auto"
            aria-controls="sidebar"
            aria-expanded={drawerOpen}
            aria-label="Open menu"
            onClick={openDrawer}
          >
            <Icon d="M4 6h16M4 12h16M4 18h16" className="icon iconSize-20" size={20} />
          </button>
          <Link className="brand topbar__brand" href={homePath} aria-label={`${APP_NAME} home`}>
            <BrandLogo />
          </Link>

          <GlobalSearch mobileOpen={searchOpen} onMobileClose={() => setSearchOpen(false)} />

          <button type="button" className="assistant-btn" aria-label="Assistant">
            <Icon d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2 2M16 16l2 2M6 18l2-2M16 8l2-2" />
            <span>Assistant</span>
          </button>

          <div className="topbar__tools">
            <button
              type="button"
              className="tb-btn topbar__search-btn"
              aria-label="Search"
              onClick={() => setSearchOpen((v) => !v)}
            >
              <svg
                className="icon iconSize-20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden
              >
                <circle cx="11" cy="11" r="7" />
                <path d="m20 20-3.5-3.5" />
              </svg>
            </button>

            <div className="dropdown" data-dropdown>
              <button
                type="button"
                className="btn-crm btn-crm--primary topbar__create"
                aria-haspopup="menu"
                aria-expanded={openMenu === 'create'}
                onClick={() => toggleMenu('create')}
              >
                <Icon d="M12 5v14M5 12h14" />
                <span className="topbar__create-text">Create</span>
              </button>
              <div className="dropdown__menu" role="menu" hidden={openMenu !== 'create'}>
                <Link
                  className="dropdown__item"
                  role="menuitem"
                  href="/contacts?create=1"
                  onClick={closeMenus}
                >
                  <Icon d="M12 8a4 4 0 1 0-.001-8.001A4 4 0 0 0 12 8ZM4 21a8 8 0 0 1 16 0" />
                  Contact
                </Link>
                <Link
                  className="dropdown__item"
                  role="menuitem"
                  href="/companies?create=1"
                  onClick={closeMenus}
                >
                  <Icon d="M5 3h14v18H5zM9 7h2M13 7h2M9 11h2M13 11h2M9 15h2M13 15h2M10 21v-3h4v3" />
                  Company
                </Link>
                <Link
                  className="dropdown__item"
                  role="menuitem"
                  href="/deals?create=1"
                  onClick={closeMenus}
                >
                  <Icon d="M3 7h18v13H3zM8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M3 12h18" />
                  Deal
                </Link>
                {/* QA go-live (Tickets 957): Ticket is always offered, not only once the objects load. */}
                {me.role !== 'read_only' ? (
                  <Link
                    className="dropdown__item"
                    role="menuitem"
                    href="/tickets?create=1"
                    onClick={closeMenus}
                  >
                    <Icon d="M4 5h16v14H4zM4 9h16M9 13h6" />
                    Ticket
                  </Link>
                ) : null}
                {/* HUB-746 #5: the business's other custom objects (Leads, Events) too. */}
                {me.role !== 'read_only'
                  ? sortObjectLinks(objectLinks.filter((o) => o.href !== '/tickets')).map((o) => (
                      <Link
                        key={o.href}
                        className="dropdown__item"
                        role="menuitem"
                        href={`${o.href}?create=1`}
                        onClick={closeMenus}
                      >
                        <Icon d="M4 5h16v14H4zM4 9h16M9 13h6" />
                        {o.singular ?? o.label}
                      </Link>
                    ))
                  : null}
                {me.role !== 'read_only' ? (
                  <Link
                    className="dropdown__item"
                    role="menuitem"
                    href="/quotes/new"
                    onClick={closeMenus}
                  >
                    <Icon d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5M9 13h6M9 17h6" />
                    Quote
                  </Link>
                ) : null}
              </div>
            </div>

            <div className="topbar__icons">
              <div className="dropdown tb-btn--hide-md" data-dropdown>
                <button
                  type="button"
                  className="tb-btn"
                  data-tip="Help"
                  aria-haspopup="menu"
                  aria-expanded={openMenu === 'help'}
                  aria-label="Help"
                  onClick={() => toggleMenu('help')}
                >
                  <Icon
                    d="M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM9.5 9a2.5 2.5 0 1 1 3.5 2.3c-.6.3-1 .9-1 1.6V14M12 17h.01"
                    className="icon iconSize-20"
                    size={20}
                  />
                </button>
                <div className="dropdown__menu" role="menu" hidden={openMenu !== 'help'}>
                  <p className="dropdown__title">Help</p>
                  <button type="button" className="dropdown__item" role="menuitem">
                    <Icon d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5M9 13h6M9 17h6" />
                    Knowledge base
                  </button>
                  <button type="button" className="dropdown__item" role="menuitem">
                    <Icon d="M3 5h18v14H3zM3.5 6.5l8.5 6 8.5-6" />
                    Contact support
                  </button>
                </div>
              </div>

              <Link
                className={cn('tb-btn', pathname.startsWith('/settings') && 'is-active')}
                href="/settings/profile"
                data-tip="Settings"
                aria-label="Settings"
              >
                <Icon
                  d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0"
                  className="icon iconSize-20"
                  size={20}
                />
              </Link>

              <div className="dropdown" data-dropdown>
                <button
                  type="button"
                  className="tb-btn"
                  data-tip="Notifications"
                  aria-haspopup="true"
                  aria-expanded={openMenu === 'notif'}
                  aria-label="Notifications"
                  onClick={() => toggleMenu('notif')}
                >
                  <Icon
                    d="M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0"
                    className="icon iconSize-20"
                    size={20}
                  />
                  {unread > 0 ? (
                    <span className="tb-badge" aria-label={`${unread} unread`}>
                      {unread > 99 ? '99+' : unread}
                    </span>
                  ) : null}
                </button>
                <div className="dropdown__menu dropdown__menu--wide" hidden={openMenu !== 'notif'}>
                  <div className="dropdown__head">
                    <p className="dropdown__title crm-p-0">Notifications</p>
                  </div>
                  {notes.length ? (
                    notes.map((n) => (
                      <Link
                        key={n.id}
                        className={cn('dropdown__item tb-note', !n.readAt && 'is-unread')}
                        href={n.link || '/notifications'}
                        onClick={() => setOpenMenu(null)}
                      >
                        <span className="tb-note__title">{n.title}</span>
                        <small className="crm-text-body-secondary">
                          {new Date(n.createdAt).toLocaleDateString('en-US', {
                            month: 'short',
                            day: 'numeric',
                          })}
                        </small>
                      </Link>
                    ))
                  ) : (
                    <p className="dropdown__item crm-text-body-secondary">No new notifications</p>
                  )}
                </div>
              </div>
            </div>

            <span className="topbar__divider" aria-hidden />

            <div className="dropdown" data-dropdown>
              <button
                type="button"
                className="account-btn"
                aria-haspopup="menu"
                aria-expanded={openMenu === 'account'}
                aria-label={`Account menu for ${me.business.name}`}
                onClick={() => toggleMenu('account')}
              >
                <span className="avatar avatar--xs" aria-hidden>
                  {avatarSrc ? <img src={avatarSrc} alt="" /> : initials || '?'}
                </span>
                {hasOtherAccounts ? <AccountBadge business={me.business} /> : null}
                <span className="account-btn__name">{me.business.name}</span>
                <Icon
                  d="m10 10-5.5 5.5L4 20l4.5-.5L14 14M13 7l3-3 4 4-3 3M3 3l18 18"
                  className="icon iconSize-16 account-btn__mode"
                  size={16}
                />
                <Icon d="m7 10 5 5 5-5" className="icon iconSize-16 account-btn__caret" size={16} />
              </button>

              <div
                className="dropdown__menu dropdown__menu--account"
                role="menu"
                hidden={openMenu !== 'account'}
              >
                <div className="account-card">
                  <span className="avatar avatar--lg" aria-hidden>
                    {avatarSrc ? <img src={avatarSrc} alt="" /> : initials || '?'}
                  </span>
                  <div className="crm-overflow-hidden">
                    <p className="account-card__name">{me.user.name}</p>
                    <p className="account-card__email">{me.user.email}</p>
                    <Link
                      className="link link--underline"
                      href="/settings/profile"
                      onClick={closeMenus}
                    >
                      Profile &amp; Preferences
                    </Link>
                  </div>
                </div>

                <AccountSwitcher
                  current={me.business}
                  role={me.role}
                  memberships={me.memberships}
                  switching={switchingBusiness}
                  onSwitch={(b) => void onSwitchBusiness(b.id, b.name)}
                />

                <div className="dropdown__section">
                  <button
                    type="button"
                    className="dropdown__item dropdown__item--strong"
                    role="menuitem"
                    data-theme-toggle
                    onClick={toggleTheme}
                  >
                    {theme === 'dark' ? (
                      <Icon d="M12 3a4 4 0 0 0 0 8 8.5 8.5 0 1 1 0-8Z" />
                    ) : (
                      <Icon d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8Z" />
                    )}
                    <span className="theme-label">
                      {theme === 'dark' ? 'Light mode' : 'Dark mode'}
                    </span>
                  </button>
                  <hr className="dropdown__rule" />
                  <button
                    type="button"
                    className="dropdown__item dropdown__item--strong"
                    role="menuitem"
                    onClick={onLogout}
                  >
                    Sign out
                  </button>
                </div>
              </div>
            </div>
          </div>
        </header>

        <main className="app__main" id="main" tabIndex={-1}>
          {me.impersonator ? (
            <div
              className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-3"
              style={{
                padding: '10px 16px',
                background: 'var(--warning-bg, #fef3c7)',
                color: 'var(--warning, #92400e)',
                borderBottom: '1px solid var(--border)',
                fontSize: 14,
                fontWeight: 600,
              }}
              role="status"
            >
              <span>
                Viewing as {me.user.name} ({me.user.email}). Signed in as admin{' '}
                {me.impersonator.name}.
              </span>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                disabled={exiting}
                onClick={() => void onStopImpersonating()}
              >
                Exit
              </button>
            </div>
          ) : null}
          {children}
        </main>
      </div>
    </div>
  );
}
