<script lang="ts">
  import { app, dismissStaleInvite } from '../lib/app.svelte';
  import { t } from '../lib/i18n/index.svelte';
  import { botUsername } from '../lib/deeplink';
  import { telegramOpenLink } from '../lib/telegram';
  import Modal from './Modal.svelte';

  // Point at the bot the player signed in through (its service language), falling back to
  // the interface locale, so an ru player is sent to the ru bot and an en player to the en one.
  const username = $derived(botUsername(app.session?.serviceLanguage || app.locale));
  // Split the message around the {bot} token so the bot handle renders as an inline link.
  const parts = $derived(t('friends.staleInvite').split('{bot}'));

  function openBot() {
    if (username) {
      const url = `https://t.me/${username}`;
      // Inside Telegram, openTelegramLink navigates to the bot chat natively; elsewhere fall
      // back to a new tab.
      if (!telegramOpenLink(url) && typeof window !== 'undefined') window.open(url, '_blank');
    }
    dismissStaleInvite();
  }
</script>

{#if app.staleInvite}
  <Modal title={t('friends.staleInviteTitle')} onclose={dismissStaleInvite}>
    <p class="msg">{parts[0]}{#if username}<button type="button" class="bot" onclick={openBot}>@{username}</button>{/if}{parts[1] ?? ''}</p>
    <button class="ok" onclick={dismissStaleInvite}>{t('common.ok')}</button>
  </Modal>
{/if}

<style>
  .msg {
    margin: 0 0 16px;
    line-height: 1.5;
  }
  .bot {
    background: none;
    border: none;
    padding: 0;
    font: inherit;
    color: var(--accent);
    cursor: pointer;
  }
  .ok {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid var(--accent);
    background: var(--accent);
    color: var(--accent-text);
    border-radius: var(--radius-sm);
  }
</style>
