<script setup lang="ts">
import { computed, ref } from 'vue'
import type { ChapterInfo, SceneNode, EndingDef, PlayerTreeNode } from '@engine/types'
import { useI18n } from '@/composables/useI18n'
import TreeFlow from './TreeFlow.vue'

const { t } = useI18n()

const props = defineProps<{
  chapters: ChapterInfo[]
  endings: EndingDef[]
  scenes: Record<string, SceneNode>
  visitedIds: Set<string>
  unlockedChapterIds: Set<string>
}>()

const emit = defineEmits<{
  startChapter: [chapterId: string]
  startAtScene: [chapterId: string, sceneId: string]
  close: []
}>()

const showChapterPicker = ref(false)

function isOtherChapterStart(sceneId: string, ownChapterId: string): boolean {
  return props.chapters.some(c => c.id !== ownChapterId && c.startScene === sceneId)
}

function collectReachable(startId: string, chapterId: string): Set<string> {
  const visited = new Set<string>()
  const queue = [startId]
  while (queue.length > 0) {
    const id = queue.shift()!
    if (visited.has(id)) continue
    const scene = props.scenes[id]
    if (!scene) continue
    visited.add(id)
    if (scene.choices) {
      for (const c of scene.choices) {
        if (c.targetScene && !visited.has(c.targetScene) && !isOtherChapterStart(c.targetScene, chapterId))
          queue.push(c.targetScene)
      }
    }
    if (scene.nextScene && !visited.has(scene.nextScene) && !isOtherChapterStart(scene.nextScene, chapterId))
      queue.push(scene.nextScene)
    if (scene.qte) {
      if (scene.qte.successScene && !visited.has(scene.qte.successScene) && !isOtherChapterStart(scene.qte.successScene, chapterId))
        queue.push(scene.qte.successScene)
      if (scene.qte.failScene && !visited.has(scene.qte.failScene) && !isOtherChapterStart(scene.qte.failScene, chapterId))
        queue.push(scene.qte.failScene)
    }
    if (scene.hotspots) {
      for (const h of scene.hotspots) {
        if (h.targetScene && !visited.has(h.targetScene) && !isOtherChapterStart(h.targetScene, chapterId))
          queue.push(h.targetScene)
      }
    }
  }
  return visited
}

const chapterReachable = computed(() => {
  const result: Record<string, Set<string>> = {}
  for (const ch of props.chapters) {
    result[ch.id] = collectReachable(ch.startScene, ch.id)
  }
  return result
})

const chapterEndings = computed(() => {
  const result: Record<string, EndingDef[]> = {}
  for (const ch of props.chapters) {
    result[ch.id] = props.endings.filter((e) => chapterReachable.value[ch.id]?.has(e.sceneId))
  }
  return result
})

function chapterProgress(chapterId: string) {
  const reachable = chapterReachable.value[chapterId]
  if (!reachable || reachable.size === 0) return { count: 0, total: 0, pct: 0 }
  let count = 0
  for (const id of reachable) {
    if (props.visitedIds.has(id)) count++
  }
  return { count, total: reachable.size, pct: Math.round((count / reachable.size) * 100) }
}

function lockHint(sceneId: string): string {
  for (const [, src] of Object.entries(props.scenes)) {
    if (src.choices) {
      for (const c of src.choices) {
        if (c.targetScene === sceneId && c.conditions && c.conditions.length > 0) {
          return `${c.conditions[0].variable} ${c.conditions[0].op} ${c.conditions[0].value}`
        }
      }
    }
    if (src.hotspots) {
      for (const h of src.hotspots) {
        if (h.targetScene === sceneId && h.conditions && h.conditions.length > 0) {
          return `${h.conditions[0].variable} ${h.conditions[0].op} ${h.conditions[0].value}`
        }
      }
    }
  }
  return ''
}

function endingStatus(endingId: string) {
  return props.visitedIds.has(props.endings.find(e => e.id === endingId)?.sceneId ?? '')
}

function chaptersByProgress() {
  return [...props.chapters].sort((a, b) => {
    const pa = chapterProgress(a.id).pct
    const pb = chapterProgress(b.id).pct
    return pb - pa
  })
}

const defaultChapter = computed(() => {
  const sorted = chaptersByProgress()
  for (const ch of sorted) {
    if (chapterProgress(ch.id).pct > 0) return ch
  }
  return sorted[0] ?? null
})

const currentChapterId = ref<string>('')

if (defaultChapter.value) {
  currentChapterId.value = defaultChapter.value.id
}

function selectChapter(chapterId: string) {
  if (!props.unlockedChapterIds.has(chapterId)) return
  currentChapterId.value = chapterId
  showChapterPicker.value = false
}

