<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { fetchBlocksOverview, fetchBlocksBoard } from '../api.js'
import KanbanBoard from './KanbanBoard.vue'

const props = defineProps({
  topic: { type: String, required: true },
  generating: { type: Boolean, default: false },
  progress: { type: String, default: null },
  ready: { type: Boolean, default: false },
  partial: { type: Boolean, default: false },
})
const emit = defineEmits(['close', 'resetStage', 'restartAll', 'continueAll', 'addResearch', 'requeueDead', 'removeAll', 'cancel'])

// ── Live-Kanban-Board (Poll 1.2s solange generiert) ────────────────────────────
// State ZUERST deklarieren: die immediate-Watches unten rufen load() synchron beim
// Setup — spätere const-Deklarationen wären dort noch TDZ (ReferenceError).
const board = ref(null)
const items = ref([])
const loading = ref(true)
const error = ref(null)
let timer = null
let lastDone = -1

async function pollBoard() {
  try {
    board.value = await fetchBlocksBoard(props.topic)
    if (board.value.done !== lastDone) {  // neue fertige Blöcke → Grid live nachladen
      lastDone = board.value.done
      load()
    }
  } catch { /* Board noch leer */ }
}

function startPoll() {
  stopPoll()
  timer = setInterval(pollBoard, 1200)
}
function stopPoll() {
  if (timer) { clearInterval(timer); timer = null }
}

watch(() => props.topic, () => { board.value = null; lastDone = -1; pollBoard(); load() }, { immediate: true })
watch(() => props.generating, (g) => {
  if (g) startPoll()
  else { stopPoll(); pollBoard(); load() }  // Endstand + fertige Blöcke nachladen
}, { immediate: true })
onUnmounted(stopPoll)

const inventoryCols = computed(() => (board.value?.columns || []).filter((c) => c.board === 'inventory'))
const artefactCols = computed(() => (board.value?.columns || []).filter((c) => c.board === 'artefacts'))
const boardEmpty = computed(() => !(board.value?.columns || []).some((c) => c.total > 0))
const dead = computed(() => board.value?.dead || [])

// Spalten, auf die zurückgesetzt werden kann (Terminal-Spalten sind kein Reset-Ziel).
const RESETTABLE = new Set(['ingest', 'cluster', 'pair_check', 'consensus_gate', 'clarify', 'naming',
  'naming_check', 'fragment_filter', 'grouping', 'gap_check', 'done',
  'subblocks', 'facts', 'levels', 'relevance', 'question_pattern', 'artefacts', 'finalize', 'outline'])
const sel = ref(null)          // gewählte Spalte {board, key, label}
const confirm = ref(null)      // 2-Klick-Bestätigung für destruktive Aktionen

function stageClick(c) {
  if (props.generating || !RESETTABLE.has(c.key)) return
  confirm.value = null
  sel.value = sel.value?.key === c.key ? null : { board: c.board, key: c.key, label: c.label }
}
function arm(action, fn) {
  if (confirm.value === action) { confirm.value = null; fn() }
  else confirm.value = action
}
function resetHere(restart) {
  const s = sel.value
  sel.value = null
  confirm.value = null
  emit('resetStage', { board: s.board, stage: s.key, restart })
}

// ── Fertige Blöcke (Grid) ──────────────────────────────────────────────────────
const LEVELS = [
  { key: 'beginner', label: 'Beginner' },
  { key: 'advanced', label: 'Advanced' },
  { key: 'expert', label: 'Expert' },
]
const LEGACY_LEVEL = { einfach: 'beginner', mittel: 'advanced', schwer: 'expert' }

async function load() {
  if (!items.value.length) loading.value = true  // Spinner nur beim Erstladen, Live-Reload flackert nicht
  error.value = null
  try {
    items.value = await fetchBlocksOverview(props.topic)
  } catch (e) {
    items.value = []
    error.value = 'Overview not available — create blocks first.'
  } finally {
    loading.value = false
  }
}

function relevant(b) {
  const withRelevance = (b.subblocks || []).filter((s) => s.relevance)
  return !withRelevance.length || withRelevance.some((s) => s.relevance === 'relevant')
}

function groups(b) {
  return LEVELS
    .map((st) => ({ ...st, subs: (b.subblocks || []).filter((s) => (LEGACY_LEVEL[s.level] || s.level) === st.key) }))
    .filter((g) => g.subs.length)
}

const subTotal = computed(() => items.value.reduce((n, b) => n + (b.subblocks?.length || 0), 0))
</script>

