type VojoElectronApi = {
  platform: NodeJS.Platform;
  openExternal: (url: string) => Promise<void>;
};

declare global {
  interface Window {
    vojoElectron?: VojoElectronApi;
  }
}

export const isElectron = (): boolean => typeof window !== 'undefined' && !!window.vojoElectron;

export const openExternalUrl = async (url: string): Promise<void> => {
  const api = window.vojoElectron;
  if (api) {
    await api.openExternal(url);
    return;
  }
  window.open(url, '_blank', 'noopener');
};

export const setupExternalLinkHandler = (): (() => void) | undefined => {
  const api = window.vojoElectron;
  if (!api) return undefined;

  const handler = (e: MouseEvent) => {
    const anchor = (e.target as HTMLElement).closest?.(
      'a[target="_blank"]'
    ) as HTMLAnchorElement | null;
    if (!anchor?.href) return;
    if (anchor.dataset.mentionId) return;

    e.preventDefault();
    api.openExternal(anchor.href);
  };

  document.addEventListener('click', handler, true);
  return () => document.removeEventListener('click', handler, true);
};
