<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';

  // The single bot's @username, for the deep link.
  const username = $derived(botUsername());
  // 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>
