<script setup lang="ts">
// Avatar dropdown in the topbar. Click the avatar → menu with identity card,
// quick theme toggle, profile/devices/security/help links, and Sign out.
//
// During the prototype OIDC is bypassed (`definePageMeta({ oidcAuth: { enabled: false } })`),
// so `useOidcAuth().user` is empty — we fall back to a fixture identity. Once
// auth is wired, the real session populates name + email automatically.

const { state: tweaks, setTheme } = usePortalTweaks()
const toast = useToast()
const route = useRoute()
const router = useRouter()

// Try the real session first; fall back to fixture for prototype review.
let oidc: ReturnType<typeof useOidcAuth> | null = null
try { oidc = useOidcAuth() } catch { oidc = null }

const open = ref(false)
const rootRef = ref<HTMLElement | null>(null)

const displayName = computed<string>(() => {
  const u = oidc?.user?.value
  const name = (u?.userInfo as { name?: string } | undefined)?.name
  return name || (u?.userName as string | undefined) || 'Anne Hansen'
})
const email = computed(() => {
  const u = oidc?.user?.value
  return (u?.userInfo as { email?: string } | undefined)?.email || 'anne@baslund.dk'
})

function toggle() {
  open.value = !open.value
}
function close() {
  open.value = false
}

function flipTheme() {
  const next = tweaks.value.theme === 'dark' ? 'light' : 'dark'
  setTheme(next)
}
function pickTheme(v: 'light' | 'dark') {
  setTheme(v)
}

async function signOut() {
  close()
  // Use our custom /api/auth/sign-out (see server/api/auth/sign-out.get.ts).
  // It clears the local session and bounces to /signed-out which fires
  // Authentik's end-session in a hidden iframe. Cleaner than nuxt-oidc-auth's
  // RP-initiated chain because Authentik 2025 doesn't honor
  // post_logout_redirect_uri reliably.
  await navigateTo('/api/auth/sign-out', { external: true })
}

function go(path: string) {
  close()
  router.push(path)
}

function onDocClick(e: MouseEvent) {
  if (!rootRef.value || !open.value) return
  if (!rootRef.value.contains(e.target as Node)) close()
}

// Auto-close on route change so the menu doesn't linger after navigation.
watch(() => route.path, close)

onMounted(() => {
  const onKey = (e: KeyboardEvent) => {
    if (e.key === 'Escape' && open.value) close()
  }
  document.addEventListener('keydown', onKey)
  document.addEventListener('mousedown', onDocClick)
  onBeforeUnmount(() => {
    document.removeEventListener('keydown', onKey)
    document.removeEventListener('mousedown', onDocClick)
  })
})
</script>

<template>
  <div ref="rootRef" class="usermenu">
    <button class="trigger" :class="{ on: open }" type="button" :title="displayName" @click="toggle">
      <Avatar :name="displayName" :size="28" />
    </button>

    <Transition name="menu">
      <div v-if="open" class="menu" role="menu" aria-label="User menu">
        <div class="ident">
          <Avatar :name="displayName" :size="36" />
          <div class="ident-meta">
            <div class="ident-name">{{ displayName }}</div>
            <Mono dim>{{ email }}</Mono>
          </div>
        </div>

        <div class="divider" />

        <!-- Theme segmented control -->
        <div class="row-label"><Eyebrow>Theme</Eyebrow></div>
        <div class="seg">
          <button :class="{ on: tweaks.theme === 'light' }" @click="pickTheme('light')">
            <UiIcon name="sun" :size="13" />
            Light
          </button>
          <button :class="{ on: tweaks.theme === 'dark' }" @click="pickTheme('dark')">
            <UiIcon name="moon" :size="13" />
            Dark
          </button>
        </div>

        <div class="divider" />

        <!-- Personal links -->
        <button class="item" role="menuitem" @click="go('/profile')">
          <UiIcon name="users" :size="14" />
          <span class="label">My profile</span>
          <Mono dim>⌘P</Mono>
        </button>
        <button class="item" role="menuitem" @click="go('/devices')">
          <UiIcon name="device" :size="14" />
          <span class="label">Devices &amp; sessions</span>
        </button>
        <button class="item" role="menuitem" @click="go('/security')">
          <UiIcon name="shield" :size="14" />
          <span class="label">Security</span>
        </button>
        <button class="item" role="menuitem" @click="go('/help')">
          <UiIcon name="help" :size="14" />
          <span class="label">Help &amp; support</span>
        </button>

        <div class="divider" />

        <button class="item danger" role="menuitem" @click="signOut">
          <UiIcon name="logout" :size="14" />
          <span class="label">Sign out</span>
        </button>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.usermenu { position: relative; }

.trigger {
  appearance: none;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 999px;
  padding: 0;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.trigger:hover { border-color: var(--border); }
.trigger.on { border-color: var(--border-hi); }

.menu {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  z-index: 100;
  width: 260px;
  background: var(--elevated);
  border: 1px solid var(--border);
  border-radius: 10px;
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.32);
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.ident {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
}
.ident-meta { min-width: 0; flex: 1; }
.ident-name {
  font-size: 13px;
  font-weight: 600;
  font-family: var(--font-display);
  letter-spacing: -0.01em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.divider { height: 1px; background: var(--border); margin: 4px 0; }

.row-label { padding: 8px 10px 4px 10px; }

.seg {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px;
  padding: 3px;
  margin: 0 4px;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: 7px;
}
.seg button {
  appearance: none;
  border: 0;
  background: transparent;
  color: var(--text-dim);
  font-family: inherit;
  font-size: 12px;
  font-weight: 500;
  padding: 6px 8px;
  border-radius: 5px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}
.seg button:hover { color: var(--text); }
.seg button.on { background: var(--text); color: var(--bg); }

.item {
  appearance: none;
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 8px 10px;
  background: transparent;
  border: 0;
  border-radius: 6px;
  color: var(--text);
  font-family: inherit;
  font-size: 13px;
  text-align: left;
  text-decoration: none;
  cursor: pointer;
}
.item:hover { background: var(--surface); }
.item .label { flex: 1; }
.item.danger { color: var(--bad); }
.item.danger:hover { background: rgba(240, 88, 88, 0.08); }

.menu-enter-active, .menu-leave-active { transition: opacity 0.12s, transform 0.12s; }
.menu-enter-from, .menu-leave-to { opacity: 0; transform: translateY(-4px); }
</style>
