<template>
  <div class="app-container">
    <!-- Navigation -->
    <nav class="main-nav">
      <button
        class="nav-btn"
        :class="{ active: currentPage === 'quiz' }"
        @click="currentPage = 'quiz'"
      >
        Quiz Generator
      </button>
      <button
        class="nav-btn"
        :class="{ active: currentPage === 'media' }"
        @click="currentPage = 'media'"
      >
        Media Manager
      </button>
      <button
        class="nav-btn"
        :class="{ active: currentPage === 'admin' }"
        @click="currentPage = 'admin'"
      >
        Upload Files
      </button>
      <button
        class="nav-btn"
        :class="{ active: currentPage === 'downloader' }"
        @click="currentPage = 'downloader'"
      >
        Openings Downloader
      </button>
    </nav>

    <!-- Quiz Generator Page -->
    <div v-if="currentPage === 'quiz'" class="app-layout">
      <!-- Left Sidebar - Selected Openings Summary -->
      <aside class="sidebar">
      <h3>Selected Openings</h3>
      <div class="selected-summary">
        <div v-if="allSelectedOpenings.length === 0" class="empty-state">
          No openings selected
        </div>
        <div
          v-for="(item, index) in allSelectedOpenings"
          :key="index"
          class="selected-item"
          :class="'difficulty-' + item.difficulty"
        >
          <span class="item-number">{{ index + 1 }}</span>
          <div class="item-info">
            <div class="item-anime">{{ item.animeName }}</div>
            <div class="item-op">{{ item.opNumber }}</div>
          </div>
          <button class="btn-remove-small" @click="removeFromSection(item.sectionIndex, item.openingIndex)">×</button>
        </div>
      </div>
      <div class="summary-stats" v-if="allSelectedOpenings.length > 0">
        <div>Total: {{ allSelectedOpenings.length }} openings</div>
        <div class="difficulty-stats">
          <span class="stat easy">{{ difficultyCount.easy }} Easy</span>
          <span class="stat medium">{{ difficultyCount.medium }} Medium</span>
          <span class="stat hard">{{ difficultyCount.hard }} Hard</span>
        </div>
      </div>
    </aside>

    <!-- Main Content -->
    <main class="main-content">
      <h1>Anime Quiz Generator</h1>
      <p class="subtitle">Generate "Guess the Anime Opening" videos</p>

      <div v-if="healthStatus" class="status-indicator" :class="healthStatus.status === 'healthy' ? 'success' : 'error'">
        <span>{{ healthStatus.status === 'healthy' ? 'Backend connected' : 'Backend issue' }}</span>
      </div>

      <!-- Global Settings -->
      <div class="card settings-card">
        <h2>Global Settings</h2>
        <div class="settings-grid">
          <div class="setting-group">
            <label>Video Mode</label>
            <div class="mode-selector">
              <button class="mode-btn" :class="{ active: mode === 'shorts' }" @click="mode = 'shorts'">
                <span class="icon">📱</span>
                <span>Shorts</span>
              </button>
              <button class="mode-btn" :class="{ active: mode === 'full' }" @click="mode = 'full'">
                <span class="icon">🖥️</span>
                <span>Full</span>
              </button>
            </div>
          </div>

          <div class="setting-group">
            <label>Default Guess Duration (sec)</label>
            <input type="number" v-model.number="defaultAudioDuration" min="1" max="15" step="1" />
          </div>

          <div class="setting-group">
            <label>Default Start Time (sec)</label>
            <input type="number" v-model.number="defaultStartTime" min="0" step="5" />
          </div>

          <div class="setting-group">
            <label class="checkbox-label" style="display: flex;">
              <input type="checkbox" v-model="defaultContinueAudio" />
              <span style="margin-top: 1px; margin-left: -8px;">Continue audio after reveal</span>
            </label>
          </div>

          <div class="setting-group" v-if="content.background_videos.length">
            <label>Background Video</label>
            <select v-model="backgroundVideo">
              <option value="">Auto (random)</option>
              <option v-for="bg in content.background_videos" :key="bg" :value="bg">{{ bg }}</option>
            </select>
          </div>
        </div>
      </div>

      <!-- Sections -->
      <div class="card sections-card">
        <div class="sections-header">
          <h2>Sections</h2>
          <button class="btn-add-section" @click="addSection">+ Add Section</button>
        </div>

        <div v-if="sections.length === 0" class="empty-sections">
          No sections yet. Add a section to start selecting openings.
        </div>

        <div v-for="(section, sIndex) in sections" :key="sIndex" class="section-item" :class="'section-' + section.difficulty">
          <div class="section-header">
            <div class="section-title">
              <span class="section-badge" :class="section.difficulty">{{ section.difficulty.toUpperCase() }}</span>
              <span>Section {{ sIndex + 1 }} ({{ section.openings.length }} openings)</span>
            </div>
            <div class="section-actions">
              <button class="btn-settings" @click="openSectionSettings(sIndex)">⚙️ Settings</button>
              <button class="btn-add" @click="openModal(sIndex)">+ Add Openings</button>
              <button class="btn-remove" @click="removeSection(sIndex)">🗑️</button>
            </div>
          </div>

          <!-- Section Settings (collapsible) -->
          <div v-if="section.showSettings" class="section-settings">
            <div class="settings-row">
              <div class="setting-group">
                <label>Difficulty</label>
                <select v-model="section.difficulty">
                  <option value="easy">Easy</option>
                  <option value="medium">Medium</option>
                  <option value="hard">Hard</option>
                </select>
              </div>
              <div class="setting-group">
                <label>
                  <input type="checkbox" v-model="section.overrideDuration" />
                  Override Duration
                </label>
                <input
                  v-if="section.overrideDuration"
                  type="number"
                  v-model.number="section.audioDuration"
                  min="1" max="15"
                />
              </div>
              <div class="setting-group">
                <label>
                  <input type="checkbox" v-model="section.overrideStartTime" />
                  Override Start Time
                </label>
                <input
                  v-if="section.overrideStartTime"
                  type="number"
                  v-model.number="section.startTime"
                  min="0"
                />
              </div>
              <div class="setting-group">
                <label>
                  <input type="checkbox" v-model="section.overrideContinueAudio" />
                  Override Continue Audio
                </label>
                <select v-if="section.overrideContinueAudio" v-model="section.continueAudio">
                  <option :value="true">Yes</option>
                  <option :value="false">No</option>
                </select>
              </div>
            </div>
          </div>

          <!-- Section Openings Preview -->
          <div class="section-openings" v-if="section.openings.length > 0">
            <div
              v-for="(op, opIndex) in section.openings"
              :key="opIndex"
              class="opening-item"
            >
              <div class="opening-poster-thumb">
                <img v-if="op.poster" :src="'/api/media/posters/' + op.poster" :alt="op.animeName" />
                <div v-else class="no-poster-thumb">?</div>
              </div>
              <div class="opening-item-info">
                <div class="opening-item-name">{{ op.animeName }}</div>
                <div class="opening-item-op">{{ op.opNumber }}</div>
              </div>
              <select
                class="poster-select"
                :value="op.poster || ''"
                @change="updatePoster(sIndex, opIndex, $event.target.value)"
              >
                <option value="">No poster</option>
                <option v-for="poster in getPostersForAnime(op.animeName)" :key="poster" :value="poster">
                  {{ poster }}
                </option>
                <optgroup label="All posters" v-if="content.posters.length > 0">
                  <option v-for="poster in content.posters" :key="'all-' + poster" :value="poster">
                    {{ poster }}
                  </option>
                </optgroup>
              </select>
              <button class="btn-remove-item" @click="removeOpening(sIndex, opIndex)">×</button>
            </div>
          </div>
        </div>
      </div>

      <!-- Generate Button -->
      <div class="card">
        <button class="btn-generate" @click="generate" :disabled="generating || !canGenerate">
          {{ generating ? 'Generating...' : 'Generate Video' }}
        </button>

        <div v-if="generating" class="progress-container">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progress + '%' }"></div>
          </div>
          <p class="progress-text">{{ progressMessage }}</p>
        </div>

        <div v-if="error" class="error-message">{{ error }}</div>
      </div>

      <!-- Result -->
      <div v-if="result" class="card result-card">
        <h3>Video Generated!</h3>
        <video class="video-preview" :src="'/api' + result.video_url" controls></video>
        <a class="btn-download" :href="'/api/download/' + result.filename" :download="result.filename">
          Download Video
        </a>
      </div>
    </main>

    <!-- Modal for Opening Selection -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal">
        <div class="modal-header">
          <h2>Select Openings for Section {{ currentSectionIndex + 1 }}</h2>
          <button class="modal-close" @click="closeModal">×</button>
        </div>

        <div class="modal-search">
          <input type="text" v-model="searchQuery" placeholder="Search anime..." />
        </div>

        <div class="modal-body">
          <div class="openings-grid">
            <div
              v-for="opening in filteredOpenings"
              :key="opening.filename"
              class="opening-card"
              :class="{ selected: isOpeningSelected(opening.filename) }"
              @click="toggleOpeningSelection(opening)"
            >
              <div class="card-poster">
                <img v-if="opening.associatedPoster" :src="'/api/media/posters/' + opening.associatedPoster" :alt="opening.animeName" />
                <div v-else class="no-poster">No Poster</div>
              </div>
              <div class="card-info">
                <div class="card-anime">{{ opening.animeName }}</div>
                <div class="card-op">{{ opening.opNumber }}</div>
                <div class="card-song" v-if="opening.songName">{{ opening.songName }}</div>
              </div>
              <div class="card-check" v-if="isOpeningSelected(opening.filename)">✓</div>

              <!-- Poster selector -->
              <div class="poster-selector" v-if="isOpeningSelected(opening.filename) && opening.availablePosters.length > 1" @click.stop>
                <select v-model="selectedPosters[opening.filename]" @change="updateOpeningPoster(opening.filename)">
                  <option v-for="poster in opening.availablePosters" :key="poster" :value="poster">
                    {{ poster }}
                  </option>
                </select>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <div class="selection-count">{{ tempSelectedOpenings.length }} selected</div>
          <button class="btn-cancel" @click="closeModal">Cancel</button>
          <button class="btn-confirm" @click="confirmSelection" :disabled="tempSelectedOpenings.length === 0">
            Add to Section
          </button>
        </div>
      </div>
    </div>
    </div>

    <!-- Media Manager -->
    <MediaManager v-if="currentPage === 'media'" />

    <!-- Admin Page (Upload Files) -->
    <AdminPage v-if="currentPage === 'admin'" />

    <!-- Openings Downloader -->
    <OpeningsDownloader v-if="currentPage === 'downloader'" />
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import AdminPage from './components/AdminPage.vue'
import MediaManager from './components/MediaManager.vue'
import OpeningsDownloader from './components/OpeningsDownloader.vue'

