// The shell owns navigation, the command palette and the toast stack. Screens are
// pure views: they receive `go` and `notify` and never manage chrome themselves.

const NAV_GROUPS = [
  { items: [
    { id: 'home', label: 'Inicio', icon: 'space_dashboard' },
    { id: 'tasks', label: 'Pendientes', icon: 'inbox', count: 7, dot: true }
  ] },
  { label: 'Trabajo', items: [
    { id: 'clients', label: 'Clientes', icon: 'business', count: 12 },
    { id: 'project', label: 'Proyectos', icon: 'folder_open', count: 23 },
    { id: 'artifact', label: 'Outputs', icon: 'description', count: 148 }
  ] },
  { label: 'Negocio', items: [
    { id: 'microapps', label: 'Microapps', icon: 'monitoring' }
  ] },
  { label: 'Sistema', items: [
    { id: 'agents', label: 'Agentes', icon: 'auto_awesome', count: 17 },
    { id: 'flows', label: 'Workflows', icon: 'account_tree', count: 9 },
    { id: 'knowledge', label: 'Conocimiento', icon: 'library_books' },
    { id: 'runs', label: 'Ejecuciones', icon: 'history' }
  ] }
];

const VIEW_TITLES = {
  home: ['Inicio', 'Command center'],
  clients: ['ACME Industrial', 'Cliente 360'],
  project: ['Automatización comercial', 'Proyecto'],
  agents: ['Agentes', 'Biblioteca'],
  agent: ['Research Agent', 'Espacio de trabajo'],
  flows: ['Propuesta comercial', 'Workflow'],
  artifact: ['Propuesta — Automatización comercial', 'Output'],
  microapps: ['Microapps con IA', 'Panel del embudo'],
  tasks: ['Pendientes', 'Tareas del equipo'],
  knowledge: ['Conocimiento', 'Bases y fuentes'],
  runs: ['Ejecuciones', 'Historial']
};

