"use client";

import { useState } from "react";
import { VisualizationContainer } from "./visualization-container";
import type { VisualizationExample } from "@/types";
import type { VisualizationData, VisualizationStep } from "@/types/visualization";

interface PatternVisualizationProps {
  examples: VisualizationExample[];
}

function transformToVisualizationData(
  example: VisualizationExample
): VisualizationData {
  const steps: VisualizationStep[] = example.steps.map((step) => ({
    id: step.id,
    description: step.description,
    structures: step.structures as VisualizationStep["structures"],
    variables: step.variables,
    codeHighlight: step.codeHighlight,
  }));

  return {
    id: example.id,
    title: example.title,
    code: example.code,
    steps,
    totalSteps: steps.length,
  };
}

export function PatternVisualization({ examples }: PatternVisualizationProps) {
  const [selectedIndex, setSelectedIndex] = useState(0);

  if (!examples || examples.length === 0) {
    return null;
  }

  const selectedExample = examples[selectedIndex];
  const visualizationData = transformToVisualizationData(selectedExample);

  return (
    <div className="space-y-4">
      {/* Example selector (if multiple) */}
      {examples.length > 1 && (
        <div className="flex flex-wrap gap-2">
          {examples.map((example, index) => (
            <button
              key={example.id}
              onClick={() => setSelectedIndex(index)}
              className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                index === selectedIndex
                  ? "bg-primary text-primary-foreground"
                  : "bg-muted text-muted-foreground hover:bg-muted/80"
              }`}
            >
              {example.title}
            </button>
          ))}
        </div>
      )}

      {/* Visualization */}
      <VisualizationContainer data={visualizationData} />
    </div>
  );
}
