/**
 * Core types for the algorithm visualization system.
 *
 * The visualization system is designed around a narrative structure:
 * Problem -> Intuition -> Pattern -> Code -> Execution
 *
 * Each step changes exactly one thing to maintain clarity.
 */

/** Phases of algorithm explanation */
export type VisualizationPhase =
  | 'problem'
  | 'intuition'
  | 'pattern'
  | 'code'
  | 'execution';

/** State of an individual array element */
export interface ArrayElementState {
  value: number;
  index: number;
  state: 'normal' | 'highlighted' | 'dimmed' | 'success' | 'comparing';
}

/** Complete array state */
export interface ArrayState {
  id: string;
  elements: ArrayElementState[];
  label?: string;
}

/** Pointer pointing to an array index */
export interface PointerState {
  id: string;
  name: string;
  index: number;
  color: 'left' | 'right' | 'mid' | 'default';
  showValue?: boolean;
}

/** Tracked variable value */
export interface VariableState {
  id: string;
  name: string;
  value: string | number;
  previousValue?: string | number;
  derivation?: string;
}

/** Decision callout shown during execution */
export interface DecisionCallout {
  question: string;
  answer: string;
  action: string;
}

/** Calculation bubble showing arithmetic */
export interface CalculationState {
  id: string;
  expression: string;
  result: string;
  position: 'above' | 'below' | 'inline';
  anchorElementId?: string;
}

/** Animation descriptor for transitions */
export interface Animation {
  type: 'move' | 'highlight' | 'fade' | 'appear' | 'disappear' | 'calculate';
  targetId: string;
  duration?: number;
  delay?: number;
}

/** Complete state of all visual elements at a step */
export interface DataState {
  arrays: ArrayState[];
  pointers: PointerState[];
  variables: VariableState[];
  calculations: CalculationState[];
  // LinkedList support
  linkedLists?: LinkedListState[];
  linkedListPointers?: LinkedListPointerState[];
  // Stack support
  stacks?: StackState[];
  // Tree support
  trees?: BinaryTreeState[];
  // Queue support
  queues?: QueueState[];
  // Grid support (for DP visualizations)
  grids?: GridState[];
  gridPointers?: GridPointerState[];
  // Decision tree support (for Backtracking)
  decisionTrees?: DecisionTreeState[];
  // Heap support
  heaps?: HeapState[];
  // Interval support
  intervals?: IntervalListState[];
  // Trie support
  tries?: TrieState[];
  // Union-Find support
  unionFind?: UnionFindState[];
  // Bit Manipulation support
  bitManipulation?: BitManipulationState[];
}

/** Single step in the visualization */
export interface VisualizationStep {
  id: string;
  phase: VisualizationPhase;
  explanation: string;
  decision?: DecisionCallout;
  codeLine?: number;
  codeHighlightLines?: number[];
  dataState: DataState;
  animation?: Animation;
}

/** Code definition for the algorithm */
export interface AlgorithmCode {
  language: 'typescript' | 'python' | 'javascript';
  code: string;
}

/** Pattern/technique classification */
export interface AlgorithmPattern {
  name: string;
  description: string;
}

/** Complete algorithm definition */
export interface AlgorithmDefinition {
  id: string;
  title: string;
  slug: string;
  pattern: AlgorithmPattern;
  problemStatement: string;
  intuition: string;
  code: AlgorithmCode;
  steps: VisualizationStep[];
  initialExample?: {
    input: Record<string, unknown>;
    expected: unknown;
  };
}

/** Playback speed options */
export type PlaybackSpeed = 0.5 | 1 | 2;

/** Visualization playback state */
export interface PlaybackState {
  isPlaying: boolean;
  currentStepIndex: number;
  speed: PlaybackSpeed;
}

/** Controls returned by the useVisualization hook */
export interface VisualizationControls {
  play: () => void;
  pause: () => void;
  togglePlay: () => void;
  stepForward: () => void;
  stepBackward: () => void;
  goToStep: (index: number) => void;
  goToFirst: () => void;
  goToLast: () => void;
  setSpeed: (speed: PlaybackSpeed) => void;
}

/** Return type of useVisualization hook */
export interface UseVisualizationReturn {
  currentStep: VisualizationStep;
  currentStepIndex: number;
  totalSteps: number;
  playback: PlaybackState;
  controls: VisualizationControls;
  currentPhase: VisualizationPhase;
  progress: number;
}

// ============================================
// LinkedList Types
// ============================================

/** State of a linked list node */
export interface LinkedListNodeState {
  id: string;
  value: number;
  index: number;
  state: 'normal' | 'highlighted' | 'dimmed' | 'success' | 'comparing';
  isNull?: boolean;
}

/** Complete linked list state */
export interface LinkedListState {
  id: string;
  nodes: LinkedListNodeState[];
  label?: string;
}

/** Pointer for linked list visualization */
export interface LinkedListPointerState {
  id: string;
  name: string;
  nodeIndex: number;
  color: 'slow' | 'fast' | 'prev' | 'curr' | 'next' | 'default';
}

// ============================================
// Stack Types
// ============================================

/** State of a stack element */
export interface StackElementState {
  id: string;
  value: number | string;
  state: 'normal' | 'highlighted' | 'popped' | 'pushing';
}

