<script lang="ts">
  import { PanelLeft, Settings, Sparkles } from 'lucide-svelte';

  import ThemeToggle from '$lib/components/ThemeToggle.svelte';
  import WorkspaceSearchField from '$lib/components/navigation/WorkspaceSearchField.svelte';
  import type { SearchItem } from '$lib/navigation/client-navigation';
  import { tooltip } from '$lib/actions/tooltip';
  import type { AppSession } from '$lib/session';

  let {
    sessionHydrated,
    session,
    showSidebarToggle,
    sidebarOpen,
    userInitials,
    userMenuOpen,
    canUseWorkspaceSearch,
    searchQuery = $bindable(''),
    searchOpen = $bindable(false),
    searchFocusRequest,
    filteredSearchItems,
    hiddenResultCount,
    canOpenSettings,
    onRunSearchItem,
    onToggleSidebar,
    onToggleUserMenu,
    onOpenSettings,
    onSignOut,
    onShowWhatsNew
  }: {
    sessionHydrated: boolean;
    session: AppSession | null;
    showSidebarToggle: boolean;
    sidebarOpen: boolean;
    userInitials: string;
    userMenuOpen: boolean;
    canUseWorkspaceSearch: boolean;
    searchQuery?: string;
    searchOpen?: boolean;
    searchFocusRequest: number;
    filteredSearchItems: SearchItem[];
    hiddenResultCount: number;
    canOpenSettings: boolean;
    onRunSearchItem: (item: SearchItem) => void | Promise<void>;
    onToggleSidebar: () => void;
    onToggleUserMenu: () => void;
    onOpenSettings: () => void;
    onSignOut: () => void;
    onShowWhatsNew: () => void;
  } = $props();
</script>

