<template>
  <header class="topbar">
    <div class="topbar-title">
      <span class="eyebrow">PowerShell Operations Platform</span>
      <h2>{{ activeTitle }}</h2>
    </div>
    <div class="topbar-search">
      <Search :size="17" />
      <span>Search scripts, hosts, runplans</span>
    </div>
    <div class="topbar-actions">
      <button class="ghost-button topbar-action-button" type="button" aria-label="Open help library" @click="$emit('open-help')">
        <CircleHelp :size="17" />Help
      </button>
      <button class="ghost-button topbar-action-button" type="button" aria-label="Refresh current view" @click="$emit('refresh')">
        <RefreshCcw :size="17" />Refresh
      </button>
      <div class="top-profile-menu">
        <button class="profile-trigger topbar-profile-trigger" type="button" aria-label="Open profile menu" @click="profileOpen = !profileOpen">
          <span class="avatar top-avatar">
            <img v-if="user?.avatarUrl" :src="user.avatarUrl" alt="" />
            <template v-else>{{ initials }}</template>
          </span>
        </button>
        <div v-if="profileOpen" class="profile-menu-card glass-panel">
          <div class="profile-menu-head">
            <span class="avatar large">
              <img v-if="user?.avatarUrl" :src="user.avatarUrl" alt="" />
              <template v-else>{{ initials }}</template>
            </span>
            <div>
              <strong>{{ user?.displayName || 'Operator' }}</strong>
              <small>{{ user?.email }}</small>
            </div>
          </div>
          <button class="profile-menu-action" type="button" @click="openProfile">
            <UserCircle :size="16" /> My profile
          </button>
          <button class="profile-menu-action danger" type="button" @click="logout">
            <LogOut :size="16" /> Sign out
          </button>
        </div>
      </div>
    </div>
  </header>
</template>

<script setup>
import { computed, ref } from 'vue';
import { CircleHelp, LogOut, RefreshCcw, Search, UserCircle } from '@lucide/vue';

const props = defineProps({
  activeTitle: { type: String, required: true },
  user: { type: Object, default: null }
});

const emit = defineEmits(['refresh', 'logout', 'open-profile', 'open-help']);
const profileOpen = ref(false);

const initials = computed(() => (props.user?.displayName || 'PS').split(/\s+/).map((part) => part[0]).join('').slice(0, 2).toUpperCase());

function openProfile() {
  profileOpen.value = false;
  emit('open-profile');
}

function logout() {
  profileOpen.value = false;
  emit('logout');
}
</script>
