'use client';

import { motion } from 'framer-motion';
import { cn } from '@/lib/utils';
import type { BinaryTreeNodeState } from '@/lib/visualizations/types';

interface TreeNodeProps {
  node: BinaryTreeNodeState;
  x: number;
  y: number;
  radius?: number;
  className?: string;
}

const STATE_CLASSES = {
  normal: 'fill-[var(--surface-variant)] stroke-[var(--border)]',
  current: 'fill-[var(--primary)]/20 stroke-[var(--primary)]',
  visiting: 'fill-[var(--info)]/20 stroke-[var(--info)]',
  visited: 'fill-[var(--success)]/20 stroke-[var(--success)] opacity-70',
  highlighted: 'fill-[var(--primary)]/30 stroke-[var(--primary)]',
} as const;

const TEXT_CLASSES = {
  normal: 'fill-[var(--foreground)]',
  current: 'fill-[var(--primary)]',
  visiting: 'fill-[var(--info)]',
  visited: 'fill-[var(--success)]',
  highlighted: 'fill-[var(--primary)]',
} as const;

export function TreeNode({
  node,
  x,
  y,
  radius = 24,
  className,
}: TreeNodeProps) {
  const isActive = node.state === 'current' || node.state === 'highlighted';

  return (
    <motion.g
      initial={false}
      animate={{
        scale: isActive ? 1.1 : 1,
      }}
      transition={{
        type: 'spring',
        stiffness: 300,
        damping: 30,
      }}
      style={{ transformOrigin: `${x}px ${y}px` }}
      className={cn(className)}
    >
      <motion.circle
        cx={x}
        cy={y}
        r={radius}
        strokeWidth={2}
        className={cn(
          'transition-colors duration-200',
          STATE_CLASSES[node.state]
        )}
        initial={false}
        animate={{
          filter: isActive ? 'drop-shadow(0 0 8px var(--primary))' : 'none',
        }}
        transition={{ duration: 0.2 }}
      />
      <text
        x={x}
        y={y}
        textAnchor="middle"
        dominantBaseline="central"
        className={cn(
          'pointer-events-none select-none font-mono text-sm font-medium',
          TEXT_CLASSES[node.state]
        )}
      >
        {node.value}
      </text>
    </motion.g>
  );
}
