<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Mega Giveaway Tết 2025</title>
  <style>
    /* Your existing CSS styles */
    .result p, h1 { color: #ff4d4d; }
    body {
      font-family: Arial, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
      background: linear-gradient(135deg, #ff4d4d, #fc0);
      background-size: 200% 200%;
      animation: 10s infinite gradientAnimation;
    }
    @keyframes gradientAnimation {
      0%, 100% { background-position: 0 50%; }
      50% { background-position: 100% 50%; }
    }
    .container {
      text-align: center;
      background: rgba(255, 255, 255, 0.9);
      padding: 30px;
      border-radius: 15px;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
      border: 2px solid #fc0;
      overflow: hidden;
      position: relative;
    }
    .container::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255, 204, 0, 0.2), transparent 70%);
      animation: 20s linear infinite rotateBackground;
      pointer-events: none;
    }
    @keyframes rotateBackground {
      0% { transform: rotate(0); }
      100% { transform: rotate(360deg); }
    }
    h1 {
      font-size: 2.5rem;
      margin-bottom: 20px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
    }
    button {
      padding: 12px 24px;
      font-size: 18px;
      cursor: pointer;
      border: none;
      background-color: #ff4d4d;
      color: #fff;
      border-radius: 25px;
      transition: background-color 0.3s, transform 0.3s;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
      z-index: 1;
    }
    button:hover {
      background-color: #e60000;
      transform: translateY(-2px);
    }
    button:disabled {
      background-color: #ccc;
      cursor: not-allowed;
      transform: none;
    }
    .result {
      margin-top: 20px;
      font-size: 20px;
      color: #333;
      background: rgba(255, 255, 255, 0.8);
      padding: 15px;
      border-radius: 10px;
      border: 1px solid #fc0;
      display: none;
    }
    .result p {
      margin: 10px 0;
    }
    .result strong {
      color: #fc0;
    }
    .loading-spinner {
      border: 4px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top: 4px solid #ff4d4d;
      width: 40px;
      height: 40px;
      animation: 1s linear infinite spin;
      margin: 20px auto;
      display: none;
    }
    @keyframes spin {
      0% { transform: rotate(0); }
      100% { transform: rotate(360deg); }
    }
    .password-container {
      display: inline-flex;
      align-items: center;
      gap: 10px;
    }
    .password-container button {
      background: 0 0;
      border: none;
      cursor: pointer;
      font-size: 20px;
      color: #ff4d4d;
      padding: 0;
    }
    .password-container button:hover {
      color: #e60000;
    }

    /* Hide the reCAPTCHA badge */
    .grecaptcha-badge {
      visibility: hidden;
    }

    /* Add a link to Google's Privacy Policy and Terms of Service */
    .recaptcha-notice {
      font-size: 12px;
      color: #666;
      margin-top: 10px;
    }
    .recaptcha-notice a {
      color: #666;
      text-decoration: underline;
    }
  </style>
  <!-- Load Google reCAPTCHA API with Vietnamese language -->
  <script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback&hl=vi" async defer></script>
