/* Claims Desk shell — TOP-NAV shell, one navigation owner (the bar owns all
   five destinations; there is no sidebar and no second row of navigation).
   Density: 64px bar, 24px page gutters, 32px table rows — tight operational
   tables against generous decision surfaces.
   Separation: hairlines and full-bleed bands on the --sidebar page plane;
   cards are the only raised surface, one elevation step, never nested.
   Active state: foreground token + a persistent 2px underline, derived from
   the route; counts sit after the label inside the item.
   App-scope duties: search → the bar's palette field · session and account →
   the bar's account menu · utility → the bar (notifications, theme) · page
   context → the page header's breadcrumb and title.
   Primary content per destination:
     Work queue — burn-down band over one dense claims table
     Sign-off   — the waiting figures over one table, and what came back
     Payments   — release pipeline over one settlements table
     Responses  — the disputed offer, full width, beside the offer ledger
     Recovery   — the recovery rate, its breakdown, and the recoveries table
   Responses is the destination that would most plausibly have been a table and
   is not: it answers "where has my offer been refused, and by how much", which
   is one record at a time, not a list to scan. */
(() => {
  const { Button, Input, Kbd, Avatar, MenuItem, MenuGroupLabel, MenuSeparator, Toast, ToastRegion, Tabs, TabsList, TabsTab } = window.OriginDesignSystem_7c998b;

  /* Declared once for the product: 1280 full bar · 1024 search collapses to an
     icon · below 1024 the destinations collapse into one menu. Nothing is lost
     on the way down — the menu carries the same labels and the same counts. */
  function useShellMode() {
    const read = () => (window.innerWidth >= 1280 ? "full" : window.innerWidth >= 1024 ? "compact" : "menu");
    const [mode, setMode] = React.useState(read);
    React.useEffect(() => {
      const onResize = () => setMode(read());
      window.addEventListener("resize", onResize);
      return () => window.removeEventListener("resize", onResize);
    }, []);
    return mode;
  }

  const badgeFor = (route, data) => {
    if (!route.badge) return null;
    const spec = NAV_BADGES[route.badge];
    return { count: spec.count(data), label: spec.label };
  };

  function Destinations({ path, data, onNavigate }) {
    return (
      <nav className="cd-dests" aria-label="Claims desk">
        {CLAIMS_DESTINATIONS.map((route) => {
          const active = path === route.path || (route.path !== "/" && path.indexOf(route.path + "/") === 0) || (route.path === "/" && path.indexOf("/claims/") === 0);
          const badge = badgeFor(route, data);
          return (
            <button type="button" key={route.path} className="cd-dest" aria-current={active ? "page" : undefined} onClick={() => onNavigate(route.path)}>
              {route.label}
              {badge && badge.count > 0 ? <span className="cd-dest__count" aria-label={badge.count + " " + badge.label}>{badge.count}</span> : null}
            </button>
          );
        })}
      </nav>
    );
  }

  function DestinationsMenu({ path, data, onNavigate }) {
    const current = CLAIMS_DESTINATIONS.find((r) => path === r.path || (r.path !== "/" && path.indexOf(r.path + "/") === 0)) || CLAIMS_DESTINATIONS[0];
    const trigger = (
      <Button variant="ghost" size="sm" aria-label="Destinations">
        <Icon name="menu" />{current.label}<Icon name="chevron-down" />
      </Button>
    );
    return (
      <Floating trigger={trigger} align="start" width="15rem" label="Destinations">
        {(close) => CLAIMS_DESTINATIONS.map((route) => {
          const badge = badgeFor(route, data);
          return (
            <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>
              {route.label}{badge && badge.count > 0 ? <span className="cd-dest__count"> {badge.count}</span> : null}
            </MenuItem>
          );
        })}
      </Floating>
    );
  }

  function AccountMenu({ mode, onNavigate, user }) {
    const trigger = (
      <button type="button" className="cd-account" aria-label={"Account — " + user.name}>
        <Avatar size={28} src={user.avatar} alt="" fallback={(user.name || "").trim().split(/\s+/).slice(0, 2).map((w) => w[0] || "").join("").toUpperCase() || "?"} />
        <span className="cd-account__text">
          <span className="cd-account__name">{user.name}</span>
          <span className="cd-account__role">{user.role}</span>
        </span>
      </button>
    );
    return (
      <Floating trigger={trigger} align="end" width="16rem" label="Account">
        {(close) => (
          <>
            <MenuGroupLabel>{user.name} · {user.role}</MenuGroupLabel>
            {CLAIMS_ACCOUNT_MENU.map((route) => (
              <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>{route.label}</MenuItem>
            ))}
          </>
        )}
      </Floating>
    );
  }

  /* The panel is a state of the bar, not a destination; /notifications behind
     it is. The panel shows the newest few and hands off the rest. */
  const PANEL_LIMIT = 5;

  function NotificationsButton({ items, readIds, unread, onRead, onOpen, onNavigate }) {
    const newest = items.slice().sort((a, b) => b.at - a.at).slice(0, PANEL_LIMIT);
    const trigger = (
      <span className="cd-utility">
        <Button variant="ghost" size="icon-sm" aria-label={unread ? unread + " unread notifications" : "Notifications"}><Icon name="bell" /></Button>
        {unread ? <span className="cd-badge-dot" aria-hidden="true">{unread}</span> : null}
      </span>
    );
    return (
      <Floating trigger={trigger} align="end" width="23rem" role="dialog" panelClass="o-popover cd-notify" label="Notifications">
        {(close) => (
          <>
            <div className="cd-notify__head">
              <span className="o-popover__title">Notifications</span>
              {unread ? <Button variant="ghost" size="xs" onClick={onRead}>Mark all read</Button> : null}
            </div>
            <div className="cd-notify__list">
              {newest.map((n) => (
                <button type="button" key={n.id} className={"cd-notify__item" + (readIds.indexOf(n.id) === -1 ? " is-unread" : "")} onClick={() => { onOpen(n); close(); }}>
                  <span className="cd-notify__title">{n.title}</span>
                  <span className="cd-notify__body">{n.body}</span>
                  <span className="cd-notify__time" title={formatAbsolute(n.at)}>{formatWhen(n.at, CLAIMS_NOW)}</span>
                </button>
              ))}
            </div>
            <div className="cd-notify__foot">
              <button type="button" className="cd-record__link" onClick={() => { onNavigate("/notifications"); close(); }}>
                See all {formatCount(items.length)} notifications
              </button>
            </div>
          </>
        )}
      </Floating>
    );
  }

  /* The claim's three views. Registered routes, reached by tabs — never a
     second set of top-level destinations. */
  function ClaimTabs({ claim, view, onNavigate }) {
    return (
      <Tabs value={view} onValueChange={(next) => onNavigate(resolvePath(CLAIM_VIEWS.find((v) => v.value === next).route.path, { id: claim.id }))}>
        <TabsList variant="underline">
          {CLAIM_VIEWS.map((v) => (
            <TabsTab key={v.value} value={v.value}>{v.label}</TabsTab>
          ))}
        </TabsList>
      </Tabs>
    );
  }

  /* The settings views. Same device as the claim's tabs, reading the same route
     table — the strip never carries a label the table does not have. */
  function SettingsTabs({ view, onNavigate }) {
    return (
      <Tabs value={view} onValueChange={(next) => onNavigate(SETTINGS_VIEWS.find((v) => v.value === next).route.path)}>
        <TabsList variant="underline">
          {SETTINGS_VIEWS.map((v) => (
            <TabsTab key={v.value} value={v.value}>{v.label}</TabsTab>
          ))}
        </TabsList>
      </Tabs>
    );
  }

  function ClaimsShell({ path, onNavigate, dark, onToggleTheme, data, user, notifications, readIds, unread, onRead, onOpenNotification, palette, toasts, onDismissToast, children }) {
    registerBreadcrumbNavigate(onNavigate);
    const mode = useShellMode();
    return (
      <div className="cd-shell" data-mode={mode}>
        <header className="cd-bar">
          {mode === "menu" ? <DestinationsMenu path={path} data={data} onNavigate={onNavigate} /> : null}
          <button type="button" className="cd-brand" onClick={() => onNavigate("/")} aria-label={CLAIMS_CARRIER.name + " — " + CLAIMS_CARRIER.desk}>
            <img className="cd-brand__mark" src="../../assets/templates/logos/03-logo-demo.svg" alt="" width="40" height="40" />
            <span className="cd-brand__name">{CLAIMS_CARRIER.name}</span>
          </button>
          {mode === "menu" ? null : <Destinations path={path} data={data} onNavigate={onNavigate} />}
          <div className="cd-bar__end">
            {mode === "full" ? (
              <div className="cd-search" onClick={() => palette.setOpen(true)}>
                <Input readOnly size="sm" aria-label="Search the claims desk" placeholder="Search claims, containers, recoveries…" startAddon={<Icon name="search" />} endAddon={<Kbd>⌘K</Kbd>} onFocus={() => palette.setOpen(true)} />
              </div>
            ) : (
              <FloatingTip label="Search claims, containers, recoveries" side="bottom">
                <Button variant="ghost" size="icon-sm" aria-label="Search the claims desk" onClick={() => palette.setOpen(true)}><Icon name="search" /></Button>
              </FloatingTip>
            )}
            <NotificationsButton items={notifications} readIds={readIds} unread={unread} onRead={onRead} onOpen={onOpenNotification} 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>
            <AccountMenu mode={mode} onNavigate={onNavigate} user={user} />
          </div>
        </header>

        <main className="cd-main">{children}</main>

        <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, { ClaimsShell, ClaimTabs, SettingsTabs, useShellMode });
})();
