// panel.jsx — Entry point. All components loaded via separate script tags.
// Load order: api.js → formatters.js → useDashboardData.js → ui.jsx →
//             models.jsx → accounts.jsx → users.jsx → layout.jsx → overview.jsx →
//             vms.jsx → logs.jsx → panel.jsx (this file)

// React globals (from UMD build)
const useState = React.useState;
const useEffect = React.useEffect;
const useCallback = React.useCallback;

// ── Tab Definitions ───────────────────────────────────────────
// Mapping of tab keys to render functions that produce the tab content.
// Each function receives the full `data` object from useDashboardData.
const TAB_DEFINITIONS = {
  home: (data) => (
    <HomeTab
      health={data.health}
      connected={data.connected}
      budget={data.budget}
      costs={data.costs}
    />
  ),
  overview: (data) => (
    <OverviewTab
      budget={data.budget}
      connected={data.connected}
      health={data.health}
      models={data.models}
      providers={data.providers}
      accounts={data.accounts}
      context={data.resourcesContext}
      costs={data.costs}
      refresh={data.refresh}
    />
  ),
  projects: (data) => (
    <ProjectsPanel
      selectedProject={data.selectedProject}
      setSelectedProject={data.setSelectedProject}
      lastAction={data.lastAction}
      viewMode={data.viewMode}
      setLastAction={data.setLastAction}
      setViewMode={data.setViewMode}
      setContext={data.setContext}
    />
  ),
  diagnostics: (data) => <DiagnosticsPanel />,
  voice: (data) => <VoiceChat proxymBase={_api()} apiKey={_key()} />,
  accounts: (data) => (
    <AccountsPanel
      accounts={data.accounts}
      onRefresh={data.refresh}
    />
  ),
  models: (data) => (
    <Card title={`Available Models (${data.models?.length || 0})`}>
      <ModelsTable models={data.models} />
    </Card>
  ),
  vms: (data) => (
    <VMsPanel
      vms={data.vms}
      onRefresh={data.refresh}
    />
  ),
  tasks: (data) => (
    <TasksPanelRefactored
      viewMode={data.viewMode}
      setViewMode={data.setViewMode}
      filterStatus={data.filterStatus}
      setFilterStatus={data.setFilterStatus}
      filterAgent={data.filterAgent}
      setFilterAgent={data.setFilterAgent}
      searchQuery={data.searchQuery}
      setSearchQuery={data.setSearchQuery}
    />
  ),
  tickets: (data) => (
    <TicketsPanelRefactored
      selectedTicket={data.selectedTicket}
      setSelectedTicket={data.setSelectedTicket}
      filterStatus={data.filterStatus}
      setFilterStatus={data.setFilterStatus}
      searchQuery={data.searchQuery}
      setSearchQuery={data.setSearchQuery}
    />
  ),
  human: (data) => (
    <HumanTaskPanelRefactored
      viewMode={data.viewMode}
      setViewMode={data.setViewMode}
      filterStatus={data.filterStatus}
      setFilterStatus={data.setFilterStatus}
    />
  ),
  tools: (data) => (
    <ToolsPanelRefactored
      selectedTool={data.selectedTool}
      setSelectedTool={data.setSelectedTool}
    />
  ),
  environments: (data) => <EnvironmentsPanel />,
  users: (data) => <UsersPanel />,
  setup: (data) => <SetupPanel />,
  integrations: (data) => <IntegrationsPanel />,
  system: (data) => <SystemPanel />,
};

// ── Tab Renderer Component ───────────────────────────────────
// Handles rendering of a tab with error boundaries and fallbacks.
function TabRenderer({ tab, data }) {
  const renderFn = TAB_DEFINITIONS[tab];
  
  if (!renderFn) {
    console.error(`Tab component not found for tab: ${tab}`);
    return (
      <div className="p-6 text-center">
        <div className="text-red-600 font-medium">Tab not available</div>
        <div className="text-gray-500 text-sm mt-1">The tab "{tab}" could not be loaded.</div>
      </div>
    );
  }

  try {
    return renderFn(data);
  } catch (error) {
    console.error(`Error rendering tab ${tab}:`, error);
    return (
      <div className="p-6 text-center">
        <div className="text-red-600 font-medium">Error rendering tab</div>
        <div className="text-gray-500 text-sm mt-1">{error.message}</div>
      </div>
    );
  }
}

// ── Main Dashboard ───────────────────────────────────────────

function Dashboard() {
  const data = useDashboardData();
  const rootStyle = {
    backgroundColor: "var(--dashboard-bg)",
    color: "var(--dashboard-text)",
  };

  return (
    <div className="min-h-screen pb-20 transition-colors duration-200" data-theme={data.theme} style={rootStyle}>
      <DashboardHeader
        connected={data.connected}
        lastRefresh={data.lastRefresh}
        health={data.health}
        onRefresh={data.refresh}
        theme={data.theme}
        onToggleTheme={data.toggleTheme}
      />
      <TabNav tab={data.tab} onTabChange={data.setTab} theme={data.theme} />
      <main className="max-w-7xl mx-auto px-6 py-6">
        <TabRenderer tab={data.tab} data={data} />
      </main>
      <LogPanel logs={data.logs} error={data.logsError} source={data.logsSource} />
    </div>
  );
}

// Render the app (wait for async /config load if present)
const _startDashboard = async () => {
  try {
    if (globalThis.__APP_CONFIG_READY__) {
      await globalThis.__APP_CONFIG_READY__;
    }
  } catch {
    // ignore — dashboard can still boot with defaults
  }
  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(<Dashboard />);
};

_startDashboard();
