import type { WordPosition } from './usePixelWordPositions'

export const KLAUSUR_API = '/klausur-api'

export interface OverlayReconstructionProps {
  sessionId: string | null
  onNext: () => void
  /** When set, use this data directly instead of fetching from the session API. */
  wordResultOverride?: WordResultData
}

export interface WordResultData {
  cells: GridCellCompat[]
  image_width: number
  image_height: number
  [key: string]: unknown
}

/** Minimal GridCell shape used by overlay reconstruction. */
export interface GridCellCompat {
  cell_id: string
  text: string
  row_index: number
  col_index: number
  col_type: string
  bbox_pct: { x: number; y: number; w: number; h: number }
  confidence?: number
  bbox_px?: { x: number; y: number; w: number; h: number }
  ocr_engine?: string
  is_bold?: boolean
  status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
  word_boxes?: unknown[]
}

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 interface RowItemCompat {
  y: number
}

export interface RowResultCompat {
  rows?: RowItemCompat[]
}

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

export type TextColor = 'red' | 'blue' | 'black'

export type PositioningMode = 'cluster' | 'slide'

export interface OverlayReconstructionState {
  status: OverlayStatus
  error: string
  cells: EditableCell[]
  gridCells: GridCellCompat[]
  editedTexts: Map<string, string>
  undoStack: UndoAction[]
  redoStack: UndoAction[]
  rows: RowItemCompat[]
  imageNaturalSize: { w: number; h: number } | null
  fontScale: number
  globalBold: boolean
  imageRotation: 0 | 180
  textOpacity: number
  textColor: TextColor
  positioningMode: PositioningMode
  changedCount: number
  sortedCellIds: string[]
  medianCellHeightPx: number
  cellWordPositions: Map<string, WordPosition[]>
  reconRef: React.RefObject<HTMLDivElement | null>
  reconWidth: number

  // Actions
  setFontScale: (v: number) => void
  setGlobalBold: (fn: (b: boolean) => boolean) => void
  setImageRotation: (fn: (r: 0 | 180) => 0 | 180) => void
  setTextOpacity: (v: number) => void
  setTextColor: (c: TextColor) => void
  setPositioningMode: (fn: (m: PositioningMode) => PositioningMode) => void
  handleTextChange: (cellId: string, newText: string) => void
  undo: () => void
  redo: () => void
  resetCell: (cellId: string) => void
  handleKeyDown: (e: React.KeyboardEvent, cellId: string) => void
  getDisplayText: (cell: EditableCell) => string
  isEdited: (cell: EditableCell) => boolean
  saveReconstruction: () => Promise<void>
  loadSessionData: () => Promise<void>
  setError: (msg: string) => void
  setImageNaturalSize: (size: { w: number; h: number }) => void
}
