/* Hearth shell — SIDEBAR shell, LABELLED mode, one navigation owner. The sidebar
   owns every top-level destination; the top bar is utility only and repeats
   nothing.
   Frame: one plane for the whole shell — --sidebar, the design system's light
   neutral — carrying a 264px WHITE sidebar panel inset --space-3 on all four
   sides, and a content column that paints nothing of its own where every region
   is a card: one hairline, --radius-2xl, one elevation step, never nested. The
   gap between cards is the only separator.
   Density: generous — 34px nav rows, 24px page gutters, 44px table rows.
   Active state: --sidebar-accent wash + foreground token + medium weight.
   Recession: --muted surface, muted text, no primary control, link and badge
   kept — a device updating or switched out of the house, and a paused routine.
   Corner and motion character: 16px cards, 10px controls, transitions only on
   width and background, never on a number.
   App-scope duties: search → top bar, a read-only field that opens the palette ·
   session and account → the sidebar footer, at every width · utility → top bar
   (notifications, theme) · page context → the page header.
   TEN destinations over two groups of five — this is a house with five people in
   it, not a department. The first group is what the house is DOING and what
   somebody standing in the hall reaches for; the second is what keeps it running.
   The four registers a household consults occasionally — Bills, Access,
   Providers, Log — hang off the destination they belong to rather than taking a
   line of their own; each is a registered route with a full screen, reached from
   a button on its parent and from the palette's Registers group.
   Primary content per destination:
     Today      — the house in one view: a verdict card, four figures, then the
                  two columns of what is happening and what wants a person
     Rooms      — canvas of room cards with live controls
     Cameras    — the live view first: one focused camera at 16:9 with its
                  controls, the others as tiles, the clips, and the shutters
     Climate    — chart-led: the derived comfort target, zones, and a day strip
                  per zone showing the schedule against now
     Security   — board: the alarm, then every way in as a row with its grants
     Devices    — the hub's verdict and a connection test, what the hub can hear
                  but has not taken in, what wants a person, then the whole list
     Routines   — three sections, each running its own predicate
     People     — canvas of people over the requests waiting on an answer
     Energy     — chart-led: fourteen days, the tariff windows as a day strip,
                  the battery, and where the draw is going right now
     Upkeep     — list of jobs, consumables measured in hours rather than dates
   Climate is the destination that would most plausibly have been a plain table
   and is not: the question a heating screen answers is "why is the house this
   temperature", which is a chain — who is home, who is awake, what each zone was
   told — and the strip shows the answer against the clock in one glance.
   Sign-in and the reset flow render with no shell at all (AGENTS §7.1). */

const {
  Button, Input, Kbd, Avatar, MenuItem, MenuGroupLabel,
  Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator,
  Toast, ToastRegion,
} = window.OriginDesignSystem_7c998b;

const HEARTH_MARK = "../../assets/templates/logos/01-logo-demo.svg";
/* The product's name, which is what the brand block carries (§6.3) — the house it
   is running is named underneath it. */
const HEARTH_PRODUCT = "Hearth";

/* One declaration for the whole shell: 1280 labelled · 1024 icon rail, labels
   become tooltips · below 900 an off-canvas drawer carrying the labelled
   sidebar whole. */
function useShellMode() {
  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;
}

function NavLink({ route, active, badge, rail, onNavigate }) {
  const button = (
    <button type="button" className="hh-link" aria-current={active ? "page" : undefined}
      aria-label={rail ? route.label + (badge && badge.count ? " — " + badge.count + " " + badge.label : "") : undefined}
      onClick={() => onNavigate(route.path)}>
      <Icon name={route.icon} size={17} />
      {rail ? null : <span className="hh-link__label">{route.label}</span>}
      {!rail && badge && badge.count > 0 ? <span className="hh-link__count" aria-label={badge.count + " " + badge.label}>{badge.count}</span> : null}
      {rail && badge && badge.count > 0 ? <span className="hh-dot" aria-hidden="true" /> : null}
    </button>
  );
  return rail ? <FloatingTip label={route.label + (badge && badge.count ? " · " + badge.count + " " + badge.label : "")}>{button}</FloatingTip> : button;
}

function Sidebar({ path, data, now, viewer, rail, onNavigate, onClose }) {
  return (
    <nav className="hh-side" data-rail={rail ? "true" : "false"} aria-label={HEARTH_PRODUCT + " — sections"}>
      <div className="hh-brand">
        <img className="hh-brand__mark" src={HEARTH_MARK} alt="" aria-hidden="true" width="26" height="26" />
        {rail ? null : (
          <span className="hh-brand__text">
            <span className="hh-brand__name">{HEARTH_PRODUCT}</span>
            <span className="hh-brand__sub">{householdName(data.members)} · {membersHome(data.members).length} home</span>
          </span>
        )}
      </div>
      <div className="hh-nav">
        {HEARTH_SIDEBAR.map((group) => (
          <div className="hh-group" key={group.label}>
            <span className="hh-group__label">{group.label}</span>
            {group.items.map((route) => {
              const spec = route.badge ? HEARTH_NAV_BADGES[route.badge] : null;
              return (
                <NavLink key={route.path} route={route} rail={rail}
                  active={route.path === path || (route.path !== "/" && path.indexOf(route.path + "/") === 0)}
                  badge={spec ? { count: spec.count(data, now), label: spec.label } : null}
                  onNavigate={(p) => { onNavigate(p); if (onClose) onClose(); }} />
              );
            })}
          </div>
        ))}
      </div>
      <div className="hh-side__foot">
        <AccountMenu rail={rail} viewer={viewer} onNavigate={(p) => { onNavigate(p); if (onClose) onClose(); }} />
      </div>
    </nav>
  );
}

