<script setup lang="ts">
import { computed, onMounted, onUnmounted, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Collection, FullScreen, Monitor, ScaleToOriginal, Setting, SwitchButton } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useQuizStore } from '@/stores/quiz'

const router = useRouter()
const auth = useAuthStore()
const quiz = useQuizStore()
const fullscreen = shallowRef(false)
const settingsVisible = shallowRef(false)
const fullscreenIcon = computed(() => (fullscreen.value ? ScaleToOriginal : FullScreen))
const fullscreenTitle = computed(() => (fullscreen.value ? '退出全屏' : '全屏'))
const canEnterAdmin = computed(() => auth.user?.role === 'admin' || auth.permissionCodes.size > 0)

function syncFullscreenState() {
  fullscreen.value = Boolean(document.fullscreenElement)
}

async function toggleFullscreen() {
  if (document.fullscreenElement) {
    await document.exitFullscreen()
    return
  }
  await document.documentElement.requestFullscreen()
}

async function logout() {
  try {
    await ElMessageBox.confirm('确认退出当前账号？', '退出登录', {
      type: 'warning',
      confirmButtonText: '退出',
      cancelButtonText: '取消',
    })
  } catch {
    return
  }
  auth.clearSession()
  await router.replace('/login')
}

onMounted(() => {
  syncFullscreenState()
  document.addEventListener('fullscreenchange', syncFullscreenState)
})

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', syncFullscreenState)
})
</script>

<template>
  <div class="quiz-shell">
    <header class="quiz-header">
      <button class="quiz-brand" @click="router.push('/quiz')">
        <Collection class="w-5 h-5" />
        <span>QuickQuiz</span>
      </button>
      <div class="quiz-actions">
        <ElTooltip :content="fullscreenTitle" placement="bottom">
          <ElButton :icon="fullscreenIcon" circle @click="toggleFullscreen" />
        </ElTooltip>
        <ElTooltip content="学习设置" placement="bottom">
          <ElButton :icon="Setting" circle @click="settingsVisible = true" />
        </ElTooltip>
        <ElTooltip v-if="canEnterAdmin" content="管理后台" placement="bottom">
          <ElButton :icon="Monitor" circle @click="router.push('/admin')" />
        </ElTooltip>
        <ElButton :icon="SwitchButton" circle @click="logout" />
      </div>
    </header>
    <RouterView />

    <ElDialog v-model="settingsVisible" title="学习设置" width="min(420px, calc(100vw - 24px))">
      <ElForm label-position="top">
        <ElFormItem label="答对后自动下一题">
          <ElSwitch
            :model-value="quiz.autoNextOnCorrect"
            active-text="开启"
            inactive-text="关闭"
            @update:model-value="(value: boolean) => quiz.updateSettings({ autoNextOnCorrect: value })"
          />
        </ElFormItem>
        <ElFormItem label="切题动画时长">
          <ElInputNumber
            :model-value="quiz.animationDuration"
            :min="0"
            :max="600"
            :step="20"
            controls-position="right"
            class="w-full"
            @update:model-value="(value: number | undefined) => quiz.updateSettings({ animationDuration: value ?? 0 })"
          />
          <p class="setting-tip">单位毫秒，设置为 0 时关闭动画。</p>
        </ElFormItem>
      </ElForm>
    </ElDialog>
  </div>
</template>

<style scoped>
.quiz-shell {
  min-height: 100vh;
}

.quiz-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 16px;
  border-bottom: 1px solid var(--qq-line);
  background: rgba(247, 248, 244, 0.94);
  backdrop-filter: blur(12px);
}

.quiz-brand {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  border: 0;
  background: transparent;
  color: var(--qq-ink);
  font-weight: 800;
  cursor: pointer;
}

.quiz-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.setting-tip {
  margin: 8px 0 0;
  color: var(--qq-muted);
  font-size: 13px;
}
</style>
