"use client";
import React, { useState } from "react";

export function TreeView({ nodes = [], renderItem, className = "" }) {
  const [expandedIds, setExpandedIds] = useState(new Set());

  const toggleCategoryExpand = (categoryId, parentChildren) => {
    setExpandedIds((prev) => {
      const newExpanded = new Set(prev);

      const isAlreadyExpanded = newExpanded.has(categoryId);

      // Collapse all siblings (other nodes under the same parent)
      parentChildren?.forEach((sibling) => {
        newExpanded.delete(sibling.id);
      });

      // Toggle current
      if (!isAlreadyExpanded) {
        newExpanded.add(categoryId);
      }

      return newExpanded;
    });
  };

  const renderTree = (currentNodes = [], level = 0, parentChildren = []) => {
    if (!Array.isArray(currentNodes)) return null;

    return currentNodes.map((node) => {
      const isExpanded = expandedIds.has(node.id);
      const hasChildren =
        Array.isArray(node.children) && node.children.length > 0;

      return (
        <div key={node.id} className={`tree-node ${level > 0 ? "pl-5" : ""}`}>
          {renderItem({
            node,
            level,
            isExpanded,
            onToggle: () => toggleCategoryExpand(node.id, currentNodes),
          })}

          {hasChildren && isExpanded && (
            <div className="pl-1">
              {renderTree(node.children, level + 1, node.children)}
            </div>
          )}
        </div>
      );
    });
  };

  return (
    <div className={`tree-view ${className}`}>
      {renderTree(nodes, 0, nodes)}
    </div>
  );
}
