'use client';

import { useVisualization } from '@/lib/visualizations/use-visualization';
import type { AlgorithmDefinition } from '@/lib/visualizations/types';
import { VisualizationContainer } from '../core/visualization-container';
import { BinaryTreeView } from '../data-structures/binary-tree-view';
import { StackView } from '../data-structures/stack-view';
import { ArrayView } from '../data-structures/array-view';

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

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

  const { dataState } = currentStep;
  const tree = dataState.trees?.[0] ?? null;
  const traversalStack = dataState.stacks?.[0] ?? null;
  const outputArray = dataState.arrays?.[0] ?? null;

  // Find the current node ID based on node states
  const currentNodeId = tree?.nodes.find((n) => n.state === 'current')?.id;

  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 items-start gap-8">
        {/* Left: Binary tree */}
        {tree && (
          <BinaryTreeView
            tree={tree}
            currentNodeId={currentNodeId}
          />
        )}

        {/* Right side: Stack + Output */}
        <div className="flex flex-col gap-6">
          {/* Traversal stack */}
          {traversalStack && (
            <StackView stack={traversalStack} />
          )}

          {/* Output array */}
          {outputArray && (
            <ArrayView
              array={outputArray}
              pointers={dataState.pointers}
              elementSize="sm"
              showIndices={false}
            />
          )}
        </div>
      </div>
    </VisualizationContainer>
  );
}
