/**
 * ╔═══════════════════════════════════════════════════════════════════════════╗
 * ║                    MIND MAP VIEW COMPONENT                                ║
 * ║═══════════════════════════════════════════════════════════════════════════║
 * ║  Hierarchical idea visualization and brainstorming                        ║
 * ║  Part of the Visual Cortex Layer                                         ║
 * ╚═══════════════════════════════════════════════════════════════════════════╝
 */

import { useMemo } from 'react';
import { MermaidDiagram } from './MermaidDiagram';
import { cn } from '@/lib/utils';

export interface MindMapNode {
  id: string;
  label: string;
  children?: MindMapNode[];
  icon?: string;
  style?: 'default' | 'highlight' | 'warning' | 'success';
}

export interface MindMapViewProps {
  /** Central topic / root node */
  root: MindMapNode;
  /** Diagram title */
  title?: string;
  /** Custom class */
  className?: string;
  /** Callback when rendered */
  onRender?: (svg: string) => void;
}

// Style to color mapping
const STYLE_COLORS: Record<string, string> = {
  default: '#3b82f6',
  highlight: '#f59e0b',
  warning: '#ef4444',
  success: '#22c55e',
};

export function MindMapView({
  root,
  title,
  className,
  onRender,
}: MindMapViewProps) {
  const mermaidCode = useMemo(() => {
    const lines: string[] = ['mindmap'];

    // Recursively build mindmap structure
    const buildNode = (node: MindMapNode, indent: number = 1) => {
      const indentStr = '  '.repeat(indent);
      const icon = node.icon ? `::icon(${node.icon})` : '';

      // Root uses different syntax
      if (indent === 1) {
        lines.push(`${indentStr}root((${node.label}))${icon}`);
      } else {
        // Alternate shapes for visual variety
        const shapes = ['', '()', '[]', '{{}}'];
        const shapeIndex = (indent - 1) % shapes.length;
        const shape = shapes[shapeIndex];

        if (shape === '()') {
          lines.push(`${indentStr}(${node.label})${icon}`);
        } else if (shape === '[]') {
          lines.push(`${indentStr}[${node.label}]${icon}`);
        } else if (shape === '{{}}') {
          lines.push(`${indentStr}{{${node.label}}}${icon}`);
        } else {
          lines.push(`${indentStr}${node.label}${icon}`);
        }
      }

      // Process children
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          buildNode(child, indent + 1);
        });
      }
    };

    buildNode(root);

    return lines.join('\n');
  }, [root]);

  return (
    <div className={cn('mindmap-view', className)}>
      <MermaidDiagram
        code={mermaidCode}
        title={title}
        theme="dark"
        zoomable={true}
        onRender={onRender}
      />
    </div>
  );
}

export default MindMapView;
