<script setup lang="ts">
import { ref } from 'vue'
import { Panel, ResizeHandle } from 'mpr-ui-framework'
import 'mpr-ui-framework/src/tokens.css'
import LogPanel from './panels/LogPanel.vue'
import FunnelPanel from './panels/FunnelPanel.vue'
import PipelineGraphPanel from './panels/PipelineGraphPanel.vue'
import FramePanel from './panels/FramePanel.vue'
import BrandTablePanel from './panels/BrandTablePanel.vue'
import TimelinePanel from './panels/TimelinePanel.vue'
import CostStatsPanel from './panels/CostStatsPanel.vue'
import SourceSelector from './panels/SourceSelector.vue'
import StageConfigSliders from './components/StageConfigSliders.vue'
import FrameStrip from './components/FrameStrip.vue'
import { usePipelineStore } from './stores/pipeline'
import { useSSEConnection } from './composables/useSSEConnection'
import { useCheckpointLoader } from './composables/useCheckpointLoader'
import { useEditorState } from './composables/useEditorState'

const pipeline = usePipelineStore()
const logPanel = ref<{ clear: () => void } | null>(null)

// SSE connection + pipeline status
const {
  jobId, stats, runContext, status, sseConnected, source,
  stopPipeline, onJobStarted: sseJobStarted,
} = useSSEConnection()

// Checkpoint frames + navigation
const {
  currentFrameImage, currentFrameRef,
  checkpointFrames, checkpointFrameIndex,
  stripSelStart, stripSelEnd, stripSelEndOverride,
  setCheckpointFrame: cpSetFrame,
} = useCheckpointLoader(jobId, source)

// Editor overlays + CV result accumulation
const {
  editorOverlays, editorBoxes,
  updateDisplayForFrame, onReplayResult,
} = useEditorState(currentFrameRef)

// Wire checkpoint frame change to editor display update
function setCheckpointFrame(index: number) {
  cpSetFrame(index)
  const frame = checkpointFrames.value[index]
  if (frame) updateDisplayForFrame(frame.seq)
}

// Wire job start to clear log panel
function onJobStarted(newJobId: string) {
  logPanel.value?.clear()
  sseJobStarted(newJobId)
}

// Resizable splits
const pipelineWidth = ref(320)
const detectionsFlex = ref(3)
const viewerHeight = ref(240)
const timelineFlex = ref(1)
const tableFlex = ref(1)
const slidersWidth = ref(210)

function onPipelineResize(delta: number) {
  pipelineWidth.value = Math.max(200, Math.min(500, pipelineWidth.value + delta))
}

function onViewerResize(delta: number) {
  viewerHeight.value = Math.max(120, Math.min(400, viewerHeight.value + delta))
}

function onDetectionsResize(delta: number) {
  detectionsFlex.value = Math.max(1, Math.min(6, detectionsFlex.value + delta * 0.01))
}

function onTimelineResize(delta: number) {
  const shift = delta * 0.02
  timelineFlex.value = Math.max(0.3, Math.min(3, timelineFlex.value + shift))
  tableFlex.value = Math.max(0.3, Math.min(3, tableFlex.value - shift))
}

function onSlidersResize(delta: number) {
  slidersWidth.value = Math.max(210, Math.min(350, slidersWidth.value - delta))
}
</script>

