'use client';

import { useVisualization } from '@/lib/visualizations/use-visualization';
import type { AlgorithmDefinition, LinkedListState, LinkedListPointerState } from '@/lib/visualizations/types';
import { VisualizationContainer } from '../core/visualization-container';
import { LinkedListView } from '../data-structures/linked-list-view';

interface LinkedListVisualizationProps {
  algorithm: AlgorithmDefinition;
  className?: string;
}

export function LinkedListVisualization({
  algorithm,
  className,
}: LinkedListVisualizationProps) {
  const {
    currentStep,
    currentStepIndex,
    totalSteps,
    playback,
    controls,
    currentPhase,
    progress,
  } = useVisualization(algorithm);

  const { dataState } = currentStep;

  // Extract linked list and pointers from dataState
  // We store linkedLists in a custom field, falling back to empty
  const linkedList: LinkedListState = (dataState as { linkedLists?: LinkedListState[] }).linkedLists?.[0] ?? {
    id: 'empty',
    nodes: [],
  };

  const linkedListPointers: LinkedListPointerState[] =
    (dataState as { linkedListPointers?: LinkedListPointerState[] }).linkedListPointers ?? [];

  return (
    <VisualizationContainer
      title={algorithm.title}
      pattern={algorithm.pattern}
      code={algorithm.code}
      currentLine={currentStep.codeLine}
      highlightLines={currentStep.codeHighlightLines}
      explanation={currentStep.explanation}
      decision={currentStep.decision}
      phase={currentPhase}
      variables={dataState.variables}
      currentStepIndex={currentStepIndex}
      totalSteps={totalSteps}
      isPlaying={playback.isPlaying}
      speed={playback.speed}
      controls={controls}
      progress={progress}
      className={className}
    >
      <div className="flex flex-col items-center justify-center">
        <LinkedListView
          list={linkedList}
          pointers={linkedListPointers}
        />
      </div>
    </VisualizationContainer>
  );
}
