/* Parley shell — SIDEBAR shell, labelled mode, one navigation owner (the
   sidebar owns all five destinations and the thread list nested under Chats;
   the toolbar is page context and utility only).
   Density: reading first — 30px nav rows, 24px page gutters, a 46rem measure
   for the conversation, 14px chrome around 16px prose.
   Separation: hairlines on the tinted --sidebar plane. The conversation has no
   card around it; the composer, the rail panels and the record cards are the
   only raised surfaces, one elevation step, never nested.
   Active state: --sidebar-accent wash + foreground token + medium weight,
   derived from the route — for the destination rows and the nested thread rows
   alike.
   App-scope duties: search → the sidebar header's read-only field, which opens
   the same palette ⌘K opens, and whose footer row leads to the full results
   screen · session and account → the sidebar footer, whose menu carries the
   person's own settings and the workspace's · utility → the toolbar (keyboard
   shortcuts, theme) · page context → the toolbar's breadcrumb, which is the one
   place a breadcrumb appears; page headers carry the title only, because the
   thread screen cannot spend forty pixels of reading height on a second one.
   Declined: notifications. There is nothing in this product that happens while
   you are not looking — a turn either lands in the thread you are reading or
   it is not running.
   Primary content per destination:
     Chats     — the thread: a conversation and its composer, with the context
                 rail beside it
     Shared    — table of other people's threads, plus their projects
     Projects  — cards, one per project, stacked in two columns
     Library   — table of saved prompts
     Files     — table
     Usage     — the day chart over the model and person tables
   Chats is the destination that would most plausibly have been a table and is
   not: a conversation is read top to bottom, so the list of them belongs in
   the nav and the screen belongs to one thread at a time.
   Settings and auth are registered off the sidebar; auth renders no shell. */
