"use client";

import { create } from "zustand";

interface WorkspaceState {
  activeTeamId: string | null;
  initialized: boolean;
  /** true once the user has explicitly chosen any workspace (team or personal) */
  hasExplicitChoice: boolean;
  initWorkspace: () => void;
  setActiveTeamId: (teamId: string | null) => void;
}

const STORAGE_KEY = "mindavio-active-team-id";
// Sentinel stored when user explicitly picks Personal workspace
const PERSONAL_SENTINEL = "__personal__";

export const useWorkspaceStore = create<WorkspaceState>((set) => ({
  activeTeamId: null,
  initialized: false,
  hasExplicitChoice: false,

  initWorkspace: () => {
    if (typeof window === "undefined") return;
    const stored = localStorage.getItem(STORAGE_KEY);
    set({
      activeTeamId: stored && stored !== PERSONAL_SENTINEL ? stored : null,
      initialized: true,
      // If any value (including sentinel) is stored, the user has made an explicit choice
      hasExplicitChoice: stored !== null,
    });
  },

  setActiveTeamId: (teamId) => {
    if (typeof window !== "undefined") {
      if (teamId) {
        localStorage.setItem(STORAGE_KEY, teamId);
      } else {
        // Store sentinel instead of removing key so we know personal was chosen deliberately
        localStorage.setItem(STORAGE_KEY, PERSONAL_SENTINEL);
      }
    }

    set({ activeTeamId: teamId, hasExplicitChoice: true });
  },
}));
