<script setup lang="ts">
// Portal topbar: workspace label, optional org switcher (partner admins), global
// search, app launcher, notifications, profile menu.

import type { PartnerTenantDoc } from '~/types/partner'

const launcher = useAppLauncher()
const drawer = useNotificationDrawer()
const partnerMode = usePartnerMode()
const router = useRouter()
const route = useRoute()
const { partner, isPartnerStaff } = useMe()

// Real customer tenants drive the org switcher. Shared 'partner-tenants' key
// dedupes with the sidebar + customers page; gated to partner-staff so the
// global shell doesn't 403 the partner-scoped endpoint for end-users/admins.
const { data: tenants } = useFetch<PartnerTenantDoc[]>('/api/partner/tenants', {
  key: 'partner-tenants',
  default: () => [],
  immediate: isPartnerStaff.value,
})
const PLAN_LABEL: Record<string, string> = { mvp: 'Starter', pro: 'Business', enterprise: 'Enterprise' }
const partnerLabel = computed(() => partner.value?.name ?? 'Partner')

// Section context is URL-driven (same rule as the sidebar). The org switcher
// only appears in the partner section or when acting-as a customer.
type Section = 'partner' | 'admin' | 'user'
const section = computed<Section>(() => {
  if (partnerMode.isActive.value) return 'admin'
  if (route.path.startsWith('/partner')) return 'partner'
  if (route.path.startsWith('/admin')) return 'admin'
  return 'user'
})
const showOrgSwitcher = computed(() =>
  section.value === 'partner' || partnerMode.isActive.value,
)

const activeCustomer = computed(() =>
  (tenants.value ?? []).find((c) => c._id === partnerMode.activeCustomerId.value) || null,
)

const orgSwitcherOpen = ref(false)
function pickCustomer(id: string) {
  orgSwitcherOpen.value = false
  partnerMode.enter(id)
  router.push('/admin')
}
function leaveCustomerMode() {
  orgSwitcherOpen.value = false
  partnerMode.exit()
  router.push('/partner/customers')
}

// Dummy global search — opens AppLauncher for now until real search is wired.
const searchValue = ref('')
</script>

<template>
  <header>
    <!-- Org switcher · only in the partner section or when acting as a customer -->
    <button
      v-if="showOrgSwitcher"
      class="orgswitch"
      @click="orgSwitcherOpen = !orgSwitcherOpen"
    >
      <span
        class="org-chip"
        :style="{ background: activeCustomer?.brandColor || '#0A0A0A' }"
      >
        {{ (activeCustomer?.name || 'NordicMSP').slice(0, 1) }}
      </span>
      <span class="org-name">{{ activeCustomer?.name || `${partnerLabel} · Partner view` }}</span>
      <UiIcon name="chevDown" :size="12" />
    </button>

    <button class="palette" type="button" @click="launcher.show">
      <UiIcon name="search" :size="13" stroke="var(--text-mute)" />
      <input
        v-model="searchValue"
        type="text"
        placeholder="Search mail, files, people…"
        @click.stop
        @focus.stop
      />
      <span class="kbd">⌘K</span>
    </button>

    <div class="right">
      <button class="icon-btn" title="Apps" @click="launcher.toggle">
        <UiIcon name="waffle" :size="14" />
      </button>
      <button class="icon-btn" title="Notifications" @click="drawer.toggle">
        <UiIcon name="bell" :size="14" />
        <span v-if="drawer.unreadCount.value > 0" class="icon-btn-dot" />
      </button>
      <PortalUserMenu />
    </div>

    <!-- Org switcher dropdown -->
    <Teleport to="body">
      <div v-if="orgSwitcherOpen" class="org-drop-scrim" @click="orgSwitcherOpen = false" />
      <div v-if="orgSwitcherOpen" class="org-drop">
        <div class="org-drop-head">
          <Eyebrow>{{ partnerLabel }} · {{ (tenants?.length ?? 0) }} customers</Eyebrow>
        </div>
        <button class="org-drop-row" :class="{ on: !partnerMode.isActive.value }" @click="leaveCustomerMode">
          <span class="org-drop-chip" style="background: #0A0A0A">{{ partnerLabel.charAt(0).toUpperCase() }}</span>
          <div class="org-drop-meta">
            <div class="org-drop-name">Partner view</div>
            <Mono dim>portfolio overview</Mono>
          </div>
        </button>
        <div class="org-drop-divider" />
        <button
          v-for="c in tenants"
          :key="c._id"
          class="org-drop-row"
          :class="{ on: partnerMode.activeCustomerId.value === c._id }"
          @click="pickCustomer(c._id)"
        >
          <span class="org-drop-chip" :style="{ background: c.brandColor || '#0A0A0A' }">{{ c.name.slice(0, 1) }}</span>
          <div class="org-drop-meta">
            <div class="org-drop-name">{{ c.name }}</div>
            <Mono dim>{{ c.domains?.[0] || c.slug }} · {{ PLAN_LABEL[c.plan ?? 'pro'] }}</Mono>
          </div>
        </button>
      </div>
    </Teleport>
  </header>
