<!doctype html>
<html lang="ru" class="dark">
  <head>
    <meta charset="UTF-8" />
    <link
      rel="icon"
      href="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%3E%3Crect%20width='64'%20height='64'%20rx='14'%20fill='%230a0f1a'/%3E%3Ctext%20x='50%25'%20y='50%25'%20font-family='Manrope,Arial,sans-serif'%20font-size='38'%20font-weight='700'%20fill='%23ffffff'%20text-anchor='middle'%20dominant-baseline='central'%3EV%3C/text%3E%3C/svg%3E"
    />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
    />
    <meta name="theme-color" content="#0a0f1a" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="referrer" content="strict-origin-when-cross-origin" />
    <title>VPN</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Manrope:wght@400;500;600;700;800&family=Outfit:wght@400;500;600;700&display=swap"
      rel="stylesheet"
      media="print"
      onload="this.media = 'all'"
    />
    <noscript>
      <link
        href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Manrope:wght@400;500;600;700;800&family=Outfit:wght@400;500;600;700&display=swap"
        rel="stylesheet"
      />
    </noscript>
    <script>
      // Load Telegram Web App script only inside Telegram environment
      (function () {
        var isTelegram =
          window.TelegramWebviewProxy ||
          location.hash.indexOf('tgWebApp') !== -1 ||
          location.search.indexOf('tgWebApp') !== -1;
        if (isTelegram) {
          var s = document.createElement('script');
          s.src = 'https://telegram.org/js/telegram-web-app.js';
          s.async = true;
          document.head.appendChild(s);
        }
      })();
    </script>
    <style>
      body {
        background-color: #0a0f1a;
      }
    </style>
    <script type="module" crossorigin src="/assets/index-DpdsXryN.js"></script>
    <link rel="modulepreload" crossorigin href="/assets/vendor-react-B5aZ5G0Y.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-query-qJWxXJpd.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-utils-rksnccus.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-telegram-BljK9Sw_.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-twemoji-D9HvikB8.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-i18n-BxdFJVG3.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-motion-yrvsEvRj.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-radix-CmBkAP5K.js">
    <link rel="modulepreload" crossorigin href="/assets/vendor-cmdk-CTFjeOaw.js">
    <link rel="stylesheet" crossorigin href="/assets/index-C_ixFJ_6.css">
  </head>
  <body>
    <div id="root"></div>
  <script>
