<script lang="ts">
  import { app, dismissStaleInvite } from '../lib/app.svelte';
  import { router } from '../lib/router.svelte';
  import { t } from '../lib/i18n/index.svelte';
  import { botUsername } from '../lib/deeplink';
  import { insideTelegram, telegramDialogsAvailable, telegramOpenLink, telegramShowPopup } from '../lib/telegram';
  import { openExternalUrl } from '../lib/links';
  import { BOT_BUTTON_ID, botInfoPopup } from '../lib/nativedialogs';
  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://telegram.me/${username}`;
      // Inside Telegram, openTelegramLink navigates to the bot chat natively; elsewhere fall
      // back to a new tab (routed out of the Android VK WebView by openExternalUrl).
      if (!telegramOpenLink(url)) openExternalUrl(url);
    }
    dismissStaleInvite();
  }

  // Native path: when the notice fires inside the Mini App with native popups, present Telegram's
  // own popup instead of the in-app modal. insideTelegram()/dialogs are evaluated at fire time, not
  // captured at init: this component mounts before bootstrap loads the SDK, so a captured value
  // would be stale. The popup's "open bot" button opens the bot chat; any other dismissal clears the
  // notice; the `shown` guard fires it once per notice.
  // The notice is raised during boot; wait until the loading cover for the current route is gone —
  // the tile splash on the lobby (splashDone), the plain loading screen elsewhere (app.ready) — so
  // the native popup never appears over the splash.
  const ready = $derived(router.route.name === 'lobby' ? app.splashDone : app.ready);
  let shown = false;
  $effect(() => {
    if (app.staleInvite && !shown && ready && insideTelegram() && telegramDialogsAvailable()) {
      shown = true;
      void telegramShowPopup(
        botInfoPopup(t('friends.staleInviteTitle'), t('friends.staleInvite'), username ?? '', t('common.ok')),
      ).then((id) => (id === BOT_BUTTON_ID ? openBot() : dismissStaleInvite()));
    } else if (!app.staleInvite) {
      shown = false;
    }
  });
</script>

{#if app.staleInvite && ready && !(insideTelegram() && telegramDialogsAvailable())}
  <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>