(() => {
  const {
    Sidebar, SidebarHeader, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupLabel,
    SidebarMenu, SidebarMenuItem, SidebarMenuButton, SidebarMenuBadge, SidebarInset, SidebarSeparator,
    Button, Input, Kbd, Avatar, MenuItem, MenuGroupLabel, Separator,
    Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator,
    Dialog, DialogPopup, DialogHeader, DialogTitle, DialogDescription, DialogPanel,
    Toast, ToastRegion,
  } = window.OriginDesignSystem_7c998b;

  /* Declared once for the product: 1280 expanded with the context rail · 1024
     icon rail, labels become tooltips, the context rail folds above the
     conversation · below that an off-canvas drawer. The account menu never
     collapses into an overflow. */
  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;
  }

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

  function BrandBlock({ rail }) {
    return (
      <div className="pl-brand">
        <img className="pl-brand__mark" src="../../assets/templates/logos/08-logo-demo.svg" alt="" width="26" height="26" />
        {rail ? null : (
          <span className="pl-brand__text">
            <span className="pl-brand__name">Parley</span>
            <span className="pl-brand__sub">{WORKSPACE.name} · {labelOf(PLANS, WORKSPACE.plan)}</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="pl-rail-dot" aria-hidden="true" />
            : (
              <span className="pl-nav__badge">
                <FloatingTip label={badge.count + " " + badge.label} side="bottom">
                  <SidebarMenuBadge aria-label={badge.count + " " + badge.label}>{badge.count}</SidebarMenuBadge>
                </FloatingTip>
              </span>
            )
        ) : null}
      </SidebarMenuItem>
    );
  }

  /* Chats' within-destination level, in the shell rather than on the page.
     Every row is the registered /chats/:id route; in the icon rail the titles
     become the tooltip on a single row rather than being dropped. */
  function ThreadList({ threads, path, now, rail, archivedCount, onNavigate }) {
    if (rail) {
      return (
        <>
          <FloatingTip label={threads.length + " conversations — open the sidebar or press ⌘K"}>
            <SidebarMenuButton aria-label="Recent conversations" onClick={() => onNavigate(resolvePath("/chats/:id", { id: threads[0].id }))}>
              <Icon name="history" size={16} />
            </SidebarMenuButton>
          </FloatingTip>
          {archivedCount ? (
            <FloatingTip label={archivedCount + " archived " + (archivedCount === 1 ? "conversation" : "conversations")}>
              <SidebarMenuButton isActive={path === "/chats/archived"} aria-label={"Archived chats — " + archivedCount} onClick={() => onNavigate("/chats/archived")}>
                <Icon name="archive" size={16} />
              </SidebarMenuButton>
            </FloatingTip>
          ) : null}
        </>
      );
    }
    const groups = [];
    threads.forEach((thread) => {
      const label = thread.pinned ? "Pinned" : ageBucket(THREAD_FLAGS.lastActivityAt(thread), now);
      const group = groups.find((g) => g.label === label) || (groups.push({ label: label, items: [] }), groups[groups.length - 1]);
      group.items.push(thread);
    });
    return (
      <div className="pl-threads">
        {groups.map((group) => (
          <React.Fragment key={group.label}>
            <div className="pl-threads__group">{group.label}</div>
            {group.items.map((thread) => {
              const to = resolvePath("/chats/:id", { id: thread.id });
              return (
                <button type="button" key={thread.id} className="pl-thread-row" data-active={path === to} onClick={() => onNavigate(to)}>
                  <span className="pl-thread-row__title">{thread.title}</span>
                  {thread.visibility === "private"
                    ? <span className="pl-thread-row__age">{formatAge(THREAD_FLAGS.lastActivityAt(thread), now)}</span>
                    : (
                      <FloatingTip side="bottom" label={statusValue(VISIBILITY, thread.visibility).label + " · last reply " + formatAge(THREAD_FLAGS.lastActivityAt(thread), now)}>
                        <span className="pl-thread-row__mark"><Icon name={thread.visibility === "link" ? "link" : "users"} size={13} /></span>
                      </FloatingTip>
                    )}
                </button>
              );
            })}
          </React.Fragment>
        ))}
        {archivedCount ? (
          <button type="button" className="pl-thread-row" data-active={path === "/chats/archived"} onClick={() => onNavigate("/chats/archived")}>
            <span className="pl-thread-row__title pl-muted">Archived</span>
            <span className="pl-thread-row__age">{archivedCount}</span>
          </button>
        ) : null}
      </div>
    );
  }

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

  /* Every shortcut listed here is bound in App.jsx or the composer. */
  const SHORTCUTS = [
    { keys: ["⌘", "K"], label: "Search chats, projects and files" },
    { keys: ["⌘", "⇧", "O"], label: "New chat" },
    { keys: ["↵"], label: "Send — ⇧↵ for a new line" },
    { keys: ["Esc"], label: "Stop the turn that is writing" },
  ];

  function ShortcutsDialog({ open, onClose }) {
    if (!open) return null;
    return (
      <Dialog open onOpenChange={(next) => { if (!next) onClose(); }}>
        <DialogPopup>
          <DialogHeader>
            <DialogTitle>Keyboard</DialogTitle>
            <DialogDescription>Four shortcuts, all of them live.</DialogDescription>
          </DialogHeader>
          <DialogPanel>
            <div className="pl-shortcuts">
              {SHORTCUTS.map((s) => (
                <div className="pl-shortcut" key={s.label}>
                  <span>{s.label}</span>
                  <span className="pl-chips">{s.keys.map((k) => <Kbd key={k}>{k}</Kbd>)}</span>
                </div>
              ))}
            </div>
          </DialogPanel>
        </DialogPopup>
      </Dialog>
    );
  }

  /* The one breadcrumb in the product. Every segment before the last navigates
     to its own route; the last is never a link. */
  function Crumbs({ path, labels, params, onNavigate }) {
    const trail = breadcrumb(path, PARLEY_ROUTES);
    if (!trail.length) return <span className="pl-toolbar__title">{path}</span>;
    return (
      <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={() => onNavigate(href)}>{label}</BreadcrumbLink>;
                })()}
              </BreadcrumbItem>
            </React.Fragment>
          ))}
        </BreadcrumbList>
      </Breadcrumb>
    );
  }

  /* Page headers carry the title and the page-scope actions. The breadcrumb is
     in the toolbar and is not repeated here. */
  function PageHead({ title, note, actions }) {
    return (
      <header className="pl-head">
        <div className="pl-head__text">
          <h1 className="pl-title">{title}</h1>
          {note ? <p className="pl-head__note">{note}</p> : null}
        </div>
        {actions ? <div className="pl-head__actions">{actions}</div> : null}
      </header>
    );
  }

  function ParleyShell({ path, onNavigate, dark, onToggleTheme, data, user, threads, palette, crumbLabels, crumbParams, onNewChat, toasts, onDismissToast, archivedCount, children }) {
    const mode = useShellMode();
    const [drawer, setDrawer] = React.useState(false);
    const [shortcuts, setShortcuts] = React.useState(false);
    React.useEffect(() => { if (mode !== "drawer") setDrawer(false); }, [mode]);
    const rail = mode === "rail";
    const navOpen = mode !== "drawer" || drawer;
    const go = (next) => { onNavigate(next); setDrawer(false); };

    return (
      <div className="pl-shell" data-mode={mode}>
        {mode === "drawer" && drawer ? <div className="pl-scrim" onClick={() => setDrawer(false)} /> : null}
        {navOpen ? (
          <Sidebar className="pl-nav" aria-label="Parley">
            <SidebarHeader>
              <div className="pl-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>
              <div className="pl-nav__actions">
                <span className="pl-nav__new">
                  {rail
                    ? <FloatingTip label="New chat"><Button variant="outline" size="icon-sm" aria-label="New chat" onClick={() => { onNewChat(); setDrawer(false); }}><Icon name="pen-line" size={16} /></Button></FloatingTip>
                    : <Button variant="outline" size="sm" onClick={() => { onNewChat(); setDrawer(false); }}><Icon name="pen-line" size={14} />New chat</Button>}
                </span>
                {rail ? (
                  <FloatingTip label="Search — ⌘K"><Button variant="ghost" size="icon-sm" aria-label="Search Parley" onClick={() => palette.setOpen(true)}><Icon name="search" size={16} /></Button></FloatingTip>
                ) : (
                  <div className="pl-nav__search" onClick={() => palette.setOpen(true)}>
                    <Input readOnly size="sm" aria-label="Search Parley" placeholder="Search chats, files…"
                      startAddon={<Icon name="search" size={14} />} endAddon={<Kbd>⌘K</Kbd>} onFocus={() => palette.setOpen(true)} />
                  </div>
                )}
              </div>
            </SidebarHeader>
            <SidebarContent>
              {PARLEY_SIDEBAR.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 (
                        <React.Fragment key={route.path}>
                          <NavRow route={route} rail={rail} active={isActive(route, path)}
                            badge={spec ? { count: spec.count(data), label: spec.label } : null} onNavigate={go} />
                          {route.path === "/" ? <SidebarMenuItem><ThreadList threads={threads} path={path} now={data.now} rail={rail} archivedCount={archivedCount} onNavigate={go} /></SidebarMenuItem> : null}
                        </React.Fragment>
                      );
                    })}
                  </SidebarMenu>
                </SidebarGroup>
              ))}
            </SidebarContent>
            <SidebarFooter>
              <SidebarSeparator />
              <AccountMenu rail={rail} onNavigate={go} user={user} />
            </SidebarFooter>
          </Sidebar>
        ) : null}

        <SidebarInset className="pl-inset">
          <div className="pl-toolbar">
            {mode === "drawer" ? <Button variant="ghost" size="icon-sm" aria-label="Open navigation" onClick={() => setDrawer(true)}><Icon name="menu" size={16} /></Button> : null}
            <div className="pl-toolbar__context"><Crumbs path={path} labels={crumbLabels} params={crumbParams} onNavigate={onNavigate} /></div>
            <div className="pl-toolbar__utility">
              <FloatingTip label="Keyboard" side="bottom">
                <Button variant="ghost" size="icon-sm" aria-label="Keyboard shortcuts" onClick={() => setShortcuts(true)}><Icon name="command" size={16} /></Button>
              </FloatingTip>
              <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="pl-content">{children}</div>
        </SidebarInset>

        <ShortcutsDialog open={shortcuts} onClose={() => setShortcuts(false)} />
        <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, { ParleyShell, PageHead, useShellMode });
})();