</template>

<style scoped>
header {
  height: 52px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 16px;
  background: var(--bg);
  border-bottom: 1px solid var(--border);
}

.orgswitch {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 5px 10px;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-family: inherit;
  font-size: 12px;
  color: var(--text);
  cursor: pointer;
  flex-shrink: 0;
}
.orgswitch:hover { background: var(--elevated); }
.org-chip {
  width: 18px; height: 18px;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: #F4F3EE;
  font-family: var(--font-mono);
  font-weight: 700;
  font-size: 10px;
}
.org-name { font-weight: 500; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

.palette {
  flex: 1;
  min-width: 0;
  max-width: 540px;
  display: flex;
  align-items: center;
  gap: 10px;
  height: 32px;
  padding: 0 12px;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: 6px;
  cursor: text;
  color: var(--text-mute);
  font-family: inherit;
  font-size: 12px;
  text-align: left;
}
.palette input {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  font: inherit;
  color: var(--text);
  min-width: 0;
}
.palette input::placeholder { color: var(--text-mute); }

.kbd {
  font-family: var(--font-mono);
  font-size: 10px;
  padding: 2px 6px;
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 3px;
  color: var(--text-mute);
  flex-shrink: 0;
}

.right {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.icon-btn {
  position: relative;
  height: 32px;
  width: 32px;
  border-radius: 6px;
  background: var(--surface);
  border: 1px solid var(--border);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--text);
  cursor: pointer;
}
.icon-btn:hover { background: var(--elevated); }
.icon-btn-dot {
  position: absolute;
  top: 6px;
  right: 7px;
  width: 6px;
  height: 6px;
  border-radius: 999px;
  background: var(--bad);
  border: 1.5px solid var(--bg);
}

.org-drop-scrim {
  position: fixed;
  inset: 0;
  z-index: 90;
  background: transparent;
}
.org-drop {
  position: fixed;
  top: 56px;
  left: 232px;
  z-index: 100;
  width: 320px;
  max-height: 60vh;
  overflow-y: auto;
  background: var(--elevated);
  border: 1px solid var(--border);
  border-radius: 8px;
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.32);
  padding: 6px;
}
.org-drop-head { padding: 8px 10px 4px 10px; }
.org-drop-row {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 8px 10px;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 6px;
  color: var(--text);
  font-family: inherit;
  font-size: 13px;
  text-align: left;
  cursor: pointer;
}
.org-drop-row:hover { background: var(--surface); }
.org-drop-row.on { background: var(--surface); border-color: var(--border); }
.org-drop-chip {
  width: 22px; height: 22px;
  border-radius: 5px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: #F4F3EE;
  font-family: var(--font-mono);
  font-weight: 700;
  font-size: 11px;
}
.org-drop-meta { min-width: 0; flex: 1; }
.org-drop-name { font-weight: 500; }
.org-drop-divider { height: 1px; background: var(--border); margin: 6px 0; }
</style>
