// State management
let state = {
    theme: 'light',
    extensionEnabled: true,
    autoConvert: false,
    conversionType: 'image',
    isOnGoogleDrive: false,
    currentUrl: ''
  };
  
  // Initialize
  document.addEventListener('DOMContentLoaded', initializeExtension);
  
  async function initializeExtension() {
    await loadSettings();
    await checkCurrentSite();
    setupEventListeners();
    applyTheme();
    
    // Decide what to show based on site
    if (state.isOnGoogleDrive) {
      // On Google Drive - show normal interface
      hideNotOnDriveWarning();
      showMainContent();
      updateExtensionState();
      checkInitialLinkState();
    } else {
      // Not on Google Drive - show only warning
      showNotOnDriveWarning();
      hideMainContent();
    }
  }
  
  // Intelligent site detection with multiple methods
  async function checkCurrentSite() {
    try {
      // Method 1: Get active tab URL
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      if (tab && tab.url) {
        state.currentUrl = tab.url;
        state.isOnGoogleDrive = isGoogleDriveDomain(tab.url);
        
        console.log('Directli - Current URL:', state.currentUrl);
        console.log('Directli - Is Google Drive:', state.isOnGoogleDrive);
      }
    } catch (error) {
      console.error('Error checking site:', error);
      state.isOnGoogleDrive = false;
    }
    
    // Method 2: Verify with content script
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tab && tab.id) {
        const response = await chrome.tabs.sendMessage(tab.id, { type: 'CHECK_DOMAIN' });
        if (response && response.isGoogleDrive !== undefined) {
          state.isOnGoogleDrive = response.isGoogleDrive;
          console.log('Directli - Content script confirmed:', state.isOnGoogleDrive);
        }
      }
    } catch (error) {
      console.log('Directli - Content script check failed, using URL check');
    }
    
    // Method 3: Check URL patterns
    if (state.currentUrl) {
      state.isOnGoogleDrive = isGoogleDriveDomain(state.currentUrl);
    }
  }
  
  // Check if URL is Google Drive domain
  function isGoogleDriveDomain(url) {
    if (!url) return false;
    
    const urlLower = url.toLowerCase();
    const drivePatterns = [
      'drive.google.com',
      'docs.google.com',
      'sheets.google.com',
      'slides.google.com',
      'forms.google.com'
    ];
    
    return drivePatterns.some(pattern => urlLower.includes(pattern));
  }
  
  // Show "Not on Google Drive" warning and hide everything else
  function showNotOnDriveWarning() {
    const warning = document.getElementById('notOnDriveWarning');
    if (warning) {
      warning.classList.add('show');
    }
  }
  
  // Hide "Not on Google Drive" warning
  function hideNotOnDriveWarning() {
    const warning = document.getElementById('notOnDriveWarning');
    if (warning) {
      warning.classList.remove('show');
    }
  }
  
  // Show main content sections
  function showMainContent() {
    const mainSections = document.getElementById('mainSections');
    if (mainSections) {
      mainSections.classList.remove('hidden');
    }
  }
  
  // Hide main content sections
  function hideMainContent() {
    const mainSections = document.getElementById('mainSections');
    if (mainSections) {
      mainSections.classList.add('hidden');
    }
  }
  
  // Check initial link state (only if on Google Drive)
  function checkInitialLinkState() {
    const inputLink = document.getElementById('inputLink').value.trim();
    if (!inputLink) {
      showDriveWarning();
    } else if (!isGoogleDriveLink(inputLink)) {
      showDriveWarning();
    } else {
      hideDriveWarning();
    }
  }
  
  // Load settings from storage with fallback
  async function loadSettings() {
    try {
      const data = await chrome.storage.local.get(['theme', 'extensionEnabled', 'autoConvert', 'conversionType']);
      state.theme = data.theme || 'light';
      state.extensionEnabled = data.extensionEnabled !== undefined ? data.extensionEnabled : true;
      state.autoConvert = data.autoConvert || false;
      state.conversionType = data.conversionType || 'image';
    } catch (error) {
      console.error('Error loading settings:', error);
    }
    
    // Update UI
    document.getElementById('extensionToggle').checked = state.extensionEnabled;
    document.getElementById('autoConvertToggle').checked = state.autoConvert;
    
    // Update conversion type buttons
    document.querySelectorAll('.type-btn').forEach(btn => {
      btn.classList.remove('active');
      if (btn.dataset.type === state.conversionType) {
        btn.classList.add('active');
      }
    });
  }
  
  // Save settings with multiple fallbacks
  async function saveSettings() {
    try {
      await chrome.storage.local.set(state);
    } catch (error) {
      console.error('Error saving settings:', error);
    }
  }
  
  // Setup all event listeners
  function setupEventListeners() {
    // Theme toggle
    document.getElementById('themeToggle').addEventListener('click', toggleTheme);
    
    // Extension toggle
    document.getElementById('extensionToggle').addEventListener('change', toggleExtension);
    
    // Auto convert toggle
    document.getElementById('autoConvertToggle').addEventListener('change', toggleAutoConvert);
    
    // Conversion type buttons
    document.getElementById('imageBtn').addEventListener('click', () => setConversionType('image'));
    document.getElementById('fileBtn').addEventListener('click', () => setConversionType('file'));
    
    // Input link events
    const inputLink = document.getElementById('inputLink');
    inputLink.addEventListener('input', handleInputChange);
    inputLink.addEventListener('paste', handlePasteEvent);
    inputLink.addEventListener('change', handleInputChange);
    
    // Keyup with debounce
    let typingTimer;
    inputLink.addEventListener('keyup', () => {
      clearTimeout(typingTimer);
      typingTimer = setTimeout(() => {
        const input = inputLink.value.trim();
        if (input && isGoogleDriveLink(input) && state.autoConvert && state.extensionEnabled) {
          convertLink();
        }
      }, 500);
    });
    
    // Button actions
    document.getElementById('pasteBtn').addEventListener('click', pasteFromClipboard);
    document.getElementById('convertBtn').addEventListener('click', convertLink);
    document.getElementById('copyBtn').addEventListener('click', copyToClipboard);
  }
  
  // Theme management
  function toggleTheme() {
    state.theme = state.theme === 'light' ? 'dark' : 'light';
    applyTheme();
    saveSettings();
  }
  
  function applyTheme() {
    const body = document.body;
    const themeIcon = document.querySelector('#themeToggle i');
    
    if (state.theme === 'dark') {
      body.classList.add('dark-mode');
      themeIcon.className = 'fas fa-sun';
    } else {
      body.classList.remove('dark-mode');
      themeIcon.className = 'fas fa-moon';
    }
  }
  
  // Extension enable/disable
  function toggleExtension() {
    state.extensionEnabled = document.getElementById('extensionToggle').checked;
    saveSettings();
    updateExtensionState();
    
    if (state.extensionEnabled) {
      showStatus('Extension enabled', 'success');
      
      // Notify content scripts to start monitoring if auto-convert is on
      if (state.autoConvert) {
        chrome.tabs.query({}, (tabs) => {
          tabs.forEach(tab => {
            if (tab.id) {
              chrome.tabs.sendMessage(tab.id, {
                type: 'START_MONITORING'
              }, () => {
                if (chrome.runtime.lastError) {
                  console.log('Tab message error (expected):', chrome.runtime.lastError.message);
                }
              });
            }
          });
        });
      }
    } else {
      showStatus('Extension disabled', 'error');
      
      // Notify content scripts to stop monitoring
      chrome.tabs.query({}, (tabs) => {
        tabs.forEach(tab => {
          if (tab.id) {
            chrome.tabs.sendMessage(tab.id, {
              type: 'STOP_MONITORING'
            }, () => {
              if (chrome.runtime.lastError) {
                console.log('Tab message error (expected):', chrome.runtime.lastError.message);
              }
            });
          }
        });
      });
    }
  }
  
  function updateExtensionState() {
    const content = document.getElementById('mainContent');
    const mainSections = document.getElementById('mainSections');
    
    if (state.extensionEnabled) {
      content.classList.remove('disabled');
      // Re-check link state when re-enabled
      const inputLink = document.getElementById('inputLink').value.trim();
      if (state.isOnGoogleDrive) {
        if (!inputLink || !isGoogleDriveLink(inputLink)) {
          showDriveWarning();
        } else {
          hideDriveWarning();
        }
      }
    } else {
      content.classList.add('disabled');
      // Clear output when disabled
      document.getElementById('outputLink').value = '';
    }
  }
  
  // Auto convert functionality
  function toggleAutoConvert() {
    state.autoConvert = document.getElementById('autoConvertToggle').checked;
    saveSettings();
    
    // Notify all content scripts
    chrome.tabs.query({}, (tabs) => {
      tabs.forEach(tab => {
        if (tab.id) {
          chrome.tabs.sendMessage(tab.id, {
            type: state.autoConvert && state.extensionEnabled ? 'START_MONITORING' : 'STOP_MONITORING'
          }, () => {
            if (chrome.runtime.lastError) {
              console.log('Tab message error (expected for some tabs):', chrome.runtime.lastError.message);
            }
          });
        }
      });
    });
    
    if (state.autoConvert) {
      showStatus('🎯 Auto convert enabled - Copy Drive links to auto-convert!', 'success');
    } else {
      showStatus('Auto convert disabled', 'error');
    }
  }
  
  // Input handling with auto-convert
  function handleInputChange(e) {
    if (!state.extensionEnabled) return;
    
    const input = e.target.value.trim();
    
    if (input && isGoogleDriveLink(input)) {
      hideDriveWarning();
      if (state.autoConvert) {
        setTimeout(() => {
          convertLink();
        }, 100);
      }
    } else if (input && !isGoogleDriveLink(input)) {
      showDriveWarning();
      document.getElementById('outputLink').value = '';
    } else {
      hideDriveWarning();
      document.getElementById('outputLink').value = '';
    }
  }
  
  // Handle paste event
  function handlePasteEvent(e) {
    if (!state.extensionEnabled) return;
    
    try {
      const pastedText = e.clipboardData.getData('text');
      if (pastedText && isGoogleDriveLink(pastedText)) {
        hideDriveWarning();
        if (state.autoConvert) {
          setTimeout(() => {
            convertLink();
          }, 150);
        } else {
          showStatus('Drive link detected. Click convert button.', 'success');
        }
      } else if (pastedText) {
        showDriveWarning();
      }
    } catch (error) {
      console.error('Paste event error:', error);
    }
    
    setTimeout(() => {
      const input = document.getElementById('inputLink').value.trim();
      if (input && isGoogleDriveLink(input)) {
        hideDriveWarning();
        if (state.autoConvert) {
          convertLink();
        }
      } else if (input) {
        showDriveWarning();
      }
    }, 200);
  }
  
  // Paste from clipboard
  async function pasteFromClipboard() {
    try {
      const text = await navigator.clipboard.readText();
      document.getElementById('inputLink').value = text;
      
      if (isGoogleDriveLink(text)) {
        hideDriveWarning();
        if (state.autoConvert) {
          setTimeout(() => {
            convertLink();
          }, 100);
        } else {
          showStatus('Link pasted. Click convert button.', 'success');
        }
      } else {
        showDriveWarning();
        showStatus('Pasted text is not a Google Drive link', 'error');
      }
    } catch (error) {
      try {
        const inputField = document.getElementById('inputLink');
        inputField.focus();
        inputField.select();
        document.execCommand('paste');
        
        setTimeout(() => {
          const pastedText = inputField.value.trim();
          if (isGoogleDriveLink(pastedText)) {
            hideDriveWarning();
            if (state.autoConvert) {
              convertLink();
            } else {
              showStatus('Link pasted. Click convert button.', 'success');
            }
          } else if (pastedText) {
            showDriveWarning();
          }
        }, 100);
      } catch (e) {
        showStatus('Please paste manually (Ctrl+V or Cmd+V)', 'error');
        document.getElementById('inputLink').focus();
      }
    }
  }
  
  // Conversion type selection
  function setConversionType(type) {
    state.conversionType = type;
    
    document.querySelectorAll('.type-btn').forEach(btn => {
      btn.classList.remove('active');
      if (btn.dataset.type === type) {
        btn.classList.add('active');
      }
    });
    
    saveSettings();
    
    const inputLink = document.getElementById('inputLink').value.trim();
    if (inputLink && isGoogleDriveLink(inputLink)) {
      if (state.autoConvert) {
        convertLink();
      } else {
        showStatus(`Switched to ${type === 'image' ? 'Direct View' : 'Direct Download'} mode`, 'success');
      }
    }
  }
  
  // Main conversion function
  function convertLink() {
    if (!state.extensionEnabled) {
      showStatus('Extension is disabled', 'error');
      return;
    }
    
    const inputLink = document.getElementById('inputLink').value.trim();
    
    if (!inputLink) {
      showStatus('Please enter a Google Drive link', 'error');
      showDriveWarning();
      return;
    }
    
    if (!isGoogleDriveLink(inputLink)) {
      showStatus('Invalid Google Drive link', 'error');
      showDriveWarning();
      document.getElementById('outputLink').value = '';
      return;
    }
    
    hideDriveWarning();
    
    const convertedLink = convertDriveLink(inputLink, state.conversionType);
    
    if (convertedLink) {
      document.getElementById('outputLink').value = convertedLink;
      
      const typeLabel = state.conversionType === 'image' ? 'Direct View' : 'Direct Download';
      showStatus(`✓ Converted to ${typeLabel} link!`, 'success');
      
      if (state.autoConvert) {
        setTimeout(() => {
          copyToClipboardSilent(convertedLink);
        }, 200);
      }
    } else {
      showStatus('Failed to convert link. Please check the link format.', 'error');
      showDriveWarning();
      document.getElementById('outputLink').value = '';
    }
  }
  
  // Show Drive link warning (only when on Google Drive but no valid link)
  function showDriveWarning() {
    const warning = document.getElementById('driveWarningFull');
    const mainSections = document.getElementById('mainSections');
    
    if (warning && mainSections) {
      warning.classList.add('show');
      mainSections.classList.add('hidden');
    }
  }
  
  // Hide Drive link warning
  function hideDriveWarning() {
    const warning = document.getElementById('driveWarningFull');
    const mainSections = document.getElementById('mainSections');
    
    if (warning && mainSections) {
      warning.classList.remove('show');
      mainSections.classList.remove('hidden');
    }
  }
  
  // Check if link is a Google Drive link
  function isGoogleDriveLink(link) {
    if (!link || typeof link !== 'string') return false;
    
    const patterns = [
      /drive\.google\.com\/file\/d\//,
      /drive\.google\.com\/open\?id=/,
      /docs\.google\.com\/.*\/d\//,
      /drive\.google\.com\/.*id=/,
      /drive\.google\.com\/uc\?/
    ];
    
    return patterns.some(pattern => pattern.test(link));
  }
  
  // Extract file ID
  function extractFileId(link) {
    let match = link.match(/\/d\/([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    match = link.match(/[?&]id=([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    match = link.match(/open\?id=([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    match = link.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
    if (match) return match[1];
    
    if (/^[a-zA-Z0-9_-]{25,}$/.test(link)) {
      return link;
    }
    
    match = link.match(/\/([a-zA-Z0-9_-]{25,})(?:[/?]|$)/);
    if (match) return match[1];
    
    const parts = link.split(/[/?&=#]/);
    for (const part of parts) {
      if (/^[a-zA-Z0-9_-]{25,}$/.test(part)) {
        return part;
      }
    }
    
    return null;
  }
  
  // Convert Drive link
  function convertDriveLink(link, type) {
    const fileId = extractFileId(link);
    
    if (!fileId) {
      console.error('Could not extract file ID');
      return null;
    }
    
    if (type === 'image') {
      return `https://drive.google.com/uc?export=view&id=${fileId}`;
    } else {
      return `https://drive.google.com/uc?export=download&id=${fileId}`;
    }
  }
  
  // Copy to clipboard
  async function copyToClipboard() {
    const outputLink = document.getElementById('outputLink').value;
    
    if (!outputLink) {
      showStatus('No link to copy', 'error');
      return;
    }
    
    await copyToClipboardDirect(outputLink);
  }
  
  // Silent copy
  async function copyToClipboardSilent(text) {
    try {
      await navigator.clipboard.writeText(text);
      showStatus('✓ Link converted & copied to clipboard!', 'success');
      
      const copyBtn = document.getElementById('copyBtn');
      const originalHTML = copyBtn.innerHTML;
      copyBtn.innerHTML = '<i class="fas fa-check"></i>';
      setTimeout(() => {
        copyBtn.innerHTML = originalHTML;
      }, 2000);
    } catch (error) {
      try {
        const textarea = document.getElementById('outputLink');
        textarea.select();
        document.execCommand('copy');
        showStatus('✓ Link converted & copied!', 'success');
      } catch (e) {
        showStatus('Link converted! Use copy button to copy.', 'success');
      }
    }
  }
  
  // Copy with feedback
  async function copyToClipboardDirect(text) {
    try {
      await navigator.clipboard.writeText(text);
      showStatus('Link copied to clipboard!', 'success');
      
      const copyBtn = document.getElementById('copyBtn');
      const originalHTML = copyBtn.innerHTML;
      copyBtn.innerHTML = '<i class="fas fa-check"></i>';
      setTimeout(() => {
        copyBtn.innerHTML = originalHTML;
      }, 2000);
    } catch (error) {
      try {
        const textarea = document.getElementById('outputLink');
        textarea.select();
        document.execCommand('copy');
        showStatus('Link copied to clipboard!', 'success');
      } catch (e) {
        showStatus('Could not copy. Please copy manually.', 'error');
        document.getElementById('outputLink').select();
      }
    }
  }
  
  // Show status message
  function showStatus(message, type) {
    const statusMessage = document.getElementById('statusMessage');
    const statusText = document.getElementById('statusText');
    const icon = statusMessage.querySelector('i');
    
    statusText.textContent = message;
    statusMessage.className = 'status-message show ' + type;
    
    if (type === 'success') {
      icon.className = 'fas fa-check-circle';
    } else {
      icon.className = 'fas fa-exclamation-circle';
    }
    
    setTimeout(() => {
      statusMessage.classList.remove('show');
    }, 4000);
  }
  
  // Background message listener
  try {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.type === 'CONVERT_LINK') {
        const converted = convertDriveLink(request.link, state.conversionType);
        sendResponse({ success: true, link: converted });
      }
    });
  } catch (error) {
    console.error('Message listener error:', error);
  }