<script lang="ts">
  import { untrack } from 'svelte';
  import { ChevronDown, LogOut, Settings } from 'lucide-svelte';
  import type { ComponentType } from 'svelte';
  import { tooltip } from '$lib/actions/tooltip';

  import {
    groupHasActiveChild,
    matchesRoute,
    type FooterLink,
    type NavEntry,
    type NavItem
  } from '$lib/navigation/client-navigation';

  let {
    brandHref,
    currentPath,
    collapsed = false,
    entries,
    footerItems,
    appVersion,
    currentYear,
    canOpenSettings,
    onOpenSettings,
    onSignOut
  }: {
    brandHref: string;
    currentPath: string;
    collapsed?: boolean;
    entries: NavEntry[];
    footerItems: FooterLink[];
    appVersion: string;
    currentYear: number;
    canOpenSettings: boolean;
    onOpenSettings: () => void;
    onSignOut: () => void;
  } = $props();

  // ── Collapse state ──────────────────────────────────────────────
  // Smart auto-expand: the group holding the current page opens itself, other
  // groups stay exactly as the user left them, and the whole map survives a
  // reload through sessionStorage. Multiple groups may be open at once.
  const STORAGE_KEY = 'hsf:nav:open-groups';

  function restoreOpenState(): Record<string, boolean> {
    if (typeof window === 'undefined') return {};
    try {
      return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) ?? '{}');
    } catch {
      return {};
    }
  }

  let openGroups = $state<Record<string, boolean>>(restoreOpenState());
  let lastAutoExpanded = $state<string | null>(null);

  function persistOpenState() {
    if (typeof window === 'undefined') return;
    try {
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(openGroups));
    } catch {
      // Private-mode storage failures shouldn't break navigation.
    }
  }

  const activeGroupId = $derived.by(() => {
    for (const entry of entries) {
      if (entry.kind === 'group' && groupHasActiveChild(entry.group, currentPath)) {
        return entry.group.id;
      }
    }
    return null;
  });

  // Open the active group once each time it changes, collapsing any other open
  // group so only one family is ever expanded (accordion). Because this only
  // fires on a *change* of activeGroupId, a user who manually closes the group
  // they're standing in won't have it reopened under them.
  $effect(() => {
    const id = activeGroupId;
    if (id) {
      if (lastAutoExpanded !== id) {
        openGroups = { [id]: true };
        persistOpenState();
        lastAutoExpanded = id;
      }
    } else if (lastAutoExpanded !== null) {
      // Just landed on a standalone module (Dashboard, Throughput, Reporting)
      // from inside a family. Collapse the open family so the rail tidies itself,
      // and forget the last auto-expanded group so returning to it — say
      // Throughput → Order Management — fires the expand again. The
      // `lastAutoExpanded !== null` guard makes this a one-shot per transition, so
      // a group the user manually opens while on a standalone page stays open.
      openGroups = {};
      persistOpenState();
      lastAutoExpanded = null;
    }
  });

  const isOpen = (id: string) => openGroups[id] ?? false;

  // Accordion: opening a group collapses every other group; closing just shuts
  // the one. So expanding Order Management folds an already-open Operations away.
  function toggleGroup(id: string) {
    openGroups = isOpen(id) ? {} : { [id]: true };
    persistOpenState();
  }

  // Expand a group without ever collapsing it. Used by a linkable group header
  // (Order Management) so clicking the label reveals its submenu the same way a
  // toggle group does — the route may not change (you're already on its page),
  // so the auto-expand effect can't be relied on to open it. The chevron remains
  // the way to collapse the family.
  function openGroup(id: string) {
    if (isOpen(id)) return;
    openGroups = { [id]: true };
    persistOpenState();
  }

  // ── Third-level submenus (e.g. Integrations → Xero) ─────────────
  // Tracked independently of the top-level accordion: a nested submenu can be
  // open at the same time as its parent group, and toggling a top-level family
  // must not wipe a sibling's nested state. Keyed by "<groupId>:<childHref>".
  const SUB_STORAGE_KEY = 'hsf:nav:open-subgroups';

  function restoreSubState(): Record<string, boolean> {
    if (typeof window === 'undefined') return {};
    try {
      return JSON.parse(window.sessionStorage.getItem(SUB_STORAGE_KEY) ?? '{}');
    } catch {
      return {};
    }
  }

  let openSubGroups = $state<Record<string, boolean>>(restoreSubState());
  let lastAutoExpandedSub = $state<string | null>(null);
  let logoutConfirmOpen = $state(false);

  function persistSubState() {
    if (typeof window === 'undefined') return;
    try {
      window.sessionStorage.setItem(SUB_STORAGE_KEY, JSON.stringify(openSubGroups));
    } catch {
      // Private-mode storage failures shouldn't break navigation.
    }
  }

  const subKey = (groupId: string, child: NavItem) => `${groupId}:${child.href}`;

  /** True when a child row owns a nested submenu whose grandchild is active. */
  function subGroupActive(child: NavItem) {
    return child.children?.some((g) => matchesRoute(g.href, currentPath, g.exact)) ?? false;
  }

  const activeSubKey = $derived.by(() => {
    for (const entry of entries) {
      if (entry.kind !== 'group') continue;
      for (const child of entry.group.children) {
        if (child.children?.length && subGroupActive(child)) {
          return subKey(entry.group.id, child);
        }
      }
    }
    return null;
  });

  // Auto-open the submenu holding the current page, once per change. `untrack`
  // reads the current map without making it a dependency — otherwise writing it
  // back would retrigger this effect endlessly.
  $effect(() => {
    const key = activeSubKey;
    if (key) {
      if (lastAutoExpandedSub !== key) {
        openSubGroups = { ...untrack(() => openSubGroups), [key]: true };
        persistSubState();
        lastAutoExpandedSub = key;
      }
    } else {
      lastAutoExpandedSub = null;
    }
  });

  const isSubOpen = (key: string) => openSubGroups[key] ?? false;

  function toggleSubGroup(key: string) {
    openSubGroups = { ...openSubGroups, [key]: !isSubOpen(key) };
    persistSubState();
  }

  // Reveal a nested submenu without collapsing it, mirroring openGroup for the
  // third level: clicking the Integrations label opens its connected-systems
  // list even when the route doesn't change.
  function openSubGroup(key: string) {
    if (isSubOpen(key)) return;
    openSubGroups = { ...openSubGroups, [key]: true };
    persistSubState();
  }

  function handleLogoutAction() {
    if (collapsed) {
      logoutConfirmOpen = true;
      return;
    }

    onSignOut();
  }

  function closeLogoutConfirm() {
    logoutConfirmOpen = false;
  }

  function confirmSignOut() {
    logoutConfirmOpen = false;
    onSignOut();
  }