/** Complete stack state */
export interface StackState {
  id: string;
  elements: StackElementState[];
  label?: string;
}

// ============================================
// Binary Tree Types
// ============================================

/** State of a binary tree node */
export interface BinaryTreeNodeState {
  id: string;
  value: number;
  state: 'normal' | 'current' | 'visiting' | 'visited' | 'highlighted';
  left: string | null;
  right: string | null;
}

/** Complete binary tree state */
export interface BinaryTreeState {
  id: string;
  nodes: BinaryTreeNodeState[];
  rootId: string;
  label?: string;
}

// ============================================
// Queue Types
// ============================================

/** State of a queue element */
export interface QueueElementState {
  id: string;
  value: number | string;
  state: 'normal' | 'highlighted' | 'enqueued' | 'dequeued';
}

/** Complete queue state */
export interface QueueState {
  id: string;
  elements: QueueElementState[];
  label?: string;
}

// ============================================
// Decision Tree Types (for Backtracking)
// ============================================

/** State of a decision tree node for backtracking */
export interface DecisionNodeState {
  id: string;
  value: string; // Current subset as string: "[]", "[1]", "[1,2]"
  state: 'normal' | 'exploring' | 'complete' | 'backtracking' | 'current';
  left: string | null; // Include branch
  right: string | null; // Exclude branch
  decision?: string; // "Include 2?" label
  depth: number; // Recursion depth (0-indexed)
}

/** Complete decision tree state */
export interface DecisionTreeState {
  id: string;
  nodes: DecisionNodeState[];
  rootId: string;
  label?: string;
  currentPath?: string[]; // IDs of nodes in current exploration path
}

// ============================================
// Grid Types (for DP visualizations)
// ============================================

/** State of a grid cell */
export interface GridCellState {
  id: string;
  value: number | string;
  row: number;
  col: number;
  state: 'normal' | 'highlighted' | 'comparing' | 'computing' | 'success' | 'dimmed';
}

/** Complete grid state */
export interface GridState {
  id: string;
  cells: GridCellState[][]; // 2D array: cells[row][col]
  colLabels?: (string | number)[];
  rowLabels?: (string | number)[];
  label?: string;
}

/** Pointer for grid visualization */
export interface GridPointerState {
  id: string;
  name: string;
  row: number;
  col: number;
  color: 'current' | 'dependency' | 'result' | 'default';
}

// ============================================
// Heap Types
// ============================================

/** State of a heap node */
export interface HeapNodeState {
  id: string;
  value: number;
  index: number;  // Position in heap array (0-indexed)
  state: 'normal' | 'comparing' | 'swapping' | 'settled' | 'highlighted' | 'removing';
}

/** Complete heap state */
export interface HeapState {
  id: string;
  elements: HeapNodeState[];
  label?: string;
  heapType: 'min' | 'max';
  maxSize?: number;  // For bounded heaps (like top-k)
}

// ============================================
// Interval Types
// ============================================

/** State of a single interval */
export interface IntervalState {
  id: string;
  start: number;
  end: number;
  state: 'normal' | 'highlighted' | 'merging' | 'merged' | 'dimmed';
  label?: string;  // Optional label like "[1,3]"
}

/** Complete interval list state */
export interface IntervalListState {
  id: string;
  intervals: IntervalState[];
  label?: string;
  minValue?: number;  // Timeline range
  maxValue?: number;
}

// ============================================
// Trie Types
// ============================================

/** State of a trie node */
export interface TrieNodeState {
  id: string;
  char: string;  // Character this node represents (empty for root)
  state: 'normal' | 'current' | 'found' | 'notfound' | 'highlighted' | 'creating';
  isEndOfWord: boolean;
  children: string[];  // IDs of child nodes
}

/** Complete trie state */
export interface TrieState {
  id: string;
  nodes: TrieNodeState[];
  rootId: string;
  label?: string;
  currentPath?: string[];  // Node IDs in current traversal
  searchWord?: string;     // Word being processed
  searchIndex?: number;    // Current character index
}

// ============================================
// Bit Manipulation Types
// ============================================

/** State of a bit representation display */
export interface BitState {
  id: string;
  value: number;
  bits: string;  // Binary string like "0010"
  label?: string;
  state: 'normal' | 'highlighted' | 'comparing' | 'result' | 'cancelled';
}

/** Complete bit manipulation state */
export interface BitManipulationState {
  id: string;
  operands: BitState[];
  operation?: 'XOR' | 'AND' | 'OR' | 'NOT';
  result?: BitState;
  label?: string;
}

// ============================================
// Union-Find Types
// ============================================

/** State of a union-find node */
export interface UnionFindNodeState {
  id: string;
  value: number;           // Element value (1-indexed for this problem)
  parentId: string | null; // Parent pointer (null = self/root)
  rank: number;            // For union by rank optimization
  state: 'normal' | 'root' | 'finding' | 'compressing' | 'merging' | 'highlighted' | 'cycle';
}

/** Complete union-find forest state */
export interface UnionFindState {
  id: string;
  nodes: UnionFindNodeState[];
  label?: string;
  currentEdge?: [number, number];  // Edge being processed
  findPath?: string[];             // Path during find operation
  message?: string;                // Operation status message
}
