'use client';

import { useState } from 'react';

interface UseJsonExpandOptions {
  maxAutoExpandDepth: number;
  maxAutoExpandArrayItems: number;
  maxAutoExpandObjectKeys: number;
}

/**
 * Manages expand/collapse state for JsonTree.
 * null = smart auto-expand mode (uses depth/size heuristics)
 * true = all expanded (user override)
 * false = all collapsed (user override)
 */
export function useJsonExpand({
  maxAutoExpandDepth,
  maxAutoExpandArrayItems,
  maxAutoExpandObjectKeys,
}: UseJsonExpandOptions) {
  const [expandAll, setExpandAll] = useState<boolean | null>(null);
  const [renderKey, setRenderKey] = useState(0);

  // Reflects the effective visual state — used to show correct icon
  const isExpanded = expandAll === true || (expandAll === null && maxAutoExpandDepth > 0);

  const toggle = () => {
    setExpandAll(isExpanded ? false : true);
    setRenderKey(prev => prev + 1);
  };

  const shouldExpandNodeInitially = (
    _keyPath: readonly (string | number)[],
    nodeData: unknown,
    level: number,
  ): boolean => {
    if (expandAll === true) return true;
    if (expandAll === false) return false;
    // null = auto mode
    if (level <= maxAutoExpandDepth) return true;
    if (Array.isArray(nodeData) && nodeData.length <= maxAutoExpandArrayItems) return true;
    if (nodeData && typeof nodeData === 'object' && !Array.isArray(nodeData)) {
      return Object.keys(nodeData).length <= maxAutoExpandObjectKeys;
    }
    return false;
  };

  return { isExpanded, toggle, renderKey, shouldExpandNodeInitially };
}
