/* Marketing Desk shell — SIDEBAR shell, one navigation owner (the sidebar owns every
   top-level destination; the pane header is utility only).
   Frame: one tinted plane, the sidebar sitting directly on it, the content in a
   single rounded pane inset 10/8/14 with one hairline edge and no shadow. The
   pane is the only scroll owner.
   Density: comfortable — 32px nav rows, 24px pane gutters, 44px table rows.
   Separation: the frame separates by tint and gap, so inside the pane content is
   separated by full-bleed hairline rules and the gutter — never by a bordered
   card and never by elevation. Rounding belongs to the pane and to controls.
   Active state: --sidebar-accent wash + foreground token + medium weight.
   App-scope duties: search → pane header palette · account → sidebar footer ·
   utility → pane header (notifications, theme) · page context → pane header's
   second row, the page header band.
   Primary content per destination:
     Overview    — figure row over the delivery chart, then the two lists of
                   work that is actually waiting on somebody
     Journeys    — list-detail; the record is a step ladder, each step carrying
                   its own drop-off meter
     Broadcasts  — figure row and a delivery-by-day chart over the send table;
                   /broadcasts/:id is one send's funnel, or what it will go to
     Audiences   — two column stacks of audiences, each one its rule, its
                   materialised count, its share of the reachable list and a
                   five-member sample; /audiences/:id is one audience's members
                   and everything that sends to it
     Content     — a filterable table of email templates whose usage column is
                   derived from what points at them
     Deliverability — a matrix of three DNS checks over three domains, then the
                   table of what is actually failing to deliver
   Journeys is the destination that would most plausibly have been a table and
   is not: the question a journey answers is "where do people stop", which a
   ladder shows in one glance and a row cannot show at all.
   Workspace settings and the team screen are registered off the sidebar, reached
   from the account menu, and are the only two staged screens in the product.
   Sign-in renders with no shell at all (AGENTS §7.1). */

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

/* One declaration for the whole shell: 1280 labelled sidebar · 1024 icon rail ·
   below that a drawer over the pane. */
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 BRAND_MARK = "../../assets/templates/logos/07-logo-demo.svg";
Object.assign(window, { BRAND_MARK });

function BrandBlock({ rail, workspace }) {
  return (
    <div className="md-brand">
      <img className="md-brand__logo" src={BRAND_MARK} alt="" width="28" height="28" />
      {rail ? null : (
        <span className="md-brand__text">
          <span className="md-brand__name">Marketing Desk</span>
          <span className="md-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="md-rail-dot" aria-hidden="true" /> : <SidebarMenuBadge aria-label={badge.count + " " + badge.label}>{badge.count}</SidebarMenuBadge>
      ) : null}
    </SidebarMenuItem>
  );
}

function AccountMenu({ rail, onNavigate, profile, workspace }) {
  const trigger = (
    <button type="button" className={"md-account" + (rail ? " md-account--rail" : "")} aria-label={"Account — " + profile.name}>
      <Avatar size={rail ? 28 : 32} src={profile.avatar} alt="" fallback={initialsOf(profile.name)} />
      {rail ? null : (
        <span className="md-account__text">
          <span className="md-account__name">{profile.name}</span>
          <span className="md-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} · {workspace.name}</MenuGroupLabel>
          {MD_ACCOUNT_MENU.map((route) => (
            <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>{route.label}</MenuItem>
          ))}
          <MenuItem onClick={() => { onNavigate("/signin"); close(); }}>Sign out</MenuItem>
        </>
      )}
    </Floating>
  );
}

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

/* The pane's own header. In drawer mode the navigation trigger takes the
   leading slot — the pane header's leading edge is where the sidebar went. */
function PaneHead({ mode, dark, onToggleTheme, onOpenPalette, onOpenDrawer, notifications, unread, onRead, onNavigate }) {
  return (
    <div className="md-pane-head">
      {mode === "drawer" ? (
        <Button variant="ghost" size="icon-sm" aria-label="Open navigation" onClick={onOpenDrawer}><Icon name="menu" /></Button>
      ) : null}
      <div className="md-search" onClick={onOpenPalette}>
        <Input
          readOnly
          size="sm"
          aria-label="Search Marketing Desk"
          placeholder="Search journeys, broadcasts, audiences…"
          startAddon={<Icon name="search" />}
          endAddon={<Kbd>⌘K</Kbd>}
          onFocus={onOpenPalette}
        />
      </div>
      <span className="md-search-btn">
        <FloatingTip label="Search — ⌘K" side="bottom">
          <Button variant="ghost" size="icon-sm" aria-label="Search Marketing Desk" onClick={onOpenPalette}><Icon name="search" /></Button>
        </FloatingTip>
      </span>
      <div className="md-pane-head__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>
  );
}

/* Every screen renders PageHeader 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;

/* The last crumb NAMES the record. The trail still comes from the route table —
   nothing is added to it — but a parameterised route's own segment reads the
   record's name rather than the generic label the table carries, because
   "Journeys / Journey" tells the reader nothing they cannot already see. It is
   still not a link (§5). */
function PageHeader({ path, title, actions, params, crumb }) {
  const trail = breadcrumb(path, MD_ROUTES).map((seg, i, all) => (
    crumb && i === all.length - 1 ? Object.assign({}, seg, { label: crumb }) : seg
  ));
  return (
    <header className="md-page-header">
      <div>
        <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="md-page-title">{title}</h1>
      </div>
      {actions ? <div className="md-page-header__actions">{actions}</div> : null}
    </header>
  );
}

function MdShell({ 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="md-shell" data-mode={mode}>
      {mode === "drawer" && drawer ? <div className="md-drawer-scrim" onClick={() => setDrawer(false)} /> : null}
      {navOpen ? (
        <Sidebar className="md-nav" aria-label="Marketing Desk">
          <SidebarHeader>
            <div className="md-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>
            {MD_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} workspace={workspace} />
          </SidebarFooter>
        </Sidebar>
      ) : null}

      <SidebarInset className="md-pane">
        <PaneHead
          mode={mode}
          dark={dark}
          onToggleTheme={onToggleTheme}
          onOpenPalette={() => palette.setOpen(true)}
          onOpenDrawer={() => setDrawer(true)}
          notifications={notifications}
          unread={unread}
          onRead={onRead}
          onNavigate={onNavigate}
        />
        {children}
      </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, { MdShell, PageHeader, useShellMode, NavRow, AccountMenu });