function buildPlayerTree(sceneId: string, chapterId: string, depth: number, pathSet: Set<string>): PlayerTreeNode | null {
  if (depth > 10) return null
  if (pathSet.has(sceneId)) return null
  const scene = props.scenes[sceneId]
  const label = scene?.id ?? sceneId
  const visited = props.visitedIds.has(sceneId)
  const hint = visited ? '' : lockHint(sceneId)
  const locked = !visited && hint !== ''
  pathSet.add(sceneId)
  const children: PlayerTreeNode[] = []
  if (scene) {
    function pushChild(target: string | undefined) {
      if (!target) return
      if (isOtherChapterStart(target, chapterId)) {
        const gatewayCh = props.chapters.find(c => c.startScene === target)
        children.push({
          sceneId: '',
          label: gatewayCh ? (t(gatewayCh.labelKey || gatewayCh.label)) : target,
          visited: false,
          locked: !props.unlockedChapterIds.has(gatewayCh?.id ?? ''),
          children: [],
          isGateway: true,
          gatewayChapterId: gatewayCh?.id,
        })
        return
      }
      const child = buildPlayerTree(target, chapterId, depth + 1, pathSet)
      if (child) children.push(child)
    }
    if (scene.choices) {
      for (const c of scene.choices) pushChild(c.targetScene)
    }
    pushChild(scene.nextScene)
    if (scene.qte) {
      pushChild(scene.qte.successScene)
      pushChild(scene.qte.failScene)
    }
    if (scene.hotspots) {
      for (const h of scene.hotspots) pushChild(h.targetScene)
    }
  }
  pathSet.delete(sceneId)
  return { sceneId, label, visited, locked, lockHint: hint, children }
}

function buildTreeForChapter(chapterId: string): PlayerTreeNode | null {
  const ch = props.chapters.find(c => c.id === chapterId)
  if (!ch) return null
  return buildPlayerTree(ch.startScene, chapterId, 0, new Set())
}

function onSelectScene(sceneId: string) {
  if (ch.value) {
    emit('startAtScene', ch.value.id, sceneId)
  }
}

const ch = computed(() => props.chapters.find(c => c.id === currentChapterId.value) ?? null)
const endings = computed(() => chapterEndings.value[currentChapterId.value] || [])
const progress = computed(() => chapterProgress(currentChapterId.value))
const tree = computed(() => buildTreeForChapter(currentChapterId.value))
</script>

<template>
  <div class="story-overlay" @keydown.escape="showChapterPicker ? (showChapterPicker = false) : emit('close')">
    <div class="story-shell">
      <div class="story-header">
        <button class="back-btn" @click="emit('close')">← {{ t('ui.back') }}</button>
        <h2 class="story-title">{{ ch ? t(ch.labelKey || ch.label) : t('ui.story') }}</h2>
      </div>

      <div class="story-body">
        <TreeFlow
          v-if="tree"
          :node="tree"
          :scenes="scenes"
          :key="currentChapterId"
          @select-scene="onSelectScene"
          @select-gateway="selectChapter"
        />
        <div v-else class="story-empty">暂无故事数据</div>
      </div>

      <div class="story-footer">
        <div class="footer-left">
          <div class="footer-progress">
            <div class="footer-bar">
              <div class="footer-fill" :style="{ width: progress.pct + '%' }"></div>
            </div>
          </div>

          <div class="footer-details">
            <div class="footer-stat">
              <span class="stat-value">{{ progress.count }}</span>
              <span class="stat-unit">/{{ progress.total }} 场景</span>
            </div>
            <div class="footer-endings" v-if="endings.length">
              <span
                v-for="end in endings"
                :key="end.id"
                class="ending-chip"
                :class="{ unlocked: endingStatus(end.id) }"
              >{{ endingStatus(end.id) ? '✓' : '🔒' }} {{ t(end.labelKey || end.label) }}</span>
            </div>
          </div>
        </div>

        <div class="footer-right">
          <button class="chapter-btn" @click="showChapterPicker = !showChapterPicker">
            {{ t('ui.chapters') }}
          </button>
        </div>
      </div>

      <Transition name="picker-fade">
        <div v-if="showChapterPicker" class="chapter-picker" @click.self="showChapterPicker = false">
          <div class="picker-panel">
            <div class="picker-grid">
              <div
                v-for="ch in chaptersByProgress()"
                :key="ch.id"
                class="picker-card"
                :class="{ locked: !unlockedChapterIds.has(ch.id), active: ch.id === currentChapterId }"
                @click="selectChapter(ch.id)"
              >
                <div class="picker-thumb">
                  <img v-if="ch.thumbnail" :src="ch.thumbnail" class="picker-thumb-img" />
                  <div v-else class="picker-thumb-place">?</div>
                  <div v-if="!unlockedChapterIds.has(ch.id)" class="picker-lock">🔒</div>
                </div>
                <div class="picker-label">{{ t(ch.labelKey || ch.label) }}</div>
                <div class="picker-progress" v-if="unlockedChapterIds.has(ch.id)">
                  <div class="picker-bar-bg">
                    <div class="picker-bar-fill" :style="{ width: chapterProgress(ch.id).pct + '%' }"></div>
                  </div>
                  <span class="picker-pct">{{ chapterProgress(ch.id).pct }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </div>
  </div>
</template>

<style scoped>
.story-overlay {
  position: fixed;
  inset: 0;
  background: rgba(8,6,4,0.92);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  display: flex;
  align-items: stretch;
  justify-content: center;
  z-index: 200;
  flex-direction: column;
}

.story-shell {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.story-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  flex-shrink: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent);
}

