<script setup lang="ts">
import { ref, watch } from 'vue'
import { Panel, ResizeHandle, SplitPane } 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 CompareView from './panels/CompareView.vue'
import StageConfig from './components/StageConfig.vue'
import OverlayControls from './components/OverlayControls.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'
import { useHashRouter } from './composables/useHashRouter'

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

// SSE connection + pipeline status
const {
  jobId, stats, runContext, status, paused, pauseAfterStage,
  sseConnected, source,
  stopPipeline, pausePipeline, resumePipeline, stepPipeline,
  togglePauseAfterStage, 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: _onReplayResult, setActiveStage,
  saveOverlaysToCache,
} = useEditorState(currentFrameRef)

function onReplayResult(result: any) {
  _onReplayResult(result)
}

// Set active stage when editor opens
watch(() => pipeline.editorStage, (stage) => {
  if (stage) setActiveStage(stage)
}, { immediate: true })

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

// Save overlays to S3 cache then close editor
function closeEditorWithSave() {
  saveOverlaysToCache(pipeline.timelineId, pipeline.jobId)
  // Small delay to let the save requests fire before navigation
  setTimeout(() => pipeline.closeEditor(), 100)
}

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

</script>

<template>
  <div class="app">
    <header>
      <h1>Detection Pipeline</h1>
      <span class="status-badge" :class="status">{{ status }}</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 class="header-btn" title="Compare jobs" @click="pipeline.openCompare()">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
          <rect x="1" y="3" width="6" height="10" rx="1"/><rect x="9" y="3" width="6" height="10" rx="1"/><path d="M8 5v6"/>
        </svg>
      </button>

      <!-- Transport controls — visible when a pipeline is running -->
      <div v-if="sseConnected && (status === 'live' || status === 'processing' || paused)" class="transport">
        <button
          v-if="paused"
          class="header-btn play-btn"
          title="Resume"
          @click="resumePipeline"
        >
          <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><polygon points="2,1 11,6 2,11"/></svg>
        </button>
        <button
          v-else
          class="header-btn pause-btn"
          title="Pause after current stage"
          @click="pausePipeline"
        >
          <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><rect x="2" y="1" width="3" height="10"/><rect x="7" y="1" width="3" height="10"/></svg>
        </button>
        <button
          class="header-btn step-btn"
          title="Run one stage"
          @click="stepPipeline"
          :disabled="!paused"
        >
          <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><polygon points="1,1 7,6 1,11"/><rect x="8" y="1" width="2.5" height="10"/></svg>
        </button>
        <button
          class="header-btn stop-btn"
          title="Stop pipeline"
          @click="stopPipeline"
        >
          <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><rect width="10" height="10"/></svg>
        </button>
        <label class="pause-toggle" title="Pause after each stage">
          <input type="checkbox" :checked="pauseAfterStage" @change="togglePauseAfterStage" />
          <span>step</span>
        </label>
      </div>

      <span v-if="paused" class="status-badge paused">PAUSED</span>
      <span class="job-id">job: {{ jobId || '—' }}</span>
    </header>

    <SplitPane direction="horizontal" :initial-size="320" size-mode="px" :min="200" :max="500">
      <template #first>
        <PipelineGraphPanel :source="source" :status="status" />
      </template>
      <template #second>

        <!-- === NORMAL MODE === -->
        <SplitPane v-if="pipeline.layoutMode === 'normal'" direction="vertical" :initial-size="240" size-mode="px" :min="120" :max="400">
          <template #first>
            <SplitPane direction="horizontal" :initial-size="1" size-mode="ratio" :min="0.3" :max="3">
              <template #first>
                <FramePanel :source="source" :status="status" />
              </template>
              <template #second>
                <FunnelPanel :source="source" :status="status" />
              </template>
            </SplitPane>
          </template>
          <template #second>
            <SplitPane direction="horizontal" :initial-size="3" size-mode="ratio" :min="1" :max="6">
              <template #first>
                <Panel title="Detections" :status="status">
                  <SplitPane direction="vertical" :initial-size="1" size-mode="ratio" :min="0.3" :max="3">
                    <template #first>
                      <TimelinePanel :source="source" :status="status" :embedded="true" />
                    </template>
                    <template #second>
                      <BrandTablePanel :source="source" :status="status" :embedded="true" />
                    </template>
                  </SplitPane>
                </Panel>
              </template>
              <template #second>
                <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>
              </template>
            </SplitPane>
          </template>
        </SplitPane>

        <!-- === BBOX EDITOR MODE === -->
        <div v-else-if="pipeline.layoutMode === 'bbox_editor'" class="editor-layout">
          <div class="editor-top">
            <SplitPane direction="horizontal" :initial-size="245" size-mode="px" :min="245" :max="350" anchor="second">
              <template #first>
                <FramePanel :source="source" :status="status" :overlays="editorOverlays" :frame-image="currentFrameImage" :editor-boxes="editorBoxes" />
              </template>
              <template #second>
                <div class="editor-sliders">
                  <StageConfig
                    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>
              </template>
            </SplitPane>
          </div>

          <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 }"
          />

          <div class="editor-bottom">
            <OverlayControls :overlays="editorOverlays" />
            <button class="editor-close" @click="closeEditorWithSave()">✕ Close</button>
          </div>
        </div>

        <!-- === STAGE EDITOR MODE === -->
        <Panel v-else-if="pipeline.layoutMode === 'stage_editor'" :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>

        <!-- === SOURCE SELECTOR MODE === -->
        <SourceSelector v-else-if="pipeline.layoutMode === 'source_selector'" @job-started="(id: string, opts: any) => onJobStarted(id, opts)" />

        <!-- === COMPARE MODE === -->
        <CompareView v-else-if="pipeline.layoutMode === 'compare'" />

      </template>
    </SplitPane>

    <!-- Bottom bar: Log (hidden in source selector) -->
    <div v-if="pipeline.layoutMode !== 'source_selector'" class="log-row">
      <LogPanel ref="logPanel" :source="source" :status="status" />
    </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);
}
.transport {
  display: flex;
  align-items: center;
  gap: 2px;
}

.play-btn { color: var(--status-live); }
.pause-btn { color: var(--text-secondary); }
.step-btn { color: var(--text-secondary); }
.step-btn:disabled { opacity: 0.3; cursor: not-allowed; }
.stop-btn {
  background: var(--status-error);
  color: #000;
  font-size: 12px;
  font-weight: 700;
}
.stop-btn:hover {
  opacity: 0.8;
}

.pause-toggle {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  color: var(--text-dim);
  cursor: pointer;
  margin-left: 4px;
}
.pause-toggle input { accent-color: var(--status-processing); }

.status-badge.paused { background: var(--status-processing); color: #000; }

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

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

/* 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 */
.editor-layout {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

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

.editor-sliders {
  padding: var(--space-2);
  background: var(--surface-2);
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
}

.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);
}


/* 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>
