<script setup lang="ts">
import { computed, ref } from 'vue'
import type { ChapterInfo, SceneNode, EndingDef, PlayerTreeNode } from '@engine/types'
import { useI18n } from '@/composables/useI18n'
import TreeNode from './TreeNode.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]
  close: []
}>()

const expandedChapterId = ref<string | null>(null)

function collectReachable(startId: 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)) queue.push(c.targetScene)
      }
    }
    if (scene.nextScene && !visited.has(scene.nextScene)) queue.push(scene.nextScene)
    if (scene.qte) {
      if (scene.qte.successScene && !visited.has(scene.qte.successScene)) queue.push(scene.qte.successScene)
      if (scene.qte.failScene && !visited.has(scene.qte.failScene)) queue.push(scene.qte.failScene)
    }
    if (scene.hotspots) {
      for (const h of scene.hotspots) {
        if (h.targetScene && !visited.has(h.targetScene)) 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)
  }
  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 endingStatus(endingId: string) {
  return props.visitedIds.has(props.endings.find(e => e.id === endingId)?.sceneId ?? '')
}

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 buildPlayerTree(sceneId: 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) {
    if (scene.choices) {
      for (const c of scene.choices) {
        if (c.targetScene) {
          const child = buildPlayerTree(c.targetScene, depth + 1, pathSet)
          if (child) children.push(child)
        }
      }
    }
    if (scene.nextScene) {
      const child = buildPlayerTree(scene.nextScene, depth + 1, pathSet)
      if (child) children.push(child)
    }
    if (scene.qte) {
      if (scene.qte.successScene) {
        const child = buildPlayerTree(scene.qte.successScene, depth + 1, pathSet)
        if (child) children.push(child)
      }
      if (scene.qte.failScene) {
        const child = buildPlayerTree(scene.qte.failScene, depth + 1, pathSet)
        if (child) children.push(child)
      }
    }
    if (scene.hotspots) {
      for (const h of scene.hotspots) {
        if (h.targetScene) {
          const child = buildPlayerTree(h.targetScene, depth + 1, pathSet)
          if (child) children.push(child)
        }
      }
    }
  }

  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, 0, new Set())
}

function toggleExpand(chapterId: string) {
  expandedChapterId.value = expandedChapterId.value === chapterId ? null : chapterId
}
</script>

<template>
  <div class="story-overlay" @click.self="emit('close')" @keydown.escape="emit('close')">
    <div class="story-panel">
      <h2 class="story-title">{{ t('ui.story') }}</h2>

      <div class="story-grid">
        <div
          v-for="ch in chapters"
          :key="ch.id"
          class="story-card"
          :class="{ locked: !unlockedChapterIds.has(ch.id), expanded: expandedChapterId === ch.id }"
        >
          <div class="card-main" @click="unlockedChapterIds.has(ch.id) && toggleExpand(ch.id)">
            <div class="card-thumb">
              <img v-if="ch.thumbnail" :src="ch.thumbnail" class="thumb-img" />
              <div v-else class="thumb-placeholder">?</div>
            </div>
            <div class="card-label">{{ t(ch.labelKey || ch.label) }}</div>

            <div class="card-progress" v-if="unlockedChapterIds.has(ch.id)">
              <div class="mini-progress-bar">
                <div class="mini-progress-fill" :style="{ width: chapterProgress(ch.id).pct + '%' }"></div>
              </div>
              <div class="mini-progress-text">{{ chapterProgress(ch.id).pct }}%</div>
            </div>

            <div class="card-endings" v-if="chapterEndings[ch.id]?.length">
              <span
                v-for="end in chapterEndings[ch.id]"
                :key="end.id"
                class="ending-tag"
                :class="{ unlocked: endingStatus(end.id) }"
              >{{ endingStatus(end.id) ? '✅' : '🔒' }} {{ t(end.labelKey || end.label) }}</span>
            </div>

            <button
              v-if="unlockedChapterIds.has(ch.id)"
              class="card-start-btn"
              @click.stop="emit('startChapter', ch.id)"
            >▶ {{ t('ui.startChapter') }}</button>
          </div>

          <div class="card-recap" v-if="expandedChapterId === ch.id">
            <TreeNode
              v-if="buildTreeForChapter(ch.id)"
              :node="buildTreeForChapter(ch.id)!"
              :depth="0"
            />
          </div>
        </div>
      </div>

      <button class="story-close" @click="emit('close')">{{ t('ui.close') }}</button>
    </div>
  </div>
</template>

<style scoped>
.story-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.88);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 200;
}

.story-panel {
  background: #1a1a2e;
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 10px;
  padding: 36px 40px;
  max-width: 800px;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
}

.story-title {
  text-align: center;
  font-size: 22px;
  font-weight: 400;
  color: #ddd;
  letter-spacing: 3px;
  margin-bottom: 24px;
}

.story-grid {
  display: flex;
  gap: 16px;
  justify-content: center;
  overflow-y: auto;
  padding-right: 8px;
}

.story-card {
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  width: 240px;
  overflow: hidden;
  transition: border-color 0.2s;
}

.story-card.locked {
  opacity: 0.4;
}

.story-card.expanded {
  border-color: rgba(255, 255, 255, 0.2);
}

.card-main {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 14px;
  cursor: pointer;
}

.story-card.locked .card-main {
  cursor: default;
}

.card-thumb {
  width: 140px;
  height: 78px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.thumb-placeholder {
  font-size: 28px;
  color: #555;
}

.card-label {
  font-size: 14px;
  color: #ddd;
  text-align: center;
}

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

.mini-progress-bar {
  flex: 1;
  height: 4px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
  overflow: hidden;
}

.mini-progress-fill {
  height: 100%;
  background: #4caf50;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.mini-progress-text {
  font-size: 11px;
  color: #888;
  white-space: nowrap;
}

.card-endings {
  display: flex;
  flex-direction: column;
  gap: 3px;
  width: 100%;
}

.ending-tag {
  font-size: 11px;
  color: #666;
}

.ending-tag.unlocked {
  color: #ccc;
}

.card-start-btn {
  padding: 6px 20px;
  margin-top: 4px;
  font-size: 12px;
  color: #8cf;
  background: rgba(100, 200, 255, 0.08);
  border: 1px solid rgba(100, 200, 255, 0.2);
  border-radius: 3px;
  cursor: pointer;
  transition: background 0.15s;
}

.card-start-btn:hover {
  background: rgba(100, 200, 255, 0.15);
}

.card-recap {
  border-top: 1px solid rgba(255, 255, 255, 0.06);
  padding: 12px 14px;
  max-height: 220px;
  overflow-y: auto;
}

.story-close {
  margin-top: 20px;
  padding: 10px 36px;
  font-size: 14px;
  color: #888;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.15s, color 0.15s;
  align-self: center;
}

.story-close:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ccc;
}
</style>