function WorkspaceShell({ initialView = 'home' }) {
  const { SidebarNav, Topbar, ContextSwitcher, SearchField, IconButton, Avatar, CommandPalette, Kbd, Toast, Button, EmptyState } = window.EG;
  const [view, setView] = React.useState(initialView);
  const [paletteOpen, setPaletteOpen] = React.useState(false);
  const [query, setQuery] = React.useState('Analiza la reunión con ACME y genera propuesta');
  const [collapsed, setCollapsed] = React.useState(false);
  const [toasts, setToasts] = React.useState([]);
  const [theme, setTheme] = React.useState('dark');

  const notify = (t) => {
    const id = Date.now() + Math.random();
    setToasts(list => [...list, { ...t, id }]);
    setTimeout(() => setToasts(list => list.filter(x => x.id !== id)), 5200);
  };
  const go = (v) => { setView(v); setPaletteOpen(false); };

  React.useEffect(() => {
    const onKey = e => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); setPaletteOpen(o => !o); }
      if (e.key === 'Escape') setPaletteOpen(false);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  const Screen = {
    home: ScreenHome, clients: ScreenClient, agents: ScreenAgents, agent: ScreenAgentWork,
    project: ScreenProject, flows: ScreenFlows, artifact: ScreenArtifact,
    microapps: ScreenMicroapps
  }[view];

  const [title, kicker] = VIEW_TITLES[view] || ['—', ''];

  return (
    <div className="ws">
      <SidebarNav collapsed={collapsed} activeId={view} onSelect={go} groups={NAV_GROUPS}
        header={
          <div className="ws-row" style={{ justifyContent: 'space-between' }}>
            <a href="#" onClick={e => { e.preventDefault(); go('home'); }} className="ws-row" style={{ gap: 9 }}>
              <img src="../../assets/logo-icon.png" alt="" style={{ width: 22 }} />
              {!collapsed && <span className="eg-wordmark" style={{ fontSize: 10, color: 'var(--text-primary)' }}>Esteban Guzmán</span>}
            </a>
            {!collapsed && <IconButton icon="left_panel_close" label="Colapsar" size="sm" onClick={() => setCollapsed(true)} />}
          </div>
        }
        footer={
          collapsed
            ? <IconButton icon="left_panel_open" label="Expandir" size="sm" onClick={() => setCollapsed(false)} />
            : <div className="ws-row" style={{ justifyContent: 'space-between' }}>
                <span className="ws-row" style={{ gap: 8 }}>
                  <Avatar name="Esteban Guzmán" size="xs" />
                  <span style={{ font: 'var(--type-body-sm)', fontSize: 12, color: 'var(--text-tertiary)' }}>Esteban</span>
                </span>
                <span className="ws-row" style={{ gap: 2 }}>
                  <IconButton icon={theme === 'dark' ? 'light_mode' : 'dark_mode'} label="Tema" size="sm" onClick={() => setTheme(t => t === 'dark' ? 'light' : 'dark')} />
                  <IconButton icon="settings" label="Configuración" size="sm" />
                  <IconButton icon="logout" label="Cerrar sesión" size="sm" onClick={() => window.WorkspaceAuth && window.WorkspaceAuth.salir()} />
                </span>
              </div>
        } />

      <div className="ws-main">
        <Topbar
          left={<ContextSwitcher client="ACME Industrial" project="Automatización comercial" clientCode="AC" onClick={() => go('clients')} />}
          center={<div onClick={() => setPaletteOpen(true)} style={{ width: 380, minWidth: 0, maxWidth: '100%' }}><SearchField width="100%" size="sm" placeholder="Buscar" shortcut="⌘K" readOnly /></div>}
          right={<>
            <Button size="sm" variant="quiet" icon="bolt" onClick={() => { notify({ tone: 'running', title: 'Ejecución iniciada', description: 'Propuestas Agent · ACME Industrial' }); go('agent'); }}>Ejecutar</Button>
            <IconButton icon="notifications" label="Actividad" size="sm" badge />
            <IconButton icon="help" label="Ayuda" size="sm" />
          </>} />

        <div className="ws-scroll" style={{ overflow: view === 'agent' || view === 'flows' ? 'hidden' : 'auto', display: 'flex', flexDirection: 'column' }}>
          {Screen
            ? <Screen go={go} notify={notify} title={title} kicker={kicker} openPalette={() => setPaletteOpen(true)} />
            : <div style={{ margin: 'auto' }}>
                <EmptyState icon="construction" title={title} description="Esta área existe en la arquitectura pero todavía no está diseñada." hint="Se añade sin cambiar la navegación." action={<Button size="sm" variant="secondary" onClick={() => go('home')}>Volver a inicio</Button>} />
              </div>}
        </div>
      </div>

      {paletteOpen && (
        <CommandPalette
          query={query} onQueryChange={setQuery} onClose={() => setPaletteOpen(false)}
          detected={[{ label: 'cliente', value: 'ACME Industrial' }, { label: 'proyecto', value: 'Automatización comercial' }, { label: 'agente', value: 'Propuestas' }]}
          groups={window.EGData.paletteGroups}
          onSelect={item => {
            setPaletteOpen(false);
            if (item.label.indexOf('Cliente 360') === 0) return go('clients');
            if (item.label.indexOf('Automatización comercial') === 0) return go('project');
            if (item.label.indexOf('Nuevo workflow') === 0) return go('flows');
            if (item.label.indexOf('Propuestas Agent') === 0) return go('agent');
            notify({ tone: 'running', title: 'Ejecución iniciada', description: item.label });
            go('agent');
          }}
          footer={<>
            <span className="ws-row" style={{ gap: 6, font: 'var(--type-mono-sm)', color: 'var(--text-muted)' }}><Kbd>↵</Kbd>ejecutar</span>
            <span className="ws-row" style={{ gap: 6, font: 'var(--type-mono-sm)', color: 'var(--text-muted)' }}><Kbd>⌘</Kbd><Kbd>↵</Kbd>en segundo plano</span>
            <span className="ws-row" style={{ gap: 6, font: 'var(--type-mono-sm)', color: 'var(--text-muted)', marginLeft: 'auto' }}>escribe <span style={{ color: 'var(--accent-text)' }}>@</span> para elegir agente</span>
          </>} />
      )}

      <div style={{ position: 'fixed', right: 20, bottom: 20, zIndex: 200, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {toasts.map(t => <Toast key={t.id} {...t} onClose={() => setToasts(list => list.filter(x => x.id !== t.id))} />)}
      </div>
    </div>
  );
}

Object.assign(window, { WorkspaceShell });
