export function subyBase() {
  const host = location.hostname;
  if (host.endsWith('.z6.mm.mk') || host === 'z6.mm.mk') return '.z6.mm.mk';
  if (host.endsWith('.suby.pl') || host === 'suby.pl') return '.suby.pl';
  return host;
}

export function subyPortal() {
  return location.hostname.endsWith('z6.mm.mk')
    ? 'https://gry.z6.mm.mk:11443'
    : 'https://gry.suby.pl';
}

export function subyValidHost() {
  return /\.(suby\.pl|z6\.mm\.mk)$/.test(location.hostname);
}

export function subyNick() {
  try {
    const queryNick = new URLSearchParams(location.search).get('nick');
    if (queryNick) {
      const nick = queryNick.trim().slice(0, 20);
      if (nick) {
        subyNickSet(nick);
        return nick;
      }
    }
  } catch (_error) {
    // Query parsing is optional in embedded browser shells.
  }

  try {
    const match = document.cookie.match(/(?:^|;\s*)suby_nick=([^;]*)/);
    if (match) return decodeURIComponent(match[1]).trim().slice(0, 20);
  } catch (_error) {
    // Cookie access can be disabled.
  }

  try {
    return (localStorage.getItem('suby_nick') || '').slice(0, 20);
  } catch (_error) {
    return '';
  }
}

export function subyNickSet(value) {
  const nick = String(value || '').trim().slice(0, 20);
  if (!nick) return '';

  try {
    document.cookie = `suby_nick=${encodeURIComponent(nick)};domain=${subyBase()};path=/;max-age=31536000;samesite=lax`;
  } catch (_error) {
    // localStorage remains available as a per-origin fallback.
  }

  try {
    localStorage.setItem('suby_nick', nick);
  } catch (_error) {
    // Storage can be denied in private contexts.
  }
  return nick;
}

let beaconSent = false;

export function subyPlayBeacon(game, nick) {
  if (beaconSent || !subyValidHost()) return;
  beaconSent = true;
  try {
    fetch(`${subyPortal()}/api/event`, {
      method: 'POST',
      keepalive: true,
      headers: { 'Content-Type': 'text/plain' },
      body: JSON.stringify({ game, nick: nick != null ? nick : subyNick(), type: 'play' })
    }).catch(() => {});
  } catch (_error) {
    // Telemetry must never interrupt a game launch.
  }
}

export function subyDirectRedirect() {
  if (typeof location === 'undefined') return Promise.resolve(false);
  const host = location.hostname;
  if (!/\.suby\.pl$/.test(host)) return Promise.resolve(false);

  try {
    if (new URLSearchParams(location.search).get('nodirect')) return Promise.resolve(false);
  } catch (_error) {
    return Promise.resolve(false);
  }

  const subdomain = host.replace(/\.suby\.pl$/, '');
  return fetch(`https://${subdomain}.z6.mm.mk:11443/healthz`, {
    mode: 'no-cors',
    cache: 'no-store',
    signal: AbortSignal.timeout(2000)
  }).then(() => {
    const target = new URL(location.href);
    target.hostname = `${subdomain}.z6.mm.mk`;
    target.port = '11443';
    const nick = subyNick();
    if (nick && !target.searchParams.get('nick')) target.searchParams.set('nick', nick);
    location.replace(target.href);
    return true;
  }).catch(() => false);
}