<template>
  <div class="app">
    <header>
      <h1>Detection Pipeline</h1>
      <span class="status-badge" :class="status">{{ status }}</span>
      <span v-if="runContext" class="run-info">
        {{ runContext.run_type }} · run: {{ runContext.run_id }}
      </span>
      <button class="header-btn" title="Select source" @click="pipeline.openSourceSelector()">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
          <path d="M2 4h4l2 2h6v8H2V4z"/><path d="M2 4V2h12v2"/>
        </svg>
      </button>
      <button
        v-if="sseConnected && (status === 'live' || status === 'processing')"
        class="header-btn stop-btn"
        title="Stop pipeline"
        @click="stopPipeline"
      >■</button>
      <span class="job-id">job: {{ jobId || '—' }}</span>
    </header>

    <div class="main-layout">
      <!-- Left column: Pipeline control (full height) -->
      <div class="pipeline-col" :style="{ width: pipelineWidth + 'px' }">
        <PipelineGraphPanel :source="source" :status="status" />
      </div>
      <ResizeHandle direction="horizontal" @resize="onPipelineResize" />

      <!-- Right area: mode-dependent content -->
      <div class="content-col">

        <!-- === NORMAL MODE === -->
        <template v-if="pipeline.layoutMode === 'normal'">
          <div class="viewer-row" :style="{ height: viewerHeight + 'px' }">
            <FramePanel :source="source" :status="status" />
            <FunnelPanel :source="source" :status="status" />
          </div>
          <ResizeHandle direction="vertical" @resize="onViewerResize" />

          <div class="detections-stats-row">
            <div class="detections-col" :style="{ flex: detectionsFlex }">
              <Panel title="Detections" :status="status">
                <div class="detections-stack">
                  <div class="timeline-section" :style="{ flex: timelineFlex }">
                    <TimelinePanel :source="source" :status="status" :embedded="true" />
                  </div>
                  <ResizeHandle direction="vertical" @resize="onTimelineResize" />
                  <div class="table-section" :style="{ flex: tableFlex }">
                    <BrandTablePanel :source="source" :status="status" :embedded="true" />
                  </div>
                </div>
              </Panel>
            </div>
            <ResizeHandle direction="horizontal" @resize="onDetectionsResize" />
            <div class="stats-col">
              <Panel title="Pipeline" :status="status">
                <div class="pipeline-stats">
                  <div class="stat" v-for="s in [
                    { label: 'Frames', value: stats?.frames_extracted ?? '—' },
                    { label: 'After filter', value: stats?.frames_after_scene_filter ?? '—' },
                    { label: 'Regions', value: stats?.regions_detected ?? '—' },
                    { label: 'OCR resolved', value: stats?.regions_resolved_by_ocr ?? '—' },
                    { label: 'VLM escalated', value: stats?.regions_escalated_to_local_vlm ?? '—' },
                    { label: 'Cloud escalated', value: stats?.regions_escalated_to_cloud_llm ?? '—' },
                  ]" :key="s.label">
                    <span class="label">{{ s.label }}</span>
                    <span class="value">{{ s.value }}</span>
                  </div>
                </div>
              </Panel>
              <CostStatsPanel :source="source" :status="status" />
            </div>
          </div>
        </template>

        <!-- === BBOX EDITOR MODE === -->
        <template v-else-if="pipeline.layoutMode === 'bbox_editor'">
          <div class="editor-layout">
            <!-- Top: frame + sliders side by side -->
            <div class="editor-top">
              <div class="editor-frame">
                <FramePanel :source="source" :status="status" :overlays="editorOverlays" :frame-image="currentFrameImage" :editor-boxes="editorBoxes" />
              </div>
              <ResizeHandle direction="horizontal" @resize="onSlidersResize" />
              <div class="editor-sliders" :style="{ width: slidersWidth + 'px' }">
                <StageConfigSliders
                  v-if="pipeline.editorStage"
                  :stage="pipeline.editorStage"
                  :job-id="jobId"
                  :frame-image="currentFrameImage"
                  :frame-ref="currentFrameRef"
                  :frames="checkpointFrames"
                  :selection-start="stripSelStart"
                  :selection-end="stripSelEnd"
                  @replay-result="onReplayResult"
                />
              </div>
            </div>

            <!-- Frame strip: thumbnails + selection handles -->
            <FrameStrip
              v-if="checkpointFrames.length > 0"
              :frames="checkpointFrames"
              :current-index="checkpointFrameIndex"
              :selection-start="stripSelStart"
              :selection-end="stripSelEnd"
              @frame-click="setCheckpointFrame"
              @selection-change="(s, e) => { stripSelStart.value = s; stripSelEndOverride.value = e }"
            />

            <!-- Bottom: debug overlays + close -->
            <div class="editor-bottom">
              <div class="overlay-controls">
                <template v-if="editorOverlays.length > 0">
                  <label v-for="(overlay, idx) in editorOverlays" :key="idx" class="overlay-toggle">
                    <input type="checkbox" v-model="overlay.visible" />
                    <span class="overlay-label">{{ overlay.label }}</span>
                    <input
                      type="range"
                      min="0" max="1" step="0.05"
                      :value="overlay.opacity ?? 0.5"
                      @input="(e: Event) => overlay.opacity = Number((e.target as HTMLInputElement).value)"
                      class="opacity-slider"
                    />
                    <span class="opacity-value">{{ Math.round((overlay.opacity ?? 0.5) * 100) }}%</span>
                  </label>
                </template>
              </div>
              <button class="editor-close" @click="pipeline.closeEditor()">✕ Close</button>
            </div>
          </div>
        </template>

        <!-- === STAGE EDITOR MODE === -->
        <template v-else-if="pipeline.layoutMode === 'stage_editor'">
          <Panel :title="`Stage Config — ${pipeline.editorStage?.replace(/_/g, ' ')}`" :status="status">
            <div class="editor-placeholder">
              <div class="editor-config">
                <p>Stage: <strong>{{ pipeline.editorStage }}</strong></p>
                <p>Config fields will be auto-generated from stage registry</p>
                <button class="editor-close" @click="pipeline.closeEditor()">✕ Close</button>
              </div>
            </div>
          </Panel>
        </template>

        <!-- === SOURCE SELECTOR MODE === -->
        <template v-else-if="pipeline.layoutMode === 'source_selector'">
          <SourceSelector @job-started="onJobStarted" />
        </template>

      </div>
    </div>

    <!-- Bottom bar: Log or Blob viewer depending on mode -->
    <div class="log-row">
      <template v-if="pipeline.layoutMode === 'source_selector'">
        <!-- no log in source selector -->
      </template>
      <template v-else>
        <LogPanel ref="logPanel" :source="source" :status="status" />
      </template>
    </div>
  </div>
