<script setup lang="ts">
import { computed } from 'vue'
import { LogOut, Shield, Trash2, Unlink, X } from '@lucide/vue'

import type { AuthSession } from '../types/awards'

const props = defineProps<{
  accountOpen: boolean
  privacyOpen: boolean
  deleteConfirm: boolean
  session: AuthSession | null
  privacyContentHtml: string
  privacyEmail: string
  accountActionError: string
  accountActionSuccess: string
  authLoading: boolean
}>()

defineEmits<{
  'close-account': []
  'close-privacy': []
  'open-privacy': []
  'request-delete': []
  'cancel-delete': []
  logout: []
  'bind-team-twitch': []
  'disconnect-team-twitch': []
  'confirm-delete': []
}>()

const isTeamPasswordSession = computed(() => Boolean(props.session?.teamLogin && props.session.twitchUserId.startsWith('team:')))
const isTwitchAuthenticated = computed(() => Boolean(props.session && !isTeamPasswordSession.value))
const profileHandle = computed(() => props.session?.teamLogin ?? props.session?.twitchUserId ?? '')
const displayInitial = computed(() => (props.session?.displayName ?? profileHandle.value).charAt(0).toUpperCase())
const role = computed(() => props.session?.role ?? 'viewer')
const isTeamSession = computed(() => Boolean(props.session?.teamLogin))
const isParticipantSession = computed(() => !isTeamSession.value)
const canBindTwitch = computed(() => isTeamSession.value && !props.session?.mustChangePassword)
const hasBoundTwitch = computed(() => Boolean(props.session?.boundTwitchUserId))
const showTeamLoginDetail = computed(() => Boolean(props.session?.teamLogin && !isTeamSession.value))
const authStatusLabel = computed(() => {
  if (isTeamPasswordSession.value) return 'Angemeldet mit Team-Login'
  if (isTeamSession.value) return 'Admin-Login über Twitch'
  return 'Angemeldet über Twitch'
})
const authStatusText = computed(() => {
  if (isTeamPasswordSession.value && hasBoundTwitch.value) return 'Twitch ist verknüpft, diese Session läuft aber über den Team-Login.'
  if (isTeamPasswordSession.value) return 'Du bist mit Login und Passwort angemeldet.'
  if (isTeamSession.value) return 'Diese Admin-Session nutzt deinen verknüpften Twitch-Account.'
  return 'Diese Session nutzt deinen Twitch-Account.'
})
const primaryIdentityLabel = computed(() => isTeamSession.value ? 'Team-Login' : 'Twitch-ID')
const logoutLabel = computed(() => !isTeamSession.value && isTwitchAuthenticated.value ? 'Von Twitch abmelden' : 'Abmelden')
</script>