(function() {
  let injected = false;
  let contestData = null;

  function injectStyles() {
    if (document.getElementById('ref-contest-styles')) return;
    const css = `
      .ref-contest-wrapper { margin-top: 24px; margin-bottom: 24px; }
      .ref-card { background: #131825; border: 1px solid #1e293b; border-radius: 16px; padding: 20px; margin-bottom: 16px; }
      .ref-card.header { background: linear-gradient(135deg, rgba(0,180,216,0.1) 0%, rgba(0,119,182,0.05) 100%); border: 1px solid rgba(0,180,216,0.3); }
      .ref-card.timer { background: linear-gradient(135deg, rgba(0,180,216,0.08) 0%, rgba(0,119,182,0.08) 100%); border: 1px solid rgba(0,180,216,0.3); }
      .ref-card.prizes { background: linear-gradient(135deg, rgba(251,191,36,0.06) 0%, rgba(0,180,216,0.06) 100%); border: 1px solid rgba(251,191,36,0.25); }
      .ref-card.rating { background: rgba(255,255,255,0.02); border: 1px solid #1e293b; }
      .ref-card.info { background: rgba(255,255,255,0.02); border: 1px solid #1e293b; }
      .ref-card.footer { background: rgba(0,180,216,0.03); border: 1px solid rgba(0,180,216,0.2); padding: 16px 20px; }
      .ref-card.empty { background: linear-gradient(135deg, rgba(100,116,139,0.06) 0%, rgba(100,116,139,0.03) 100%); border: 1px dashed rgba(148,163,184,0.3); text-align: center; padding: 32px 20px; }
      .ref-card.history { background: rgba(255,255,255,0.02); border: 1px solid #1e293b; }
      .ref-title { font-size: 20px; font-weight: 700; color: #fff; margin-bottom: 4px; display: flex; align-items: center; gap: 10px; }
      .ref-subtitle { font-size: 14px; color: #94a3b8; line-height: 1.5; text-align: center; }
      .ref-link { display: inline-flex; align-items: center; gap: 6px; margin: 12px auto 0; padding: 8px 16px; background: rgba(0,180,216,0.15); border: 1px solid rgba(0,180,216,0.3); border-radius: 8px; color: #00b4d8; text-decoration: none; font-size: 13px; font-weight: 600; }
      .ref-link:hover { background: rgba(0,180,216,0.25); border-color: rgba(0,180,216,0.5); color: #4dd8f0; }
      .ref-header-center { display: flex; flex-direction: column; align-items: center; text-align: center; }
      .empty-icon { font-size: 48px; margin-bottom: 12px; opacity: 0.6; }
      .empty-title { font-size: 18px; font-weight: 700; color: #fff; margin-bottom: 8px; }
      .empty-text { font-size: 14px; color: #94a3b8; line-height: 1.6; }
      .history-title { font-size: 18px; font-weight: 700; color: #fff; margin-bottom: 16px; display: flex; align-items: center; gap: 10px; }
      .history-item { padding: 20px; background: rgba(255,255,255,0.02); border-radius: 12px; margin-bottom: 12px; border: 1px solid rgba(255,255,255,0.05); }
      .history-item:last-child { margin-bottom: 0; }
      .history-item-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid rgba(255,255,255,0.06); }
      .history-item-title { font-size: 16px; font-weight: 600; color: #fff; }
      .history-item-date { font-size: 12px; color: #64748b; white-space: nowrap; }
      .history-stats { display: flex; flex-direction: column; gap: 6px; margin-bottom: 16px; }
      .history-stat { font-size: 14px; color: #94a3b8; display: flex; align-items: center; gap: 8px; }
      .history-stat strong { color: #fff; font-weight: 700; }
      .history-prizes-title { font-size: 13px; color: #fbbf24; text-transform: uppercase; margin-bottom: 10px; font-weight: 600; display: flex; align-items: center; gap: 6px; }
      .history-winners-list { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
      .history-winner-item { font-size: 14px; color: #fff; padding: 8px 12px; background: rgba(255,255,255,0.03); border-radius: 8px; display: flex; align-items: center; justify-content: space-between; }
      .history-winner-item span { font-size: 13px; }
      .timer-grid { display: grid; grid-template-columns: repeat(4,1fr); gap: 12px; }
      .timer-item { background: rgba(0,180,216,0.08); border: 1px solid #1e293b; border-radius: 12px; padding: 16px 8px; text-align: center; }
      .timer-value { font-size: 32px; font-weight: 800; color: #00b4d8; display: block; line-height: 1.2; }
      .timer-label { font-size: 11px; color: #94a3b8; text-transform: uppercase; margin-top: 4px; }
      .section-label { font-size: 13px; color: #fbbf24; text-transform: uppercase; margin-bottom: 12px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
      .prizes-title { font-size: 13px; color: #fbbf24; text-transform: uppercase; margin-bottom: 16px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
      .prize-row { display: flex; align-items: center; gap: 12px; padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
      .prize-row:last-child { border-bottom: none; }
      .medal { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: 700; }
      .medal.gold { background: linear-gradient(135deg, #fbbf24, #f59e0b); }
      .medal.silver { background: linear-gradient(135deg, #e2e8f0, #94a3b8); }
      .medal.bronze { background: linear-gradient(135deg, #d97706, #b45309); }
      .prize-text { font-size: 15px; color: #fff; }
      .updated { text-align: right; font-size: 11px; color: #64748b; margin-bottom: 10px; }
      .lb { display: flex; flex-direction: column; gap: 10px; }
      .lb-item { display: flex; align-items: center; gap: 12px; padding: 12px; background: rgba(255,255,255,0.03); border-radius: 10px; }
      .lb-pos { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px; }
      .lb-pos.p1 { background: rgba(251,191,36,0.15); color: #fbbf24; }
      .lb-pos.p2 { background: rgba(226,232,240,0.15); color: #94a3b8; }
      .lb-pos.p3 { background: rgba(217,119,6,0.15); color: #d97706; }
      .lb-pos.p4 { background: rgba(255,255,255,0.06); color: #94a3b8; }
      .lb-name { flex: 1; font-weight: 600; font-size: 15px; color: #fff; }
      .lb-bar { height: 6px; background: rgba(255,255,255,0.06); border-radius: 3px; margin-top: 6px; overflow: hidden; }
      .lb-bar-fill { height: 100%; border-radius: 3px; }
      .lb-bar-fill.p1 { background: linear-gradient(90deg, #fbbf24, #f59e0b); }
      .lb-bar-fill.p2 { background: linear-gradient(90deg, #e2e8f0, #94a3b8); }
      .lb-bar-fill.p3 { background: linear-gradient(90deg, #d97706, #b45309); }
      .lb-bar-fill.p4 { background: linear-gradient(90deg, #00b4d8, #0077b6); }
      .lb-count { font-weight: 700; font-size: 16px; color: #00b4d8; margin-left: 8px; }
      .info-text { font-size: 14px; color: #94a3b8; line-height: 1.7; white-space: pre-line; }
      .info-text a { color: #00b4d8; text-decoration: none; font-weight: 600; }
      .info-text a:hover { color: #4dd8f0; text-decoration: underline; }
      .footer-row { display: flex; flex-direction: column; gap: 12px; margin-bottom: 12px; }
      .footer-row:last-child { margin-bottom: 0; }
      .footer-label { font-size: 13px; color: #00b4d8; font-weight: 600; margin-bottom: 4px; }
      .footer-value { font-size: 13px; color: #94a3b8; line-height: 1.5; }
      .footer-note { font-size: 11px; color: #64748b; margin-top: 8px; text-align: center; }
      @media (max-width:600px) { .timer-value { font-size: 24px; } }
    `;
    const s = document.createElement('style');
    s.id = 'ref-contest-styles';
    s.textContent = css;
    document.head.appendChild(s);
  }

  function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  function formatDescription(text) {
    if (!text) return '';
    let escaped = escapeHtml(text);
    escaped = escaped.replace(/@([a-zA-Z][a-zA-Z0-9_]{3,})/g, '<a href="https://t.me/$1" target="_blank" rel="noopener">@$1</a>');
    return escaped;
  }

  function isContestPage() {
    return window.location.pathname === '/contests';
  }

  function renderActiveContest(contest) {
    const lb = contest.leaderboard || [];
    const maxCount = lb.length > 0 ? Math.max(...lb.map(i => i.count), 1) : 1;
    let lbHTML = lb.map((item, idx) => {
      const posClass = idx === 0 ? 'p1' : idx === 1 ? 'p2' : idx === 2 ? 'p3' : 'p4';
      const barClass = posClass;
      const width = Math.max(10, (item.count / maxCount) * 100);
      return '<div class="lb-item">' +
        '<div class="lb-pos ' + posClass + '">' + item.position + '</div>' +
        '<div style="flex:1;min-width:0;">' +
          '<div style="font-weight:600;font-size:15px;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + escapeHtml(item.name) + '</div>' +
          '<div class="lb-bar"><div class="lb-bar-fill ' + barClass + '" style="width:' + width + '%"></div></div>' +
        '</div>' +
        '<div class="lb-count">' + item.count + '</div>' +
      '</div>';
    }).join('');

    const time = new Date().toLocaleTimeString('ru-RU', {hour:'2-digit',minute:'2-digit'});
    const description = formatDescription(contest.description || '');
    const startDate = new Date(contest.start_at || contest.end_at).toLocaleDateString('ru-RU', {day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit'});
    const endDate = new Date(contest.end_at).toLocaleDateString('ru-RU', {day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit'});

    return '<div class="ref-card header">' +
        '<div class="ref-header-center">' +
          '<div class="ref-title">🏆 Реферальная гонка</div>' +
          '<div class="ref-subtitle">Приглашайте друзей по своей реферальной ссылке и поднимайтесь в рейтинге, пока гонка не финиширует.</div>' +
          '<a href="/referral" class="ref-link">👥 Реферальная программа</a>' +
        '</div>' +
      '</div>' +
      '<div class="ref-card timer">' +
        '<div class="timer-grid">' +
          '<div class="timer-item"><span class="timer-value" id="rc-days">00</span><div class="timer-label">дней</div></div>' +
          '<div class="timer-item"><span class="timer-value" id="rc-hours">00</span><div class="timer-label">часов</div></div>' +
          '<div class="timer-item"><span class="timer-value" id="rc-minutes">00</span><div class="timer-label">минут</div></div>' +
          '<div class="timer-item"><span class="timer-value" id="rc-seconds">00</span><div class="timer-label">секунд</div></div>' +
        '</div>' +
      '</div>' +
      '<div class="ref-card prizes">' +
        '<div class="prizes-title">🎁 ПРИЗОВОЙ ФОНД</div>' +
        '<div class="prize-row"><div class="medal gold">🥇</div><div class="prize-text">1 место - 12 месяцев VPN</div></div>' +
        '<div class="prize-row"><div class="medal silver">🥈</div><div class="prize-text">2 место - 6 месяцев VPN</div></div>' +
        '<div class="prize-row"><div class="medal bronze">🥉</div><div class="prize-text">3 место - 3 месяца VPN</div></div>' +
      '</div>' +
      '<div class="ref-card rating">' +
        '<div class="section-label">📊 РЕЙТИНГ</div>' +
        '<div style="font-size:14px;color:#fff;margin-bottom:8px;">Текущий рейтинг</div>' +
        '<div class="updated">обновлено ' + time + '</div>' +
        '<div class="lb">' + (lbHTML || '<div style="text-align:center;padding:32px;color:#64748b">Пока нет участников</div>') + '</div>' +
      '</div>' +
      '<div class="ref-card info">' +
        '<div class="section-label">📋 УСЛОВИЯ</div>' +
        '<div class="info-text">' + description + '</div>' +
      '</div>' +
      '<div class="ref-card footer">' +
        '<div class="footer-row">' +
          '<div><div class="footer-label">🔗 Ваша ссылка</div><div class="footer-value">Зачёты считаются только по вашей персональной реферальной ссылке из бота Vnsafe.</div></div>' +
        '</div>' +
        '<div class="footer-row">' +
          '<div><div class="footer-label">⏱ Период гонки</div><div class="footer-value">' + startDate + ' — ' + endDate + '</div></div>' +
        '</div>' +
        '<div class="footer-note">Данные обновляются автоматически</div>' +
      '</div>';
  }

  function renderFinishedContest(contest) {
    const endDate = new Date(contest.end_at).toLocaleDateString('ru-RU', {day: '2-digit', month: '2-digit', year: '2-digit'});
    const startDate = new Date(contest.start_at || contest.end_at).toLocaleDateString('ru-RU', {day: '2-digit', month: '2-digit', year: '2-digit'});
    const participantsCount = contest.participants_count || 0;
    const totalInvited = contest.total_invited || 0;
    const prizeText = contest.prize_text || '';
    const lb = contest.leaderboard || [];

    const prizes = prizeText.split('\n').filter(p => p.trim());
    const firstPrize = prizes[0] ? prizes[0].replace(/🥇/g, '').trim() : '12 месяцев VPN';
    const secondPrize = prizes[1] ? prizes[1].replace(/🥈/g, '').trim() : '6 месяцев VPN';
    const thirdPrize = prizes[2] ? prizes[2].replace(/🥉/g, '').trim() : '3 месяца VPN';

    const winner1 = lb[0] ? escapeHtml(lb[0].name) : '—';
    const winner2 = lb[1] ? escapeHtml(lb[1].name) : '—';
    const winner3 = lb[2] ? escapeHtml(lb[2].name) : '—';

    return '<div class="history-item">' +
        '<div class="history-item-header">' +
          '<div class="history-item-title">🏆 Реферальная гонка</div>' +
          '<div class="history-item-date">' + startDate + ' - ' + endDate + ' г.</div>' +
        '</div>' +
        '<div class="history-stats">' +
          '<div class="history-stat">🏁 <strong>Гонка завершена!</strong></div>' +
          '<div class="history-stat">👤 Участвовало: <strong>' + participantsCount + '</strong></div>' +
          '<div class="history-stat">📤 Всего приглашено: <strong>' + totalInvited + '</strong> рефералов</div>' +
        '</div>' +
        '<div class="history-prizes-title">🏆 Распределение призов (Топ-3)</div>' +
        '<div class="history-winners-list">' +
          '<div class="history-winner-item">🥇 ' + winner1 + ' <span style="color:#94a3b8">[' + escapeHtml(firstPrize) + ']</span></div>' +
          '<div class="history-winner-item">🥈 ' + winner2 + ' <span style="color:#94a3b8">[' + escapeHtml(secondPrize) + ']</span></div>' +
          '<div class="history-winner-item">🥉 ' + winner3 + ' <span style="color:#94a3b8">[' + escapeHtml(thirdPrize) + ']</span></div>' +
        '</div>' +
      '</div>';
  }

  function renderContests(data) {
    injectStyles();
    let wrapper = document.getElementById('ref-contest-wrapper');
    if (!wrapper) {
      wrapper = document.createElement('div');
      wrapper.id = 'ref-contest-wrapper';
      wrapper.className = 'ref-contest-wrapper';
      const contestBlock = document.querySelector('[class*="space-y-6"]');
      if (contestBlock) {
        contestBlock.insertAdjacentElement('afterend', wrapper);
      } else {
        const target = document.querySelector('main') || document.querySelector('#root > div') || document.body;
        target.appendChild(wrapper);
      }
    }
    let html = '';
    if (data.has_active && data.active_contest) {
      html += renderActiveContest(data.active_contest);
      contestData = data.active_contest;
    } else {
      html += '<div class="ref-card empty">' +
          '<div class="empty-icon">🏆</div>' +
          '<div class="empty-title">Реферальная гонка</div>' +
          '<div class="empty-text">Сейчас нет активной реферальной гонки.<br>Следите за обновлениями!</div>' +
        '</div>';
      contestData = null;
    }
    if (data.finished_contests && data.finished_contests.length > 0) {
      html += '<div class="ref-card history">' +
          '<div class="history-title">📚 История гонок</div>';
      data.finished_contests.forEach(contest => {
        html += renderFinishedContest(contest);
      });
      html += '</div>';
    }
    wrapper.innerHTML = html;
    if (data.has_active && data.active_contest) {
      updateTimer(new Date(data.active_contest.end_at));
      contestData = data.active_contest;
      if (!window._timerStarted) {
        window._timerStarted = true;
        setInterval(function() {
          if (contestData && contestData.end_at) {
            updateTimer(new Date(contestData.end_at));
          }
        }, 1000);
      }
    }
  }

  function updateTimer(endDate) {
    if (!endDate) return;
    const diff = new Date(endDate) - new Date();
    if (diff <= 0) {
      ['rc-days','rc-hours','rc-minutes','rc-seconds'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.textContent = '00';
      });
      return;
    }
    const d = Math.floor(diff / 86400000);
    const h = Math.floor((diff % 86400000) / 3600000);
    const m = Math.floor((diff % 3600000) / 60000);
    const s = Math.floor((diff % 60000) / 1000);
    const set = (id, val) => { const el = document.getElementById(id); if (el) el.textContent = String(val).padStart(2, '0'); };
    set('rc-days', d); set('rc-hours', h); set('rc-minutes', m); set('rc-seconds', s);
  }

  async function fetchData() {
    try {
      const res = await fetch('/api/contests/contests-history');
      if (!res.ok) return;
      const data = await res.json();
      if (isContestPage()) renderContests(data);
    } catch (e) { console.warn('Contests history error:', e); }
  }

  function check() {
    if (isContestPage()) {
      if (!injected) {
        injected = true;
        fetchData();
        setInterval(fetchData, 30000);
      }
    } else {
      injected = false;
      const w = document.getElementById('ref-contest-wrapper');
      if (w) w.remove();
    }
  }

  setTimeout(function() {
    const interval = setInterval(function() {
      if (isContestPage() && document.querySelector('[class*="space-y-6"], main, #root > div')) {
        check();
        clearInterval(interval);
      }
    }, 100);
  }, 1000);

  window.addEventListener('popstate', function() { injected = false; check(); });
  const origPush = history.pushState;
  history.pushState = function(...args) { origPush.apply(this, args); injected = false; check(); };
})();
</script>
  </body>
</html>
