<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>BibSonomy</title>
  <link rel="stylesheet" type="text/css" href="/resources/css/bootstrap-style.css" />
  <link type="image/png" href="/resources/image/favicon.png" rel="icon" />
  <style>
    body {
      background: #f5f5f5;
    }

    /* Skeleton/ghost page background */
    .skeleton-page {
      filter: blur(2px);
      opacity: 0.3;
      pointer-events: none;
    }

    .skeleton-block {
      background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
      background-size: 200% 100%;
      animation: shimmer 2s infinite;
      border-radius: 4px;
      margin: 10px 0;
    }

    @keyframes shimmer {
      0% { background-position: 200% 0; }
      100% { background-position: -200% 0; }
    }

    .skeleton-nav {
      height: 40px;
      margin: 20px 0;
    }

    .skeleton-content {
      height: 100px;
      margin: 15px 0;
    }

    .skeleton-sidebar {
      height: 200px;
    }

    .loading-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.92);
      backdrop-filter: blur(8px);
      z-index: 9999;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .loading-content {
      text-align: center;
      padding: 40px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.1);
      max-width: 400px;
    }

    .spinner {
      border: 4px solid #f3f3f3;
      border-top: 4px solid #2780e3;
      border-radius: 50%;
      width: 60px;
      height: 60px;
      animation: spin 1s linear infinite;
      margin: 0 auto 20px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .loading-title {
      color: #333;
      font-size: 20px;
      font-weight: 500;
      margin-bottom: 10px;
    }

    #status {
      font-size: 13px;
      color: #666;
      margin-top: 15px;
      font-family: 'Courier New', monospace;
    }

    .fun-message {
      font-size: 12px;
      color: #999;
      margin-top: 8px;
      font-style: italic;
    }
  </style>
</head>
<body>
  <!-- Skeleton page that appears to be loading in background -->
  <div class="skeleton-page">
    <!-- BibSonomy Header -->
    <div class="container header">
      <div class="bib-header" id="page-header">
        <div class="row">
          <div class="col-md-6">
            <div id="logo">
              <h1><a title="home" href="/">BibSonomy</a></h1>
              <p><small>The blue social bookmark and publication sharing system.</small></p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Skeleton Navigation -->
    <div class="container">
      <div class="skeleton-block skeleton-nav"></div>
    </div>

    <!-- Skeleton Content Blocks -->
    <div class="container" style="margin-top: 30px;">
      <div class="row">
        <div class="col-md-8">
          <div class="skeleton-block skeleton-content"></div>
          <div class="skeleton-block skeleton-content"></div>
          <div class="skeleton-block skeleton-content"></div>
        </div>
        <div class="col-md-4">
          <div class="skeleton-block skeleton-sidebar"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Loading Overlay -->
  <div class="loading-overlay" id="loadingOverlay">
    <div class="loading-content">
      <div class="spinner" id="spinner"></div>
      <div class="loading-title">Verifying your browser...</div>
      <div id="status">Warming up the hamsters...</div>
      <div class="fun-message" id="funMessage"></div>
    </div>
  </div>

  <!-- Main Content Area (hidden until loaded) -->
  <div class="container" style="margin-top: 20px; display: none;" id="mainContent">
    <!-- Content will be shown after verification -->
  </div>

  <script>
    // Fun messages to display while computing
    const funMessages = [
      "Teaching sand to think...",
      "Consulting the crystal ball...",
      "Asking the magic 8-ball...",
      "Convincing electrons to cooperate...",
      "Bribing the CPU with coffee...",
      "Summoning the hash demons...",
      "Rolling for initiative...",
      "Generating random excuses...",
      "Calculating the meaning of life...",
      "Reticulating splines...",
      "Calibrating probability matrices...",
      "Feeding the algorithm hamsters..."
    ];

    let messageIndex = 0;
    let messageInterval;

    function updateFunMessage() {
      document.getElementById('funMessage').textContent = funMessages[messageIndex];
      messageIndex = (messageIndex + 1) % funMessages.length;
    }

    // Simple SHA-256 PoW implementation (based on SubtleCrypto)
    async function sha256(message) {
      const msgBuffer = new TextEncoder().encode(message);
      const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }

    async function solvePoW(difficulty = 4) {
      const challenge = Math.random().toString(36).substring(7);
      const timestamp = Math.floor(Date.now() / 1000); // Unix timestamp in seconds
      let nonce = 0;
      const prefix = '0'.repeat(difficulty);
      const startTime = Date.now();

      // Start cycling through fun messages
      updateFunMessage();
      messageInterval = setInterval(updateFunMessage, 2500);

      while (true) {
        const hash = await sha256(challenge + nonce + timestamp);
        if (hash.startsWith(prefix)) {
          const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
          clearInterval(messageInterval);
          return { challenge, nonce, hash, timestamp, elapsed };
        }
        nonce++;

        // Update UI every 1000 attempts
        if (nonce % 1000 === 0) {
          const attemptsText = nonce >= 10000
            ? `${(nonce / 1000).toFixed(0)}k attempts`
            : `${nonce.toLocaleString()} attempts`;
          document.getElementById('status').textContent = attemptsText + '...';
          // Yield to UI thread
          await new Promise(r => setTimeout(r, 0));
        }
      }
    }

    async function verify() {
      try {
        // Solve PoW (difficulty 4 = ~65k attempts avg, ~1-3 sec on modern CPU)
        const solution = await solvePoW(4);

        // Show success state
        document.getElementById('status').textContent = `Solved in ${solution.elapsed}s! 🎉`;
        document.getElementById('funMessage').textContent = 'Success! Redirecting...';

        // Request verification cookie from server
        const response = await fetch('/pow-challenge/verify', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(solution),
          credentials: 'include'
        });

        if (response.ok) {
          // Redirect to original URL
          const params = new URLSearchParams(window.location.search);
          const returnUrl = decodeURIComponent(params.get('return') || '/');
          window.location.href = returnUrl;
        } else {
          throw new Error('Verification failed');
        }
      } catch (error) {
        clearInterval(messageInterval);
        document.getElementById('status').textContent = 'Unable to load page. Please try again.';
        document.getElementById('status').style.color = '#e74c3c';
        document.getElementById('funMessage').textContent = '';
        document.getElementById('spinner').style.display = 'none';
      }
    }

    // Auto-start on page load
    verify();
  </script>
</body>
</html>