<template>
  <div class="bk-view">
    <header class="bk-head">
      <h1>{{ topic }}</h1>
      <span class="bk-sub">Blocks overview</span>
      <span v-if="items.length" class="bk-count">{{ items.length }} Blocks · {{ subTotal }} Subblocks</span>
      <span class="bk-spacer"></span>
      <button class="bk-close" title="Close" @click="emit('close')">✕</button>
    </header>

    <section class="bk-board">
      <div class="bk-steps-top">
        <div v-if="progress" class="bk-progress"><span class="bk-progress-dot"></span>{{ progress }}</div>
        <div v-if="!generating" class="bk-global-actions">
          <button class="bk-act play" @click="emit('restartAll')">{{ ready || partial ? '+ Research' : 'Generate' }}</button>
          <button v-if="partial" class="bk-act" @click="emit('continueAll')">Continue</button>
          <button
            v-if="dead.length"
            class="bk-act"
            :title="dead.map((d) => d.title + ': ' + d.error).join('\n')"
            @click="emit('requeueDead')"
          >⟳ {{ dead.length }} dead</button>
          <button
            v-if="ready || partial"
            class="bk-act danger"
            :class="{ armed: confirm === 'remove' }"
            @click="arm('remove', () => emit('removeAll'))"
          >{{ confirm === 'remove' ? 'Sure?' : 'Remove' }}</button>
        </div>
        <div v-else class="bk-global-actions">
          <button class="bk-act" @click="emit('addResearch')">+ Research</button>
          <button class="bk-act danger" @click="emit('cancel')">Cancel</button>
        </div>
      </div>

      <div v-if="boardEmpty && !generating" class="bk-board-empty">No board yet — generation streams live cards through the columns here.</div>
      <template v-else>
        <div class="bk-board-label">Inventar</div>
        <KanbanBoard
          :columns="inventoryCols"
          :agents="board?.agents || []"
          :generating="generating"
          :selectable="!generating"
          :selectedKey="sel?.board === 'inventory' ? sel.key : null"
          @stageClick="stageClick"
        />
        <div class="bk-board-label">Artefakte</div>
        <KanbanBoard
          :columns="artefactCols"
          :generating="generating"
          :selectable="!generating"
          :selectedKey="sel?.board === 'artefacts' ? sel.key : null"
          @stageClick="stageClick"
        />
      </template>

      <div v-if="sel && !generating" class="bk-step-actions">
        <span class="bk-step-actions-label">Ab «{{ sel.label }}»:</span>
        <button class="bk-act play" @click="resetHere(true)">↻ neu generieren</button>
        <button class="bk-act danger" :class="{ armed: confirm === 'reset' }" @click="arm('reset', () => resetHere(false))">{{ confirm === 'reset' ? 'Sure?' : '✕ nur zurücksetzen' }}</button>
        <button class="bk-act ghost" @click="sel = null; confirm = null">Abbrechen</button>
      </div>
    </section>

    <div v-if="loading" class="bk-empty-state">Loading…</div>
    <div v-else-if="error && !generating" class="bk-empty-state">{{ error }}</div>
    <div v-else-if="!items.length" class="bk-empty-state">No blocks yet.</div>

    <div v-else class="bk-grid">
      <article
        v-for="b in items"
        :key="b.num"
        class="bk-card"
        :class="{ 'bk-irrelevant': !relevant(b) }"
        :title="relevant(b) ? null : 'Not relevant — comes later in the &quot;Rest&quot;'"
      >
        <h3 class="bk-title"><span class="bk-num">{{ b.num }}</span>{{ b.title }}</h3>
        <p v-if="b.description" class="bk-desc">{{ b.description }}</p>
        <div v-if="b.subblocks && b.subblocks.length" class="bk-levels">
          <div v-for="g in groups(b)" :key="g.key" class="bk-level" :class="'st-' + g.key">
            <span class="bk-level-label">{{ g.label }}</span>
            <ul>
              <li v-for="s in g.subs" :key="s.title" :class="{ rand: s.relevance === 'peripheral' }">
                {{ s.title }}<span v-if="s.relevance === 'peripheral'" class="rand-tag" title="Peripheral topic — comes later in the 'Rest'">Edge</span>
              </li>
            </ul>
          </div>
        </div>
        <p v-else class="bk-no-subs">No subblocks.</p>
      </article>
    </div>
  </div>
</template>

<style scoped>
.bk-view {
  flex: 1;
  min-width: 0;
  height: 100dvh;
  display: flex;
  flex-direction: column;
  overflow-y: auto;   /* EIN Seitenfluss: Board scrollt mit, nur der Kopf bleibt stehen */
  background: var(--bg-preview);
}