const STORAGE_KEY = 'animeQuizSettings'

export default {
  name: 'App',
  components: {
    AdminPage,
    MediaManager,
    OpeningsDownloader
  },
  setup() {
    // Navigation
    const currentPage = ref('quiz')
    // Load saved settings from localStorage
    const loadSettings = () => {
      try {
        const saved = localStorage.getItem(STORAGE_KEY)
        if (saved) {
          return JSON.parse(saved)
        }
      } catch (e) {
        console.error('Failed to load settings:', e)
      }
      return null
    }

    const savedSettings = loadSettings()

    // Global settings
    const mode = ref(savedSettings?.mode || 'shorts')
    const defaultAudioDuration = ref(savedSettings?.defaultAudioDuration || 5)
    const defaultStartTime = ref(savedSettings?.defaultStartTime || 30)
    const defaultContinueAudio = ref(savedSettings?.defaultContinueAudio || false)
    const backgroundVideo = ref(savedSettings?.backgroundVideo || '')

    // State
    const generating = ref(false)
    const progress = ref(0)
    const progressMessage = ref('')
    const error = ref('')
    const result = ref(null)
    const healthStatus = ref(null)

    // Content from backend
    const content = reactive({
      audio_files: [],
      background_videos: [],
      posters: []
    })

    // Sections
    const sections = ref(savedSettings?.sections || [])

    // Save settings to localStorage
    const saveSettings = () => {
      try {
        const settings = {
          mode: mode.value,
          defaultAudioDuration: defaultAudioDuration.value,
          defaultStartTime: defaultStartTime.value,
          defaultContinueAudio: defaultContinueAudio.value,
          backgroundVideo: backgroundVideo.value,
          sections: sections.value
        }
        localStorage.setItem(STORAGE_KEY, JSON.stringify(settings))
      } catch (e) {
        console.error('Failed to save settings:', e)
      }
    }

    // Watch for changes and save
    watch([mode, defaultAudioDuration, defaultStartTime, defaultContinueAudio, backgroundVideo], saveSettings)
    watch(sections, saveSettings, { deep: true })

    // Modal state
    const showModal = ref(false)
    const currentSectionIndex = ref(-1)
    const searchQuery = ref('')
    const tempSelectedOpenings = ref([])
    const selectedPosters = reactive({})

    // Parse audio filename: "anime name_opnum_song name.mp3"
    const parseAudioFilename = (filename) => {
      const nameWithoutExt = filename.replace(/\.[^/.]+$/, '')
      const parts = nameWithoutExt.split('_')

      if (parts.length >= 2) {
        return {
          animeName: parts[0],
          opNumber: parts[1] || 'OP',
          songName: parts.slice(2).join(' ') || ''
        }
      }
      return {
        animeName: nameWithoutExt,
        opNumber: 'OP',
        songName: ''
      }
    }

    // Find associated posters for an anime
    const findAssociatedPosters = (animeName) => {
      const normalizedAnimeName = animeName.toLowerCase()
      return content.posters.filter(poster => {
        const normalizedPoster = poster.toLowerCase()
        return normalizedPoster.includes(normalizedAnimeName)
      })
    }

    // Processed openings with parsed info
    const processedOpenings = computed(() => {
      return content.audio_files.map(filename => {
        const parsed = parseAudioFilename(filename)
        const availablePosters = findAssociatedPosters(parsed.animeName)
        return {
          filename,
          animeName: parsed.animeName,
          opNumber: parsed.opNumber,
          songName: parsed.songName,
          availablePosters,
          associatedPoster: availablePosters[0] || null
        }
      })
    })

    // Filtered openings for search
    const filteredOpenings = computed(() => {
      if (!searchQuery.value) return processedOpenings.value
      const query = searchQuery.value.toLowerCase()
      return processedOpenings.value.filter(op =>
        op.animeName.toLowerCase().includes(query) ||
        op.songName.toLowerCase().includes(query)
      )
    })

    // All selected openings across sections (for sidebar)
    const allSelectedOpenings = computed(() => {
      const result = []
      sections.value.forEach((section, sIndex) => {
        section.openings.forEach((op, opIndex) => {
          result.push({
            ...op,
            difficulty: section.difficulty,
            sectionIndex: sIndex,
            openingIndex: opIndex
          })
        })
      })
      return result
    })

    // Difficulty counts
    const difficultyCount = computed(() => {
      const counts = { easy: 0, medium: 0, hard: 0 }
      allSelectedOpenings.value.forEach(op => {
        counts[op.difficulty]++
      })
      return counts
    })

    // Can generate
    const canGenerate = computed(() => {
      return allSelectedOpenings.value.length > 0
    })

    // Section management
    const getNextDifficulty = () => {
      const count = sections.value.length
      if (count === 0) return 'easy'
      if (count === 1) return 'medium'
      return 'hard'
    }

    const addSection = () => {
      sections.value.push({
        difficulty: getNextDifficulty(),
        openings: [],
        showSettings: false,
        overrideDuration: false,
        audioDuration: defaultAudioDuration.value,
        overrideStartTime: false,
        startTime: defaultStartTime.value,
        overrideContinueAudio: false,
        continueAudio: defaultContinueAudio.value
      })
    }

    const removeSection = (index) => {
      sections.value.splice(index, 1)
    }

    const openSectionSettings = (index) => {
      sections.value[index].showSettings = !sections.value[index].showSettings
    }

    // Modal functions
    const openModal = (sectionIndex) => {
      currentSectionIndex.value = sectionIndex
      tempSelectedOpenings.value = []
      searchQuery.value = ''
      showModal.value = true
    }

    const closeModal = () => {
      showModal.value = false
      currentSectionIndex.value = -1
      tempSelectedOpenings.value = []
    }

    const isOpeningSelected = (filename) => {
      return tempSelectedOpenings.value.some(op => op.filename === filename)
    }

    const toggleOpeningSelection = (opening) => {
      const index = tempSelectedOpenings.value.findIndex(op => op.filename === opening.filename)
      if (index >= 0) {
        tempSelectedOpenings.value.splice(index, 1)
        delete selectedPosters[opening.filename]
      } else {
        tempSelectedOpenings.value.push({ ...opening })
        if (opening.associatedPoster) {
          selectedPosters[opening.filename] = opening.associatedPoster
        }
      }
    }

    const updateOpeningPoster = (filename) => {
      const opening = tempSelectedOpenings.value.find(op => op.filename === filename)
      if (opening) {
        opening.associatedPoster = selectedPosters[filename]
      }
    }

    const confirmSelection = () => {
      const section = sections.value[currentSectionIndex.value]
      tempSelectedOpenings.value.forEach(op => {
        // Check if already in section
        if (!section.openings.some(existing => existing.filename === op.filename)) {
          section.openings.push({
            filename: op.filename,
            animeName: op.animeName,
            opNumber: op.opNumber,
            songName: op.songName,
            poster: selectedPosters[op.filename] || op.associatedPoster
          })
        }
      })
      closeModal()
    }

    const removeOpening = (sectionIndex, openingIndex) => {
      sections.value[sectionIndex].openings.splice(openingIndex, 1)
    }

    const removeFromSection = (sectionIndex, openingIndex) => {
      sections.value[sectionIndex].openings.splice(openingIndex, 1)
    }

    // Get posters associated with anime name
    const getPostersForAnime = (animeName) => {
      const normalizedName = animeName.toLowerCase()
      return content.posters.filter(poster =>
        poster.toLowerCase().includes(normalizedName)
      )
    }

    // Update poster for an opening in a section
    const updatePoster = (sectionIndex, openingIndex, poster) => {
      sections.value[sectionIndex].openings[openingIndex].poster = poster || null
    }

    // Validate saved settings against available content
    const validateSettings = () => {
      // Check background video
      if (backgroundVideo.value && !content.background_videos.includes(backgroundVideo.value)) {
        backgroundVideo.value = ''
      }

      // Check sections openings
      sections.value.forEach(section => {
        // Filter out openings with non-existent audio files
        section.openings = section.openings.filter(op =>
          content.audio_files.includes(op.filename)
        )

        // Clear invalid posters
        section.openings.forEach(op => {
          if (op.poster && !content.posters.includes(op.poster)) {
            op.poster = null
          }
        })
      })

      // Remove empty sections
      sections.value = sections.value.filter(section => section.openings.length > 0)
    }

    // API functions
    const fetchContent = async () => {
      try {
        const response = await fetch('/api/content')
        const data = await response.json()
        content.audio_files = data.audio_files
        content.background_videos = data.background_videos
        content.posters = data.posters

        // Validate saved settings after content is loaded
        validateSettings()
      } catch (e) {
        console.error('Failed to fetch content:', e)
      }
    }

    const checkHealth = async () => {
      try {
        const response = await fetch('/api/health')
        healthStatus.value = await response.json()
      } catch (e) {
        healthStatus.value = { status: 'error', ffmpeg: false }
      }
    }

    const generate = async () => {
      error.value = ''
      result.value = null
      generating.value = true
      progress.value = 10
      progressMessage.value = 'Preparing video generation...'

      try {
        // Build questions from sections
        const questions = []
        sections.value.forEach(section => {
          const audioDuration = section.overrideDuration ? section.audioDuration : defaultAudioDuration.value
          const startTime = section.overrideStartTime ? section.startTime : defaultStartTime.value
          const continueAudio = section.overrideContinueAudio ? section.continueAudio : defaultContinueAudio.value

          section.openings.forEach(op => {
            questions.push({
              anime: op.animeName,
              opening_file: op.filename,
              start_time: startTime,
              difficulty: section.difficulty,
              poster: op.poster || null,
              // Per-question settings (need backend update for this)
              audio_duration: audioDuration,
              continue_audio: continueAudio
            })
          })
        })

        const payload = {
          mode: mode.value,
          questions,
          audio_duration: defaultAudioDuration.value,
          background_video: backgroundVideo.value || null,
          continue_audio: defaultContinueAudio.value
        }

        progress.value = 30
        progressMessage.value = 'Generating video (this may take a few minutes)...'

        const response = await fetch('/api/generate', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        })

        const data = await response.json()

        if (data.success) {
          progress.value = 100
          progressMessage.value = 'Video generated successfully!'
          result.value = data
        } else {
          throw new Error(data.error || 'Generation failed')
        }
      } catch (e) {
        error.value = e.message
      } finally {
        generating.value = false
      }
    }

    onMounted(() => {
      checkHealth()
      fetchContent()
    })

    return {
      // Navigation
      currentPage,
      // Global settings
      mode,
      defaultAudioDuration,
      defaultStartTime,
      defaultContinueAudio,
      backgroundVideo,
      // State
      generating,
      progress,
      progressMessage,
      error,
      result,
      healthStatus,
      content,
      // Sections
      sections,
      addSection,
      removeSection,
      openSectionSettings,
      // Modal
      showModal,
      currentSectionIndex,
      searchQuery,
      tempSelectedOpenings,
      selectedPosters,
      filteredOpenings,
      openModal,
      closeModal,
      isOpeningSelected,
      toggleOpeningSelection,
      updateOpeningPoster,
      confirmSelection,
      removeOpening,
      removeFromSection,
      getPostersForAnime,
      updatePoster,
      // Computed
      allSelectedOpenings,
      difficultyCount,
      canGenerate,
      // Actions
      generate
    }
  }
}
</script>

<style>
/* Import base styles then add component-specific */
</style>
