"use client";

import { HEADER_ICON_BUTTON } from "@enode/ui/header-button";
import { Suspense, useCallback, useMemo, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { useMediaQuery } from "@enode/core/use-media-query";
import { useTranslation } from "@enode/core/translations/hooks";
import { Sidebar as NavSidebar } from "@enode/ui/sidebar";
import { AnnouncementBanner } from "@enode/ui/announcements/announcement-banner";
import { SidebarIcon } from "@enode/ui/icons";
import { AccountMenu } from "./account-menu";
import { NotificationSheet } from "./notifications/notification-bell";
import { Sidebar as NavContent, type DrawerAction } from "./sidebar";
import { useSidebarNav } from "./sidebar-nav";
import { GlobalSearchDialog } from "./global-search/global-search-dialog";
import { useGlobalSearchHotkey } from "./global-search/global-search-hotkey";
import { FindTargetScroller } from "./global-search/find-target-scroller";
import type { SearchActionId } from "./global-search/search-rank";
import { RosterUploadDrawer } from "../app/dashboard/users/roster-upload-drawer";
import {
  SidebarControlProvider,
  type SidebarControl,
} from "./sidebar-control";
import { DataExportDrawer } from "../app/dashboard/data/export/data-export-drawer";
import type { ExportSeed } from "../app/dashboard/data/export/export-flow";
import { MigrationDrawer } from "../app/dashboard/migration/migration-drawer";
import { ActionDrawerProvider, type ActionDrawerApi } from "./action-drawer";
import { SHELL_MAIN_ID, ShellCoverProvider, type CoverShell } from "./shell-cover";
import { useTrackInAppHistory } from "./in-app-history";

// Responsive shell built on the shared @enode/ui Sidebar. ≥1024px the sidebar
// is flush chrome (surface="bare") on the window colour and the CONTENT is the
// card: <main> gets a border-only rounded edge with an 8px gutter (ADR 0020).
// Below 1024px the sidebar is a slide-in overlay panel and the content is
// full-bleed. The sidebar is open by default and collapsible to nothing via
// its header control, with a toggle in the page header (or a floating
// fallback) to bring it back.
const PERSISTENT_QUERY = "(min-width: 1024px)";
// The nav column's width: the old floating card's inner width (272px minus
// its 16px gutter each side), so the nav content keeps its size.
const SIDEBAR_WIDTH = 240;
// Below this the account menu is a bottom sheet (see account-menu.tsx), so the
// overlay sidebar steps aside before it opens.
const ACCOUNT_SHEET_QUERY = "(max-width: 639.98px)";

export function AppShell({ children }: { children: ReactNode }) {
  const { t } = useTranslation();
  // One boolean drives both modes (collapse on desktop / overlay on mobile).
  // Until the user toggles it (null), the default is mode-derived: open as the
  // persistent desktop column, closed as the mobile overlay — a drawer covering
  // the page is the wrong first paint on a phone.
  const [sidebarChoice, setSidebarOpen] = useState<boolean | null>(null);
  const [accountMenuOpen, setAccountMenuOpen] = useState(false);
  // The phone notifications sheet, presented here (the bell lives in the
  // overlay sidebar, which closes first).
  const [notificationsOpen, setNotificationsOpen] = useState(false);
  const router = useRouter();
  // Which on-demand action drawer (data export / migration / roster) is open, if
  // any. Held at the shell level so it overlays regardless of the current route
  // and survives the mobile sidebar overlay closing on tap.
  const [actionDrawer, setActionDrawer] = useState<DrawerAction | null>(null);
  // Preselection for the export drawer when opened from a table's multi-select;
  // cleared whenever a drawer opens without one.
  const [exportSeed, setExportSeed] = useState<ExportSeed | undefined>(undefined);

  const actionDrawerApi = useMemo<ActionDrawerApi>(
    () => ({
      openDrawer: (action) => {
        setExportSeed(undefined);
        setActionDrawer(action);
      },
      openExportDrawer: (seed) => {
        setExportSeed(seed);
        setActionDrawer("export");
      },
      openSettings: (options) => {
        // The overlay sidebar auto-collapses on navigation.
        router.push("/dashboard/settings" + (options?.section ? `?section=${options.section}` : ""));
      },
    }),
    [router],
  );
  // Auto-collapse on navigation only in overlay mode; the persistent column
  // stays as the user left it. serverFallback=true: SSR paints the (majority)
  // desktop layout; a phone flips to collapsed at hydration instead of desktop
  // flashing a closed sidebar on every load.
  const persistent = useMediaQuery(PERSISTENT_QUERY, true);
  const accountMenuIsSheet = useMediaQuery(ACCOUNT_SHEET_QUERY, false);

  // Reset the user's manual choice whenever the layout crosses the persistent
  // breakpoint so the sidebar falls back to its mode-derived default: the open
  // desktop column, the hidden mobile overlay. Without this a sidebar the user
  // opened on desktop would stay open — as a page-covering overlay — after the
  // window shrinks to compact. Storing the previous value and adjusting during
  // render (not in an effect) applies the reset before paint, so compact never
  // flashes the drawer in. See React's "adjusting state on prop change" pattern.
  const [prevPersistent, setPrevPersistent] = useState(persistent);
  if (prevPersistent !== persistent) {
    setPrevPersistent(persistent);
    setSidebarOpen(null);
  }

  const sidebarOpen = sidebarChoice ?? persistent;

  // How many PageShells are mounted with an inline open-button. While ≥1, the
  // floating fallback button is suppressed (PageShell renders the opener in its
  // header instead — it no longer covers the title).
  const [inlineOpeners, setInlineOpeners] = useState(0);
  const registerInlineOpener = useCallback(() => {
    setInlineOpeners((n) => n + 1);
    return () => setInlineOpeners((n) => n - 1);
  }, []);
  const sidebarControl = useMemo<SidebarControl>(
    () => ({
      collapsed: !sidebarOpen,
      open: () => setSidebarOpen(true),
      registerInlineOpener,
    }),
    [sidebarOpen, registerInlineOpener],
  );

  // How many full-window screens (a live session's display) lie over the shell
  // right now. While ≥1 the sidebar is `inert`: it is still drawn underneath,
  // but no Tab stop, pointer or screen reader reaches it.
  const [covers, setCovers] = useState(0);
  const coverShell = useCallback<CoverShell>(() => {
    setCovers((n) => n + 1);
    return () => setCovers((n) => n - 1);
  }, []);
  const covered = covers > 0;
  // Lets Settings' close go Back only when Back stays in the portal.
  useTrackInAppHistory();
  // Stable, so the menu's Escape listener is not re-attached on every render.
  const closeAccountMenu = useCallback(() => setAccountMenuOpen(false), []);
  const closeNotifications = useCallback(() => setNotificationsOpen(false), []);
  // The global search (docs/global-search.md): the sidebar's search field and
  // ⌘K / Ctrl+K anywhere — not while a live display covers the shell.
  const [searchOpen, setSearchOpen] = useState(false);
  const closeSearch = useCallback(() => setSearchOpen(false), []);
  const { sections: navSections } = useSidebarNav();
  const openSearch = useCallback(() => {
    // One overlay at a time on a phone: the sidebar overlay steps aside.
    if (!persistent) setSidebarOpen(false);
    setSearchOpen(true);
  }, [persistent]);
  useGlobalSearchHotkey(openSearch, !covered);
  // A task started from the search, the way its own button starts it.
  const [rosterFromSearch, setRosterFromSearch] = useState(false);
  const runSearchAction = (action: SearchActionId) => {
    if (action === "export") actionDrawerApi.openExportDrawer();
    else if (action === "migration") actionDrawerApi.openDrawer("migration");
    else {
      // The roster upload belongs to the Users page: go there and open it.
      router.push("/dashboard/users");
      setRosterFromSearch(true);
    }
  };

  return (
    // Inner-scroll shell (matches the tracking app): the dashboard is locked to
    // the viewport (`h-dvh` handles the mobile URL-bar resize) and never scrolls
    // the window — the persistent chrome (sidebar, page header) stays put and a
    // single content pane scrolls. Scoped to the dashboard only; the public
    // login route keeps document-scroll (see root layout). See
    // docs/decisions/0004-portal-inner-scroll.md.
    <SidebarControlProvider value={sidebarControl}>
    <ActionDrawerProvider value={actionDrawerApi}>
    <ShellCoverProvider value={coverShell}>
    <div className="flex h-dvh overflow-hidden bg-background lg:bg-surface-base">
      {/* ≥lg (= PERSISTENT_QUERY's 1024px) the window takes the chrome colour
          the flush sidebar sits on; the content card below paints
          `bg-background`. */}
      {/* `contents`: the wrapper only carries `inert`; the sidebar stays the
          flex child it was. */}
      <div className="contents" inert={covered} aria-hidden={covered || undefined}>
      <NavSidebar
        open={sidebarOpen}
        onClose={() => setSidebarOpen(false)}
        ariaLabel={t("Main navigation")}
        width={SIDEBAR_WIDTH}
        surface="bare"
      >
        <NavContent
          onNavigate={persistent ? undefined : () => setSidebarOpen(false)}
          onClose={() => setSidebarOpen(false)}
          onOpenAccountMenu={() => {
            // A phone sheet never stacks on the overlay sidebar: close it first.
            if (!persistent && accountMenuIsSheet) setSidebarOpen(false);
            setAccountMenuOpen(true);
          }}
          accountMenuOpen={accountMenuOpen}
          onOpenDrawer={actionDrawerApi.openDrawer}
          onOpenSearch={openSearch}
          onOpenNotifications={
            persistent
              ? undefined
              : () => {
                  setSidebarOpen(false);
                  setNotificationsOpen(true);
                }
          }
        />
      </NavSidebar>
      </div>

      {/* Content column. ≥lg it holds the content card with an 8px gutter on
          top, right and bottom — and on the left too while the sidebar is
          collapsed, so the card never touches the window edge (the open
          sidebar provides that spacing itself). */}
      <div
        className={`relative flex min-h-0 min-w-0 flex-1 flex-col lg:py-2 lg:pr-2 ${
          sidebarOpen ? "" : "lg:pl-2"
        }`}
      >
        {/* Bounded, non-scrolling flex column. Pages own their own scroll
            region (via PageShell), so the window never scrolls; planner /
            performance opt out and fill this box with their own internal
            scroll. `min-h-0` lets the pane shrink instead of pushing overflow
            back onto the window. ≥lg it is the content card: border only, no
            shadow (ADR 0005), and never a transform / filter / backdrop-filter
            — that would make it the containing block of the `fixed` live
            displays and drawers drawn inside it (ADR 0020). */}
        <main
          id={SHELL_MAIN_ID}
          className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background lg:rounded-2xl lg:border lg:border-surface-stroke"
        >
          {/* Floating fallback to re-open the collapsed sidebar — used only by
              pages that DON'T render a PageShell (planner, performance). PageShell
              pages register an inline header opener, which suppresses this.
              Inside the card, so it sits on the content, not the gutter. */}
          {!sidebarOpen && inlineOpeners === 0 && !covered && (
            <div className="absolute top-3 left-3 z-30">
              <button
                type="button"
                onClick={() => setSidebarOpen(true)}
                aria-label={t("Open navigation")}
                className={HEADER_ICON_BUTTON}
              >
                <SidebarIcon className="size-5" />
              </button>
            </div>
          )}
          <AnnouncementBanner />
          {children}
        </main>
      </div>

      {/* Account menu, opened from the sidebar's avatar. */}
      {/* The menu closes itself (`onClose`) before it navigates. */}
      <AccountMenu
        open={accountMenuOpen}
        onClose={closeAccountMenu}
        onNavigate={(href) => {
          router.push(href);
          if (!persistent) setSidebarOpen(false);
        }}
        onOpenSettings={() => {
          router.push("/dashboard/settings");
          if (!persistent) setSidebarOpen(false);
        }}
      />

      <NotificationSheet
        open={notificationsOpen}
        onClose={closeNotifications}
      />

      <GlobalSearchDialog
        open={searchOpen}
        sections={navSections}
        onClose={closeSearch}
        onNavigate={(href) => router.push(href)}
        onAction={runSearchAction}
      />
      {rosterFromSearch && <RosterUploadDrawer onClose={() => setRosterFromSearch(false)} />}
      {/* Lights up the setting a search result opened (`?find=`); reads the
          address, so it needs its own Suspense boundary in a static export. */}
      <Suspense fallback={null}>
        <FindTargetScroller />
      </Suspense>

      {/* On-demand action drawers, opened from the sidebar's Data section.
          Mounted conditionally — each plays its own slide-out before closing. */}
      {actionDrawer === "export" && (
        <DataExportDrawer
          onClose={() => setActionDrawer(null)}
          seed={exportSeed}
        />
      )}
      {actionDrawer === "migration" && (
        <MigrationDrawer onClose={() => setActionDrawer(null)} />
      )}
    </div>
    </ShellCoverProvider>
    </ActionDrawerProvider>
    </SidebarControlProvider>
  );
}
