/* Recruitment Desk shell — SIDEBAR shell, labelled mode, one navigation owner
   (the sidebar owns every destination; the toolbar is utility only).
   Density: roomy desk — 32px nav rows, 32px page gutters, 36px table rows.
   Separation: hairlines on the tinted --sidebar plane; cards are the only
   raised surface, one elevation step, never nested.
   Active state: --sidebar-accent wash + foreground token + medium weight,
   derived from the route.
   App-scope duties: search → the toolbar's palette field · session and account
   → the sidebar footer · utility → the toolbar (notifications, theme) · page
   context → the page header's breadcrumb and title.
   Two nav groups, both labelled: reviewing, and running the hiring.
   The fold: the sidebar collapses to an icon rail on the chevron button in the
   toolbar's leading slot — beside the drawer's menu button, before the search
   field — and unfolds again from the same button, at every width where a rail
   and a labelled sidebar are both possible. It is a utility action on the
   content side rather than a footer control, so it sits where the reader's eye
   already is when they want the width back. The reader's choice wins over the
   viewport's default once made, and holds for the session. Below 900px the whole
   thing becomes a drawer and the button is not offered, because the menu button
   owns the nav there and there is no rail to fold to.
   Primary content per destination:
     Your desk      — the day's work waiting on you, over the same arrays
     Applications   — table
     Interviews     — the day ladder, one row per booked conversation
     Offers         — table, the offers out, soonest to run out first
     Requisitions   — table, each seat with its pipeline as a stage strip
     Compliance     — table, one row per live application, three checks on each
     Talent pool    — a grid of faces, people we said we would talk to again
     Insights       — the funnel, chart-led
     Desk team      — table, who owns what
   Interviews is the destination that would most plausibly have been a table and
   is not: it answers "what is happening today", which is a question about time,
   so the days are the display and the conversations sit in them.
   Auth renders no shell (AGENTS §7.1); /me/profile is registered off the
   sidebar and reached from the account menu. */
