'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 { CalculationBubble } from '../primitives/calculation-bubble';

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

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

  const { dataState } = currentStep;
  const originalArray = dataState.arrays[0];
  const prefixArray = dataState.arrays[1] ?? null;
  const calculation = dataState.calculations[0] ?? null;

  // Filter pointers for each array
  // Pointers for original array: those with index < original array length
  // Pointers for prefix array: shown on prefix array if it exists
  const originalPointers = prefixArray
    ? dataState.pointers.filter(
        (p) =>
          p.name === 'num' ||
          p.name === 'curr' ||
          p.name === 'i' ||
          p.name === 'j'
      )
    : dataState.pointers;

  const prefixPointers = prefixArray
    ? dataState.pointers.filter(
        (p) =>
          p.name === 'prefix[i]' ||
          p.name === 'prefix[j+1]' ||
          (p.name !== 'num' &&
            p.name !== 'curr' &&
            p.name !== 'i' &&
            p.name !== 'j')
      )
    : [];

  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">
        {/* Fixed height area for calculation bubble */}
        <div className="flex h-8 items-center justify-center">
          <CalculationBubble calculation={calculation} />
        </div>

        {/* Original array */}
        {originalArray && (
          <ArrayView
            array={originalArray}
            pointers={originalPointers}
            elementSize="sm"
          />
        )}

        {/* Prefix sum array (appears during execution) */}
        {prefixArray && (
          <ArrayView
            array={prefixArray}
            pointers={prefixPointers}
            elementSize="sm"
          />
        )}
      </div>
    </VisualizationContainer>
  );
}