</script>

{#snippet leafLink(item: NavItem, showIcon: boolean)}
  {@const Icon = item.icon}
  <a
    class="rail-row"
    class:active={matchesRoute(item.href, currentPath, item.exact)}
    class:icon-only={collapsed}
    href={item.href}
    use:tooltip={collapsed ? { label: item.label, placement: 'right' } : ''}
  >
    {#if showIcon && Icon}
      <span class="rail-icon"><Icon size={18} strokeWidth={1.75} /></span>
    {/if}
    {#if !collapsed}
      <span class="rail-text">{item.label}</span>
      {#if item.badge}<span class="rail-badge">{item.badge}</span>{/if}
    {/if}
  </a>
{/snippet}

{#snippet actionRow(label: string, Icon: ComponentType, active: boolean, onSelect: () => void)}
  {@const RowIcon = Icon}
  <button
    type="button"
    class="rail-row"
    class:active
    class:icon-only={collapsed}
    onclick={onSelect}
    use:tooltip={collapsed ? { label, placement: 'right' } : ''}
  >
    <span class="rail-icon"><RowIcon size={18} strokeWidth={1.75} /></span>
    {#if !collapsed}
      <span class="rail-text">{label}</span>
    {/if}
  </button>
{/snippet}

<aside class:collapsed={collapsed} class="sidebar">
  <div class="brand-row">
    <a class="brand" href={brandHref}>
      {#if !collapsed}
        <span class="brand-kicker">Hunter App</span>
        <span class="brand-wordmark">Hunter Premium Produce</span>
        <span class="brand-subtitle">Operations workspace</span>
      {:else}
        <span class="brand-mini">HP</span>
      {/if}
    </a>
  </div>

  <div class="sidebar-body">
    <div class="rail-scroll">
      <div class="rail-section-head">
        {#if !collapsed}
          <p class="rail-section-label">Modules</p>
        {/if}
      </div>

      <nav class="rail-nav" aria-label="Workspace navigation">
        {#each entries as entry}
          {#if entry.kind === 'item'}
            {@render leafLink(entry.item, true)}
          {:else}
            {@const group = entry.group}
            {@const GroupIcon = group.icon}
            {@const groupActive = groupHasActiveChild(group, currentPath)}
            {@const open = isOpen(group.id)}
            {@const headerHref = group.href ?? group.children[0]?.href}
            {#if collapsed}
              <a
                class="rail-row icon-only"
                class:active={groupActive}
                href={headerHref}
                use:tooltip={{ label: group.label, placement: 'right' }}
              >
                <span class="rail-icon"><GroupIcon size={18} strokeWidth={1.75} /></span>
              </a>
            {:else}
            <div class="rail-group">
              {#if headerHref}
                <!-- Every family header both navigates and reveals its submenu:
                     the label goes to the family's landing route (Order Management
                     → its queue; Operations → its first tool) and opens the child
                     list, while the chevron toggles independently. The header never
                     takes the full active pill — that belongs to the matching child
                     row — it only gets the subtle within-active emphasis when
                     collapsed. -->
                <div class="rail-group-head" class:within-active={groupActive && !open}>
                  <a
                    class="rail-row rail-group-link"
                    href={headerHref}
                    onclick={() => openGroup(group.id)}
                  >
                    <span class="rail-icon"><GroupIcon size={18} strokeWidth={1.75} /></span>
                    <span class="rail-text">{group.label}</span>
                  </a>
                  <button
                    type="button"
                    class="rail-chevron-btn"
                    aria-expanded={open}
                    aria-label={`${open ? 'Collapse' : 'Expand'} ${group.label}`}
                    onclick={() => toggleGroup(group.id)}
                  >
                    <span class="rail-chevron" class:open aria-hidden="true">
                      <ChevronDown size={15} strokeWidth={2} />
                    </span>
                  </button>
                </div>
              {:else}
                <button
                  type="button"
                  class="rail-row rail-group-toggle"
                  class:within-active={groupActive && !open}
                  aria-expanded={open}
                  onclick={() => toggleGroup(group.id)}
                >
                  <span class="rail-icon"><GroupIcon size={18} strokeWidth={1.75} /></span>
                  <span class="rail-text">{group.label}</span>
                  <span class="rail-group-meta">
                    <span class="rail-chevron" class:open aria-hidden="true">
                      <ChevronDown size={15} strokeWidth={2} />
                    </span>
                  </span>
                </button>
              {/if}

              {#if open}
                <div class="rail-children">
                  {#each group.children as child}
                    {#if child.children?.length}
                      {@const key = subKey(group.id, child)}
                      {@const subOpen = isSubOpen(key)}
                      {@const subActive = subGroupActive(child)}
                      <!-- Third layer: child row links to its own page; chevron
                           reveals the nested submenu (e.g. Integrations → Xero). -->
                      <div class="rail-group-head rail-subgroup-head" class:within-active={subActive && !subOpen}>
                        <a
                          class="rail-row rail-group-link"
                          class:active={matchesRoute(child.href, currentPath, child.exact)}
                          href={child.href}
                          onclick={() => openSubGroup(key)}
                        >
                          <span class="rail-text">{child.label}</span>
                          {#if child.badge}<span class="rail-badge">{child.badge}</span>{/if}
                        </a>
                        <button
                          type="button"
                          class="rail-chevron-btn"
                          aria-expanded={subOpen}
                          aria-label={`${subOpen ? 'Collapse' : 'Expand'} ${child.label}`}
                          onclick={() => toggleSubGroup(key)}
                        >
                          <span class="rail-chevron" class:open={subOpen} aria-hidden="true">
                            <ChevronDown size={15} strokeWidth={2} />
                          </span>
                        </button>
                      </div>
                      {#if subOpen}
                        <div class="rail-children rail-subchildren">
                          {#each child.children as grandchild}
                            {@render leafLink(grandchild, false)}
                          {/each}
                        </div>
                      {/if}
                    {:else}
                      {@render leafLink(child, false)}
                    {/if}
                  {/each}
                </div>
              {/if}
            </div>
            {/if}
          {/if}
        {/each}
      </nav>
    </div>

    <div class="sidebar-meta">
      <div class="rail-nav">
        {#each footerItems as item}
          {@render leafLink(item as NavItem, true)}
        {/each}

        {#if canOpenSettings}
          {@render actionRow('Settings', Settings, currentPath.startsWith('/settings'), onOpenSettings)}
        {/if}
        {@render actionRow('Logout', LogOut, false, handleLogoutAction)}
      </div>

      {#if !collapsed}
        <div class="sidebar-meta-foot">
          <div class="sidebar-meta-top">
            <span class="version-pill">
              <span class="meta-label">Build</span>
              <span>{appVersion}</span>
            </span>
          </div>
          <div class="sidebar-meta-bottom">
            <small>&copy; {currentYear} Hunter Premium Produce</small>
            <div class="powered-by">
              <span>Powered by</span>
              <img src="/lean101-isotipo.png" alt="Lean 101" class="lean101-logo" />
              <strong>Lean 101</strong>
            </div>
          </div>
        </div>
      {/if}
    </div>
  </div>
</aside>

{#if logoutConfirmOpen}
  <div class="logout-dialog-backdrop" aria-hidden="true" onclick={closeLogoutConfirm}></div>
  <div
    class="logout-dialog"
    role="dialog"
    aria-modal="true"
    aria-labelledby="logout-dialog-title"
    aria-describedby="logout-dialog-description"
  >
    <div class="logout-dialog-copy">
      <p class="logout-dialog-kicker">Confirm Logout</p>
      <h2 id="logout-dialog-title">Log out of the workspace?</h2>
      <p id="logout-dialog-description">Your current client session will be closed and you will return to sign-in.</p>
    </div>
    <div class="logout-dialog-actions">
      <button type="button" class="logout-dialog-cancel" onclick={closeLogoutConfirm}>Cancel</button>
      <button type="button" class="logout-dialog-confirm" onclick={confirmSignOut}>Log out</button>
    </div>
  </div>
{/if}

<style>
  /* Monochrome rail with a blue selected pill. Colours come from the --sidebar-*
     tokens, which are overridden in dark mode (see theme.css) so the rail themes
     alongside the content instead of staying a bright light strip. */
  .sidebar {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    padding: 1rem 0.8rem 0.85rem;
    background: var(--sidebar-bg);
    border-right: 1px solid var(--sidebar-border);
    position: sticky;
    top: 0;
    height: 100vh;
    overflow: hidden;
  }

  .sidebar.collapsed {
    align-items: center;
    padding: 1rem 0.5rem 0.85rem;
  }

  .rail-section-label {
    margin: 0;
    color: var(--sidebar-text-muted);
    font-size: 0.65rem;
    font-weight: 700;
    letter-spacing: 0.12em;
    text-transform: uppercase;
  }

  .sidebar-body {
    min-height: 0;
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 0.75rem;
  }

  .rail-scroll {
    min-height: 0;
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 0.55rem;
    overflow-y: auto;
    scrollbar-width: thin;
    padding-right: 0.15rem;
  }

  .rail-section-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
    padding: 0 0.5rem;
  }

  .brand-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 0.9rem;
    padding: 0.15rem 0.35rem 0.95rem;
    border-bottom: 1px solid var(--sidebar-border);
  }

  .brand {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.16rem;
    min-width: 0;
    padding: 0.08rem 0 0.1rem;
  }

  .brand-mini {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 0.9rem;
    background: var(--sidebar-active-bg);
    color: var(--sidebar-active-text);
    font-size: 0.78rem;
    font-weight: 800;
    letter-spacing: 0.08em;
  }

  .brand-kicker {
    color: var(--sidebar-text-muted);
    font-size: 0.66rem;
    font-weight: 700;
    letter-spacing: 0.12em;
    text-transform: uppercase;
  }

  .brand-wordmark {
    font-size: 1rem;
    font-weight: 700;
    line-height: 1.2;
    letter-spacing: -0.01em;
    color: var(--sidebar-text-strong);
  }

  .brand-subtitle {
    color: var(--sidebar-text-muted);
    font-size: 0.8rem;
    line-height: 1.3;
  }

  /* ── Navigation rows ─────────────────────────────────────────── */
  .rail-nav {
    display: grid;
    gap: 0.18rem;
  }

  .sidebar.collapsed .rail-nav {
    justify-items: center;
  }

  .rail-row {
    position: relative;
    display: flex;
    align-items: center;
    gap: 0.72rem;
    width: 100%;
    min-height: 2.8rem;
    padding: 0.62rem 0.72rem;
    border: none;
    border-radius: 0.9rem;
    background: transparent;
    color: var(--sidebar-text);
    font-size: 0.92rem;
    font-weight: 500;
    letter-spacing: -0.01em;
    text-align: left;
    cursor: pointer;
    transition: background-color 160ms ease, color 160ms ease;
  }

  .rail-row:hover {
    background: var(--sidebar-hover);
    color: var(--sidebar-text-strong);
  }

  .rail-row:hover .rail-icon {
    color: var(--sidebar-text-strong);
  }

  .rail-row.active,
  .rail-row.active:hover {
    background: var(--sidebar-active-bg);
    color: var(--sidebar-active-text);
    font-weight: 600;
  }

  .rail-row.active .rail-text,
  .rail-row.active:hover .rail-text {
    color: var(--sidebar-active-text);
  }

  .rail-row.active .rail-icon {
    color: var(--sidebar-active-text);
  }

  .rail-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    width: 1.5rem;
    height: 1.5rem;
    color: var(--sidebar-icon);
    transition: color 140ms ease;
  }

  .rail-text {
    min-width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .rail-badge {
    margin-left: auto;
    flex-shrink: 0;
    padding: 0.12rem 0.42rem;
    border-radius: 999px;
    border: 1px solid var(--sidebar-border);
    background: transparent;
    color: var(--sidebar-text-muted);
    font-size: 0.58rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    line-height: 1.5;
  }

  .rail-row.icon-only {
    justify-content: center;
    gap: 0;
    width: 3rem;
    min-width: 3rem;
    min-height: 3rem;
    padding: 0;
    border-radius: 0.95rem;
  }

  .rail-row.active .rail-badge {
    border-color: color-mix(in srgb, var(--sidebar-active-text) 26%, transparent);
    color: var(--sidebar-active-text);
    background: color-mix(in srgb, var(--sidebar-active-text) 12%, transparent);
  }

  .rail-group {
    display: grid;
    gap: 0.2rem;
  }

  .rail-group-meta {
    margin-left: auto;
    display: inline-flex;
    align-items: center;
    gap: 0.42rem;
  }

  .rail-group-toggle.within-active {
    color: var(--sidebar-text-strong);
    font-weight: 600;
  }

  .rail-group-toggle.within-active .rail-icon,
  .rail-group-toggle.within-active .rail-chevron {
    color: var(--sidebar-text-strong);
  }

  /* ── Linkable group header (label links, chevron toggles) ────── */
  /* The label and chevron stay separate click targets (navigate vs toggle) but
     share one hover pill on the wrapper, so the whole header — icon, title,
     chevron — lights up as a single button instead of two halves. */
  .rail-group-head {
    display: flex;
    align-items: center;
    gap: 0;
    border-radius: 0.8rem;
    transition: background-color 160ms ease;
  }

  .rail-group-head:hover {
    background: var(--sidebar-hover);
  }

  .rail-group-head:hover .rail-group-link,
  .rail-group-head:hover .rail-icon,
  .rail-group-head:hover .rail-chevron {
    color: var(--sidebar-text-strong);
  }

  /* Let the wrapper own the hover background; the inner targets stay transparent
     so they don't paint a second, mismatched pill on top. */
  .rail-group-head .rail-group-link:hover,
  .rail-group-head .rail-chevron-btn:hover {
    background: transparent;
  }

  /* Category headers carry the lighter second-level row treatment (size, weight,
     radius); only the leading icon and chevron mark them as parents. Standalone
     top-level destinations (Dashboard, Throughput) keep the larger base row. */
  .rail-group-head .rail-group-link,
  .rail-group-toggle {
    min-height: 2.45rem;
    padding: 0.48rem 0.62rem 0.48rem 0.72rem;
    font-size: 0.88rem;
    border-radius: 0.8rem;
  }

  .rail-group-head .rail-group-link {
    flex: 1;
    min-width: 0;
  }

  .rail-group-head.within-active .rail-group-link {
    color: var(--sidebar-text-strong);
    font-weight: 600;
  }

  .rail-group-head.within-active .rail-group-link .rail-icon {
    color: var(--sidebar-text-strong);
  }

  .rail-chevron-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.42rem;
    flex-shrink: 0;
    min-height: 2.45rem;
    padding: 0 0.58rem;
    border: none;
    border-radius: 0.8rem;
    background: transparent;
    color: var(--sidebar-icon);
    cursor: pointer;
    transition: background-color 160ms ease, color 160ms ease;
  }

  .rail-chevron-btn:hover {
    background: var(--sidebar-hover);
    color: var(--sidebar-text-strong);
  }

  .rail-group-head.within-active .rail-chevron-btn {
    color: var(--sidebar-text-strong);
  }

  .rail-chevron {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    color: var(--sidebar-icon);
    transition: transform 200ms cubic-bezier(0.22, 1, 0.36, 1);
  }

  .rail-chevron.open {
    transform: rotate(180deg);
  }

  .rail-children {
    position: relative;
    display: grid;
    gap: 0.18rem;
    margin: 0 0 0.15rem;
    padding-left: 1.2rem;
    animation: rail-reveal 170ms cubic-bezier(0.22, 1, 0.36, 1);
  }

  .rail-children::before {
    content: '';
    position: absolute;
    top: 0.34rem;
    bottom: 0.34rem;
    left: 0.58rem;
    width: 1px;
    background: var(--sidebar-border);
  }

  .rail-children .rail-row {
    min-height: 2.45rem;
    padding: 0.48rem 0.62rem 0.48rem 0.82rem;
    font-size: 0.88rem;
    border-radius: 0.8rem;
  }

  /* Third level: nest the submenu a little deeper than its parent row, with its
     own guide line, so the hierarchy reads as Group › Section › Item. */
  .rail-subgroup-head {
    margin-left: 0.1rem;
  }

  .rail-subchildren {
    margin-left: 0.5rem;
    padding-left: 0.95rem;
    animation: none;
  }

  .rail-subchildren .rail-row {
    min-height: 2.2rem;
    font-size: 0.85rem;
  }

  @keyframes rail-reveal {
    from {
      opacity: 0;
      transform: translateY(-4px);
    }
    to {
      opacity: 1;
      transform: none;
    }
  }

  @media (prefers-reduced-motion: reduce) {
    .rail-chevron,
    .rail-children {
      transition: none;
      animation: none;
    }
  }

  /* ── Footer / meta ───────────────────────────────────────────── */
  .sidebar-meta {
    margin-top: auto;
    display: grid;
    gap: 0.75rem;
    padding-top: 0.75rem;
    border-top: 1px solid var(--sidebar-border);
    flex-shrink: 0;
  }

  .sidebar.collapsed .sidebar-body,
  .sidebar.collapsed .rail-scroll,
  .sidebar.collapsed .sidebar-meta {
    align-items: center;
  }

  .sidebar.collapsed .rail-section-head {
    justify-content: center;
    padding: 0;
    min-height: 0.35rem;
  }

  .sidebar.collapsed .brand-row,
  .sidebar.collapsed .sidebar-meta,
  .sidebar.collapsed .sidebar-meta-foot {
    width: 100%;
  }

  .sidebar-meta-foot {
    display: grid;
    gap: 0.55rem;
    padding: 0.7rem 0.5rem 0;
    border-top: 1px solid var(--sidebar-border);
    color: var(--sidebar-text-muted);
    font-size: 0.76rem;
  }

  .sidebar-meta-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.65rem;
  }

  .sidebar-meta-bottom {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.45rem;
  }

  .sidebar-meta-foot small {
    font-size: 0.72rem;
    line-height: 1.35;
  }

  .powered-by {
    display: flex;
    align-items: center;
    gap: 0.35rem;
    color: var(--sidebar-text-muted);
    white-space: nowrap;
  }

  .powered-by span {
    font-size: 0.72rem;
    font-weight: 500;
  }

  .powered-by strong {
    font-size: 0.76rem;
    font-weight: 600;
    color: var(--sidebar-text);
  }

  .lean101-logo {
    width: 1.45rem;
    height: 1.45rem;
    object-fit: contain;
    opacity: 0.8;
    flex-shrink: 0;
  }

  .version-pill {
    display: inline-flex;
    align-items: center;
    gap: 0.45rem;
    padding: 0.24rem 0.56rem;
    border: 1px solid var(--sidebar-border);
    border-radius: 999px;
    background: color-mix(in srgb, var(--sidebar-text-strong) 4%, transparent);
    color: var(--sidebar-text);
    font-size: 0.72rem;
    font-weight: 600;
  }

  .meta-label {
    color: var(--sidebar-text-muted);
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }

  .logout-dialog-backdrop {
    position: fixed;
    inset: 0;
    z-index: 39;
    background: rgba(15, 23, 42, 0.22);
  }

  .logout-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 40;
    width: min(28rem, calc(100vw - 2rem));
    display: grid;
    gap: 1rem;
    padding: 1.1rem;
    border: 1px solid var(--color-border);
    border-radius: 1rem;
    background: var(--color-bg-elevated);
    box-shadow: 0 18px 48px rgba(15, 23, 42, 0.18);
    transform: translate(-50%, -50%);
  }

  .logout-dialog-copy {
    display: grid;
    gap: 0.35rem;
  }

  .logout-dialog-kicker {
    margin: 0;
    color: var(--color-text-primary);
    font-size: 0.72rem;
    font-weight: 700;
    letter-spacing: 0.1em;
    text-transform: uppercase;
  }

  .logout-dialog-copy h2,
  .logout-dialog-copy p {
    margin: 0;
  }

  .logout-dialog-copy h2 {
    font-size: 1.1rem;
    line-height: 1.2;
  }

  .logout-dialog-copy p:last-child {
    color: var(--color-text-secondary);
    line-height: 1.5;
  }

  .logout-dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.7rem;
  }

  .logout-dialog-cancel,
  .logout-dialog-confirm {
    min-height: 2.7rem;
    padding: 0.65rem 0.95rem;
    border-radius: 0.85rem;
    font-weight: 600;
    cursor: pointer;
  }

  .logout-dialog-cancel {
    border: 1px solid var(--color-border);
    background: var(--color-bg-surface);
    color: var(--color-text-primary);
  }

  .logout-dialog-confirm {
    border: 1px solid transparent;
    background: var(--color-brand);
    color: var(--color-on-brand);
  }

  .logout-dialog-cancel:hover {
    background: var(--panel-soft);
  }

  .logout-dialog-confirm:hover {
    background: var(--color-brand-hover);
  }
</style>
