'use client';

import { useVisualization } from '@/lib/visualizations/use-visualization';
import type { AlgorithmDefinition } from '@/lib/visualizations/types';
import { VisualizationContainer } from '../core/visualization-container';
import { ArrayView } from '../data-structures/array-view';
import { GridView } from '../data-structures/grid-view';
import { CalculationBubble } from '../primitives/calculation-bubble';

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

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

  const { dataState } = currentStep;
  const coinsArray = dataState.arrays.find((a) => a.id === 'coins') ?? null;
  const dpGrid = dataState.grids?.[0] ?? null;
  const calculation = dataState.calculations[0] ?? null;
  const gridPointers = dataState.gridPointers ?? [];

  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 gap-4">
        {/* Calculation bubble */}
        <div className="flex h-8 items-center justify-center">
          <CalculationBubble calculation={calculation} />
        </div>

        {/* Coins array */}
        {coinsArray && (
          <ArrayView
            array={coinsArray}
            pointers={[]}
            elementSize="sm"
          />
        )}

        {/* DP Table grid */}
        {dpGrid && (
          <GridView
            grid={dpGrid}
            pointers={gridPointers}
            cellSize="sm"
            showColLabels={true}
          />
        )}
      </div>
    </VisualizationContainer>
  );
}
