<script lang="ts">
  import { api } from '$lib/api';
  import ClientPrimaryRail from '$lib/components/navigation/ClientPrimaryRail.svelte';
  import ClientTopbar from '$lib/components/navigation/ClientTopbar.svelte';
  import WorkspaceSearchTrigger from '$lib/components/navigation/WorkspaceSearchTrigger.svelte';
  import { invalidateAll } from '$app/navigation';
  import { goto } from '$app/navigation';
  import { page } from '$app/state';
  import { clientSession, hasModuleAccess, sessionHydrated } from '$lib/session';
  import { featureFlags } from '$lib/features';
  import {
    accessControlItem,
    baseSearchItems,
    clientBreadcrumbs,
    dashboardItem,
    footerLinks,
    matchesRoute,
    mixCalculatorItem,
    pageTitle,
    reportingItem,
    type FooterLink,
    type SearchItem,
    type NavItem,
    workingDocumentItems
  } from '$lib/navigation/client-navigation';
  import { onMount, tick } from 'svelte';
  import packageInfo from '../../../package.json';
  import {
    Calculator,
    DollarSign,
    Search,
    LogOut,
    Plus,
    Menu
  } from 'lucide-svelte';

  let { children } = $props();
  const isRootRoute = $derived(page.url.pathname === '/');

  let paletteOpen = $state(false);
  let paletteQuery = $state('');
  let quickMenuOpen = $state(false);
  let userMenuOpen = $state(false);
  let navOpen = $state(false);
  let showBottomNav = $state(false);
  let isRestoringSession = $state(false);
  let restoredToken = $state<string | null>(null);
  let seededSearchItems = $state<SearchItem[]>([]);
  let seededSearchToken = $state<string | null>(null);
  let paletteInput: HTMLInputElement | null = $state(null);
  const appVersion = `v${packageInfo.version}`;
  const releaseStage = 'Beta';
  const currentYear = new Date().getFullYear();
  const visibleDashboardItem = $derived(
    !$clientSession || !dashboardItem.moduleKey || hasModuleAccess($clientSession, dashboardItem.moduleKey) ? dashboardItem : null
  );
  const visibleWorkingDocumentItems = $derived(
    !$clientSession
      ? workingDocumentItems
      : workingDocumentItems.filter((item) => !item.moduleKey || hasModuleAccess($clientSession, item.moduleKey))
  );
  const visibleMixCalculatorItem = $derived(
    !$clientSession || !mixCalculatorItem.moduleKey || hasModuleAccess($clientSession, mixCalculatorItem.moduleKey)
      ? mixCalculatorItem
      : null
  );
  const visibleReportingItem = $derived(
    !$clientSession || !reportingItem.moduleKey || hasModuleAccess($clientSession, reportingItem.moduleKey)
      ? reportingItem
      : null
  );
  const visibleFooterLinks = $derived([
    ...footerLinks,
    ...(!$clientSession || !hasModuleAccess($clientSession, 'client_access', 'manage')
      ? []
      : [{ href: accessControlItem.href, label: accessControlItem.label, shortLabel: accessControlItem.shortLabel, icon: accessControlItem.icon }])
  ] as FooterLink[]);
  const primaryBottomNavigation = $derived(
    [
      ...(visibleDashboardItem ? [visibleDashboardItem] : []),
      ...(visibleMixCalculatorItem ? [visibleMixCalculatorItem] : []),
      ...visibleWorkingDocumentItems.slice(0, 2)
    ]
  );
  const workingDocumentsActive = $derived(
    visibleWorkingDocumentItems.some((item) => matchesRoute(item.href, page.url.pathname))
  );
  const searchItems = $derived([...baseSearchItems, ...seededSearchItems]);

  function openPalette(query = '') {
    paletteQuery = query;
    paletteOpen = true;
    quickMenuOpen = false;
    userMenuOpen = false;
    navOpen = false;
  }

  function syncViewport() {
    showBottomNav = window.innerWidth <= 1180;

    if (!showBottomNav) {
      navOpen = false;
    }
  }

  async function runSearchItem(item: SearchItem) {
    paletteOpen = false;
    paletteQuery = '';
    await goto(item.href);
  }

  async function openSettings() {
    quickMenuOpen = false;
    userMenuOpen = false;
    navOpen = false;
    await goto('/settings');
  }

  const filteredSearchItems = $derived(
    searchItems.filter((item) => {
      const haystack = `${item.label} ${item.description} ${item.keywords}`.toLowerCase();
      return haystack.includes(paletteQuery.trim().toLowerCase());
    })
  );

  $effect(() => {
    page.url.pathname;
    quickMenuOpen = false;
    userMenuOpen = false;
    paletteOpen = false;
    paletteQuery = '';
    navOpen = false;
  });

  $effect(() => {
    if (paletteOpen) {
      tick().then(() => paletteInput?.focus());
    }
  });

  $effect(() => {
    const hydrated = $sessionHydrated;
    const token = $clientSession?.token ?? null;

    if (!hydrated) {
      return;
    }

    if (!token) {
      isRestoringSession = false;
      restoredToken = null;
      return;
    }

    if (restoredToken === token) {
      return;
    }

    restoredToken = token;
    isRestoringSession = true;

    // Internal Hunter Stock Feeds users are refreshed against /api/access/me;
    // legacy client-portal users keep using /api/auth/client/session.
    const refresh = $clientSession?.role === 'internal' ? api.internalSession() : api.clientSession();

    refresh
      .then((session) => {
        // /api/access/me does not re-issue a token; preserve the existing one.
        const nextToken = session.token ?? token;
        restoredToken = nextToken;
        clientSession.set({ ...session, token: nextToken });
        return invalidateAll();
      })
      .catch(() => {
        restoredToken = null;
        clientSession.clear();
      })
      .finally(() => {
        isRestoringSession = false;
      });
  });

  // Search palette items are seeded lazily — three list endpoints worth of
  // data only when the user actually opens the palette, not on every login or
  // navigation. Subsequent opens hit the api.ts cache.
  $effect(() => {
    const hydrated = $sessionHydrated;
    const session = $clientSession;
    const token = session?.token ?? null;
    const shouldSeed = paletteOpen;

    if (!hydrated || !session || !token) {
      seededSearchItems = [];
      seededSearchToken = null;
      return;
    }

    if (!shouldSeed || seededSearchToken === token) {
      return;
    }

    seededSearchToken = token;

    Promise.all([
      hasModuleAccess(session, 'products') ? api.products() : Promise.resolve([]),
      hasModuleAccess(session, 'mix_master') ? api.mixes() : Promise.resolve([]),
      featureFlags.mixCalculatorSessionHistory && hasModuleAccess(session, 'mix_calculator')
        ? api.mixCalculatorSessions()
        : Promise.resolve([])
    ])
      .then(([products, mixes, sessions]) => {
        if (seededSearchToken !== token) {
          return;
        }

        seededSearchItems = [
          ...products.map((product) => ({
            href: '/products',
            label: product.name,
            description: `Product · ${product.client_name} · ${product.mix_name}`,
            keywords: `product ${product.name} ${product.client_name} ${product.mix_name} ${product.unit_of_measure}`
          })),
          ...mixes.map((mix) => ({
            href: `/mixes/${mix.id}`,
            label: mix.name,
            description: `Mix · ${mix.client_name} · ${mix.total_mix_kg}kg`,
            keywords: `mix ${mix.name} ${mix.client_name} ${mix.notes ?? ''} ${mix.ingredients.map((ingredient) => ingredient.raw_material_name).join(' ')}`
          })),
          ...sessions.map((savedSession) => ({
            href: `/mix-calculator/${savedSession.id}`,
            label: `${savedSession.session_number} · ${savedSession.product_name}`,
            description: `Mix Session · ${savedSession.prepared_by_name} · ${savedSession.mix_date}`,
            keywords: `mix calculator session ${savedSession.session_number} ${savedSession.product_name} ${savedSession.mix_name} ${savedSession.client_name} ${savedSession.prepared_by_name} ${savedSession.notes ?? ''}`
          }))
        ];
      })
      .catch(() => {
        if (seededSearchToken === token) {
          seededSearchItems = [];
        }
      });
  });

  $effect(() => {
    if ($sessionHydrated && !$clientSession && !isRootRoute) {
      goto('/', { replaceState: true });
    }
  });

  onMount(() => {
    syncViewport();

    const handleKeydown = (event: KeyboardEvent) => {
      const target = event.target as HTMLElement | null;
      const isTypingField =
        target instanceof HTMLInputElement ||
        target instanceof HTMLTextAreaElement ||
        target instanceof HTMLSelectElement ||
        target?.isContentEditable;

      if ((event.key === 'k' && (event.metaKey || event.ctrlKey)) || (!isTypingField && event.key === '/')) {
        event.preventDefault();
        openPalette();
      }

      if (event.key === 'Escape') {
        paletteOpen = false;
        quickMenuOpen = false;
        userMenuOpen = false;
        navOpen = false;
      }
    };

    window.addEventListener('keydown', handleKeydown);
    window.addEventListener('resize', syncViewport);

    return () => {
      window.removeEventListener('keydown', handleKeydown);
      window.removeEventListener('resize', syncViewport);
    };
  });

  const userInitials = $derived(
    ($clientSession?.name ?? '')
      .split(' ')
      .slice(0, 2)
      .map((w: string) => w[0])
      .join('')
      .toUpperCase() || '?'
  );