<header class="topbar">
  <div class="topbar-start">
    {#if showSidebarToggle}
      <button
        class="sidebar-toggle"
        type="button"
        aria-label={sidebarOpen ? 'Hide sidebar' : 'Show sidebar'}
        aria-pressed={sidebarOpen}
        onclick={onToggleSidebar}
        use:tooltip={sidebarOpen ? 'Hide menu' : 'Show menu'}
      >
        <PanelLeft size={17} strokeWidth={1.9} />
      </button>
    {/if}

    <a class="topbar-brand" href="/" aria-label="Hunter Premium Produce home">
      <img src="/hunter-logo-sidebar.png" alt="Hunter Premium Produce" />
    </a>
  </div>

  {#if canUseWorkspaceSearch}
    <div class="topbar-middle">
      <WorkspaceSearchField
        bind:query={searchQuery}
        bind:open={searchOpen}
        focusRequest={searchFocusRequest}
        filteredSearchItems={filteredSearchItems}
        {hiddenResultCount}
        className="topbar-search"
        onRunSearchItem={onRunSearchItem}
      />
    </div>
  {:else}
    <div class="topbar-middle"></div>
  {/if}

  <div class="topbar-actions">
    <button
      class="whats-new-toggle"
      type="button"
      onclick={onShowWhatsNew}
      aria-label="What's new"
      use:tooltip={"What's new — latest updates and changes"}
    >
      <Sparkles size={18} strokeWidth={1.75} />
    </button>

    <ThemeToggle />

    <div class="menu-wrap user-menu-wrap">
      <button aria-expanded={userMenuOpen} class="user-trigger" type="button" onclick={onToggleUserMenu}>
        <span class="user-avatar-wrap">
          <span class="user-avatar">{session ? userInitials : '?'}</span>
          <span class={`user-status-dot ${session ? 'live' : 'idle'}`}></span>
        </span>
        <span class="user-trigger-copy">
          <span class="workspace-label">{sessionHydrated ? (session ? 'Signed in' : 'Signed out') : 'Checking session'}</span>
          <strong>{sessionHydrated ? (session ? session.name || 'Client account' : 'Sign in required') : 'Restoring workspace access'}</strong>
        </span>
        <span class:open={userMenuOpen} class="chevron"></span>
      </button>

      {#if userMenuOpen}
        <div class="menu-panel user-menu-panel">
          <div class="user-menu-summary">
            <span class="user-menu-avatar">{session ? userInitials : '?'}</span>
            <div class="user-menu-summary-text">
              <strong>
                {sessionHydrated
                  ? session
                    ? session.name || 'Client account'
                    : 'Client session inactive'
                  : 'Checking saved client session'}
              </strong>
              <span>
                {sessionHydrated
                  ? session
                    ? session.email
                    : 'Return to the dashboard page to sign in.'
                  : 'Waiting for the browser session check to complete.'}
              </span>
            </div>
          </div>
          {#if canOpenSettings}
            <button type="button" class="menu-settings-btn" onclick={onOpenSettings}>
              <Settings size={15} strokeWidth={1.75} />
              Settings
            </button>
          {/if}
          {#if session}
            <button type="button" onclick={onSignOut}>Log out</button>
          {:else if !sessionHydrated}
            <button type="button" disabled>Checking session...</button>
          {:else}
            <a href="/">Go to sign-in</a>
          {/if}
        </div>
      {/if}
    </div>
  </div>
</header>

<style>
  .topbar {
    display: grid;
    grid-template-columns: minmax(0, 1fr) minmax(20rem, 3fr) minmax(0, 1fr);
    align-items: center;
    gap: 0.75rem;
    padding: 0.72rem 1.2rem;
    background: var(--panel);
    border-bottom: 1px solid var(--line);
  }

  .topbar-start {
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 0.9rem;
  }

  .topbar-brand {
    display: inline-flex;
    align-items: center;
    flex-shrink: 0;
    /* Extra right padding gives the scaled-up logo room before the divider. */
    padding-right: 1.6rem;
    border-right: 1px solid var(--color-border);
  }

  .topbar-brand img {
    height: 2rem;
    width: auto;
    display: block;
    /* Zoom the wide logo lockup in so the wordmark is legible, without growing
       the header: transform scales the visual only, leaving the 2rem layout box
       (and therefore the topbar height) untouched. Anchored left so it grows
       rightward from the topbar's left padding edge. */
    transform: scale(1.45);
    transform-origin: left center;
  }

  .sidebar-toggle {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 2.25rem;
    height: 2.25rem;
    flex-shrink: 0;
    border: 1px solid transparent;
    border-radius: 0.7rem;
    background: transparent;
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
  }

  .sidebar-toggle:hover {
    background: var(--panel-soft);
    border-color: var(--color-border);
    color: var(--color-text-primary);
  }

  .topbar-middle {
    min-width: 0;
    display: flex;
    justify-content: center;
    /* Fill the grid track; justify-self:center would collapse this to the
       field's content width and clip the placeholder. */
    justify-self: stretch;
    padding-left: 0.9rem;
  }

  :global(.topbar-search) {
    width: 100%;
    /* ~half the topbar on a large laptop; centered within its track. */
    max-width: 40rem;
  }

  .topbar-actions {
    display: flex;
    align-items: center;
    gap: 0.6rem;
    /* Never let the What's-new / theme toggles wrap above the user button. */
    flex-wrap: nowrap;
    justify-content: flex-end;
    justify-self: end;
  }

  /* Matches the ThemeToggle button so the two sit as a pair. */
  .whats-new-toggle {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 2.6rem;
    height: 2.6rem;
    flex-shrink: 0;
    border: 1px solid var(--color-border);
    border-radius: 0.82rem;
    background: var(--color-bg-surface);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
  }

  .whats-new-toggle:hover {
    background: var(--color-surface-hover);
    color: var(--color-text-primary);
  }

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

  .menu-wrap {
    position: relative;
  }

  .user-trigger {
    min-width: 14rem;
    display: inline-flex;
    align-items: center;
    gap: 0.72rem;
    padding: 0.56rem 0.76rem;
    border: 1px solid var(--color-border);
    border-radius: 0.96rem;
    background: var(--panel-soft);
    color: var(--color-text-primary);
    text-align: left;
    cursor: pointer;
  }

  .user-avatar-wrap {
    position: relative;
    flex-shrink: 0;
  }

  .user-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background: var(--color-brand);
    color: var(--color-on-brand);
    font-size: 0.72rem;
    font-weight: 700;
    letter-spacing: 0.02em;
    user-select: none;
  }

  .user-status-dot {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 0.55rem;
    height: 0.55rem;
    border-radius: 999px;
    border: 1.5px solid var(--color-bg-surface);
    background: var(--color-text-muted);
  }

  .user-status-dot.live {
    background: var(--color-success);
  }

  .user-status-dot.idle {
    background: var(--color-warning);
  }

  .user-menu-avatar {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 50%;
    background: var(--color-brand);
    color: var(--color-on-brand);
    font-size: 0.9rem;
    font-weight: 700;
    letter-spacing: 0.02em;
    user-select: none;
  }

  .user-menu-summary {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.72rem 0.78rem;
    border-radius: 0.82rem;
    background: var(--panel-soft);
  }

  .user-menu-summary-text {
    display: grid;
    gap: 0.2rem;
    min-width: 0;
  }

  .user-menu-summary-text strong {
    font-size: 0.9rem;
    font-weight: 700;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .user-menu-summary-text span {
    color: var(--muted);
    font-size: 0.8rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .user-trigger-copy {
    min-width: 0;
    display: grid;
    flex: 1;
  }

  .user-trigger-copy strong {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 0.95rem;
  }

  .user-menu-wrap {
    min-width: 0;
  }

  .user-menu-panel {
    min-width: 16rem;
  }

  .menu-settings-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .chevron {
    width: 0.54rem;
    height: 0.54rem;
    border-right: 2px solid var(--color-text-muted);
    border-bottom: 2px solid var(--color-text-muted);
    transform: rotate(45deg);
    transition: transform 140ms ease;
  }

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

  .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: var(--color-bg-elevated);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .menu-panel a,
  .menu-panel button {
    padding: 0.72rem 0.78rem;
    border-radius: 0.78rem;
    color: var(--color-text-primary);
    text-align: left;
    background: transparent;
    border: none;
    cursor: pointer;
  }

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

  /* Drop the search to its own row early: with the 252px sidebar present, a
     laptop's content width is already tight well above the sidebar's own
     collapse point, so keep the top row to brand + actions only. */
  @media (max-width: 1180px) {
    .topbar {
      grid-template-columns: minmax(0, 1fr) auto;
      grid-template-areas:
        'start actions'
        'middle middle';
    }

    .topbar-start {
      grid-area: start;
    }

    .topbar-middle {
      grid-area: middle;
      /* Span the full row instead of shrinking to the field's content width. */
      justify-self: stretch;
      padding-left: 0;
    }

    /* On its own row the field gets the whole width, which is too much — keep it
       to ~half, centered, so it reads as a search bar rather than a banner. */
    :global(.topbar-search) {
      width: 55%;
      min-width: 26rem;
      max-width: 40rem;
    }

    .topbar-actions {
      grid-area: actions;
    }
  }

  @media (max-width: 700px) {
    .topbar {
      padding: 0.72rem 1rem;
    }

    .topbar-brand {
      padding-right: 1.1rem;
    }

    .topbar-brand img {
      height: 1.6rem;
    }

    /* On phones let the user button drop onto its own line below the icon
       toggles again (the desktop nowrap rule would otherwise overflow). */
    .topbar-actions {
      flex-wrap: wrap;
    }

    .user-trigger {
      min-width: auto;
      width: 100%;
    }
  }
</style>
