/* Space tabs — topbar segmented switcher (echoes vault.dhruvshah.co's
   Notes/Files tabs, redesigned) + the app shell */

const SPACES = [
  { id: 'notes', label: 'Notes', icon: 'fileText', key: '1' },
  { id: 'files', label: 'Files', icon: 'folder', key: '2' },
  { id: 'calendar', label: 'Calendar', icon: 'calendar', key: '3' },
  { id: 'study', label: 'Study', icon: 'listUl', key: '4' },
];

function SpaceTabs({ space, onSwitch }) {
  return React.createElement('nav', { className: 'space-tabs' },
    SPACES.map(s => React.createElement('button', {
      key: s.id, className: 'space-tab' + (space === s.id ? ' on' : ''),
      onClick: () => onSwitch(s.id), title: s.label + ' — press ' + s.key,
    },
      React.createElement(Icons[s.icon], { size: 14 }),
      React.createElement('span', null, s.label),
      React.createElement('kbd', { className: 'k' }, s.key))));
}

function VaultShell() {
  const [authed, setAuthed] = React.useState(() => window.VaultDB.hasSession());
  const [showTools, setShowTools] = React.useState(false);
  const [space, setSpace] = React.useState(() => loadLS('vault-space', 'notes'));
  const [out, setOut] = React.useState(false);
  const timer = React.useRef(null);

  // Validate any stored session token on boot (clears it if the server has
  // expired/revoked it).
  React.useEffect(() => {
    if (window.VaultDB.hasSession()) {
      window.VaultDB.verifySession().then((ok) => { if (!ok) setAuthed(false); }).catch(() => {});
    }
  }, []);

  // (Re-)probe backend capabilities whenever we become authenticated. Once the
  // DB is RLS-locked the probes need the session header, so they must run
  // AFTER sign-in — not once at boot.
  React.useEffect(() => { if (authed) { try { window.VaultDB.init(); } catch (e) {} } }, [authed]);

  const unlock = () => setAuthed(true); // signIn() already minted + stored the token
  // Revoke server-side, then hard reload for a fully clean logout.
  const logout = () => { window.VaultDB.logout().finally(() => window.location.reload()); };

  const onSwitch = (id) => {
    if (id === space) return;
    setOut(true);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      setSpace(id); saveLS('vault-space', id);
      setOut(false);
    }, 170);
  };

  // Keyboard: 1 / 2 / 3 switch spaces (ignored while typing)
  React.useEffect(() => {
    const onKey = (e) => {
      const t = e.target;
      if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return;
      const hit = SPACES.find(s => s.key === e.key);
      if (hit) { e.preventDefault(); onSwitch(hit.id); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [space]);

  const tabs = React.createElement(SpaceTabs, { space, onSwitch });
  const utils = React.createElement(window.TopbarUtils, { onLogout: logout });

  if (!authed) {
    if (showTools) return React.createElement(window.ToolsLauncher, { onBack: () => setShowTools(false) });
    return React.createElement(window.LoginScreen, { onUnlock: unlock, onTools: () => setShowTools(true) });
  }

  let view = null;
  if (space === 'notes') view = React.createElement(NotesSpace, { tabs, utils });
  else if (space === 'files') view = React.createElement(FilesSpace, { tabs, utils });
  else if (space === 'study') view = React.createElement(window.StudySpace, { tabs, utils });
  else view = React.createElement(window.App, { tabs, utils });

  return React.createElement('div', { className: 'shell' },
    React.createElement('div', { className: 'space-wrap' + (out ? ' out' : '') }, view));
}

Object.assign(window, { SpaceTabs, VaultShell });