</script>

<svelte:head>
  <title>{pageTitle(page.url.pathname)} | Hunter Premium Produce</title>
</svelte:head>

{#if !$clientSession}
  <div class="signed-out-shell">
    {#if isRootRoute}
      {@render children()}
    {:else}
      <section class="locked-card loading-card signed-out-card">
        <p class="workspace-label">Checking Session</p>
        <h2>Returning to the client login screen.</h2>
        <p>Only authenticated client users can open workspace routes directly.</p>
      </section>
    {/if}
  </div>
{:else}
<div class="app-shell">
  {#if showBottomNav && navOpen}
    <button aria-label="Close navigation" class="nav-backdrop" type="button" onclick={() => (navOpen = false)}></button>
  {/if}

  {#if !showBottomNav}
    <ClientPrimaryRail
      currentPath={page.url.pathname}
      primaryItems={[
        ...(visibleDashboardItem ? [visibleDashboardItem] : []),
        ...(visibleMixCalculatorItem ? [visibleMixCalculatorItem] : []),
        ...(visibleReportingItem ? [visibleReportingItem] : [])
      ]}
      workingDocumentItems={visibleWorkingDocumentItems}
      footerItems={visibleFooterLinks}
      {appVersion}
      {releaseStage}
      {currentYear}
      onOpenSettings={openSettings}
      onSignOut={() => clientSession.clear()}
    />
  {/if}

  <div class:bottom-nav-layout={showBottomNav} class="main-shell">
    <ClientTopbar
      breadcrumbs={clientBreadcrumbs(page.url.pathname)}
      title={pageTitle(page.url.pathname)}
      sessionHydrated={$sessionHydrated}
      session={$clientSession}
      {userInitials}
      {userMenuOpen}
      onOpenPalette={() => openPalette()}
      onToggleUserMenu={() => {
        userMenuOpen = !userMenuOpen;
        quickMenuOpen = false;
      }}
      onOpenSettings={openSettings}
      onSignOut={() => clientSession.clear()}
    />

    <main class="content">
      {#if !isRootRoute && isRestoringSession}
        <section class="locked-card loading-card">
          <p class="workspace-label">Checking Session</p>
          <h2>Restoring your client workspace.</h2>
          <p>Refreshing the current page with the saved browser session before deciding whether sign-in is required.</p>
        </section>
      {:else}
        {@render children()}
      {/if}
    </main>
  </div>

  <div class="quick-fab-wrap">
    {#if quickMenuOpen}
      <div class="menu-panel quick-fab-panel">
        <a href="/mixes">Open mix costing</a>
        <a href="/mixes/new">Create mix worksheet</a>
        <a href={featureFlags.mixCalculatorSessionHistory ? '/mix-calculator' : '/mix-calculator/new'}>Open mix calculator</a>
        <a href="/mix-calculator/new">Create mix session</a>
        <a href="/products">Review delivered pricing</a>
        <button type="button" onclick={() => openPalette('')}>Search the workspace</button>
      </div>
    {/if}

    <button
      aria-expanded={quickMenuOpen}
      aria-label="Open quick access menu"
      class="quick-fab"
      type="button"
      onclick={() => {
        quickMenuOpen = !quickMenuOpen;
        userMenuOpen = false;
      }}
    >
      <span class={`quick-fab-plus ${quickMenuOpen ? 'open' : ''}`}></span>
      <span>Quick Access</span>
    </button>
  </div>
</div>

{#if showBottomNav}
  <nav class="bottom-nav" aria-label="Tablet navigation">
    {#each primaryBottomNavigation as item}
      {@const Icon = item.icon}
      <a class:active={matchesRoute(item.href, page.url.pathname)} href={item.href}>
        <span class="bottom-nav-icon"><Icon size={18} strokeWidth={1.85} /></span>
        <span>{item.label}</span>
      </a>
    {/each}

    <button aria-expanded={navOpen} class:active={navOpen} type="button" onclick={() => (navOpen = !navOpen)}>
      <span class="bottom-nav-icon"><Menu size={18} strokeWidth={1.85} /></span>
      <span>More</span>
    </button>
  </nav>

  {#if navOpen}
    <section
      aria-label="Tablet navigation drawer"
      class="bottom-drawer"
      role="dialog"
      aria-modal="true"
      onclick={(event) => event.stopPropagation()}
    >
      <div class="drawer-handle"></div>

      <div class="drawer-header">
        <div>
          <p class="workspace-label">Workspace Drawer</p>
          <strong>Hunter Premium Produce</strong>
        </div>
        <button aria-label="Close drawer" class="nav-toggle" type="button" onclick={() => (navOpen = false)}>
          <span></span>
        </button>
      </div>

      <WorkspaceSearchTrigger
        className="drawer-search"
        placeholder="Search the workspace..."
        onClick={() => openPalette()}
      />

      <div class="drawer-grid">
        <nav class="drawer-section" aria-label="All workspace pages">
          {#if visibleDashboardItem}
            {@const Icon = visibleDashboardItem.icon}
            <a class:active={matchesRoute(visibleDashboardItem.href, page.url.pathname)} href={visibleDashboardItem.href} onclick={() => (navOpen = false)}>
              <span class="nav-icon"><Icon size={18} strokeWidth={1.75} /></span>
              <span>{visibleDashboardItem.label}</span>
            </a>
          {/if}

          {#if visibleMixCalculatorItem}
            {@const Icon = visibleMixCalculatorItem.icon}
            <a class:active={matchesRoute(visibleMixCalculatorItem.href, page.url.pathname)} href={visibleMixCalculatorItem.href} onclick={() => (navOpen = false)}>
              <span class="nav-icon"><Icon size={18} strokeWidth={1.75} /></span>
              <span>{visibleMixCalculatorItem.label}</span>
            </a>
          {/if}

          {#if visibleReportingItem}
            {@const Icon = visibleReportingItem.icon}
            <a class:active={matchesRoute(visibleReportingItem.href, page.url.pathname)} href={visibleReportingItem.href} onclick={() => (navOpen = false)}>
              <span class="nav-icon"><Icon size={18} strokeWidth={1.75} /></span>
              <span>{visibleReportingItem.label}</span>
            </a>
          {/if}

          {#if visibleWorkingDocumentItems.length}
            <div class="drawer-sublist" id="drawer-working-documents-nav">
              {#each visibleWorkingDocumentItems as item}
                {@const Icon = item.icon}
                <a class:active={matchesRoute(item.href, page.url.pathname)} href={item.href} onclick={() => (navOpen = false)}>
                  <span class="nav-icon"><Icon size={18} strokeWidth={1.75} /></span>
                  <span>{item.label}</span>
                </a>
              {/each}
            </div>
          {/if}
        </nav>

        <div class="drawer-section drawer-actions">
          <a href="/mixes/new" onclick={() => (navOpen = false)}>
            <span class="nav-icon"><Plus size={18} strokeWidth={1.75} /></span>
            <span>Create mix worksheet</span>
          </a>
          <a href="/mix-calculator/new" onclick={() => (navOpen = false)}>
            <span class="nav-icon"><Calculator size={18} strokeWidth={1.75} /></span>
            <span>Create mix session</span>
          </a>
          <button type="button" onclick={openSettings}>
            <span class="nav-icon"><Settings size={18} strokeWidth={1.75} /></span>
            <span>Change settings</span>
          </button>
          <a href="/products" onclick={() => (navOpen = false)}>
            <span class="nav-icon"><DollarSign size={18} strokeWidth={1.75} /></span>
            <span>Review delivered pricing</span>
          </a>
          <button type="button" onclick={() => openPalette('')}>
            <span class="nav-icon"><Search size={18} strokeWidth={1.75} /></span>
            <span>Search the workspace</span>
          </button>
          {#if $clientSession}
            <button type="button" onclick={() => clientSession.clear()}>
              <span class="nav-icon"><LogOut size={18} strokeWidth={1.75} /></span>
              <span>Sign out</span>
            </button>
          {/if}
        </div>
      </div>

      <div class="drawer-footer">
        {#each visibleFooterLinks as item}
          <a href={item.href} onclick={() => (navOpen = false)}>
            <span>{item.label}</span>
            <small>{item.shortLabel}</small>
          </a>
        {/each}
      </div>
    </section>
  {/if}
{/if}

{/if}

{#if $clientSession && paletteOpen}
  <div class="palette-overlay" role="presentation" onclick={() => (paletteOpen = false)}>
    <div
      class="palette"
      role="dialog"
      aria-modal="true"
      aria-label="Workspace search"
      tabindex="-1"
      onclick={(event) => event.stopPropagation()}
      onkeydown={(event) => {
        if (event.key === 'Escape') {
          paletteOpen = false;
        }
      }}
    >
      <div class="palette-input-row">
        <span class="search-icon"></span>
        <input bind:this={paletteInput} bind:value={paletteQuery} placeholder="Search products, mixes, sessions, and pages..." />
        <kbd>Esc</kbd>
      </div>

      <div class="palette-results">
        {#if filteredSearchItems.length}
          {#each filteredSearchItems as item}
            <button class="palette-item" type="button" onclick={() => runSearchItem(item)}>
              <div>
                <strong>{item.label}</strong>
                <span>{item.description}</span>
              </div>
              <small>{item.href}</small>
            </button>
          {/each}
        {:else}
          <div class="palette-empty">
            <strong>No results</strong>
            <span>Try searching for mixes, products, scenarios, or pricing.</span>
          </div>
        {/if}
      </div>
    </div>
  </div>
{/if}

<style>
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

  :global(:root) {
    /* ── Brand ──────────────────────────────────────────────── */
    --color-brand:       #15803d;
    --color-brand-tint:  #f0fdf4;

    /* ── Surfaces ───────────────────────────────────────────── */
    --color-bg-app:      #f6f8fa;
    --color-bg-surface:  #ffffff;

    /* ── Borders ────────────────────────────────────────────── */
    --color-border:      #e1e4e8;
    --color-divider:     #eaecef;

    /* ── Text ───────────────────────────────────────────────── */
    --color-text-primary:   #24292f;
    --color-text-secondary: #57606a;
    --color-text-muted:     #8b949e;

    /* ── Semantic ───────────────────────────────────────────── */
    --color-success: #1a7f37;
    --color-warning: #bf8700;
    --color-error:   #cf222e;
    --color-info:    #0969da;

    /* ── Legacy aliases (keep old token names working) ───────── */
    --bg:          var(--color-bg-app);
    --panel:       var(--color-bg-surface);
    --panel-soft:  var(--color-bg-app);
    --line:        var(--color-border);
    --line-strong: var(--color-border);
    --text:        var(--color-text-primary);
    --muted:       var(--color-text-muted);
    --green:       var(--color-brand);
    --green-deep:  #1a1f1c;
    --green-soft:  var(--color-brand-tint);
    --blue-soft:   #e8f4ff;
    --shadow:      none; /* flat design — use borders, not shadows */
  }

  :global(html, body) {
    margin: 0;
    min-height: 100%;
    background: var(--color-bg-app);
    color: var(--color-text-primary);
    font-family: Inter, "Segoe UI", sans-serif;
    font-size: 14px;
  }

  :global(*) {
    box-sizing: border-box;
  }

  :global(h1, h2, h3, h4, h5, h6) {
    font-family: Inter, "Segoe UI", sans-serif;
    letter-spacing: -0.03em;
  }

  :global(button),
  :global(input),
  :global(select),
  :global(textarea) {
    font: inherit;
  }

  :global(a) {
    color: inherit;
    text-decoration: none;
  }

  .app-shell {
    display: grid;
    grid-template-columns: 252px minmax(0, 1fr);
    min-height: 100vh;
  }

  .signed-out-shell {
    min-height: 100vh;
    padding: 1.5rem;
  }

  .signed-out-card {
    margin: 0 auto;
  }

  .nav-backdrop {
    display: none;
  }

  .sidebar {
    display: flex;
    flex-direction: column;
    gap: 0.4rem;
    padding: 1.1rem 0.85rem 0.85rem;
    background: var(--panel);
    border-right: 1px solid var(--line);
    position: sticky;
    top: 0;
    height: 100vh;
    overflow-y: auto;
    scrollbar-width: thin;
  }

  .nav-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    color: #6d7d74;
    background: transparent;
    border-radius: 0.55rem;
    width: 1.6rem;
    height: 1.6rem;
    font-size: 0.68rem;
    font-weight: 700;
    letter-spacing: 0.04em;
    transition: color 140ms ease, background-color 140ms ease;
  }

  .nav-icon-mask {
    display: inline-block;
    width: 60%;
    height: 60%;
    background-color: currentColor;
    -webkit-mask: var(--nav-icon-url) center / contain no-repeat;
    mask: var(--nav-icon-url) center / contain no-repeat;
  }

  .nav-toggle,
  .action-button,
  .menu-panel button {
    border: 1px solid var(--line);
    background: var(--panel);
    cursor: pointer;
  }

  .nav-toggle {
    width: 2.05rem;
    height: 2.05rem;
    border-radius: 0.68rem;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: var(--muted);
  }

  .nav-toggle span,
  .search-icon,
  .chevron {
    position: relative;
    display: inline-block;
  }

  .nav-toggle span,
  .nav-toggle span::before,
  .nav-toggle span::after {
    width: 0.88rem;
    height: 2px;
    background: currentColor;
    border-radius: 999px;
    content: '';
  }

  .nav-toggle span::before,
  .nav-toggle span::after {
    position: absolute;
    left: 0;
  }

  .nav-toggle span::before {
    top: -0.28rem;
  }

  .nav-toggle span::after {
    top: 0.28rem;
  }

  .search-box {
    display: grid;
    grid-template-columns: auto 1fr auto;
    align-items: center;
    gap: 0.64rem;
    width: 100%;
    padding: 0.72rem 0.82rem;
    border: 1px solid var(--line);
    border-radius: 0.82rem;
    background: var(--panel-soft);
    text-align: left;
    cursor: pointer;
  }

  .search-placeholder {
    color: #93a098;
  }

  .search-icon {
    width: 0.82rem;
    height: 0.82rem;
    border: 2px solid #98a59d;
    border-radius: 999px;
  }

  .search-icon::after {
    content: '';
    position: absolute;
    right: -0.28rem;
    bottom: -0.18rem;
    width: 0.42rem;
    height: 2px;
    border-radius: 999px;
    background: #98a59d;
    transform: rotate(45deg);
  }

  kbd {
    padding: 0.1rem 0.42rem;
    border: 1px solid var(--line-strong);
    border-radius: 0.42rem;
    color: var(--muted);
    background: #fff;
    font-size: 0.76rem;
  }

  .nav-group {
    display: grid;
    gap: 0.55rem;
    padding-top: 0.15rem;
  }

  .nav-group-toggle {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
    width: 100%;
    padding: 0.72rem 0.68rem;
    border: none;
    border-radius: 0.82rem;
    background: transparent;
    color: #304038;
    cursor: pointer;
    transition: background-color 160ms ease;
  }

  .nav-group-toggle:hover,
  .nav-group-toggle.active {
    background: var(--color-brand-tint);
  }

  .nav-group-toggle.active {
    color: var(--color-brand);
    font-weight: 600;
  }

  .nav-group-toggle-copy {
    display: inline-flex;
    align-items: center;
    gap: 0.68rem;
    min-width: 0;
    white-space: nowrap;
  }

  .nav-sublist {
    position: relative;
    padding-left: 1rem;
  }

  .nav-sublist::before {
    content: '';
    position: absolute;
    top: 0.4rem;
    bottom: 0.4rem;
    left: 0.7rem;
    width: 1px;
    background: var(--line);
  }

  .nav-sublist a {
    position: relative;
  }

  .bottom-nav-icon svg {
    width: 0.9rem;
    height: 0.9rem;
  }

  /* `.nav-icon.muted` is kept for the bottom-nav (still uses letter labels). */
  .nav-icon.muted {
    color: #fff;
    background: linear-gradient(135deg, #95a39b 0%, #6e7c73 100%);
  }

  .main-shell {
    min-width: 0;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    height: 100vh;
    overflow: hidden;
  }

  .workspace-label {
    color: var(--muted);
    font-size: 0.76rem;
    font-weight: 600;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }

  .menu-panel {
    position: absolute;
    top: calc(100% + 0.45rem);
    right: 0;
    z-index: 20;
    min-width: 13rem;
    display: grid;
    gap: 0.18rem;
    padding: 0.4rem;
    border: 1px solid var(--color-border);
    border-radius: 0.96rem;
    background: rgba(255, 255, 255, 0.98);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    backdrop-filter: blur(10px);
  }

  .quick-fab-wrap {
    position: fixed;
    right: max(1rem, env(safe-area-inset-right));
    bottom: max(1rem, env(safe-area-inset-bottom));
    z-index: 46;
    display: grid;
    justify-items: end;
    gap: 0.6rem;
  }

  .quick-fab {
    display: inline-flex;
    align-items: center;
    gap: 0.72rem;
    padding: 0.88rem 1.05rem;
    border: none;
    border-radius: 999px;
    background: var(--color-brand);
    color: #fff;
    box-shadow: none;
    font-weight: 700;
    letter-spacing: 0.01em;
    cursor: pointer;
  }

  .quick-fab-panel {
    position: static;
    min-width: 15rem;
    padding: 0.45rem;
    border-radius: 1rem;
  }

  .quick-fab-plus {
    position: relative;
    width: 0.92rem;
    height: 0.92rem;
    flex-shrink: 0;
  }

  .quick-fab-plus::before,
  .quick-fab-plus::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0.92rem;
    height: 2px;
    border-radius: 999px;
    background: currentColor;
    transform: translate(-50%, -50%);
    transition: transform 140ms ease;
  }

  .quick-fab-plus::after {
    transform: translate(-50%, -50%) rotate(90deg);
  }

  .quick-fab-plus.open::before {
    transform: translate(-50%, -50%) rotate(45deg);
  }

  .quick-fab-plus.open::after {
    transform: translate(-50%, -50%) rotate(-45deg);
  }

  .menu-panel a,
  .menu-panel button {
    padding: 0.72rem 0.78rem;
    border-radius: 0.78rem;
    color: #304038;
    text-align: left;
    background: transparent;
    border: none;
  }

  .menu-panel a:hover,
  .menu-panel button:hover {
    background: var(--panel-soft);
  }

  .content {
    --content-padding: 1.34rem;
    display: flex;
    flex-direction: column;
    flex: 1;
    min-height: 0;
    min-width: 0;
    padding: var(--content-padding);
    overflow: auto;
  }

  .locked-card {
    max-width: 42rem;
    padding: 1.25rem;
    border: 1px solid var(--line);
    border-radius: 1.25rem;
    background: var(--panel);
    box-shadow: var(--shadow);
  }

  .loading-card {
    min-height: 10rem;
  }

  .locked-card h2,
  .locked-card p {
    margin: 0;
  }

  .locked-card h2 {
    margin-top: 0.35rem;
    font-size: clamp(1.7rem, 3vw, 2.2rem);
  }

  .locked-card p:last-of-type {
    margin-top: 0.45rem;
    color: var(--muted);
  }

  .locked-card a {
    display: inline-flex;
    margin-top: 1rem;
    padding: 0.78rem 0.92rem;
    border-radius: 0.88rem;
    background: var(--color-brand);
    color: #fff;
    font-weight: 600;
  }

  .palette-overlay {
    position: fixed;
    inset: 0;
    z-index: 40;
    display: grid;
    place-items: start center;
    padding: 8vh 1rem 1rem;
    background: rgba(11, 18, 14, 0.3);
    backdrop-filter: blur(10px);
  }

  .palette {
    width: min(44rem, 100%);
    border: 1px solid var(--color-border);
    border-radius: 1.2rem;
    background: var(--color-bg-surface);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
    overflow: hidden;
  }

  .palette-input-row {
    display: grid;
    grid-template-columns: auto 1fr auto;
    align-items: center;
    gap: 0.8rem;
    padding: 0.95rem 1rem;
    border-bottom: 1px solid var(--line);
  }

  .palette-input-row input {
    border: none;
    outline: none;
    background: transparent;
    color: var(--text);
    font-size: 0.98rem;
  }

  .palette-results {
    max-height: 26rem;
    overflow: auto;
    padding: 0.5rem;
  }

  .palette-item,
  .palette-empty {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    padding: 0.88rem 0.92rem;
    border: none;
    border-radius: 0.92rem;
    text-align: left;
    background: transparent;
  }

  .palette-item {
    cursor: pointer;
  }

  .palette-item:hover {
    background: var(--panel-soft);
  }

  .palette-item strong,
  .palette-empty strong {
    display: block;
    font-size: 0.96rem;
  }

  .palette-item span,
  .palette-empty span,
  .palette-item small {
    color: var(--muted);
  }

  .palette-item span {
    display: block;
    margin-top: 0.18rem;
    font-size: 0.84rem;
  }

  .palette-item small {
    flex-shrink: 0;
    font-size: 0.76rem;
  }

  .palette-empty {
    justify-content: flex-start;
  }

  .bottom-nav,
  .bottom-drawer {
    display: none;
  }

  .main-shell.bottom-nav-layout .content {
    padding-bottom: 7.25rem;
  }

  @media (max-width: 1180px) {
    .app-shell {
      grid-template-columns: 1fr;
    }

    .nav-backdrop {
      position: fixed;
      inset: 0;
      z-index: 48;
      display: block;
      border: none;
      background: rgba(11, 18, 14, 0.28);
      backdrop-filter: blur(4px);
    }

    .bottom-nav {
      position: fixed;
      left: max(0.8rem, env(safe-area-inset-left));
      right: max(0.8rem, env(safe-area-inset-right));
      bottom: max(0.8rem, env(safe-area-inset-bottom));
      z-index: 45;
      display: grid;
      grid-template-columns: repeat(5, minmax(0, 1fr));
      gap: 0.5rem;
      padding: 0.6rem;
      border: 1px solid rgba(217, 228, 221, 0.92);
      border-radius: 1.35rem;
      background: rgba(255, 255, 255, 0.96);
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      backdrop-filter: blur(16px);
    }

    .quick-fab-wrap {
      bottom: calc(max(0.8rem, env(safe-area-inset-bottom)) + 5.9rem);
    }

    .bottom-nav a,
    .bottom-nav button {
      min-width: 0;
      display: grid;
      justify-items: center;
      gap: 0.34rem;
      padding: 0.62rem 0.38rem;
      border: none;
      border-radius: 1rem;
      background: transparent;
      color: #51635a;
      text-align: center;
      font-size: 0.74rem;
      font-weight: 700;
      cursor: pointer;
    }

    .bottom-nav a.active,
    .bottom-nav button.active {
      color: var(--color-brand);
      background: var(--color-brand-tint);
    }

    .bottom-nav-icon {
      width: 2.1rem;
      height: 2.1rem;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border-radius: 0.78rem;
      color: #fff;
      background: var(--green-deep);
      font-size: 0.66rem;
      letter-spacing: 0.04em;
    }

    .bottom-nav-icon.muted {
      background: #8b949e;
    }

    .bottom-drawer {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 50;
      display: grid;
      gap: 1rem;
      padding: 0.85rem 1rem calc(6.6rem + env(safe-area-inset-bottom));
      border-top: 1px solid var(--line);
      border-radius: 1.6rem 1.6rem 0 0;
      background:
        linear-gradient(180deg, rgba(248, 251, 249, 0.98) 0%, rgba(255, 255, 255, 0.98) 100%);
      box-shadow: 0 -2px 8px rgba(0,0,0,0.06);
      backdrop-filter: blur(16px);
    }

    .drawer-handle {
      width: 3.5rem;
      height: 0.34rem;
      margin: 0 auto;
      border-radius: 999px;
      background: #c8d4ce;
    }

    .drawer-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 0.8rem;
    }

    .drawer-header strong {
      font-size: 1rem;
    }

    :global(.drawer-search) {
      background: #fff;
    }

    .drawer-grid {
      display: grid;
      gap: 0.9rem;
      grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr);
    }

    .drawer-section {
      display: grid;
      gap: 0.4rem;
    }

    .drawer-section a,
    .drawer-section button {
      display: flex;
      align-items: center;
      gap: 0.72rem;
      padding: 0.82rem 0.86rem;
      border: 1px solid var(--line);
      border-radius: 0.96rem;
      background: rgba(255, 255, 255, 0.88);
      color: #304038;
      text-align: left;
      cursor: pointer;
    }

    .drawer-section a.active {
      color: var(--green-deep);
      background: var(--green-soft);
    }

    .drawer-group {
      display: grid;
      gap: 0.4rem;
      padding-top: 0.35rem;
    }

    .drawer-group-toggle {
      padding-inline: 0.2rem;
    }

    .drawer-sublist {
      display: grid;
      gap: 0.4rem;
    }

    .drawer-footer {
      display: grid;
      gap: 0.5rem;
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .drawer-footer a {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 0.75rem;
      padding: 0.82rem 0.9rem;
      border: 1px solid var(--line);
      border-radius: 0.96rem;
      background: rgba(255, 255, 255, 0.88);
      color: #304038;
      font-weight: 600;
    }

    .drawer-footer small {
      color: var(--muted);
      font-size: 0.72rem;
      letter-spacing: 0.05em;
      text-transform: uppercase;
    }

    .content {
      --content-padding: 1rem;
      padding: 1rem;
    }
  }

  @media (min-width: 1181px) {
    .bottom-nav-layout .content {
      padding-bottom: 1.34rem;
    }
  }

  @media (min-width: 1181px) {
    .nav-toggle {
      display: none;
    }
  }

  @media (max-width: 900px) {
    .drawer-grid {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 720px) {
    .bottom-nav {
      left: max(0.55rem, env(safe-area-inset-left));
      right: max(0.55rem, env(safe-area-inset-right));
      bottom: max(0.55rem, env(safe-area-inset-bottom));
      gap: 0.32rem;
      padding: 0.45rem;
    }

    .bottom-nav a,
    .bottom-nav button {
      padding: 0.55rem 0.2rem;
      font-size: 0.68rem;
    }

    .bottom-nav-icon {
      width: 1.9rem;
      height: 1.9rem;
      font-size: 0.6rem;
    }

    .bottom-drawer {
      padding: 0.75rem 0.8rem calc(6.3rem + env(safe-area-inset-bottom));
    }

    .action-button {
      justify-content: space-between;
    }

    .menu-panel {
      left: 0;
      right: 0;
      min-width: 0;
    }

    .drawer-footer {
      grid-template-columns: 1fr;
    }

    .content {
      --content-padding: 0.92rem;
      padding: 0.92rem;
    }
  }
</style>