</template>

<style>
* { margin: 0; padding: 0; box-sizing: border-box; }

body {
  background: var(--surface-0);
  color: var(--text-primary);
  font-family: var(--font-mono);
  font-size: var(--font-size-base);
}

.app {
  min-height: 100vh;
  display: grid;
  grid-template-rows: auto 1fr auto;
  padding: var(--space-4);
  gap: var(--space-2);
}

header {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-3) 0;
  border-bottom: var(--panel-border);
  flex-shrink: 0;
}

header h1 { font-size: var(--font-size-lg); font-weight: 600; }

.status-badge {
  padding: 2px var(--space-2);
  border-radius: 4px;
  font-size: var(--font-size-sm);
  text-transform: uppercase;
}
.status-badge.idle { background: var(--status-idle); }
.status-badge.processing { background: var(--status-processing); color: #000; }
.status-badge.live { background: var(--status-live); color: #000; }
.status-badge.error { background: var(--status-error); color: #000; }

.run-info {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}


.header-btn {
  background: var(--surface-2);
  border: 1px solid var(--surface-3);
  border-radius: 4px;
  color: var(--text-secondary);
  width: 28px;
  height: 28px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s;
}
.header-btn:hover {
  background: var(--surface-3);
  color: var(--text-primary);
}
.stop-btn {
  background: var(--status-error);
  color: #000;
  font-size: 12px;
  font-weight: 700;
}
.stop-btn:hover {
  opacity: 0.8;
}

.job-id { color: var(--text-dim); font-size: var(--font-size-sm); margin-left: auto; }

/* Main layout: pipeline left, content right — both same height */
.main-layout {
  display: flex;
  gap: var(--space-2);
  min-height: 0;
  overflow: hidden;
}

.pipeline-col {
  flex-shrink: 0;
  display: flex;
  overflow: hidden;
}

.pipeline-col > * { flex: 1; }

.content-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
  min-height: 0;
  overflow: hidden;
}

/* Content rows */
.viewer-row {
  display: flex;
  gap: var(--space-2);
  flex-shrink: 0;
}
.viewer-row > * { flex: 1; overflow: hidden; }

/* Detections (75%) + Stats (25%) side by side, bottom-aligned with pipeline */
.detections-stats-row {
  display: flex;
  gap: var(--space-2);
  flex: 1;
  min-height: 0;
}

.detections-col {
  flex: 3;
  min-width: 0;
  display: flex;
}
.detections-col > * { flex: 1; display: flex; flex-direction: column; }

.stats-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
  min-width: 200px;
}
.stats-col > * { flex: 1; }

.detections-stack {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.timeline-section {
  min-height: 60px;
  overflow: auto;
}

.table-section {
  min-height: 60px;
  overflow-y: auto;
  overflow-x: hidden;
}

/* Pipeline stats list */
.pipeline-stats {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.stat {
  display: flex;
  justify-content: space-between;
  padding: var(--space-1) 0;
}

.stat .label { color: var(--text-dim); font-size: var(--font-size-sm); }
.stat .value { font-weight: 600; }

/* Log: full width bottom */
.log-row {
  flex-shrink: 0;
  height: 150px;
}

.empty { color: var(--text-dim); padding: var(--space-6); text-align: center; }

/* Editor layout — frame maximized, sliders right, overlays bottom */
.editor-layout {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.editor-top {
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.editor-frame {
  flex: 1;
  min-height: 0;
  min-width: 0;
  overflow: hidden;
  display: flex;
}
.editor-frame > * {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.editor-sliders {
  flex-shrink: 0;
  min-width: 210px;
  padding: var(--space-2);
  background: var(--surface-2);
  overflow-y: auto;
  overflow-x: hidden;
}

.editor-bottom {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-2) var(--space-3);
  background: var(--surface-2);
  border-top: var(--panel-border);
  height: 36px;
}

.editor-close {
  background: var(--surface-3);
  border: 1px solid var(--surface-3);
  border-radius: 4px;
  padding: 3px 10px;
  color: var(--text-secondary);
  font-family: var(--font-mono);
  font-size: var(--font-size-sm);
  cursor: pointer;
  margin-left: auto;
}

.editor-close:hover {
  background: var(--status-error);
  color: #000;
}

/* Stage config editor (placeholder) */
.editor-placeholder {
  display: flex;
  height: 100%;
  gap: var(--space-2);
}

.editor-config {
  padding: var(--space-4);
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.blob-placeholder {
  padding: var(--space-4);
  color: var(--text-dim);
  text-align: center;
  font-size: var(--font-size-sm);
}

.overlay-controls {
  display: flex;
  gap: var(--space-4);
  padding: var(--space-2) var(--space-3);
  align-items: center;
  height: 100%;
}

.overlay-toggle {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  cursor: pointer;
}

.overlay-toggle input[type="checkbox"] {
  accent-color: #00bcd4;
}

.overlay-label {
  min-width: 80px;
}

.opacity-slider {
  width: 80px;
  height: 3px;
}

.opacity-value {
  font-size: 10px;
  color: var(--text-dim);
  min-width: 30px;
}

/* Source selector */
.source-selector {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: var(--space-3);
  padding: var(--space-3);
}

.source-info {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.source-hint {
  color: var(--text-dim);
  margin-top: var(--space-1);
}

.source-hint code {
  background: var(--surface-2);
  padding: 1px 4px;
  border-radius: 3px;
}

.source-list {
  flex: 1;
  overflow-y: auto;
  background: var(--surface-2);
  border-radius: var(--panel-radius);
  padding: var(--space-2);
}

.source-loading {
  color: var(--text-dim);
  text-align: center;
  padding: var(--space-4);
  font-size: var(--font-size-sm);
}

.source-actions {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
}
</style>