function AccountMenu({ rail, viewer, onNavigate }) {
  const trigger = (
    <button type="button" className={"hh-account" + (rail ? " hh-account--rail" : "")} aria-label={"Account — " + viewer.name + ", " + labelOf(HOUSEHOLD_ROLES, viewer.role)}>
      <Avatar size={rail ? 30 : 34} src={viewer.avatar} alt="" fallback={initialsOf(viewer.name)} />
      {rail ? null : (
        <span className="hh-account__text">
          <span className="hh-account__name">{viewer.name}</span>
          <span className="hh-account__role">{labelOf(HOUSEHOLD_ROLES, viewer.role)}</span>
        </span>
      )}
    </button>
  );
  return (
    <Floating trigger={trigger} align="start" width="15rem" label="Account">
      {(close) => (
        <>
          <MenuGroupLabel>{viewer.name} · {labelOf(HOUSEHOLD_ROLES, viewer.role)}</MenuGroupLabel>
          {HEARTH_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="hh-utility">
      <Button variant="ghost" size="icon-sm" aria-label={unread ? unread + " unread notifications" : "Notifications"}>
        <Icon name="bell" />
      </Button>
      {unread ? <span className="hh-badge-dot" aria-hidden="true">{unread}</span> : null}
    </span>
  );
  return (
    <FloatingTip label="Notifications" side="bottom">
      <Floating trigger={trigger} align="end" width="25rem" role="dialog" panelClass="o-popover hh-notify" label="Notifications">
        {(close) => (
          <>
            <div className="hh-notify__head">
              <span className="o-popover__title">Notifications</span>
              <Button variant="ghost" size="xs" onClick={onRead}>Mark all read</Button>
            </div>
            <div>
              {items.map((n) => (
                <button type="button" key={n.id} className="hh-notify__item" onClick={() => { onNavigate(n.route); close(); }}>
                  <span className="hh-notify__title">{n.title}</span>
                  <span className="hh-notify__body">{n.body}</span>
                  <span className="hh-notify__time" title={formatAbsolute(n.at)}>{formatWhen(n.at, HEARTH_NOW)}</span>
                </button>
              ))}
            </div>
          </>
        )}
      </Floating>
    </FloatingTip>
  );
}

function TopBar({ mode, dark, onToggleTheme, onOpenPalette, onOpenDrawer, notifications, unread, onRead, onNavigate }) {
  return (
    <div className="hh-topbar">
      {mode === "drawer" ? (
        <Button variant="ghost" size="icon-sm" aria-label="Open navigation" onClick={onOpenDrawer}><Icon name="menu" /></Button>
      ) : null}
      <div className="hh-search" onClick={onOpenPalette}>
        <Input readOnly size="sm" aria-label={"Search " + RESIDENCE.short}
          placeholder="Search devices, rooms, people, jobs…"
          startAddon={<Icon name="search" />} endAddon={<Kbd>⌘K</Kbd>} onFocus={onOpenPalette} />
      </div>
      <span className="hh-search-btn">
        <FloatingTip label="Search — ⌘K" side="bottom">
          <Button variant="ghost" size="icon-sm" aria-label={"Search " + RESIDENCE.short} onClick={onOpenPalette}><Icon name="search" /></Button>
        </FloatingTip>
      </span>
      <div className="hh-topbar__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 PageHead and none of them pass the router, so the shell
   registers it once per render and the crumbs read it from here. */
let crumbNavigate = null;

function PageHead({ path, title, lede, actions, params, crumb }) {
  const trail = breadcrumb(path, HEARTH_ROUTES).map((seg, i, all) => (
    crumb && i === all.length - 1 ? Object.assign({}, seg, { label: crumb }) : seg
  ));
  return (
    <header className="hh-head">
      <div>
        {trail.length > 1 ? (
          <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={() => crumbNavigate && crumbNavigate(resolvePath(seg.path, params || {}))}>{seg.label}</BreadcrumbLink>}
                  </BreadcrumbItem>
                </React.Fragment>
              ))}
            </BreadcrumbList>
          </Breadcrumb>
        ) : null}
        <h1 className="hh-title">{title}</h1>
        {lede ? <p className="hh-lede">{lede}</p> : null}
      </div>
      {actions ? <div className="hh-actions">{actions}</div> : null}
    </header>
  );
}

function HearthShell({ path, onNavigate, dark, onToggleTheme, data, now, viewer, notifications, unread, onRead, palette, toasts, onDismissToast, children }) {
  crumbNavigate = onNavigate;
  const mode = useShellMode();
  const [drawer, setDrawer] = React.useState(false);
  React.useEffect(() => { if (mode !== "drawer") setDrawer(false); }, [mode]);

  const sidebar = (rail, onClose) => (
    <Sidebar path={path} data={data} now={now} viewer={viewer} rail={rail} onNavigate={onNavigate} onClose={onClose} />
  );

  return (
    <div className="hh-shell" data-mode={mode}>
      {mode === "drawer" ? (
        drawer ? (
          <>
            <div className="hh-scrim" onClick={() => setDrawer(false)} />
            <div className="hh-drawer">{sidebar(false, () => setDrawer(false))}</div>
          </>
        ) : null
      ) : sidebar(mode === "rail", null)}

      <main className="hh-main">
        <TopBar mode={mode} dark={dark} onToggleTheme={onToggleTheme}
          onOpenPalette={() => palette.setOpen(true)} onOpenDrawer={() => setDrawer(true)}
          notifications={notifications} unread={unread} onRead={onRead} onNavigate={onNavigate} />
        {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, { HearthShell, PageHead, AccountMenu, useShellMode, HEARTH_MARK, HEARTH_PRODUCT });
