/* Meridian shell — SIDEBAR shell, one navigation owner (the sidebar owns every
   top-level destination; the toolbar is utility only).
   Density: comfortable — 32px nav rows, 16px page gutters, 44px table rows.
   Separation: hairline rules and the tinted --sidebar plane; cards are the only
   raised surface, one elevation step, no nesting.
   Active state: --sidebar-accent wash + foreground token + medium weight.
   App-scope duties: search → toolbar palette · account → sidebar footer ·
   utility → toolbar (notifications, theme) · page context → page header.
   Eleven destinations in TWO labelled groups — Money is the platform's money
   moving, Workspace is this company's own spend, the accounts on the other side
   of it, the people here and what they are saying to each other.
   Primary content per destination:
     Dashboard   — figure row over a volume chart and four actionable cards
     Payments    — a fixed-window volume chart over the table; /payments/new is
                   a staged form with a live fee preview
     Payouts     — figure row over the approval queue, then the table;
                   /payouts/new is a staged form over the balance chain
     Disputes    — list-detail; /disputes/:id is the selection, with its thread
     Balances    — the balance broken into its three parts, over the movement
                   chart and the two tables that claim it
     Reports     — chart-led: money in and out by day, then the mixes and the
                   customer table behind it
     Expenses    — scoped figures and a spend chart over the review table
     Cards       — a canvas of card tiles, each with its own limit meter;
                   /cards/:id is one card's chart, facts, ledger and thread
     Customers   — table ordered by volume; /customers/:id is one account's
                   figures, its payments and payouts, its disputes and thread
     People      — a canvas of person tiles with faces; /people/:id is one
                   person's spend, cards, approvals, accounts and thread
     Activity    — a feed, derived from the records, with the person who did it
   Cards and People are the destinations that would most plausibly have been
   tables and are not: Cards answers "how much of this limit is left", which a
   meter shows and a row does not, and People answers "who is this and what are
   they carrying", which wants a face at a readable size.
   Settings (workspace, spend controls, team, notifications, billing), the
   profile and the auth screens are registered off the sidebar and reached from
   the account menu; auth renders with no shell at all. */

const {
  Sidebar, SidebarHeader, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupLabel,
  SidebarMenu, SidebarMenuItem, SidebarMenuButton, SidebarMenuBadge, SidebarInset, SidebarSeparator,
  Button, Input, Kbd, Avatar, Badge: ShellBadge, Separator,
  MenuItem, MenuSeparator, MenuGroupLabel,
  Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator,
  Toast, ToastRegion,
} = window.OriginDesignSystem_7c998b;

