<script lang="ts">
  import { app, dismissWelcomeRedeem } 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());
  // Greet the arriving player by their own display name.
  const name = $derived(app.profile?.displayName || app.session?.displayName || '');
  // Interpolate the name, then split the rest around the {bot} token so the bot handle renders
  // as an inline link (the {name} value is substituted first; {bot} is left for the split).
  const parts = $derived(t('friends.welcomeRedeem', { name }).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');
    }
    dismissWelcomeRedeem();
  }
</script>

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

<style>
  .msg {
    margin: 0 0 16px;
    line-height: 1.5;
    /* The greeting and the bot sentence are separated by a blank line in the message. */
    white-space: pre-line;
  }
  .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>
