// components/tools.jsx — ToolsPanel: thin orchestrator delegating to sub-components.
// Sub-components loaded as globals: ToolCard, JobRow, JobDetailsPanel, QueueSummary,
// PredictiveAlerts, HealthTrends, ToolsRegistry, ToolHealthPanelRefactored,
// ToolsDispatch, ToolsJobQueue, ToolsPanelRefactored, TableExport (shared).
// Depends on: React (useState, useCallback, useEffect), Card, get, post from api.js

// ── Hook: useTools ──────────────────────────────────────────

function useTools() {
  const [tools, setTools] = useState([]);
  const [queue, setQueue] = useState(null);
  const [jobs, setJobs] = useState([]);
  const [loading, setLoading] = useState(true);

  const refreshTools = useCallback(async () => {
    const data = await get("/dashboard/tools/");
    setTools(data?.tools || []);
  }, []);

  const refreshQueue = useCallback(async () => {
    const data = await get("/dashboard/tools/queue");
    setQueue(data);
    setJobs(data?.recent_jobs || []);
  }, []);

  const refresh = useCallback(async () => {
    setLoading(true);
    await Promise.all([refreshTools(), refreshQueue()]);
    setLoading(false);
  }, [refreshTools, refreshQueue]);

  useEffect(() => { refresh(); }, [refresh]);

  // SSE: subscribe to domain events for real-time tool/job updates
  useEffect(() => {
    // Use shared SSE service to avoid connection limits
    if (!globalThis.SSEService) {
      console.warn("SSEService not available");
      return;
    }
    
    const toolEvents = new Set([
      "JobDispatched", "JobCompleted", "JobFailed",
      "TaskAssigned", "TaskCompleted", "TaskFailed",
    ]);
    const unsubscribe = globalThis.SSEService.subscribe(
      "ToolsPanel",
      toolEvents,
      () => {
        refresh();
      }
    );
    
    return unsubscribe;
  }, [refresh]);

  return { tools, queue, jobs, loading, refresh };
}

// ── ToolsPanel (main) ───────────────────────────────────────
// Delegates to globally-loaded sub-components:
//   ToolCard, JobRow, JobDetailsPanel, QueueSummary, PredictiveAlerts,
//   HealthTrends, ToolsRegistry, ToolHealthPanelRefactored,
//   TicketDispatchTable, ToolsDispatch, ToolsJobQueue.

function ToolsPanel({ selectedTool, setSelectedTool }) {
  const { tools, queue, jobs, loading, refresh } = useTools();

  if (loading) {
    return <Card title="Tools"><p className="text-gray-400 text-sm">Loading...</p></Card>;
  }

  const available = tools.filter(t => t.available);

  return (
    <div className="space-y-6">
      <ToolsRegistry
        tools={tools}
        selectedTool={selectedTool}
        onToolSelect={setSelectedTool}
        onRefresh={refresh}
      />

      <PredictiveAlerts tools={tools} queue={queue} jobs={jobs} />

      <ToolHealthPanelRefactored />

      <ToolsDispatch tools={tools} onRefresh={refresh} />

      <ToolsJobQueue queue={queue} jobs={jobs} onRefresh={refresh} />
    </div>
  );
}
