import { useMemo } from 'react';
import type { FlowNode } from '../manifest';
import { stageColor } from './nodeShapes';

interface Props {
  nodes: FlowNode[];
  selectedNodeId: string | null;
  groupBy: 'stage' | 'menu';
  onSelectNode: (id: string) => void;
}

export function NodeListSidebar({
  nodes,
  selectedNodeId,
  groupBy,
  onSelectNode,
}: Props) {
  const grouped = useMemo(() => {
    const map = new Map<string, FlowNode[]>();
    nodes.forEach((n) => {
      const key = (groupBy === 'menu' ? n.menu : n.stage) ?? '기타';
      if (!map.has(key)) map.set(key, []);
      map.get(key)!.push(n);
    });
    return Array.from(map.entries());
  }, [nodes, groupBy]);

  return (
    <aside className="sf-sidebar">
      <div className="sf-detail-label" style={{ marginBottom: 12 }}>
        노드 ({nodes.length})
      </div>
      {grouped.map(([groupKey, groupNodes]) => (
        <div key={groupKey}>
          <div className="sf-section-title">
            {groupKey} ({groupNodes.length})
          </div>
          {groupNodes.map((node) => (
            <button
              key={node.id}
              className="sf-node-card"
              data-active={selectedNodeId === node.id}
              style={{ ['--accent' as never]: stageColor(node.stage) }}
              onClick={() => onSelectNode(node.id)}
            >
              <div className="sf-card-stage">{node.stage}</div>
              <div className="sf-card-label">{node.label}</div>
              <div className="sf-card-desc">{node.shortDescription}</div>
              <div className="sf-card-id">{node.id}</div>
            </button>
          ))}
        </div>
      ))}
      {grouped.length === 0 && (
        <div className="sf-empty">검색 결과가 없습니다.</div>
      )}
    </aside>
  );
}