.bk-head {
  position: sticky;
  top: 0;
  z-index: 3;
  display: flex;
  align-items: baseline;
  gap: 0.75rem;
  padding: 1.25rem 2rem;
  border-bottom: 1px solid var(--border);
  background: var(--panel);
}
.bk-head h1 { font-size: 1.5rem; }
.bk-sub { color: var(--text-faint); font-size: 0.9rem; font-weight: 600; }
.bk-count { color: var(--text-muted); font-size: 0.82rem; }
.bk-spacer { flex: 1; }
.bk-close {
  align-self: center;
  border: 1px solid var(--border-strong);
  border-radius: 6px;
  background: var(--panel);
  color: var(--text);
  width: 2rem;
  height: 2rem;
  cursor: pointer;
}
.bk-close:hover { border-color: var(--accent); }

/* Live board above the blocks */
.bk-board {
  padding: 0.85rem 2rem;
  border-bottom: 1px solid var(--border);
  background: var(--panel-soft);
}
.bk-board-label {
  font-size: 0.64rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-faint);
  margin: 0.5rem 0 0.3rem;
}
.bk-board-empty { color: var(--text-faint); font-size: 0.82rem; padding: 0.4rem 0; }
.bk-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.84rem;
  color: var(--accent);
  font-weight: 600;
}
.bk-progress-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--accent);
  animation: bk-pulse 1.2s ease-in-out infinite;
}
@keyframes bk-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }

.bk-steps-top { display: flex; align-items: center; gap: 1rem; min-height: 1.9rem; margin-bottom: 0.4rem; }
.bk-global-actions { margin-left: auto; display: flex; gap: 0.4rem; }

.bk-step-actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.75rem;
  padding-top: 0.7rem;
  border-top: 1px dashed var(--border-strong);
}
.bk-step-actions-label { font-size: 0.8rem; font-weight: 600; color: var(--text-muted); }

.bk-act {
  border: 1px solid var(--border-strong);
  border-radius: 6px;
  background: var(--panel);
  color: var(--text);
  font-size: 0.8rem;
  padding: 0.3rem 0.7rem;
  cursor: pointer;
  font-weight: 600;
}
.bk-act:hover { border-color: var(--accent); }
.bk-act.play { background: var(--accent); color: var(--on-accent); border-color: var(--accent); }
.bk-act.play:hover { background: var(--accent-hover); }
.bk-act.danger { color: var(--danger); border-color: var(--danger); background: transparent; }
.bk-act.danger.armed { background: var(--danger); color: #fff; }
.bk-act.ghost { color: var(--text-muted); }

.bk-empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
}

.bk-grid {
  flex: 1;
  padding: 1.5rem 2rem 4rem;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 1rem;
  align-content: start;
}

.bk-card {
  background: var(--panel);
  border: 1px solid var(--border);
  border-top: 3px solid var(--accent-border);
  border-radius: 10px;
  padding: 1rem 1.1rem;
}
.bk-card.bk-irrelevant { opacity: 0.5; }

.bk-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1rem;
  margin-bottom: 0.4rem;
}
.bk-num {
  flex: 0 0 auto;
  min-width: 26px;
  height: 26px;
  padding: 0 6px;
  border-radius: 7px;
  background: var(--accent);
  color: var(--on-accent);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 0.78rem;
  font-weight: 700;
}
.bk-desc {
  color: var(--text-muted);
  font-size: 0.85rem;
  line-height: 1.45;
  margin-bottom: 0.7rem;
}

.bk-levels { display: flex; flex-direction: column; gap: 0.55rem; }
.bk-level {
  border-left: 3px solid var(--st);
  padding-left: 0.6rem;
}
.bk-level.st-beginner { --st: var(--level-beginner); }
.bk-level.st-advanced { --st: var(--level-advanced); }
.bk-level.st-expert { --st: var(--level-expert); }

.bk-level-label {
  font-size: 0.66rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: var(--st);
}
.bk-level ul {
  list-style: disc;
  margin: 0.25rem 0 0;
  padding-left: 1.15rem;
}
.bk-level li {
  font-size: 0.85rem;
  color: var(--text);
  line-height: 1.35;
  margin-bottom: 2px;
}
.bk-level li::marker { color: var(--text-faint); }
.bk-level li.rand { color: var(--text-faint); }
.rand-tag {
  margin-left: 0.4rem;
  font-size: 0.6rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.03em;
  color: var(--text-faint);
  border: 1px solid var(--border-strong);
  border-radius: 4px;
  padding: 0 4px;
}

.bk-no-subs { color: var(--text-faint); font-size: 0.8rem; font-style: italic; }
</style>
