import { afterEach, describe, expect, it, vi } from 'vitest';
import { onInAppPageLinkClick, openExternalUrl } from './links';

// clickInAppPage fires onInAppPageLinkClick on a fake anchor whose (already absolute) href is the
// same-origin /offer/ page, and reports whether the click's default navigation was suppressed.
function clickInAppPage(href = 'https://app.example/offer/') {
  const preventDefault = vi.fn();
  const a = { href, target: '_blank' };
  onInAppPageLinkClick({ target: { closest: () => a }, preventDefault } as unknown as MouseEvent);
  return preventDefault;
}

describe('openExternalUrl', () => {
  afterEach(() => vi.unstubAllGlobals());

  it('routes through the VK away redirect inside the Android VK client', () => {
    const open = vi.fn();
    vi.stubGlobal('location', {
      pathname: '/vk/',
      search: '?vk_user_id=1&vk_platform=mobile_android&sign=x',
      href: 'https://app.example/vk/',
      origin: 'https://app.example',
    });
    vi.stubGlobal('window', { open });
    openExternalUrl('https://telegram.me/some_bot');
    expect(open).toHaveBeenCalledWith(
      `https://vk.com/away.php?to=${encodeURIComponent('https://telegram.me/some_bot')}`,
      '_blank',
    );
  });

  it('opens a plain new tab elsewhere', () => {
    const open = vi.fn();
    vi.stubGlobal('window', { open });
    openExternalUrl('https://telegram.me/some_bot');
    expect(open).toHaveBeenCalledWith('https://telegram.me/some_bot', '_blank');
  });
});

describe('onInAppPageLinkClick', () => {
  afterEach(() => vi.unstubAllGlobals());

  it('routes the same-origin offer page out through the VK away redirect', () => {
    const open = vi.fn();
    vi.stubGlobal('location', {
      pathname: '/vk/',
      search: '?vk_user_id=1&vk_platform=mobile_android&sign=x',
      href: 'https://app.example/vk/',
      origin: 'https://app.example',
    });
    vi.stubGlobal('window', { open });
    const preventDefault = clickInAppPage();
    // Same-origin, yet still escaped: the cross-origin gate is bypassed for a non-SPA page.
    expect(open).toHaveBeenCalledWith(
      `https://vk.com/away.php?to=${encodeURIComponent('https://app.example/offer/')}`,
      '_blank',
    );
    expect(preventDefault).toHaveBeenCalled();
  });

  it('routes the offer page through the Telegram in-app browser', () => {
    const openLink = vi.fn();
    vi.stubGlobal('window', { Telegram: { WebApp: { openLink } } });
    const preventDefault = clickInAppPage();
    expect(openLink).toHaveBeenCalledWith('https://app.example/offer/');
    expect(preventDefault).toHaveBeenCalled();
  });

  it('leaves the anchor to its own navigation outside a Mini App host', () => {
    const open = vi.fn();
    vi.stubGlobal('window', { open });
    const preventDefault = clickInAppPage();
    expect(open).not.toHaveBeenCalled();
    expect(preventDefault).not.toHaveBeenCalled();
  });
});
