<script setup lang="ts">
import { computed } from 'vue'
import { RouterLink, RouterView, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import TenantBrand from '@/components/TenantBrand.vue'

const auth = useAuthStore()
const router = useRouter()

interface NavItem { label: string; to: string; icon: string; show: boolean }

// Portal-/Reseller-Ebene → Topbar
const topNav = computed<NavItem[]>(() => {
  const above = auth.isResellerAdmin || auth.isPlatformAdmin
  return [
    { label: 'Dashboard', to: '/app', icon: 'M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z', show: above },
    // Plattform-Ebene: nur Reseller (Firmen/Mitarbeiter/Produkte/Bestellungen via „Einloggen als")
    { label: 'Reseller', to: '/app/resellers', icon: 'M3 21h18M5 21V7l8-4v18M19 21V11l-6-3', show: auth.isPlatformAdmin },
    // Reseller-Ebene: eigene Firmenkunden + Produkte + Bestellungen
    { label: 'Einloggen als', to: '/app/companies', icon: 'M3 7h18v13H3zM8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2', show: auth.isResellerAdmin },
    { label: 'Produkte', to: '/app/products', icon: 'M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12', show: auth.isResellerAdmin },
    { label: 'Bestellungen', to: '/app/orders', icon: 'M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4zM3 6h18M16 10a4 4 0 0 1-8 0', show: auth.isResellerAdmin },
    { label: 'Einstellungen', to: '/app/settings', icon: 'M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6', show: above },
  ].filter((i) => i.show)
})

// Firmen-Ebene → linke Sidebar (nur im Firmen-Kontext, auch via „Einloggen als")
const leftNav = computed<NavItem[]>(() => {
  const inCompany = auth.isCompanyAdmin
  return [
    { label: 'Dashboard', to: '/app', icon: 'M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z', show: inCompany },
    { label: 'Mitarbeiter', to: '/app/employees', icon: 'M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z', show: inCompany },
    { label: 'Editor', to: '/app/card-editor', icon: 'M3 5h18v14H3zM3 10h18M7 15h5', show: inCompany },
    { label: 'Bestellungen', to: '/app/orders', icon: 'M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4zM3 6h18M16 10a4 4 0 0 1-8 0', show: inCompany },
    { label: 'Standorte', to: '/app/locations', icon: 'M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0zM12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', show: inCompany },
    { label: 'Domains', to: '/app/domains', icon: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3 12h18M12 3a15 15 0 0 1 0 18 15 15 0 0 1 0-18z', show: inCompany },
    { label: 'Design', to: '/app/design', icon: 'M12 2l7 7a7 7 0 1 1-14 0z', show: inCompany },
    { label: 'Wallet', to: '/app/wallet', icon: 'M3 7h18v12H3zM3 10h18M16 14h2', show: inCompany },
    { label: 'Einstellungen', to: '/app/settings', icon: 'M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6', show: inCompany },
  ].filter((i) => i.show)
})

const levelLabel = computed(() => {
  if (auth.isPlatformAdmin) return 'Portal'
  if (auth.isResellerAdmin) return 'Reseller'
  return auth.user?.company?.name ?? 'Firma'
})
const userName = computed(() => auth.user?.name || auth.user?.email || '')
const initials = computed(() =>
  userName.value.split(/[\s@.]+/).filter(Boolean).slice(0, 2).map((s) => s[0]).join('').toUpperCase() || 'U',
)
const roleLabel = computed(() => {
  if (auth.isPlatformAdmin) return 'Plattform-Admin'
  if (auth.isResellerAdmin) return 'Reseller-Admin'
  if (auth.isCompanyAdmin) return 'Firmen-Admin'
  return 'Mitarbeiter'
})

function logout() {
  auth.logout()
  router.push('/login')
}
async function stopImpersonation() {
  await auth.stopImpersonation()
  router.push('/app')
}
</script>

<template>
  <div class="shell">
    <header class="topbar">
      <div class="topbar__brand">
        <TenantBrand size="1.2rem" />
        <span class="level" :class="'level--' + (auth.isPlatformAdmin ? 'portal' : auth.isResellerAdmin ? 'reseller' : 'firma')">{{ levelLabel }}</span>
      </div>

      <nav class="topnav" v-if="topNav.length">
        <RouterLink v-for="item in topNav" :key="item.to" :to="item.to" class="topnav__link"
                    :class="{ active: $route.path === item.to }">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"
               stroke-linecap="round" stroke-linejoin="round"><path :d="item.icon" /></svg>
          <span>{{ item.label }}</span>
        </RouterLink>
      </nav>
      <div v-else class="topnav-spacer"></div>

      <div class="topbar__user">
        <div class="user">
          <div class="user__avatar">{{ initials }}</div>
          <div class="user__meta">
            <strong>{{ userName }}</strong>
            <span class="muted">{{ roleLabel }}<template v-if="auth.user?.company"> · {{ auth.user.company.name }}</template></span>
          </div>
        </div>
        <button class="btn btn-ghost btn-sm" @click="logout">Abmelden</button>
      </div>
    </header>

    <div v-if="auth.isImpersonating" class="imp-banner">
      <span>Eingeloggt als <strong>{{ auth.actingAs?.name }}</strong> ({{ auth.actingAs?.email }})</span>
      <button class="btn btn-sm" @click="stopImpersonation">Zurück zur eigenen Ebene</button>
    </div>

    <div class="body">
      <aside v-if="leftNav.length" class="sidebar">
        <div class="sidebar__label">Firma</div>
        <nav class="sidebar__nav">
          <RouterLink v-for="item in leftNav" :key="item.to" :to="item.to" class="navlink"
                      :class="{ active: $route.path === item.to }">
            <span class="navlink__icon">
              <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"
                   stroke-linecap="round" stroke-linejoin="round"><path :d="item.icon" /></svg>
            </span>
            <span class="navlink__label">{{ item.label }}</span>
            <svg class="navlink__chev" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor"
                 stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6" /></svg>
          </RouterLink>
        </nav>
      </aside>

      <main class="content"><RouterView /></main>
    </div>
  </div>
</template>

<style scoped>
.shell { min-height: 100vh; background: var(--bg); display: flex; flex-direction: column; }

/* Topbar (Portal-/Reseller-Ebene) */
.topbar {
  display: flex; align-items: center; gap: 1.2rem; padding: .6rem 1.4rem;
  background: #fff; border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 20;
}
.topbar__brand { display: flex; align-items: center; gap: .7rem; flex-shrink: 0; }
.level { font-size: .72rem; font-weight: 700; padding: .2rem .6rem; border-radius: 999px; text-transform: uppercase; letter-spacing: .04em; }
.level--portal { background: #ede9fe; color: #5b21b6; }
.level--reseller { background: var(--psc-orange-soft); color: var(--psc-orange-dark); }
.level--firma { background: #e8f0fe; color: #2b6cb0; }

.topnav { display: flex; align-items: center; gap: .3rem; flex: 1; flex-wrap: wrap; }
.topnav-spacer { flex: 1; }
.topnav__link {
  display: inline-flex; align-items: center; gap: .45rem; padding: .5rem .85rem;
  border-radius: 999px; color: #5b5b5b; font-size: .9rem; font-weight: 600;
}
.topnav__link:hover { background: #f5f5f5; color: var(--text); text-decoration: none; }
.topnav__link.active { background: var(--psc-orange); color: #fff; }

.topbar__user { display: flex; align-items: center; gap: 1rem; flex-shrink: 0; }
.user { display: flex; align-items: center; gap: .6rem; }
.user__avatar { width: 38px; height: 38px; border-radius: 50%; flex-shrink: 0; background: var(--psc-orange-soft); color: var(--psc-orange-dark); display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: .82rem; }
.user__meta { display: flex; flex-direction: column; line-height: 1.2; }
.user__meta strong { font-size: .88rem; }
.user__meta .muted { font-size: .74rem; }

.imp-banner { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: .55rem 1.4rem; background: var(--psc-orange); color: #fff; font-size: .9rem; font-weight: 600; }
.imp-banner .btn { background: #fff; color: var(--psc-orange-dark); }

.body { display: flex; flex: 1; min-height: 0; }

/* linke Sidebar (Firmen-Ebene) */
.sidebar { width: 232px; flex-shrink: 0; background: #fff; border-right: 1px solid var(--line); display: flex; flex-direction: column; position: sticky; top: 57px; height: calc(100vh - 57px); }
.sidebar__label { font-size: .68rem; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); padding: 1.1rem 1.3rem .4rem; }
.sidebar__nav { display: flex; flex-direction: column; gap: 3px; padding: .2rem .7rem; }
.navlink { display: flex; align-items: center; gap: .75rem; padding: .6rem .7rem; border-radius: var(--radius-sm); color: #5b5b5b; font-size: .92rem; font-weight: 600; }
.navlink__icon { display: flex; color: #9a9a9a; }
.navlink__label { flex: 1; }
.navlink__chev { color: #cfcfcf; }
.navlink:hover { background: #f6f6f6; color: var(--text); text-decoration: none; }
.navlink:hover .navlink__icon { color: #6f6f6f; }
.navlink.active { background: var(--psc-orange-soft); color: var(--psc-orange-dark); }
.navlink.active .navlink__icon, .navlink.active .navlink__chev { color: var(--psc-orange); }

.content { flex: 1; min-width: 0; padding: 1.8rem; }
</style>