</head>
<body>
  <div class="container">
    <h1>Mega Giveaway Tết 2025</h1>
    <form id="giveawayForm">
      <div id="captcha"></div> 
      <button type="button" id="submitButton">Nhận quà</button>
    </form>
    <div class="result" id="result">
      <div class="loading-spinner" id="loadingSpinner"></div>
      <div id="resultContent"></div> 
    </div>
    <!-- Add a notice about reCAPTCHA -->
    <div class="recaptcha-notice">
      Trang này được bảo vệ bởi reCAPTCHA và áp dụng
      <a href="https://policies.google.com/privacy" target="_blank">Chính sách Quyền riêng tư</a> và
      <a href="https://policies.google.com/terms" target="_blank">Điều khoản Dịch vụ</a> của Google.
    </div>
  </div>
  <script>
    const SITE_KEY = 'YOUR_SITE_KEY'; // Replace with your Google reCAPTCHA site key
    const SECRET_KEY_HEX = '749dbe064890c41ba1e27e82a7931f59dc2ba271b05c872dfa78e1f5529946ce'; // Replace with your actual secret key

    // Convert hex key to Uint8Array
    const hexToUint8Array = (hex) => {
      const bytes = new Uint8Array(hex.length / 2);
      for (let i = 0; i < hex.length; i += 2) {
        bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
      }
      return bytes;
    };

    const SECRET_KEY = hexToUint8Array(SECRET_KEY_HEX);

    // Encrypt function
    const encrypt = async (text, key) => {
      const encoder = new TextEncoder();
      const data = encoder.encode(text);
      const iv = crypto.getRandomValues(new Uint8Array(16)); // Initialization vector
      const algorithm = { name: 'AES-CBC', iv };

      const cryptoKey = await crypto.subtle.importKey('raw', key, algorithm, false, ['encrypt']);
      const encrypted = await crypto.subtle.encrypt(algorithm, cryptoKey, data);

      // Combine IV and encrypted data into a single Base64-encoded string
      const combined = new Uint8Array(iv.length + encrypted.byteLength);
      combined.set(iv);
      combined.set(new Uint8Array(encrypted), iv.length);

      return btoa(String.fromCharCode(...combined));
    };

    // Decrypt function
    const decrypt = async (encryptedText, key) => {
      const combined = new Uint8Array(atob(encryptedText).split('').map((char) => char.charCodeAt(0)));
      const iv = combined.slice(0, 16); // Extract IV
      const encryptedData = combined.slice(16); // Extract encrypted data
      const algorithm = { name: 'AES-CBC', iv };

      const cryptoKey = await crypto.subtle.importKey('raw', key, algorithm, false, ['decrypt']);
      const decrypted = await crypto.subtle.decrypt(algorithm, cryptoKey, encryptedData);

      const decoder = new TextDecoder();
      return decoder.decode(decrypted);
    };

    // Fetch a random account
    const fetchRandomAccount = async (token) => {
      const button = document.getElementById('submitButton');
      const resultDiv = document.getElementById('result');
      const loadingSpinner = document.getElementById('loadingSpinner');
      const resultContent = document.getElementById('resultContent');

      // Disable the button and show the loading spinner
      button.disabled = true;
      button.textContent = 'Đang xác thực...';
      resultDiv.style.display = 'block';
      loadingSpinner.style.display = 'block';
      resultContent.innerHTML = '';

      try {
        // Prepare request payload
        const requestData = {
          action: 'getAccount',
          nonce: Math.random(),
          timestamp: Date.now(),
          token,
        };

        // Encrypt the request payload
        const encryptedRequest = await encrypt(JSON.stringify(requestData), SECRET_KEY);

        // Send the encrypted request to the server
        const response = await fetch('/api', {
          method: 'POST',
          headers: { 'Content-Type': 'text/plain' },
          body: encryptedRequest,
        });

        // Decrypt the server's response
        const encryptedResponse = await response.text();
        const decryptedResponse = await decrypt(encryptedResponse, SECRET_KEY);
        const data = JSON.parse(decryptedResponse);

        // Display the result
        resultContent.innerHTML = `
          <p><strong>Tài khoản:</strong> ${data.username}</p>
          <p><strong>Mật khẩu:</strong> 
            <span class="password-container">
              <span id="passwordText">${'*'.repeat(data.password.length)}</span>
              <button id="togglePassword">😌</button>
            </span>
          </p>
        `;

        // Toggle password visibility
        const togglePasswordButton = document.getElementById('togglePassword');
        const passwordText = document.getElementById('passwordText');
        let isPasswordVisible = false;

        togglePasswordButton.addEventListener('click', () => {
          isPasswordVisible = !isPasswordVisible;
          passwordText.textContent = isPasswordVisible ? data.password : '*'.repeat(data.password.length);
          togglePasswordButton.textContent = isPasswordVisible ? '😮' : '😌';
        });
      } catch (error) {
        resultContent.innerHTML = `<p style="color: red;">Đã xảy ra lỗi: ${error.message}</p>`;
      } finally {
        // Re-enable the button and restore its text
        button.disabled = false;
        button.textContent = 'Nhận quà';
        loadingSpinner.style.display = 'none';
      }
    };

    // Initialize Google reCAPTCHA
    const initializeRecaptcha = () => {
      window.onloadCallback = function () {
        // Render the reCAPTCHA widget
        grecaptcha.render('captcha', {
          sitekey: SITE_KEY,
          size: 'invisible', // Use invisible reCAPTCHA
          callback: function (token) {
            console.log('reCAPTCHA Token:', token); // Debugging
            fetchRandomAccount(token); // Proceed with the request
          },
        });
      };
    };

    // Initialize the page
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.getElementById('submitButton');

      // Initialize reCAPTCHA
      initializeRecaptcha();

      // Handle button click
      button.addEventListener('click', () => {
        // Execute the reCAPTCHA challenge
        grecaptcha.execute();
      });
    });
  </script>
</body>
</html>