<script lang="ts">
    import {push} from 'svelte-spa-router'
    import {auth, clearTokens} from '../stores/auth.svelte'
    import {apiLogout} from '../api/index'
    import {APP_NAME} from '../config'

    let { title = APP_NAME }: { title?: string } = $props()

  async function handleLogout() {
    try {
      if (auth.refreshToken) await apiLogout(auth.refreshToken)
    } finally {
      clearTokens()
      push('/login')
    }
  }
</script>

<nav class="navbar bg-primary text-primary-content shadow-sm sticky top-0 z-30">
  <div class="navbar-start">
    <span class="text-lg font-bold tracking-tight">{title}</span>
  </div>
  <div class="navbar-end">
    {#if auth.isLoggedIn}
      <div class="dropdown dropdown-end">
        <button tabindex="0" class="btn btn-ghost btn-circle" aria-label="Account menu">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
          </svg>
        </button>
        <ul class="dropdown-content menu p-2 shadow bg-base-100 text-base-content rounded-box w-48 mt-2">
          {#if auth.name}
            <li class="menu-title px-3 py-1 text-xs font-semibold text-base-content/50 truncate">{auth.name}</li>
          {/if}
          {#if auth.isAdmin}
            <li><button onclick={() => push('/admin')}>Admin Dashboard</button></li>
          {/if}
          <li><button onclick={handleLogout}>Log out</button></li>
        </ul>
      </div>
    {/if}
  </div>
</nav>
