// Platform-aware external-link opening. Both Mini App hosts mishandle a plain target=_blank
// anchor: Telegram shows the WebView's generic "open this link?" confirmation, and the Android VK
// client navigates the app's own WebView to the target with no way back to the game. The helpers
// below route an external URL through the platform's escape hatch (Telegram's openLink, VK's
// away.php redirect) and leave the anchor's own navigation / window.open in effect elsewhere.

import { routeExternalLinkInTelegram, telegramOpenExternalLink } from './telegram';
import { routeExternalLinkInVK, vkOpenExternalUrl } from './vk';

/**
 * onExternalLinkClick is the anchor click handler for external links. It resolves the clicked
 * anchor with closest(), so it works both attached directly on an <a> and delegated on a container
 * that renders links (e.g. {@html} markdown). Attach it as onclick on an external link or its
 * container; outside Telegram and VK it is a no-op and the anchor's own target=_blank handles the
 * click.
 */
export function onExternalLinkClick(e: MouseEvent): void {
  const a = (e.target as HTMLElement | null)?.closest('a');
  if (!a) return;
  if (routeExternalLinkInTelegram(a) || routeExternalLinkInVK(a)) e.preventDefault();
}

/**
 * onInAppPageLinkClick is the anchor click handler for a link to a standalone, same-origin page
 * that is not part of the SPA — the static legal /offer/ page. Such a page shares the app's origin
 * yet must still leave the Mini App WebView: opened in place it replaces the game, and the Android
 * VK client then strands the user there with no way back. Unlike onExternalLinkClick it therefore
 * skips the cross-origin test (the page is same-origin by design) and routes the click straight
 * through the Telegram in-app browser (openLink) or VK's away.php redirect. Outside those hosts it
 * is a no-op and the anchor's own target=_blank opens the page in a new tab / child browser.
 */
export function onInAppPageLinkClick(e: MouseEvent): void {
  const a = (e.target as HTMLElement | null)?.closest('a');
  if (!a) return;
  if (telegramOpenExternalLink(a.href) || vkOpenExternalUrl(a.href)) e.preventDefault();
}

/**
 * openExternalUrl opens an external URL from code (no anchor to click): through VK's external
 * redirect inside the Android VK client, else a plain new tab. Telegram callers try their native
 * opener (telegramOpenLink) first and use this as the fallback.
 */
export function openExternalUrl(url: string): void {
  if (vkOpenExternalUrl(url)) return;
  if (typeof window !== 'undefined') window.open(url, '_blank');
}
