// PhishProtect HTTP Warning Page Script

// Parse URL parameters
const params = new URLSearchParams(window.location.search);
const originalUrl = params.get('url') || '';
const autoUpgrade = params.get('autoUpgrade') === 'true';

console.log('PhishProtect HTTP Warning Page loaded');
console.log('Original URL:', originalUrl);
console.log('Auto-upgrade:', autoUpgrade);

// Extract and display the site URL
let siteUrl = originalUrl;
try {
  const url = new URL(originalUrl);
  siteUrl = url.hostname + url.pathname + url.search;
} catch (e) {
  console.error('Failed to parse URL:', e);
  siteUrl = originalUrl;
}

document.getElementById('site-url').textContent = siteUrl;

// Function to show status message
function showStatus(message, type = 'info') {
  const statusEl = document.getElementById('status-message');
  statusEl.textContent = message;
  statusEl.className = 'status-message ' + type;
  statusEl.style.display = 'block';
}

// Function to upgrade to HTTPS
async function upgradeToHttps() {
  console.log('Upgrade to HTTPS clicked');
  const upgradeBtn = document.getElementById('upgrade-btn');
  const upgradeText = document.getElementById('upgrade-text');

  // Disable button and show loading
  upgradeBtn.disabled = true;
  upgradeText.innerHTML = '<span class="spinner"></span>Checking HTTPS availability...';

  showStatus('Attempting to connect via HTTPS...', 'info');

  try {
    // Try to construct HTTPS URL
    const httpsUrl = originalUrl.replace(/^http:\/\//, 'https://');
    console.log('Testing HTTPS URL:', httpsUrl);

    // Simply redirect to HTTPS - let the browser handle if it works or not
    showStatus('Upgrading to HTTPS...', 'success');

    // Notify background script about upgrade attempt
    if (typeof chrome !== 'undefined' && chrome.runtime) {
      try {
        chrome.runtime.sendMessage({
          type: 'httpUpgraded',
          originalUrl: originalUrl,
          httpsUrl: httpsUrl,
          timestamp: Date.now()
        }, (response) => {
          console.log('Background notified:', response);
        });
      } catch (e) {
        console.error('Failed to notify background:', e);
      }
    }

    // Redirect after a short delay
    setTimeout(() => {
      console.log('Redirecting to:', httpsUrl);
      window.location.href = httpsUrl;
    }, 500);

  } catch (error) {
    console.error('HTTPS upgrade failed:', error);
    showStatus('Error during upgrade. Click again to try.', 'error');
    upgradeBtn.disabled = false;
    upgradeText.textContent = '🔒 Try HTTPS Again';
  }
}

// Function to go back
function goBack() {
  console.log('Go back clicked');
  if (window.history.length > 1) {
    window.history.back();
  } else {
    // Try to close tab, otherwise go to a safe page
    try {
      window.close();
    } catch (e) {
      window.location.href = 'about:blank';
    }
  }
}

// Function to show custom modal
function showModal(title, content, buttons) {
  // Remove existing modal if present
  const existing = document.getElementById('phishprotect-modal');
  if (existing) {
    existing.remove();
  }

  // Create modal overlay
  const overlay = document.createElement('div');
  overlay.id = 'phishprotect-modal';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    z-index: 2147483647;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
    animation: fadeIn 0.2s ease;
  `;

  // Create modal box
  const box = document.createElement('div');
  box.style.cssText = `
    background: #fff;
    padding: 35px;
    border-radius: 12px;
    max-width: 550px;
    width: 90%;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
    animation: slideIn 0.3s ease;
  `;

  // Title
  const titleEl = document.createElement('h2');
  titleEl.textContent = title;
  titleEl.style.cssText = `
    color: #ea4335;
    margin: 0 0 20px 0;
    font-size: 24px;
    font-weight: 700;
  `;
  box.appendChild(titleEl);

  // Content
  const contentEl = document.createElement('div');
  contentEl.innerHTML = content;
  contentEl.style.cssText = `
    margin: 0 0 25px 0;
    line-height: 1.6;
    color: #333;
    font-size: 15px;
  `;
  box.appendChild(contentEl);

  // Buttons container
  const buttonsContainer = document.createElement('div');
  buttonsContainer.style.cssText = `
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  `;

  // Add buttons
  buttons.forEach(btn => {
    const button = document.createElement('button');
    button.textContent = btn.text;
    button.style.cssText = `
      padding: 12px 24px;
      border: none;
      border-radius: 6px;
      font-size: 15px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s;
      ${btn.primary ?
        'background: #ea4335; color: #fff;' :
        'background: #e0e0e0; color: #333;'}
    `;

    button.onmouseover = () => {
      button.style.transform = 'translateY(-1px)';
      button.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.15)';
    };
    button.onmouseout = () => {
      button.style.transform = 'translateY(0)';
      button.style.boxShadow = 'none';
    };

    button.onclick = () => {
      overlay.remove();
      if (btn.callback) btn.callback();
    };

    buttonsContainer.appendChild(button);
  });

  box.appendChild(buttonsContainer);
  overlay.appendChild(box);
  document.body.appendChild(overlay);

  // Add CSS animations
  const style = document.createElement('style');
  style.textContent = `
    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }
    @keyframes slideIn {
      from { transform: translateY(-20px); opacity: 0; }
      to { transform: translateY(0); opacity: 1; }
    }
  `;
  document.head.appendChild(style);
}

// Function to proceed anyway
async function proceedAnyway() {
  console.log('Proceed anyway clicked');

  showModal(
    '⚠️ Security Warning',
    `
      <p style="margin: 0 0 15px 0;"><strong>You are about to proceed to an insecure HTTP connection.</strong></p>

      <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 15px 0; border-radius: 6px;">
        <p style="margin: 0 0 10px 0; font-weight: 600; color: #856404;">Risks:</p>
        <ul style="margin: 0; padding-left: 20px; color: #856404;">
          <li>Your data will NOT be encrypted</li>
          <li>Passwords and personal info can be intercepted</li>
          <li>Connection may be tampered with</li>
        </ul>
      </div>

      <div style="background: #d4edda; border-left: 4px solid #28a745; padding: 15px; margin: 15px 0; border-radius: 6px;">
        <p style="margin: 0 0 10px 0; font-weight: 600; color: #155724;">PhishProtect will:</p>
        <ul style="margin: 0; padding-left: 20px; color: #155724;">
          <li>Block form submissions containing passwords</li>
          <li>Warn before downloads</li>
          <li>Show persistent security warnings</li>
        </ul>
      </div>

      <p style="margin: 15px 0 0 0; font-weight: 600;">Do you want to continue?</p>
    `,
    [
      {
        text: 'Cancel',
        primary: false,
        callback: () => {
          console.log('User cancelled proceeding to HTTP');
        }
      },
      {
        text: 'Proceed (Not Recommended)',
        primary: true,
        callback: async () => {
          console.log('User confirmed proceeding to HTTP');

          // Store flag that user explicitly allowed HTTP
          if (typeof chrome !== 'undefined' && chrome.runtime) {
            try {
              chrome.runtime.sendMessage({
                type: 'allowHttp',
                url: originalUrl,
                timestamp: Date.now()
              }, (response) => {
                console.log('Background notified of allowHttp:', response);
                // Redirect to the original HTTP URL
                setTimeout(() => {
                  console.log('Redirecting to HTTP:', originalUrl);
                  window.location.href = originalUrl;
                }, 100);
              });
            } catch (e) {
              console.error('Failed to send message:', e);
              // Redirect anyway
              window.location.href = originalUrl;
            }
          } else {
            // If chrome API not available, just redirect
            window.location.href = originalUrl;
          }
        }
      }
    ]
  );
}

// Function to learn more
function learnMore() {
  console.log('Learn more clicked');

  showModal(
    'About HTTPS Security',
    `
      <p style="margin: 0 0 15px 0;">
        <strong>HTTPS (Hypertext Transfer Protocol Secure)</strong> is the secure version of HTTP.
      </p>

      <div style="background: #d4edda; border-left: 4px solid #28a745; padding: 15px; margin: 15px 0; border-radius: 6px;">
        <p style="margin: 0 0 10px 0; font-weight: 600; color: #155724;">Benefits of HTTPS:</p>
        <ul style="margin: 0; padding-left: 20px; color: #155724; line-height: 1.8;">
          <li><strong>Data Encryption:</strong> All data between your browser and the website is encrypted</li>
          <li><strong>Data Integrity:</strong> Prevents data from being modified during transfer</li>
          <li><strong>Authentication:</strong> Confirms you're connecting to the legitimate website</li>
        </ul>
      </div>

      <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 15px 0; border-radius: 6px;">
        <p style="margin: 0 0 10px 0; font-weight: 600; color: #856404;">Modern websites should always use HTTPS, especially when:</p>
        <ul style="margin: 0; padding-left: 20px; color: #856404; line-height: 1.8;">
          <li>Logging in with passwords</li>
          <li>Entering personal information</li>
          <li>Making payments</li>
          <li>Accessing sensitive data</li>
        </ul>
      </div>

      <p style="margin: 15px 0 0 0; color: #666; font-size: 14px;">
        Chrome and other browsers are phasing out support for HTTP connections.
      </p>
    `,
    [
      {
        text: 'Got It',
        primary: true,
        callback: () => {
          console.log('Learn more modal closed');
        }
      }
    ]
  );
}

// Add event listeners to buttons
document.getElementById('upgrade-btn').addEventListener('click', upgradeToHttps);
document.getElementById('back-btn').addEventListener('click', goBack);
document.getElementById('proceed-btn').addEventListener('click', proceedAnyway);
document.getElementById('learn-more-link').addEventListener('click', (e) => {
  e.preventDefault();
  learnMore();
});

// Auto-upgrade if requested
if (autoUpgrade) {
  setTimeout(() => {
    upgradeToHttps();
  }, 500);
}

// Test if page loaded correctly
console.log('Page initialized successfully');
console.log('Chrome API available:', typeof chrome !== 'undefined' && chrome.runtime);
console.log('Event listeners attached');