const USER_ID_STORAGE_KEY = "agentbyte.webui.user_id";

function createUserId(): string {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return `user-${Date.now()}`;
}

export function getOrCreateBrowserUserId(): string {
  if (typeof window === "undefined") {
    return createUserId();
  }

  const existing = window.localStorage.getItem(USER_ID_STORAGE_KEY);
  if (existing) {
    return existing;
  }

  const generated = createUserId();
  window.localStorage.setItem(USER_ID_STORAGE_KEY, generated);
  return generated;
}
