<script setup>
// Topic-wide mixed exam: picks a block (prioritized: not yet at max), then random
// within it, and reuses the normal BlockPanel. Each block has its own exam slot
// (pruefungCache), so the question pools stay separate. Booking runs per block via the
// normal exam route. Total cap = Σ cap_final of all checkable blocks.
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { fetchGuides, fetchGuideContent, fetchBlockLearnState } from '../api.js'
import BlockPanel from './BlockPanel.vue'

const props = defineProps({
  topic: { type: String, required: true },
  provider: { type: String, default: 'claude' },
})
const emit = defineEmits(['progressChanged', 'fokus-active'])

const sections = ref([])   // [{title, md, compact, num}] — checkable sections of the full version
const learnstate = ref({})  // title -> {good_answers, streak, cap, cap_aktuell, freie_level}
const active = ref(null)    // current block title
const loadError = ref(null)

const checkable = computed(() => sections.value.filter((s) => (learnstate.value[s.title]?.cap || 0) > 0))

// Total progress: Σ min(score, cap_final) / Σ cap_final over all checkable blocks.
const total = computed(() => {
  let score = 0, cap = 0
  for (const s of checkable.value) {
    const l = learnstate.value[s.title] || {}
    score += Math.min(l.good_answers || 0, l.cap || 0)
    cap += l.cap || 0
  }
  return { score, cap }
})

const activeSection = computed(() => sections.value.find((s) => s.title === active.value) || null)
const activeStatus = computed(() => learnstate.value[active.value] || null)

// Priority: blocks not yet at cap_final; among those random.
function pickBlock() {
  const unfinished = checkable.value.filter((s) => {
    const l = learnstate.value[s.title] || {}
    return (l.good_answers || 0) < (l.cap || 0)
  })
  const pool = unfinished.length ? unfinished : checkable.value
  active.value = pool.length ? pool[Math.floor(Math.random() * pool.length)].title : null
}

async function loadLearnState() {
  try {
    learnstate.value = (await fetchBlockLearnState(props.topic)).blocks || {}
  } catch { /* offline → keep old state */ }
}

onMounted(async () => {
  emit('fokus-active', true)
  try {
    const guides = await fetchGuides()
    const g = guides
      .filter((x) => x.topic === props.topic && x.format === 'Guide' && x.status === 'done')
      .sort((a, b) => (a.created_at < b.created_at ? 1 : -1))[0]
    if (!g) { loadError.value = 'No finished guide — create a guide first.'; return }
    const content = await fetchGuideContent(g.id, 4)  // full version (all subs)
    sections.value = (content.chapters || [])
      .flatMap((ch) => ch.sections || [])
      .filter((s) => s.checkable !== false)
      .map((s) => ({ title: s.title, md: s.md, compact: s.compact, num: s.num }))
    await loadLearnState()
    pickBlock()
  } catch {
    loadError.value = 'Could not load the exam.'
  }
})

onUnmounted(() => emit('fokus-active', false))

async function onStatus() {
  await loadLearnState()  // cap_aktuell/freie_level may have grown after an answer
  emit('progressChanged')
}
</script>

<template>
  <div class="ge-panel">
    <div class="ge-head">
      <h2>General Exam</h2>
      <span v-if="!loadError" class="ge-score">{{ total.score }} / {{ total.cap }}</span>
      <button v-if="active" class="ge-next" title="Check another block" @click="pickBlock">⟳ Another block</button>
    </div>

    <p v-if="loadError" class="ge-msg">{{ loadError }}</p>
    <p v-else-if="!checkable.length" class="ge-msg">No checkable blocks yet.</p>
    <p v-else-if="!active" class="ge-msg">Everything maxed out — nothing left to check. 🎉</p>

    <div v-else class="ge-body">
      <div class="ge-block">Block: <strong>{{ active }}</strong></div>
      <BlockPanel
        :key="active"
        mode="full"
        :topic="topic"
        :block="active"
        :section="activeSection?.md || ''"
        :section-compact="activeSection?.compact || ''"
        :provider="provider"
        :status="activeStatus"
        :cap="activeStatus?.cap || 0"
        @statusChanged="onStatus"
      />
    </div>
  </div>
</template>

<style scoped>
.ge-panel { padding: 16px 20px; max-width: 900px; margin: 0 auto; }
.ge-head { display: flex; align-items: center; gap: 14px; margin-bottom: 12px; }
.ge-head h2 { margin: 0; font-size: 1.1rem; }
.ge-score { font-variant-numeric: tabular-nums; color: var(--text-muted); font-weight: 600; }
.ge-next { margin-left: auto; padding: 5px 10px; border: 1px solid var(--border-strong); border-radius: 6px; background: var(--bg); cursor: pointer; }
.ge-next:hover { color: var(--accent-hover); }
.ge-msg { color: var(--text-muted); }
.ge-block { margin-bottom: 8px; color: var(--text-muted); font-size: 0.9rem; }
</style>
