<script setup lang="ts">
// Account settings page — the destination from the topbar UserMenu's
// "Settings" item. Three cards:
//   - Profile (read-only, sourced from the signed-in user's JWT claims)
//   - Security (deep links to Authentik for password / MFA / sessions —
//     identity lives there, not here)
//   - Appearance (theme/density/env, same store as the floating Tweaks panel)

interface VerifyResponse {
  iss?: string
  aud?: string
  sub?: string
  email?: string
  groups?: string[]
  exp?: number
  iat?: number
}

const { user } = useOidcAuth()
const { state: tweaks, setTheme, setDensity } = useTweaks()
const { env, hostname } = useEnv()

const ENV_LABEL: Record<'prod' | 'staging' | 'dev', string> = {
  prod: 'Production',
  staging: 'Staging',
  dev: 'Development',
}

const { data: token } = useLazyFetch<VerifyResponse>('/api/_verify-token', {
  server: false,
  default: () => ({}),
})

const displayName = computed(() => user.value?.userInfo?.name || user.value?.userName || '—')
const email = computed(
  () => (user.value?.userInfo as { email?: string } | undefined)?.email || token.value?.email || '—',
)
const subject = computed(() => token.value?.sub ?? user.value?.userName ?? '—')
// Authentik returns each group twice in the groups claim (one entry per
// matching policy binding). Dedupe so we only render each chip once.
const groups = computed(() => Array.from(new Set(token.value?.groups ?? [])))
const lastSignIn = computed(() => {
  const iat = token.value?.iat
  if (!iat) return null
  return new Date(iat * 1000)
})

const AUTHENTIK = 'https://auth.dezky.local'
const links = [
  {
    icon: 'key' as const,
    title: 'Change password',
    desc: "Opens Authentik's password change flow in a new tab.",
    href: `${AUTHENTIK}/if/user/`,
  },
  {
    icon: 'shield' as const,
    title: 'Manage MFA devices',
    desc: 'Add or remove TOTP, WebAuthn, or recovery codes.',
    href: `${AUTHENTIK}/if/user/`,
  },
  {
    icon: 'plug' as const,
    title: 'Active sessions',
    desc: 'Revoke other devices that are currently signed in as you.',
    href: `${AUTHENTIK}/if/user/`,
  },
]
</script>

<template>
  <div>
    <PageHeader
      eyebrow="Account"
      title="Settings"
      :subtitle="`Signed in as ${displayName}. Identity is managed in Authentik — security controls deep-link there.`"
    />

    <div class="stage">
      <Card :pad="0">
        <div class="head">
          <div>
            <Eyebrow>Profile</Eyebrow>
            <div class="cap">Who you are right now</div>
          </div>
          <Mono v-if="lastSignIn" dim>last sign-in · {{ lastSignIn.toLocaleString('da-DK') }}</Mono>
        </div>
        <dl class="kv">
          <div class="row">
            <dt>Name</dt>
            <dd>{{ displayName }}</dd>
          </div>
          <div class="row">
            <dt>Email</dt>
            <dd><Mono>{{ email }}</Mono></dd>
          </div>
          <div class="row">
            <dt>Subject ID</dt>
            <dd><Mono dim>{{ subject }}</Mono></dd>
          </div>
          <div class="row">
            <dt>Groups</dt>
            <dd class="groups">
              <Badge
                v-for="g in groups"
                :key="g"
                :tone="g === 'dezky-platform-admins' ? 'accent' : 'neutral'"
              >{{ g }}</Badge>
              <Mono v-if="!groups.length" dim>—</Mono>
            </dd>
          </div>
          <div class="row">
            <dt>Environment</dt>
            <dd class="env-row">
              <Badge :tone="env === 'prod' ? 'bad' : env === 'staging' ? 'warn' : 'info'" dot>
                {{ ENV_LABEL[env] }}
              </Badge>
              <Mono dim>auto-detected from {{ hostname || '—' }}</Mono>
            </dd>
          </div>
        </dl>
      </Card>

      <Card :pad="0">
        <div class="head">
          <div>
            <Eyebrow>Security</Eyebrow>
            <div class="cap">Password & MFA</div>
          </div>
        </div>
        <div class="links">
          <a v-for="l in links" :key="l.title" :href="l.href" target="_blank" rel="noopener" class="link">
            <span class="link-icon"><UiIcon :name="l.icon" :size="14" /></span>
            <span class="link-body">
              <span class="link-title">{{ l.title }}</span>
              <Mono dim>{{ l.desc }}</Mono>
            </span>
            <UiIcon name="external" :size="12" />
          </a>
        </div>
      </Card>

      <Card :pad="0">
        <div class="head">
          <div>
            <Eyebrow>Appearance</Eyebrow>
            <div class="cap">Cosmetic toggles · saved per browser</div>
          </div>
          <Mono dim>also in the floating ⚙ panel</Mono>
        </div>
        <div class="appearance">
          <section>
            <span class="label">Theme</span>
            <div class="seg">
              <button :class="{ on: tweaks.theme === 'dark' }" type="button" @click="setTheme('dark')">Dark</button>
              <button :class="{ on: tweaks.theme === 'light' }" type="button" @click="setTheme('light')">Light</button>
            </div>
          </section>
          <section>
            <span class="label">Density</span>
            <div class="seg">
              <button :class="{ on: tweaks.density === 'comfy' }" type="button" @click="setDensity('comfy')">Comfy</button>
              <button :class="{ on: tweaks.density === 'compact' }" type="button" @click="setDensity('compact')">Compact</button>
            </div>
          </section>
        </div>
      </Card>
    </div>
  </div>
</template>

<style scoped>
.stage { padding: 24px 40px 64px 40px; display: flex; flex-direction: column; gap: 16px; max-width: 880px; }

.head {
  padding: 16px 20px;
  border-bottom: 1px solid var(--border);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.cap { font-family: var(--font-display); font-weight: 600; font-size: 17px; margin-top: 4px; }

.kv { margin: 0; padding: 4px 0; }
.kv .row {
  display: grid;
  grid-template-columns: 140px 1fr;
  align-items: center;
  gap: 16px;
  padding: 10px 20px;
  border-bottom: 1px solid var(--border);
}
.kv .row:last-child { border-bottom: none; }
.kv dt {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-mute);
  font-weight: 500;
}
.kv dd { margin: 0; font-size: 13px; }
.kv dd.groups { display: flex; flex-wrap: wrap; gap: 6px; }
.kv dd.env-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }

.links { display: flex; flex-direction: column; }
.link {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 12px 20px;
  border-bottom: 1px solid var(--border);
  color: var(--text);
  text-decoration: none;
  cursor: pointer;
}
.link:last-child { border-bottom: none; }
.link:hover { background: var(--surface); }
.link-icon {
  width: 30px;
  height: 30px;
  border-radius: 6px;
  background: var(--surface);
  border: 1px solid var(--border);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--text-dim);
  flex-shrink: 0;
}
.link-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.link-title { font-size: 13px; font-weight: 500; }

.appearance { padding: 16px 20px; display: flex; flex-direction: column; gap: 16px; }
.appearance section { display: flex; flex-direction: column; gap: 8px; }
.label {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--text-mute);
  font-weight: 500;
}
.seg {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px;
  padding: 3px;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: 7px;
  max-width: 280px;
}
.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;
}
.seg button:hover { color: var(--text); }
.seg button.on { background: var(--text); color: var(--bg); }
</style>
