// workspace-switcher.jsx — Header dropdown listing the user's Workspaces.
//
// R03 / T0007 (Phase 5). Linear-style switcher: click the current
// Workspace's name in the header, get a dropdown of every Workspace
// you're a member of (with your role badge), click one to navigate to
// `/w/<id>/dashboard`. Bottom of the dropdown carries a "+ Add Workspace"
// link to `/onboard/add-workspace`.
//
// Exposes window.WorkspaceSwitcher.

(function (window) {
  'use strict';

  const { useWorkspace, useActiveWorkspaceId, workspacePath, navigateTo } =
    window.exoteamAuth || {};
  if (!useWorkspace) {
    console.error('workspace-switcher.jsx: window.exoteamAuth missing');
    return;
  }

  // role → small badge text
  const ROLE_LABEL = {
    owner: 'Owner',
    admin: 'Admin',
    member: 'Member',
    viewer: 'Viewer',
  };

  function WorkspaceSwitcher() {
    const { workspaces, loading, activeWorkspace } = useWorkspace();
    const activeWorkspaceId = useActiveWorkspaceId();
    const [open, setOpen] = React.useState(false);
    const rootRef = React.useRef(null);

    // Close on outside click.
    React.useEffect(() => {
      if (!open) return undefined;
      function onClick(e) {
        if (rootRef.current && !rootRef.current.contains(e.target)) {
          setOpen(false);
        }
      }
      document.addEventListener('mousedown', onClick);
      return () => document.removeEventListener('mousedown', onClick);
    }, [open]);

    function switchTo(wid) {
      setOpen(false);
      navigateTo(workspacePath(wid, 'dashboard'));
    }

    function addWorkspace() {
      setOpen(false);
      navigateTo('/onboard/add-workspace');
    }

    const currentLabel =
      (activeWorkspace && activeWorkspace.display_name) ||
      (activeWorkspaceId ? activeWorkspaceId.slice(0, 8) + '…' : 'Workspace');

    return (
      <div className="exo-ws-switcher" ref={rootRef}>
        <style>{`
.exo-ws-switcher { position: relative; }
.exo-ws-switcher-button {
  display: inline-flex; align-items: center; gap: 8px;
  background: rgba(0,0,0,0.04); border: 1px solid rgba(0,0,0,0.06);
  border-radius: 999px; padding: 6px 12px 6px 10px;
  font-size: 13px; color: #1d1d1f; font-weight: 500;
  cursor: pointer; font-family: inherit;
  transition: background 0.15s ease;
}
.exo-ws-switcher-button:hover { background: rgba(0,0,0,0.07); }
.exo-ws-switcher-button-dot { width: 8px; height: 8px; border-radius: 50%; background: #5b8def; flex-shrink: 0; }
.exo-ws-switcher-caret { font-size: 10px; color: #86868b; margin-left: 2px; }
.exo-ws-switcher-menu {
  position: absolute; top: calc(100% + 6px); left: 0; z-index: 50;
  min-width: 280px; max-width: 360px;
  background: #fff; border: 1px solid rgba(0,0,0,0.08);
  border-radius: 14px; box-shadow: 0 12px 32px rgba(0,0,0,0.10), 0 1px 3px rgba(0,0,0,0.05);
  padding: 6px; overflow: hidden;
}
.exo-ws-switcher-item {
  display: flex; align-items: center; gap: 10px;
  width: 100%; padding: 8px 10px;
  background: transparent; border: none;
  border-radius: 9px;
  font-family: inherit; font-size: 13.5px; color: #1d1d1f;
  text-align: left; cursor: pointer;
  transition: background 0.12s ease;
}
.exo-ws-switcher-item:hover { background: rgba(0,0,0,0.04); }
.exo-ws-switcher-item.is-active { background: rgba(91,141,239,0.08); }
.exo-ws-switcher-item-dot { width: 8px; height: 8px; border-radius: 50%; background: #5b8def; flex-shrink: 0; }
.exo-ws-switcher-item-body { flex: 1; min-width: 0; }
.exo-ws-switcher-item-name { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.exo-ws-switcher-item-role { font-size: 11px; color: #86868b; margin-top: 1px; text-transform: uppercase; letter-spacing: 0.04em; }
.exo-ws-switcher-divider { height: 1px; background: rgba(0,0,0,0.06); margin: 6px 4px; }
.exo-ws-switcher-add {
  color: #5b8def; font-weight: 500;
}
.exo-ws-switcher-empty {
  padding: 14px 12px; color: #86868b; font-size: 12.5px;
}
        `}</style>
        <button
          type="button"
          className="exo-ws-switcher-button"
          onClick={() => setOpen((v) => !v)}
          aria-haspopup="menu"
          aria-expanded={open}
        >
          <span className="exo-ws-switcher-button-dot" />
          <span>{currentLabel}</span>
          <span className="exo-ws-switcher-caret">▾</span>
        </button>
        {open && (
          <div className="exo-ws-switcher-menu" role="menu">
            {loading && (
              <div className="exo-ws-switcher-empty">Loading workspaces…</div>
            )}
            {!loading && workspaces.length === 0 && (
              <div className="exo-ws-switcher-empty">
                No workspaces yet — finish setup to create your first.
              </div>
            )}
            {workspaces.map((w) => {
              const isActive = w.workspace_id === activeWorkspaceId;
              return (
                <button
                  key={w.workspace_id}
                  type="button"
                  role="menuitem"
                  className={
                    'exo-ws-switcher-item ' + (isActive ? 'is-active' : '')
                  }
                  onClick={() => switchTo(w.workspace_id)}
                >
                  <span className="exo-ws-switcher-item-dot" />
                  <div className="exo-ws-switcher-item-body">
                    <div className="exo-ws-switcher-item-name">
                      {w.display_name || w.workspace_id}
                    </div>
                    <div className="exo-ws-switcher-item-role">
                      {ROLE_LABEL[w.role] || w.role}
                    </div>
                  </div>
                </button>
              );
            })}
            {workspaces.length > 0 && <div className="exo-ws-switcher-divider" />}
            <button
              type="button"
              role="menuitem"
              className="exo-ws-switcher-item exo-ws-switcher-add"
              onClick={addWorkspace}
            >
              <span style={{ width: 8, height: 8, lineHeight: '8px', color: '#5b8def', fontWeight: 700 }}>+</span>
              <div className="exo-ws-switcher-item-body">
                <div className="exo-ws-switcher-item-name">Add Workspace</div>
              </div>
            </button>
          </div>
        )}
      </div>
    );
  }

  window.WorkspaceSwitcher = WorkspaceSwitcher;
})(window);