.back-btn {
  padding: 6px 16px;
  font-size: 13px;
  color: #888;
  background: rgba(255,255,255,0.04);
  border: 1px solid rgba(255,255,255,0.08);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.15s;
}

.back-btn:hover {
  color: #ccc;
  background: rgba(255,255,255,0.08);
}

.story-title {
  font-size: 18px;
  font-weight: 500;
  color: #c9a84c;
  letter-spacing: 4px;
  margin-left: 16px;
}

.story-body {
  flex: 1;
  min-height: 0;
  position: relative;
  overflow: hidden;
}

.story-body :deep(.tree-flow) {
  width: 100%;
  height: 100%;
  max-height: none;
}

.story-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #444;
  font-size: 14px;
}

.story-footer {
  display: flex;
  align-items: flex-end;
  padding: 12px 20px 16px;
  flex-shrink: 0;
  background: linear-gradient(to top, rgba(0,0,0,0.5), transparent);
}

.footer-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.footer-progress {
  width: 100%;
  max-width: 400px;
}

.footer-bar {
  height: 3px;
  background: rgba(255,255,255,0.08);
  border-radius: 2px;
  overflow: hidden;
}

.footer-fill {
  height: 100%;
  background: linear-gradient(90deg, #8b6914, #c9a84c);
  border-radius: 2px;
  transition: width 0.3s ease;
}

.footer-details {
  display: flex;
  align-items: center;
  gap: 16px;
}

.footer-stat {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #c9a84c;
}

.stat-unit {
  font-size: 11px;
  color: #666;
}

.footer-endings {
  display: flex;
  gap: 6px;
}

.ending-chip {
  padding: 3px 10px;
  font-size: 11px;
  color: #555;
  background: rgba(255,255,255,0.03);
  border: 1px solid rgba(255,255,255,0.06);
  border-radius: 12px;
}

.ending-chip.unlocked {
  color: #c9a84c;
  border-color: rgba(201,168,76,0.25);
  background: rgba(201,168,76,0.06);
}

.footer-right {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-shrink: 0;
}

.chapter-btn {
  padding: 6px 16px;
  font-size: 12px;
  color: #888;
  background: rgba(255,255,255,0.04);
  border: 1px solid rgba(255,255,255,0.1);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.15s;
}

.chapter-btn:hover {
  color: #ccc;
  background: rgba(255,255,255,0.08);
}

.chapter-picker {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: 300;
}

.picker-panel {
  border: none;
  border-radius: 0;
  width: 100%;
  background: rgba(12,12,18,0.82);
  backdrop-filter: blur(8px);
  padding: 28px 40px;
  box-shadow: 0 -1px 12px rgba(0,0,0,0.25);
}

.picker-grid {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.picker-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 14px;
  background: rgba(255,255,255,0.03);
  border: 1px solid rgba(255,255,255,0.06);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
  width: 160px;
}

.picker-card:hover:not(.locked) {
  background: rgba(255,255,255,0.06);
  border-color: rgba(255,255,255,0.15);
}

.picker-card.active {
  border-color: rgba(201,168,76,0.3);
  background: rgba(201,168,76,0.06);
}

.picker-card.locked {
  opacity: 0.3;
  cursor: default;
}

.picker-thumb {
  width: 120px;
  height: 68px;
  background: rgba(0,0,0,0.4);
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.picker-thumb-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.picker-thumb-place {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 24px;
  color: #444;
}

.picker-lock {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0,0,0,0.5);
  font-size: 18px;
}

.picker-label {
  font-size: 13px;
  color: #ddd;
}

.picker-progress {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
}

.picker-bar-bg {
  flex: 1;
  height: 3px;
  background: rgba(255,255,255,0.08);
  border-radius: 2px;
  overflow: hidden;
}

.picker-bar-fill {
  height: 100%;
  background: #c9a84c;
  border-radius: 2px;
}

.picker-pct {
  font-size: 10px;
  color: #888;
}

.picker-fade-enter-active,
.picker-fade-leave-active {
  transition: all 0.2s ease;
}
.picker-fade-enter-from,
.picker-fade-leave-to {
  opacity: 0;
  transform: translateY(12px);
}

.picker-fade-enter-from,
.picker-fade-leave-to {
  opacity: 0;
}
</style>
