// Types, constants and helpers for StepReconstruction

export const KLAUSUR_API = '/klausur-api'

export type EditorMode = 'simple' | 'editor' | 'overlay'

export interface StepReconstructionProps {
  sessionId: string | null
  onNext: () => void
}

export interface EditableCell {
  cellId: string
  text: string
  originalText: string
  bboxPct: { x: number; y: number; w: number; h: number }
  colType: string
  rowIndex: number
  colIndex: number
}

export type UndoAction = { cellId: string; oldText: string; newText: string }

export type ReconstructionStatus = 'loading' | 'ready' | 'saving' | 'saved' | 'error'

// --- PageRegion / RowItem / PageZone ---
// These match the backend API response shapes used by overlay mode.

export interface PageRegion {
  x: number
  width: number
  type: string
}

export interface RowItem {
  y: number
}

export interface PageZone {
  zone_type: string
  box?: { x: number; y: number; width: number; height: number }
}

// --- Helper functions ---

export function colTypeColor(colType: string): string {
  const colors: Record<string, string> = {
    column_en: 'border-blue-400/40 focus:border-blue-500',
    column_de: 'border-green-400/40 focus:border-green-500',
    column_example: 'border-orange-400/40 focus:border-orange-500',
    column_text: 'border-purple-400/40 focus:border-purple-500',
    page_ref: 'border-cyan-400/40 focus:border-cyan-500',
    column_marker: 'border-gray-400/40 focus:border-gray-500',
  }
  return colors[colType] || 'border-gray-400/40 focus:border-gray-500'
}

/**
 * Clamp cell positions so they don't overlap with box zones.
 * Sub-session cells (inside box) are not adjusted.
 */
export function adjustCellForBoxZones(
  bboxPct: { x: number; y: number; w: number; h: number },
  cellId: string,
  boxZonesPct: { topPct: number; bottomPct: number }[],
): { x: number; y: number; w: number; h: number } {
  if (cellId.startsWith('sub_')) return bboxPct
  if (boxZonesPct.length === 0) return bboxPct

  const cellTop = bboxPct.y
  const cellBottom = bboxPct.y + bboxPct.h
  const boxMid = (boxZonesPct[0].topPct + boxZonesPct[0].bottomPct) / 2

  for (const { topPct, bottomPct } of boxZonesPct) {
    if (cellBottom <= topPct || cellTop >= bottomPct) continue
    if (cellTop < boxMid) {
      return { ...bboxPct, h: Math.max(0.5, topPct - cellTop) }
    }
    return { ...bboxPct, y: bottomPct, h: Math.max(0.5, cellBottom - bottomPct) }
  }
  return bboxPct
}
