/**
 * Shared UI event channels for cross-component communication.
 */
const SIDEBAR_EVENT = 'app:sidebar';
const ASIDE_PANELS_EVENT = 'app:aside-panels';

const dispatch = (eventName, detail = {}) => {
  document.dispatchEvent(new CustomEvent(eventName, { detail }));
};

export const requestSidebarAction = (action, options = {}) => {
  const normalizedAction = String(action || '').trim();
  if (normalizedAction === '') {
    return;
  }
  dispatch(SIDEBAR_EVENT, {
    action: normalizedAction,
    persist: Boolean(options.persist),
  });
};

export const requestAsidePanelOpen = (panel, options = {}) => {
  const normalizedPanel = String(panel || '').trim();
  if (normalizedPanel === '') {
    return;
  }
  dispatch(ASIDE_PANELS_EVENT, {
    action: 'open',
    panel: normalizedPanel,
    fromUser: options.fromUser !== false,
  });
};

export const bindAsidePanelChannel = (handler) => {
  if (typeof handler !== 'function') {
    return () => {};
  }
  const listener = (event) => {
    handler(event instanceof CustomEvent ? event.detail || {} : {});
  };
  document.addEventListener(ASIDE_PANELS_EVENT, listener);
  return () => {
    document.removeEventListener(ASIDE_PANELS_EVENT, listener);
  };
};