function useShellMode() {
  const read = () => (window.innerWidth >= 1280 ? "expanded" : window.innerWidth >= 1024 ? "rail" : "drawer");
  const [mode, setMode] = React.useState(read);
  React.useEffect(() => {
    const onResize = () => setMode(read());
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return mode;
}

function BrandBlock({ rail, workspace }) {
  return (
    <div className="fd-brand">
      <img className="fd-brand__logo" src="../../assets/templates/logos/15-logo-demo.svg" alt="" width="28" height="28" />
      {rail ? null : (
        <span className="fd-brand__text">
          <span className="fd-brand__name">Meridian</span>
          <span className="fd-brand__workspace">{workspace.name}</span>
        </span>
      )}
    </div>
  );
}

function NavRow({ route, active, rail, badge, onNavigate }) {
  const button = (
    <SidebarMenuButton isActive={active} aria-current={active ? "page" : undefined} aria-label={rail ? route.label : undefined} onClick={() => onNavigate(route.path)}>
      <Icon name={route.icon} />
      {rail ? null : <span>{route.label}</span>}
    </SidebarMenuButton>
  );
  const tip = badge && badge.count > 0 ? route.label + " — " + badge.count + " " + badge.label : route.label;
  return (
    <SidebarMenuItem>
      {rail ? <FloatingTip label={tip}>{button}</FloatingTip> : button}
      {badge && badge.count > 0 ? (
        rail ? <span className="fd-rail-dot" aria-hidden="true" /> : <SidebarMenuBadge aria-label={badge.count + " " + badge.label}>{badge.count}</SidebarMenuBadge>
      ) : null}
    </SidebarMenuItem>
  );
}

function AccountMenu({ rail, onNavigate, profile }) {
  const trigger = (
    <button type="button" className={"fd-account" + (rail ? " fd-account--rail" : "")} aria-label={"Account — " + profile.name}>
      <Avatar size={rail ? 28 : 32} src={profile.avatar} alt="" fallback={profile.name.split(" ").map((w) => w[0]).slice(0, 2).join("")} />
      {rail ? null : (
        <span className="fd-account__text">
          <span className="fd-account__name">{profile.name}</span>
          <span className="fd-account__role">{profile.role}</span>
        </span>
      )}
      {rail ? null : <Icon name="chevrons-up-down" />}
    </button>
  );
  return (
    <Floating trigger={trigger} align="start" width="15rem" label="Account">
      {(close) => (
        <>
          <MenuGroupLabel>{profile.name} · {profile.role}</MenuGroupLabel>
          {MERIDIAN_ACCOUNT_MENU.map((route) => (
            <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>{route.label}</MenuItem>
          ))}
        </>
      )}
    </Floating>
  );
}

function NotificationsButton({ items, unread, onRead, onNavigate }) {
  const trigger = (
    <span className="fd-utility">
      <Button variant="ghost" size="icon-sm" aria-label={unread ? unread + " unread notifications" : "Notifications"}>
        <Icon name="bell" />
      </Button>
      {unread ? <span className="fd-badge-dot" aria-hidden="true">{unread}</span> : null}
    </span>
  );
  return (
    <FloatingTip label="Notifications" side="bottom">
      <Floating trigger={trigger} align="end" width="22rem" role="dialog" panelClass="o-popover fd-notify" label="Notifications">
        {(close) => (
          <>
            <div className="fd-notify__head">
              <span className="o-popover__title">Notifications</span>
              <Button variant="ghost" size="xs" onClick={() => { onRead(); }}>Mark all read</Button>
            </div>
            <div className="fd-notify__list">
              {items.map((n) => (
                <button type="button" key={n.id} className="fd-notify__item" onClick={() => { onNavigate(n.route); close(); }}>
                  <span className="fd-notify__title">{n.title}</span>
                  <span className="fd-notify__body">{n.body}</span>
                  <span className="fd-notify__time" title={formatAbsolute(n.at)}>{formatWhen(n.at, MERIDIAN_NOW)}</span>
                </button>
              ))}
            </div>
          </>
        )}
      </Floating>
    </FloatingTip>
  );
}

function Toolbar({ mode, dark, onToggleTheme, onOpenPalette, onOpenDrawer, notifications, unread, onRead, onNavigate }) {
  return (
    <div className="fd-toolbar">
      {mode === "drawer" ? (
        <Button variant="ghost" size="icon-sm" aria-label="Open navigation" onClick={onOpenDrawer}><Icon name="menu" /></Button>
      ) : null}
      <div className="fd-search" onClick={onOpenPalette}>
        <Input
          readOnly
          size="sm"
          aria-label="Search Meridian"
          placeholder="Search payments, payouts, customers, people…"
          startAddon={<Icon name="search" />}
          endAddon={<Kbd>⌘K</Kbd>}
          onFocus={onOpenPalette}
        />
      </div>
      <div className="fd-toolbar__utility">
        <NotificationsButton items={notifications} unread={unread} onRead={onRead} onNavigate={onNavigate} />
        <FloatingTip label={dark ? "Switch to light" : "Switch to dark"} side="bottom">
          <Button variant="ghost" size="icon-sm" aria-label={dark ? "Switch to light theme" : "Switch to dark theme"} onClick={onToggleTheme}>
            <Icon name={dark ? "sun" : "moon"} />
          </Button>
        </FloatingTip>
      </div>
    </div>
  );
}

/* PageHeader is rendered by every screen and none of them pass the router, so the
   shell registers it once per render and the crumbs read it from here. */
let breadcrumbNavigate = null;

function PageHeader({ path, title, actions, params }) {
  const trail = breadcrumb(path, MERIDIAN_ROUTES);
  return (
    <header className="fd-page-header">
      <div className="fd-page-header__text">
        <Breadcrumb>
          <BreadcrumbList>
            {trail.map((seg, i) => (
              <React.Fragment key={seg.path}>
                {i > 0 ? <BreadcrumbSeparator /> : null}
                <BreadcrumbItem>
                  {i === trail.length - 1
                    ? <BreadcrumbPage>{seg.label}</BreadcrumbPage>
                    : seg.isNamespace ? <span>{seg.label}</span>
                      : <BreadcrumbLink href={"#" + resolvePath(seg.path, params || {})} onSelect={() => breadcrumbNavigate && breadcrumbNavigate(resolvePath(seg.path, params || {}))}>{seg.label}</BreadcrumbLink>}
                </BreadcrumbItem>
              </React.Fragment>
            ))}
          </BreadcrumbList>
        </Breadcrumb>
        <h1 className="fd-page-title">{title}</h1>
      </div>
      {actions ? <div className="fd-page-header__actions">{actions}</div> : null}
    </header>
  );
}

function MeridianShell({ path, onNavigate, dark, onToggleTheme, data, profile, workspace, notifications, unread, onRead, palette, toasts, onDismissToast, children }) {
  breadcrumbNavigate = onNavigate;
  const mode = useShellMode();
  const [drawer, setDrawer] = React.useState(false);
  React.useEffect(() => { if (mode !== "drawer") setDrawer(false); }, [mode]);
  const rail = mode === "rail";
  const navOpen = mode !== "drawer" || drawer;

  return (
    <div className="fd-shell" data-mode={mode}>
      {mode === "drawer" && drawer ? <div className="fd-drawer-scrim" onClick={() => setDrawer(false)} /> : null}
      {navOpen ? (
        <Sidebar className="fd-nav" aria-label="Meridian">
          <SidebarHeader>
            <div className="fd-nav__top">
              <BrandBlock rail={rail} workspace={workspace} />
              {mode === "drawer" ? <Button variant="ghost" size="icon-sm" aria-label="Close navigation" onClick={() => setDrawer(false)}><Icon name="x" /></Button> : null}
            </div>
          </SidebarHeader>
          <SidebarContent>
            {MERIDIAN_SIDEBAR.map((group, index) => (
              <SidebarGroup key={group.label || index}>
                {rail || !group.label ? null : <SidebarGroupLabel>{group.label}</SidebarGroupLabel>}
                <SidebarMenu>
                  {group.items.map((route) => {
                    const spec = route.badge ? NAV_BADGES[route.badge] : null;
                    return (
                      <NavRow
                        key={route.path}
                        route={route}
                        rail={rail}
                        active={route.path === path || (route.path !== "/" && path.indexOf(route.path + "/") === 0)}
                        badge={spec ? { count: spec.count(data), label: spec.label } : null}
                        onNavigate={(p) => { onNavigate(p); setDrawer(false); }}
                      />
                    );
                  })}
                </SidebarMenu>
              </SidebarGroup>
            ))}
          </SidebarContent>
          <SidebarFooter>
            <SidebarSeparator />
            <AccountMenu rail={rail} onNavigate={onNavigate} profile={profile} />
          </SidebarFooter>
        </Sidebar>
      ) : null}

      <SidebarInset className="fd-inset">
        <Toolbar
          mode={mode}
          dark={dark}
          onToggleTheme={onToggleTheme}
          onOpenPalette={() => palette.setOpen(true)}
          onOpenDrawer={() => setDrawer(true)}
          notifications={notifications}
          unread={unread}
          onRead={onRead}
          onNavigate={onNavigate}
        />
        <div className="fd-content">{children}</div>
      </SidebarInset>

      <ToastRegion>
        {toasts.map((t) => (
          <Toast key={t.id} variant={t.variant} title={t.title} description={t.description} onClose={() => onDismissToast(t.id)}
            action={t.onUndo ? <Button variant="outline" size="xs" onClick={() => { t.onUndo(); onDismissToast(t.id); }}>Undo</Button> : null} />
        ))}
      </ToastRegion>
    </div>
  );
}

Object.assign(window, { MeridianShell, PageHeader, useShellMode, NavRow, AccountMenu });
