'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 { StackView } from '../data-structures/stack-view';

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

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

  const { dataState } = currentStep;

  // Input array with i pointer
  const inputArray = dataState.arrays.find((a) => a.id === 'input');
  // Result array
  const resultArray = dataState.arrays.find((a) => a.id === 'result');
  // Stack
  const stack = dataState.stacks?.[0];

  // Filter pointers for the input array (only show 'i' pointer on input)
  const inputPointers = dataState.pointers.filter((p) => p.id === 'i');

  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">
        {/* Input array with i pointer */}
        {inputArray && (
          <ArrayView
            array={inputArray}
            pointers={inputPointers}
            elementSize="sm"
          />
        )}

        <div className="flex items-end gap-6">
          {/* Stack (left side) */}
          {stack && <StackView stack={stack} />}

          {/* Result array (right side) */}
          {resultArray && (
            <ArrayView array={resultArray} pointers={[]} elementSize="sm" />
          )}
        </div>
      </div>
    </VisualizationContainer>
  );
}