<template>
  <!-- ── Account Modal ─────────────────────────────────────── -->
  <Teleport to="body">
    <Transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="opacity-0"
      enter-to-class="opacity-100"
      leave-active-class="transition duration-150 ease-in"
      leave-from-class="opacity-100"
      leave-to-class="opacity-0"
    >
      <div
        v-if="accountOpen"
        class="fixed inset-0 z-[300] flex items-end justify-center p-4 sm:items-center sm:p-6"
        style="background:rgba(40,24,70,0.52);backdrop-filter:blur(6px);"
        @click.self="$emit('close-account')"
      >
        <Transition
          enter-active-class="transition duration-200 ease-out"
          enter-from-class="opacity-0 translate-y-4 scale-[0.97] sm:translate-y-0"
          enter-to-class="opacity-100 translate-y-0 scale-100"
        >
          <div class="w-full max-w-[480px] overflow-hidden rounded-3xl bg-white shadow-[0_40px_90px_rgba(40,24,70,0.38)]">

            <!-- Header -->
            <div class="flex items-center justify-between gap-4 border-b border-[#f1ecfb] bg-gradient-to-br from-[#f7f2ff] to-[#fff7ed] px-7 py-5">
              <div class="flex items-center gap-3.5 min-w-0">
                <div class="grid h-11 w-11 shrink-0 place-items-center rounded-2xl bg-gradient-to-br from-[#8b6cdb] to-[#7355c8] text-base font-bold text-white shadow-[0_6px_18px_rgba(124,86,196,0.3)]">
                  {{ displayInitial }}
                </div>
                <div class="min-w-0">
                  <p class="text-[10px] font-bold uppercase tracking-[0.2em] text-[#8b6cdb]">Mein Profil</p>
                  <h2 class="truncate font-['Cormorant_Garamond'] text-2xl font-bold leading-tight text-[#3f3556]">
                    @{{ profileHandle }}
                  </h2>
                </div>
              </div>
              <button
                type="button"
                class="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[#f1ecfb] text-[#8b6cdb] transition hover:bg-[#e6dcf6]"
                aria-label="Profil schließen"
                @click="$emit('close-account')"
              >
                <X class="h-4 w-4" />
              </button>
            </div>

            <!-- Scrollable body -->
            <div class="max-h-[72vh] overflow-y-auto">
              <div class="space-y-3 p-6">

                <!-- Auth status -->
                <div class="grid grid-cols-[auto_1fr] items-start gap-x-3 gap-y-1 rounded-2xl border border-[#ede4fb] bg-[#f6f1fd] px-4 py-3.5">
                  <div class="mt-0.5 shrink-0">
                    <svg v-if="isTeamPasswordSession" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#8b6cdb" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                      <path d="M15 7a4 4 0 1 1-2.8-3.82"/><path d="M13 5 21 13"/><path d="M21 13 18 16"/><path d="M18 13 16 15"/>
                    </svg>
                    <svg v-else width="18" height="18" viewBox="0 0 24 24" fill="#9146FF" aria-hidden="true">
                      <path d="M4 2L2.4 6v14.5h5V23h2.7l2.5-2.5h4L21.6 16V2H4zm15.3 13.1l-2.9 2.9h-4.4l-2.5 2.5v-2.5H6.7V3.7h12.6v11.4z"/>
                      <path d="M11.1 7.1h1.7v5h-1.7zM15.7 7.1h1.7v5h-1.7z"/>
                    </svg>
                  </div>
                  <span class="text-sm font-extrabold text-[#5f44ad]">{{ authStatusLabel }}</span>
                  <span class="col-start-2 text-xs leading-relaxed text-[#6f6685]">{{ authStatusText }}</span>
                </div>

                <!-- Saved data -->
                <div class="rounded-2xl border border-[#ede4fb] bg-[#fafafa] px-4 py-3.5">
                  <p class="mb-3 text-[10px] font-bold uppercase tracking-[0.2em] text-[#a99fc0]">Gespeicherte Daten</p>
                  <div class="space-y-2">
                    <div class="flex items-center justify-between text-sm">
                      <span class="text-[#6f6685]">{{ primaryIdentityLabel }}</span>
                      <span class="font-semibold text-[#3f3556]">@{{ profileHandle }}</span>
                    </div>
                    <div class="flex items-center justify-between text-sm">
                      <span class="text-[#6f6685]">Rolle</span>
                      <span class="text-[10px] font-bold uppercase tracking-[0.1em] text-[#8b6cdb]">{{ role }}</span>
                    </div>
                    <div v-if="showTeamLoginDetail" class="flex items-center justify-between text-sm">
                      <span class="text-[#6f6685]">Team-Login</span>
                      <span class="font-semibold text-[#3f3556]">@{{ session?.teamLogin }}</span>
                    </div>
                    <div v-if="session?.boundTwitchUserId" class="flex items-center justify-between text-sm">
                      <span class="text-[#6f6685]">Gebundenes Twitch</span>
                      <span class="font-semibold text-[#3f3556]">@{{ session.boundTwitchUserId }}</span>
                    </div>
                    <template v-if="isParticipantSession">
                      <div class="flex items-center justify-between text-sm">
                        <span class="text-[#6f6685]">Einreichungen</span>
                        <span class="font-semibold text-[#3f3556]">Clips, Votes, Nominierungen</span>
                      </div>
                    </template>
                    <template v-else>
                      <div class="flex items-start justify-between gap-4 text-sm">
                        <span class="shrink-0 text-[#6f6685]">Accountverwaltung</span>
                        <span class="text-right font-semibold text-[#3f3556]">Team-Accounts werden im Admin-Panel verwaltet.</span>
                      </div>
                    </template>
                  </div>
                </div>

                <!-- Team Twitch binding -->
                <section v-if="isTeamSession" class="rounded-2xl border border-[#ede4fb] bg-[#f8f5ff] p-4">
                  <p class="text-[11px] font-bold uppercase tracking-[0.2em] text-[#8b6cdb]">Optionaler Admin-Login</p>
                  <p v-if="hasBoundTwitch" class="mt-1.5 text-xs leading-relaxed text-[#6f6685]">
                    Dein Team-Account ist mit Twitch verbunden. Entfernst du die Verknüpfung, ist der Admin-Login per Twitch nicht mehr möglich.
                  </p>
                  <p v-else class="mt-1.5 text-xs leading-relaxed text-[#6f6685]">
                    Verbinde deinen privaten Twitch-Account. Danach kannst du dich im Admin-Panel per Twitch anmelden.
                  </p>
                  <div v-if="session?.boundTwitchUserId" class="mt-3 flex items-center justify-between rounded-xl border border-[#ede4fb] bg-white px-3.5 py-2.5 text-sm">
                    <span class="text-[#6f6685]">Aktuell verbunden</span>
                    <span class="font-extrabold text-[#3f3556]">@{{ session.boundTwitchUserId }}</span>
                  </div>
                  <p v-if="session?.mustChangePassword" class="mt-2 text-xs font-bold text-amber-600">Bitte ändere zuerst dein temporäres Passwort.</p>
                  <p v-if="accountActionError" class="mt-2 text-xs font-bold text-rose-600">{{ accountActionError }}</p>
                  <p v-if="accountActionSuccess" class="mt-2 text-xs font-bold text-emerald-600">{{ accountActionSuccess }}</p>
                  <button
                    v-if="!hasBoundTwitch"
                    :disabled="authLoading || !canBindTwitch"
                    type="button"
                    class="mt-3 flex w-full items-center justify-center gap-2 rounded-xl bg-[#6f4fd1] px-4 py-2.5 text-sm font-extrabold text-white transition hover:bg-[#5f44ad] disabled:opacity-50"
                    @click="$emit('bind-team-twitch')"
                  >
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                      <path d="M4 2L2.4 6v14.5h5V23h2.7l2.5-2.5h4L21.6 16V2H4zm15.3 13.1l-2.9 2.9h-4.4l-2.5 2.5v-2.5H6.7V3.7h12.6v11.4z"/>
                      <path d="M11.1 7.1h1.7v5h-1.7zM15.7 7.1h1.7v5h-1.7z"/>
                    </svg>
                    {{ authLoading ? 'Twitch wird geöffnet …' : 'Mit Twitch verbinden' }}
                  </button>
                  <button
                    v-else
                    :disabled="authLoading"
                    type="button"
                    class="mt-3 flex w-full items-center justify-center gap-2 rounded-xl border border-rose-200 bg-rose-50 px-4 py-2.5 text-sm font-extrabold text-rose-600 transition hover:bg-rose-100 disabled:opacity-50"
                    @click="$emit('disconnect-team-twitch')"
                  >
                    <Unlink class="h-4 w-4" />
                    {{ authLoading ? 'Entknüpft …' : 'Twitch entknüpfen' }}
                  </button>
                </section>

                <!-- Privacy -->
                <button
                  type="button"
                  class="flex w-full items-center gap-3 rounded-xl border border-[#ede4fb] bg-[#f9f6ff] px-4 py-3 text-left text-sm font-semibold text-[#6a4fb8] transition hover:bg-[#f1ecfb]"
                  @click="$emit('open-privacy')"
                >
                  <Shield class="h-4 w-4 shrink-0" />
                  Datenschutzerklärung lesen
                </button>

                <!-- Logout -->
                <button
                  type="button"
                  class="flex w-full items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-left text-sm font-semibold text-slate-500 transition hover:bg-slate-100"
                  @click="$emit('logout')"
                >
                  <LogOut class="h-4 w-4 shrink-0" />
                  {{ logoutLabel }}
                </button>

                <!-- Delete request -->
                <template v-if="isParticipantSession && !deleteConfirm">
                  <button
                    type="button"
                    class="flex w-full items-center gap-3 rounded-xl border border-rose-100 bg-rose-50 px-4 py-3 text-left text-sm font-semibold text-rose-600 transition hover:bg-rose-100"
                    @click="$emit('request-delete')"
                  >
                    <Trash2 class="h-4 w-4 shrink-0" />
                    Meine Daten löschen (Löschrecht Art. 17 DSGVO)
                  </button>
                </template>

                <!-- Delete confirmation -->
                <template v-else-if="isParticipantSession">
                  <div class="rounded-2xl border-[1.5px] border-rose-200 bg-rose-50 p-4">
                    <p class="text-sm font-semibold text-rose-800">Alle deine Daten werden sofort gelöscht.</p>
                    <p class="mt-1 text-xs leading-relaxed text-rose-600">Das umfasst Votes, Nominierungen und Clip-Einreichungen. Diese Aktion kann nicht rückgängig gemacht werden.</p>
                    <p v-if="accountActionError" class="mt-2 text-xs font-bold text-rose-700">{{ accountActionError }}</p>
                    <div class="mt-4 flex gap-2">
                      <button
                        :disabled="authLoading"
                        type="button"
                        class="flex-1 rounded-xl border border-[#e6dcf6] bg-white py-2.5 text-sm font-semibold text-[#6f6685] transition hover:bg-[#f9f6ff] disabled:opacity-50"
                        @click="$emit('cancel-delete')"
                      >Abbrechen</button>
                      <button
                        :disabled="authLoading"
                        type="button"
                        class="flex-1 rounded-xl bg-rose-600 py-2.5 text-sm font-bold text-white transition hover:bg-rose-700 disabled:opacity-50"
                        @click="$emit('confirm-delete')"
                      >{{ authLoading ? 'Löscht …' : 'Jetzt löschen' }}</button>
                    </div>
                  </div>
                </template>

              </div>
            </div>
          </div>
        </Transition>
      </div>
    </Transition>
  </Teleport>

  <!-- ── Privacy Modal ─────────────────────────────────────── -->
  <Teleport to="body">
    <Transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="opacity-0"
      enter-to-class="opacity-100"
      leave-active-class="transition duration-150 ease-in"
      leave-from-class="opacity-100"
      leave-to-class="opacity-0"
    >
      <div
        v-if="privacyOpen"
        class="fixed inset-0 z-[400] flex items-center justify-center p-6"
        style="background:rgba(40,24,70,0.52);backdrop-filter:blur(6px);"
        @click.self="$emit('close-privacy')"
      >
        <div class="flex max-h-[88vh] w-full max-w-[680px] flex-col overflow-hidden rounded-3xl bg-white shadow-[0_40px_90px_rgba(40,24,70,0.4)]">
          <div class="flex shrink-0 items-center justify-between gap-4 border-b border-[#f1ecfb] px-8 py-5">
            <div>
              <p class="text-[10px] font-bold uppercase tracking-[0.2em] text-[#8b6cdb]">Rechtliches</p>
              <h2 class="font-['Cormorant_Garamond'] text-2xl font-bold text-[#3f3556]">Datenschutzerklärung</h2>
            </div>
            <button
              type="button"
              class="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[#f1ecfb] text-[#8b6cdb] transition hover:bg-[#e6dcf6]"
              aria-label="Datenschutz schließen"
              @click="$emit('close-privacy')"
            >
              <X class="h-4 w-4" />
            </button>
          </div>
          <div class="flex-1 overflow-y-auto px-8 py-7 text-sm leading-relaxed text-[#6f6685]">
            <div v-if="privacyContentHtml" class="privacy-content" v-html="privacyContentHtml" />
            <div v-else class="rounded-2xl border border-[#f1ecfb] bg-[#fcfbff] px-4 py-3 text-sm">
              Datenschutzerklärung wird geladen.
            </div>
            <p v-if="privacyEmail" class="mt-5 text-xs text-[#a99fc0]">Kontakt: {{ privacyEmail }}</p>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
.privacy-content :deep(p) {
  margin: 0 0 14px;
}
.privacy-content :deep(p:last-child),
.privacy-content :deep(ul:last-child),
.privacy-content :deep(ol:last-child) {
  margin-bottom: 0;
}
.privacy-content :deep(ul),
.privacy-content :deep(ol) {
  margin: 0 0 14px 20px;
  padding-left: 16px;
}
.privacy-content :deep(li) {
  margin: 3px 0;
}
</style>
