import { useState, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
import type { ClassSummary, ClassDetail, NamespaceTree } from '../types/scripts';

export function useScripts() {
  const [tree, setTree] = useState<NamespaceTree[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadTree = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await invoke<NamespaceTree[]>('get_script_tree');
      setTree(result);
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
  }, []);

  const search = useCallback(async (query: string): Promise<ClassSummary[]> => {
    try {
      return await invoke<ClassSummary[]>('search_scripts', { query });
    } catch {
      return [];
    }
  }, []);

  const getClassDetail = useCallback(async (className: string): Promise<ClassDetail | null> => {
    try {
      return await invoke<ClassDetail>('get_class_detail', { className });
    } catch {
      return null;
    }
  }, []);

  return { tree, loading, error, loadTree, search, getClassDetail };
}
