// Sherpas Labs — fake auth (localStorage)
// Two roles: "team" (full access) and "partner" (external projects only).

window.SHERPAS_AUTH = (() => {
  const KEY = "sherpas_labs_user";

  // Which projects each role can open.
  const ACCESS = {
    team:    new Set(["SX-001", "SX-002", "SX-003", "SX-004", "SX-005", "SX-006"]),
    partner: new Set(["SX-001", "SX-002", "SX-003"]),
  };

  const get = () => {
    try {
      const raw = localStorage.getItem(KEY);
      return raw ? JSON.parse(raw) : null;
    } catch { return null; }
  };

  const set = (user) => {
    localStorage.setItem(KEY, JSON.stringify(user));
  };

  const clear = () => localStorage.removeItem(KEY);

  const canAccess = (user, projectId) => {
    if (!user) return false;
    return (ACCESS[user.role] || new Set()).has(projectId);
  };

  const requireAuth = () => {
    const u = get();
    if (!u) {
      // Bounce to login from anywhere.
      const here = window.location.pathname.split("/").slice(-2).join("/");
      window.location.href = (window.location.pathname.includes("/projects/") ? "../login.html" : "login.html") + "?next=" + encodeURIComponent(here);
      return null;
    }
    return u;
  };

  return { get, set, clear, canAccess, requireAuth, ACCESS };
})();
