/* global React, window */
const { useEffect: useEffectWorkspace, useState: useStateWorkspace } = React;

const WORKSPACE_STORAGE_KEY = 'pluginchatbot_selected_workspace_id';
const WORKSPACE_CHANGE_EVENT = 'pluginchatbot:workspace-changed';

function getStoredWorkspaceId() {
  try {
    return window.localStorage.getItem(WORKSPACE_STORAGE_KEY) || '';
  } catch (error) {
    return '';
  }
}

function setStoredWorkspaceId(workspaceId) {
  const safeWorkspaceId = String(workspaceId || '').trim();

  try {
    if (safeWorkspaceId) {
      window.localStorage.setItem(WORKSPACE_STORAGE_KEY, safeWorkspaceId);
    } else {
      window.localStorage.removeItem(WORKSPACE_STORAGE_KEY);
    }
  } catch (error) {}

  window.dispatchEvent(new CustomEvent(WORKSPACE_CHANGE_EVENT, {
    detail: {
      workspaceId: safeWorkspaceId,
    },
  }));
}

function initializeWorkspaceSelection(workspaces, defaultWorkspaceId = '') {
  const items = Array.isArray(workspaces) ? workspaces : [];
  const storedWorkspaceId = getStoredWorkspaceId();
  const storedExists = items.some(item => item.workspaceId === storedWorkspaceId);
  const defaultExists = items.some(item => item.workspaceId === defaultWorkspaceId);
  const nextWorkspaceId = storedExists
    ? storedWorkspaceId
    : defaultExists
      ? defaultWorkspaceId
      : items[0]?.workspaceId || '';

  if (nextWorkspaceId) {
    setStoredWorkspaceId(nextWorkspaceId);
  }

  return nextWorkspaceId;
}

function getWorkspaceSearchParams(workspaceId = getStoredWorkspaceId()) {
  const safeWorkspaceId = String(workspaceId || '').trim();
  return safeWorkspaceId ? `?workspaceId=${encodeURIComponent(safeWorkspaceId)}` : '';
}

function addWorkspaceToUrl(url, workspaceId = getStoredWorkspaceId()) {
  const safeWorkspaceId = String(workspaceId || '').trim();
  const nextUrl = new URL(url, window.location.origin);

  if (safeWorkspaceId) {
    nextUrl.searchParams.set('workspaceId', safeWorkspaceId);
  }

  return `${nextUrl.pathname}${nextUrl.search}`;
}

function useSelectedWorkspaceId() {
  const [workspaceId, setWorkspaceId] = useStateWorkspace(getStoredWorkspaceId);

  useEffectWorkspace(() => {
    const handleWorkspaceChange = event => {
      setWorkspaceId(event.detail?.workspaceId || getStoredWorkspaceId());
    };

    const handleStorage = event => {
      if (event.key === WORKSPACE_STORAGE_KEY) {
        setWorkspaceId(event.newValue || '');
      }
    };

    window.addEventListener(WORKSPACE_CHANGE_EVENT, handleWorkspaceChange);
    window.addEventListener('storage', handleStorage);

    return () => {
      window.removeEventListener(WORKSPACE_CHANGE_EVENT, handleWorkspaceChange);
      window.removeEventListener('storage', handleStorage);
    };
  }, []);

  return workspaceId;
}

window.getStoredWorkspaceId = getStoredWorkspaceId;
window.setStoredWorkspaceId = setStoredWorkspaceId;
window.initializeWorkspaceSelection = initializeWorkspaceSelection;
window.getWorkspaceSearchParams = getWorkspaceSearchParams;
window.addWorkspaceToUrl = addWorkspaceToUrl;
window.useSelectedWorkspaceId = useSelectedWorkspaceId;