// Vanday DAM — Active user session (mock multi-user, "view as")
//
// Stores which mock user the current viewer is acting as in localStorage,
// so different members can be tested locally without real account auth.
// This is a prototype affordance, not real auth — every browser tab can
// switch user freely.
(function () {
  const KEY = "vanday_active_user_id";
  const DEFAULT_ID = "u1"; // Maya Rodriguez, Owner

  function getActiveUserId() {
    try { return localStorage.getItem(KEY) || DEFAULT_ID; }
    catch { return DEFAULT_ID; }
  }

  function setActiveUserId(id) {
    try { localStorage.setItem(KEY, id); } catch {}
    // Simplest reactivity: reload so every component re-reads the active user.
    location.reload();
  }

  function getActiveUser() {
    const users = Array.isArray(window.USERS) ? window.USERS : [];
    const id = getActiveUserId();
    return users.find((u) => u.id === id) || users[0] || null;
  }

  // First letter of first name + first letter of last name.
  function cleanInitials(user) {
    if (!user || !user.name) return "?";
    const parts = user.name.trim().split(/\s+/);
    const a = (parts[0] && parts[0][0]) || "";
    const b = (parts.length > 1 && parts[parts.length - 1][0]) || "";
    return (a + b).toUpperCase() || "?";
  }

  // Permission helper: can the active user see this folder?
  function canSeeFolder(folderId) {
    const perms = window.FOLDER_PERMS && window.FOLDER_PERMS[folderId];
    if (!perms) return true; // no permission record = allow
    if (perms.link === "workspace" || perms.link === "anyone") return true;
    if (perms.link === "restricted") {
      const me = getActiveUserId();
      return (perms.members || []).some(([uid]) => uid === me);
    }
    return true;
  }

  window.VandaySession = {
    getActiveUserId,
    setActiveUserId,
    getActiveUser,
    initials: cleanInitials,
    canSeeFolder,
  };
})();
