/* Lodestay shell — TOP-NAV shell, one navigation owner (the bar owns every
   top-level destination; there is no sidebar and no second row).
   Density: comfortable — 64px bar, 28px page gutters, 40px controls.
   Separation: hairline rules on the tinted --sidebar bar; cards are the only
   raised surface, one elevation step, never nested.
   Active state: foreground token plus a 2px underline pinned to the bar's
   bottom edge — never colour alone.
   App-scope duties: search → the ⌘K palette in the bar (a read-only field that
   opens the overlay, an icon button below 1280) · session and account → the
   account menu at the trailing edge · utility → notifications and theme in the
   bar · page context → the page header's breadcrumb and title.
   Primary content per destination:
     Stays    — a canvas: results list beside a real map of Lisbon
     Trips    — sectioned list of stays, each section running its own predicate
     Saved    — column stacks of place cards, per list
     Messages — list-detail: threads beside one conversation
   Stays is the destination that would most plausibly have been a table and is
   not: a place is chosen by looking at where it is, and a table cannot say
   "ten minutes' walk from the castle, but up sixty steps". */
(() => {
  const {
    Button, Input, Kbd, Avatar, MenuItem, MenuGroupLabel, Toast, ToastRegion, Separator,
  } = window.OriginDesignSystem_7c998b;

  /* Declared once for the product: 1280 full bar with the search field · 1024
     search collapses to an icon · below 1024 the destinations collapse into one
     menu button. Nothing is lost — the menu carries every label and every
     count, and the account menu never collapses into it. */
  function useBarMode() {
    const read = () => (window.innerWidth >= 1280 ? "full" : window.innerWidth >= 1024 ? "tight" : "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 isActive = (route, path) => route.path === path || (route.path !== "/" && path.indexOf(route.path + "/") === 0) || (route.path === "/" && path.indexOf("/stays") === 0);

  function NavItem({ route, path, badge, onNavigate }) {
    const active = isActive(route, path);
    return (
      <button type="button" className="ls-nav__item" aria-current={active ? "page" : undefined} onClick={() => onNavigate(route.path)}>
        <Icon name={route.icon} size={15} />
        {route.label}
        {badge && badge.count > 0 ? <span className="ls-nav__count" aria-label={badge.count + " " + badge.label}>{badge.count}</span> : null}
      </button>
    );
  }

  function DestinationsMenu({ path, data, onNavigate }) {
    const trigger = <Button variant="outline" size="sm" aria-label="Destinations"><Icon name="menu" size={15} />{(LODESTAY_BAR.find((r) => isActive(r, path)) || LODESTAY_BAR[0]).label}<Icon name="chevron-down" size={14} /></Button>;
    return (
      <Floating trigger={trigger} align="start" width="15rem" label="Destinations" panelClass="o-menu ls-navmenu">
        {(close) => LODESTAY_BAR.map((route) => {
          const spec = route.badge ? NAV_BADGES[route.badge] : null;
          const count = spec ? spec.count(data) : 0;
          return (
            <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>
              <Icon name={route.icon} size={15} />
              {route.label}
              {count > 0 ? <span className="ls-nav__count" style={{ marginInlineStart: "auto" }} aria-label={count + " " + spec.label}>{count}</span> : null}
            </MenuItem>
          );
        })}
      </Floating>
    );
  }

  function AccountMenu({ onNavigate, user }) {
    const trigger = (
      <button type="button" className="ls-account" aria-label={"Account — " + user.name}>
        <span className="ls-account__name">{user.name.split(" ")[0]}</span>
        <Avatar size={28} src={user.avatar} alt="" fallback={user.name.split(" ").map((w) => w[0]).join("")} />
      </button>
    );
    return (
      <Floating trigger={trigger} align="end" width="15rem" label="Account">
        {(close) => (
          <>
            <MenuGroupLabel>{user.name} · Guest</MenuGroupLabel>
            {LODESTAY_ACCOUNT_MENU.map((route) => (
              <MenuItem key={route.path} onClick={() => { onNavigate(route.path); close(); }}>{route.label}</MenuItem>
            ))}
          </>
        )}
      </Floating>
    );
  }

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

  function LodestayShell({ path, onNavigate, dark, onToggleTheme, data, user, notifications, unread, onRead, palette, toasts, onDismissToast, children }) {
    const mode = useBarMode();
    return (
      <div className="ls-shell">
        <header className="ls-bar">
          <button type="button" className="ls-brand" onClick={() => onNavigate("/")} aria-label={LODESTAY_PRODUCT.name + " — home"}>
            <img className="ls-brand__logo" src="../../assets/templates/logos/28-logo-demo.svg" alt="" width="28" height="28" />
            <span className="ls-brand__name">{LODESTAY_PRODUCT.name}</span>
          </button>
          {mode === "menu" ? <DestinationsMenu path={path} data={data} onNavigate={onNavigate} /> : (
            <nav className="ls-nav" aria-label="Destinations">
              {LODESTAY_BAR.map((route) => {
                const spec = route.badge ? NAV_BADGES[route.badge] : null;
                return <NavItem key={route.path} route={route} path={path} badge={spec ? { count: spec.count(data), label: spec.label } : null} onNavigate={onNavigate} />;
              })}
            </nav>
          )}
          <div className="ls-bar__right">
            {mode === "full" ? (
              <div className="ls-search" onClick={() => palette.setOpen(true)}>
                <Input readOnly size="sm" aria-label="Search Lodestay" placeholder="Search places, trips, hosts…" startAddon={<Icon name="search" />} endAddon={<Kbd>⌘K</Kbd>} onFocus={() => palette.setOpen(true)} />
              </div>
            ) : (
              <FloatingTip label="Search places, trips, hosts — ⌘K" side="bottom">
                <Button variant="ghost" size="icon-sm" aria-label="Search Lodestay" onClick={() => palette.setOpen(true)}><Icon name="search" /></Button>
              </FloatingTip>
            )}
            <NotificationsButton items={notifications} unread={unread} onRead={onRead} onNavigate={onNavigate} now={data.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"} /></Button>
            </FloatingTip>
            <Separator orientation="vertical" style={{ height: 24 }} />
            <AccountMenu onNavigate={onNavigate} user={user} />
          </div>
        </header>
        <main className="ls-content">{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, { LodestayShell, useBarMode });
})();
