// DOM Elements
const navToggle = document.getElementById('nav-toggle');
const navMenu = document.getElementById('nav-menu');
const shortenForm = document.getElementById('shorten-form');
const urlInput = document.getElementById('url-input');
const errorMessage = document.getElementById('error-message');
const shortenedLinksContainer = document.getElementById('shortened-links');

// State
let shortenedLinks = JSON.parse(localStorage.getItem('shortenedLinks')) || [];

// Initialize the app
document.addEventListener('DOMContentLoaded', function() {
  displayShortenedLinks();
  setupEventListeners();
});

// Event Listeners
function setupEventListeners() {
  // Mobile navigation toggle
  navToggle.addEventListener('click', toggleMobileNav);

  // Form submission
  shortenForm.addEventListener('submit', handleFormSubmit);

  // Input validation on input
  urlInput.addEventListener('input', clearError);

  // Close mobile nav when clicking outside
  document.addEventListener('click', function(e) {
    if (!navMenu.contains(e.target) && !navToggle.contains(e.target)) {
      navMenu.classList.remove('active');
    }
  });
}

// Mobile Navigation
function toggleMobileNav() {
  navMenu.classList.toggle('active');
}

// Form Handling
function handleFormSubmit(e) {
  e.preventDefault();

  const url = urlInput.value.trim();

  if (!url) {
    showError('Please add a link');
    return;
  }

  if (!isValidUrl(url)) {
    showError('Please enter a valid URL');
    return;
  }

  shortenUrl(url);
}

// URL Validation
function isValidUrl(string) {
  try {
    const url = new URL(string);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch (_) {
    // Try adding https:// if no protocol is provided
    try {
      const url = new URL('https://' + string);
      return true;
    } catch (_) {
      return false;
    }
  }
}

// Error Handling
function showError(message) {
  errorMessage.textContent = message;
  errorMessage.classList.add('show');
  urlInput.classList.add('error');
}

function clearError() {
  errorMessage.classList.remove('show');
  urlInput.classList.remove('error');
}

// URL Shortening
async function shortenUrl(originalUrl) {
  try {
    // Show loading state
    const submitBtn = shortenForm.querySelector('.shorten__btn');
    const originalText = submitBtn.textContent;
    submitBtn.textContent = 'Shortening...';
    submitBtn.disabled = true;

    // Ensure URL has protocol
    let urlToShorten = originalUrl;
    if (!originalUrl.startsWith('http://') && !originalUrl.startsWith('https://')) {
      urlToShorten = 'https://' + originalUrl;
    }

    // Try multiple URL shortening services
    let shortenedUrl = null;

    // Try CleanURI with CORS proxy first
    try {
      const proxyUrl = 'https://api.allorigins.win/raw?url=';
      const cleanUriUrl = 'https://cleanuri.com/api/v1/shorten';

      const response = await fetch(proxyUrl + encodeURIComponent(cleanUriUrl), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `url=${encodeURIComponent(urlToShorten)}`
      });

      if (response.ok) {
        const data = await response.json();
        if (data.result_url) {
          shortenedUrl = data.result_url;
        }
      }
    } catch (cleanUriError) {
      console.log('CleanURI with proxy failed, trying TinyURL...');
    }

    // Try TinyURL API as fallback
    if (!shortenedUrl) {
      try {
        const tinyUrlResponse = await fetch(`https://tinyurl.com/api-create.php?url=${encodeURIComponent(urlToShorten)}`);
        if (tinyUrlResponse.ok) {
          const tinyUrl = await tinyUrlResponse.text();
          if (tinyUrl && tinyUrl.startsWith('https://tinyurl.com/')) {
            shortenedUrl = tinyUrl;
          }
        }
      } catch (tinyError) {
        console.log('TinyURL failed, trying is.gd...');
      }
    }

    // Try is.gd API as second fallback
    if (!shortenedUrl) {
      try {
        const isGdResponse = await fetch(`https://is.gd/create.php?format=simple&url=${encodeURIComponent(urlToShorten)}`);
        if (isGdResponse.ok) {
          const isGdUrl = await isGdResponse.text();
          if (isGdUrl && isGdUrl.startsWith('https://is.gd/')) {
            shortenedUrl = isGdUrl;
          }
        }
      } catch (isGdError) {
        console.log('is.gd failed, using demo fallback...');
      }
    }

    // If all APIs fail, create a mock shortened URL for demonstration
    if (!shortenedUrl) {
      // Generate a mock shortened URL for demo purposes
      const shortCode = generateShortCode();
      shortenedUrl = `https://short.ly/${shortCode}`;
      console.log('Using demo shortened URL due to CORS restrictions');

      // Show a notice to the user that this is a demo
      showDemoNotice();
    }

    // Success - create link data
    const linkData = {
      id: Date.now(),
      original: originalUrl,
      shortened: shortenedUrl,
      timestamp: new Date().toISOString()
    };

    shortenedLinks.unshift(linkData);
    localStorage.setItem('shortenedLinks', JSON.stringify(shortenedLinks));

    displayShortenedLinks();
    urlInput.value = '';
    clearError();

  } catch (error) {
    console.error('Error shortening URL:', error);
    showError('Failed to shorten URL. Please try again.');
  } finally {
    // Reset button state
    const submitBtn = shortenForm.querySelector('.shorten__btn');
    submitBtn.textContent = 'Shorten It!';
    submitBtn.disabled = false;
  }
}

