// Membrane Agency — App shell
const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const [activeNav, setActiveNav] = useStateApp('jobs');
  const [cmdkOpen, setCmdkOpen] = useStateApp(false);
  const [currentWs, setCurrentWs] = useStateApp(WORKSPACES[0]);
  const [pendingHotkey, setPendingHotkey] = useStateApp(null);

  // Keyboard shortcuts
  useEffectApp(() => {
    const onKey = (e) => {
      const inField = ['INPUT','TEXTAREA'].includes(e.target?.tagName);
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setCmdkOpen(o => !o);
        return;
      }
      if (inField) return;
      if (e.key.toLowerCase() === 'g' && !e.metaKey && !e.ctrlKey) {
        setPendingHotkey('g');
        setTimeout(() => setPendingHotkey(p => (p === 'g' ? null : p)), 1200);
        return;
      }
      if (pendingHotkey === 'g') {
        const map = { d: 'discovery', j: 'jobs', i: 'integrations', a: 'data', r: 'rules' };
        const target = map[e.key.toLowerCase()];
        if (target) { setActiveNav(target); setPendingHotkey(null); return; }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [pendingHotkey]);

  const handleCmdkAction = (action) => {
    setCmdkOpen(false);
    if (action.id.startsWith('go-')) setActiveNav(action.id.slice(3));
    else if (action.id.startsWith('switch-')) {
      const w = WORKSPACES.find(w => w.id === action.id.slice(7));
      if (w) setCurrentWs(w);
    }
  };

  return (
    <div className="app">
      <Sidebar
        activeNav={activeNav}
        onNav={setActiveNav}
        currentWs={currentWs}
        setCurrentWs={setCurrentWs}
      />
      <main className="main">
        {activeNav === 'jobs'
          ? <AgentJobsPage renderTopBar={(slot) => <TopBar activeNav={activeNav} slot={slot} workspaceName={currentWs.name}/>}/>
          : <><TopBar activeNav={activeNav} workspaceName={currentWs.name}/><Skeleton activeNav={activeNav}/></>}
      </main>
      <CmdK open={cmdkOpen} onClose={() => setCmdkOpen(false)} onAction={handleCmdkAction}/>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