(() => {
  const {
    Sidebar, SidebarHeader, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupLabel,
    SidebarMenu, SidebarMenuItem, SidebarMenuButton, SidebarMenuBadge, SidebarInset, SidebarSeparator,
    Button, Input, Kbd, Avatar, MenuItem, MenuGroupLabel, Tabs, TabsList, TabsTab,
    Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator,
    Toast, ToastRegion,
  } = window.OriginDesignSystem_7c998b;

  const BRAND_MARK = "../../assets/templates/logos/12-logo-demo.svg";

  /* Declared once for the product: 1280 expanded · 1024 icon rail with the
     labels as tooltips · below 900 an off-canvas drawer. Nothing is lost on the
     way down; the account menu never collapses into an overflow. This is the
     DEFAULT only — the reader's fold overrides it either way above 900px. */
  function useViewportMode() {
    const read = () => (window.innerWidth >= 1280 ? "expanded" : window.innerWidth >= 900 ? "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;
  }

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

  const isActive = (route, path) =>
    route.path === path || (route.path !== "/" && path.indexOf(route.path + "/") === 0);

  function BrandBlock({ rail }) {
    return (
      <div className="rd-brand">
        <img className="rd-brand__mark" src={BRAND_MARK} alt="" width="28" height="28" />
        {rail ? null : (
          <span className="rd-brand__text">
            <span className="rd-brand__name">{RD_ORG.desk}</span>
            <span className="rd-brand__sub">{RD_ORG.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} size={16} />
        {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="rd-rail-dot" aria-hidden="true" />
            : (
              <span className="rd-nav__badge">
                <FloatingTip label={badge.count + " " + badge.label} side="bottom">
                  <SidebarMenuBadge aria-label={badge.count + " " + badge.label}>{badge.count}</SidebarMenuBadge>
                </FloatingTip>
              </span>
            )
        ) : null}
      </SidebarMenuItem>
    );
  }

  function AccountMenu({ rail, onNavigate, person }) {
    const trigger = (
      <button type="button" className={"rd-account" + (rail ? " rd-account--rail" : "")} aria-label={"Account — " + person.name + ", " + labelOf(DESK_ROLES, person.role)}>
        <Avatar size={rail ? 24 : 28} src={person.photo} alt="" fallback={person.initials} />
        {rail ? null : (
          <span className="rd-account__text">
            <span className="rd-account__name">{person.name}</span>
            <span className="rd-account__role">{labelOf(DESK_ROLES, person.role)} · {labelOf(SITES, person.site)}</span>
          </span>
        )}
        {rail ? null : <Icon name="chevrons-up-down" size={14} />}
      </button>
    );
    return (
      <Floating trigger={trigger} align="start" width="16rem" label="Account">
        {(close) => (
          <>
            <MenuGroupLabel>{person.name} · {labelOf(DESK_ROLES, person.role)}</MenuGroupLabel>
            {accountMenu().map((route) => (
              <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>{route.label}</MenuItem>
            ))}
          </>
        )}
      </Floating>
    );
  }

  function NotificationsButton({ items, unread, onRead, onOpen, onNavigate, now }) {
    const trigger = (
      <span className="rd-utility">
        <Button variant="ghost" size="icon-sm" aria-label={unread ? unread + " unread notifications" : "Notifications"}><Icon name="bell" size={16} /></Button>
        {unread ? <span className="rd-badge-dot" aria-hidden="true">{unread}</span> : null}
      </span>
    );
    /* The panel shows the newest few; the count and the screen behind it read
       the same array, so “3 unread” and the inbox cannot disagree. */
    const shown = items.slice().sort((a, b) => b.at - a.at).slice(0, 5);
    return (
      <Floating trigger={trigger} align="end" width="24rem" role="dialog" panelClass="o-popover rd-notify" label="Notifications">
        {(close) => (
          <>
            <div className="rd-notify__head">
              <span className="o-popover__title">{unread ? unread + " unread" : "Notifications"}</span>
              <Button variant="ghost" size="xs" disabled={!unread} onClick={onRead}>Mark all read</Button>
            </div>
            <div className="rd-notify__list">
              {shown.map((n) => (
                <button type="button" key={n.id} className="rd-notify__item" data-unread={!n.readAt} onClick={() => { onNavigate(n.route); close(); }}>
                  <span className="rd-notify__title">{n.title}</span>
                  <span className="rd-notify__body">{n.body}</span>
                  <span className="rd-notify__time" title={formatAbsolute(n.at)}>{formatWhen(n.at, now)}</span>
                </button>
              ))}
            </div>
            <div className="rd-notify__foot">
              <span className="rd-foot">Showing {shown.length} of {items.length}.</span>
              <Button variant="outline" size="xs" onClick={() => { onOpen(); close(); }}>See all notifications</Button>
            </div>
          </>
        )}
      </Floating>
    );
  }

  /* Breadcrumb and title. Every segment before the last navigates to its own
     route; the last is never a link. */
  function PageHead({ path, title, note, actions, params, labels, avatar }) {
    const trail = breadcrumb(path, RD_ROUTES);
    return (
      <header className="rd-head">
        <div className="rd-head__id">
          {avatar ? <Avatar size={48} src={avatar.photo} alt="" fallback={avatar.initials} /> : null}
          <div className="rd-head__text">
            <Breadcrumb>
              <BreadcrumbList>
                {trail.map((seg, i) => (
                  <React.Fragment key={seg.path}>
                    {i > 0 ? <BreadcrumbSeparator /> : null}
                    <BreadcrumbItem>
                      {(() => {
                        const label = (labels && labels[seg.path]) || seg.label;
                        const href = resolvePath(seg.path, params || {});
                        if (i === trail.length - 1) return <BreadcrumbPage>{label}</BreadcrumbPage>;
                        if (seg.isNamespace) return <span>{label}</span>;
                        return <BreadcrumbLink href={"#" + href} onSelect={() => breadcrumbNavigate && breadcrumbNavigate(href)}>{label}</BreadcrumbLink>;
                      })()}
                    </BreadcrumbItem>
                  </React.Fragment>
                ))}
              </BreadcrumbList>
            </Breadcrumb>
            <h1 className="rd-title">{title}</h1>
            {note ? <p className="rd-head__note">{note}</p> : null}
          </div>
        </div>
        {actions ? <div className="rd-head__actions">{actions}</div> : null}
      </header>
    );
  }

  /* Views inside a record or a list: tabs narrow what is shown, never a second
     set of top-level destinations. */
  function ViewTabs({ views, value, onSelect }) {
    return (
      <Tabs value={value} onValueChange={onSelect}>
        <TabsList variant="underline">
          {views.map((v) => (
            <TabsTab key={v.value} value={v.value}>
              {v.label}{v.count === undefined ? null : <span className="rd-tab-count">{v.count}</span>}
            </TabsTab>
          ))}
        </TabsList>
      </Tabs>
    );
  }

  function RdShell({ path, onNavigate, dark, onToggleTheme, data, person, notifications, unread, onRead, onOpenNotifications, palette, toasts, onDismissToast, now, fold, onSetFold, children }) {
    const viewport = useViewportMode();
    breadcrumbNavigate = onNavigate;
    const [drawer, setDrawer] = React.useState(false);
    React.useEffect(() => { if (viewport !== "drawer") setDrawer(false); }, [viewport]);
    /* One effective mode: the viewport decides what is POSSIBLE, and where both
       a rail and a labelled sidebar are, the reader's own fold decides — in
       both directions, so nobody is stuck in a rail they cannot open. `fold` is
       null until they touch the button, and then it is the answer. */
    const mode = viewport === "drawer" ? "drawer" : fold === true ? "rail" : fold === false ? "expanded" : viewport;
    const rail = mode === "rail";
    const navOpen = mode !== "drawer" || drawer;
    const canFold = viewport !== "drawer";
    const groups = sidebarGroups();

    return (
      <div className="rd-shell" data-mode={mode}>
        {mode === "drawer" && drawer ? <div className="rd-scrim" onClick={() => setDrawer(false)} /> : null}
        {navOpen ? (
          <Sidebar className="rd-nav" aria-label={RD_ORG.desk}>
            <SidebarHeader>
              <div className="rd-nav__top">
                <BrandBlock rail={rail} />
                {mode === "drawer" ? <Button variant="ghost" size="icon-sm" aria-label="Close navigation" onClick={() => setDrawer(false)}><Icon name="x" size={16} /></Button> : null}
              </div>
            </SidebarHeader>
            <SidebarContent>
              {groups.map((group) => (
                <SidebarGroup key={group.label}>
                  {rail ? 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={isActive(route, path)}
                          badge={spec ? { count: spec.count(data, now), label: spec.label } : null}
                          onNavigate={(p) => { onNavigate(p); setDrawer(false); }} />
                      );
                    })}
                  </SidebarMenu>
                </SidebarGroup>
              ))}
            </SidebarContent>
            <SidebarFooter>
              <SidebarSeparator />
              <div className={"rd-nav__foot" + (rail ? " rd-nav__foot--rail" : "")}>
                <AccountMenu rail={rail} person={person} onNavigate={(p) => { onNavigate(p); setDrawer(false); }} />
              </div>
            </SidebarFooter>
          </Sidebar>
        ) : null}

        <SidebarInset className="rd-inset">
          <div className="rd-toolbar">
            {mode === "drawer" ? <Button variant="ghost" size="icon-sm" aria-label="Open navigation" onClick={() => setDrawer(true)}><Icon name="menu" size={16} /></Button> : null}
            {canFold ? (
              <FloatingTip side="bottom" label={rail ? "Unfold the sidebar" : "Fold the sidebar to icons"}>
                <Button variant="ghost" size="icon-sm" aria-expanded={!rail} aria-label={rail ? "Unfold the sidebar" : "Fold the sidebar to icons"} onClick={() => onSetFold(!rail)}>
                  <Icon name={rail ? "chevron-right" : "chevron-left"} size={16} />
                </Button>
              </FloatingTip>
            ) : null}
            <div className="rd-search" onClick={() => palette.setOpen(true)}>
              <Input readOnly size="sm" aria-label="Search the Recruitment Desk" placeholder="Search candidates, requisitions, interviews…"
                startAddon={<Icon name="search" size={14} />} endAddon={<Kbd>⌘K</Kbd>} onFocus={() => palette.setOpen(true)} />
            </div>
            <div className="rd-toolbar__utility">
              <NotificationsButton items={notifications} unread={unread} onRead={onRead} onOpen={onOpenNotifications} onNavigate={onNavigate} now={now} />
              <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"} size={16} />
                </Button>
              </FloatingTip>
            </div>
          </div>
          <div className="rd-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, { RdShell, PageHead, ViewTabs });
})();