// Generate a random short code for demo purposes
function generateShortCode() {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < 6; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// Show demo notice
function showDemoNotice() {
  // Create a temporary notice
  const notice = document.createElement('div');
  notice.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #3b3054;
    color: white;
    padding: 1rem;
    border-radius: 5px;
    z-index: 1000;
    max-width: 300px;
    font-size: 14px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  `;
  notice.innerHTML = `
    <strong>Demo Mode:</strong> Real URL shortening APIs are blocked by CORS.
    This is a demonstration with a mock shortened URL.
    <button onclick="this.parentElement.remove()" style="
      background: none;
      border: none;
      color: #2acfcf;
      cursor: pointer;
      float: right;
      font-weight: bold;
    ">×</button>
  `;

  document.body.appendChild(notice);

  // Auto-remove after 8 seconds
  setTimeout(() => {
    if (notice.parentElement) {
      notice.remove();
    }
  }, 8000);
}

// Display Shortened Links
function displayShortenedLinks() {
  shortenedLinksContainer.innerHTML = '';

  shortenedLinks.forEach(link => {
    const linkElement = createLinkElement(link);
    shortenedLinksContainer.appendChild(linkElement);
  });
}

// Create Link Element
function createLinkElement(linkData) {
  const linkDiv = document.createElement('div');
  linkDiv.className = 'shortened-link fade-in';

  linkDiv.innerHTML = `
    <div class="shortened-link__content">
      <div class="shortened-link__original">${linkData.original}</div>
      <div class="shortened-link__result">
        <a href="${linkData.shortened}" class="shortened-link__short" target="_blank" rel="noopener">
          ${linkData.shortened}
        </a>
        <button class="btn btn--primary shortened-link__copy" onclick="copyToClipboard('${linkData.shortened}', this)">
          Copy
        </button>
      </div>
    </div>
  `;

  return linkDiv;
}

// Copy to Clipboard
async function copyToClipboard(text, button) {
  try {
    await navigator.clipboard.writeText(text);

    // Update button state
    const originalText = button.textContent;
    button.textContent = 'Copied!';
    button.classList.add('copied');

    // Reset after 2 seconds
    setTimeout(() => {
      button.textContent = originalText;
      button.classList.remove('copied');
    }, 2000);
  } catch (error) {
    console.error('Failed to copy to clipboard:', error);

    // Fallback for older browsers
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();

    try {
      document.execCommand('copy');
      button.textContent = 'Copied!';
      button.classList.add('copied');

      setTimeout(() => {
        button.textContent = 'Copy';
        button.classList.remove('copied');
      }, 2000);
    } catch (fallbackError) {
      console.error('Fallback copy failed:', fallbackError);
      alert('Failed to copy to clipboard');
    }

    document.body.removeChild(textArea);
  }
}

// Smooth Scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();

    const target = document.querySelector(this.getAttribute('href'));
    if (target) {
      target.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }
  });
});

// Clear all shortened links (for development/testing)
function clearAllLinks() {
  shortenedLinks = [];
  localStorage.removeItem('shortenedLinks');
  displayShortenedLinks();
}

// Expose functions to global scope for inline event handlers
window.copyToClipboard = copyToClipboard;
window.clearAllLinks = clearAllLinks;
