// Safe JSON parser that handles PHP errors/warnings prepended to JSON responses
async function parseSafeJson(response) {
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch (err) {
    // If standard parsing fails, check if we can extract JSON from the text
    const jsonStartIndex = text.indexOf('{');
    const jsonEndIndex = text.lastIndexOf('}');
    if (jsonStartIndex !== -1 && jsonEndIndex !== -1 && jsonEndIndex > jsonStartIndex) {
      const potentialJson = text.substring(jsonStartIndex, jsonEndIndex + 1);
      try {
        return JSON.parse(potentialJson);
      } catch (nestedErr) {
        console.debug('Failed to parse extracted JSON:', nestedErr);
      }
    }
    
    // Check if the response contains HTML or PHP warning tags
    if (text.includes('Warning:') || text.includes('Notice:') || text.includes('Fatal error:') || text.includes('Error:')) {
      throw new Error('Server returned invalid response (PHP errors or warnings prepended).');
    }
    
    throw new Error('Server returned invalid JSON format.');
  }
}

// Test connection function (defined in outer scope)
async function testConnection(url, key) {
  if (!url || !key) {
    return { success: false, status: 'Not configured', message: 'Both Base URL and API Key are required.' };
  }
  
  let normalizedUrl = url.trim();
  if (normalizedUrl.endsWith('/')) {
    normalizedUrl = normalizedUrl.slice(0, -1);
  }
  
  try {
    const response = await fetch(`${normalizedUrl}/api/user`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${key}`
      }
    });
    
    if (response.ok) {
      try {
        await parseSafeJson(response);
        return { success: true, status: 'Connected', message: 'Connection successful!' };
      } catch (jsonErr) {
        return { success: false, status: 'API unavailable', message: jsonErr.message };
      }
    } else if (response.status === 401) {
      return { success: false, status: 'Invalid API key', message: 'Invalid API key. Please check your settings.' };
    } else {
      return { success: false, status: 'API unavailable', message: `Server returned status ${response.status}.` };
    }
  } catch (err) {
    console.error('Fetch connection error:', err);
    return { success: false, status: 'API unavailable', message: 'Network error. Check your Base URL and connection.' };
  }
}

document.addEventListener('DOMContentLoaded', async () => {
  const toggleBtn = document.getElementById('toggle-settings');
  const mainPanel = document.getElementById('main-panel');
  const settingsPanel = document.getElementById('settings-panel');
  const shortenBtn = document.getElementById('shorten-btn');
  const copyBtn = document.getElementById('copy-btn');
  const saveSettingsBtn = document.getElementById('save-settings');
  const testConnectionBtn = document.getElementById('test-connection');
  const apiKeyLink = document.getElementById('api-key-link');
  
  const longUrlInput = document.getElementById('long-url');
  const customSlugInput = document.getElementById('custom-slug');
  const shortUrlInput = document.getElementById('short-url');
  const resultBox = document.getElementById('result-box');
  const statusMsg = document.getElementById('status-msg');
  
  const apiUrlInput = document.getElementById('api-url');
  const apiKeyInput = document.getElementById('api-key');
  const connectionBadge = document.getElementById('connection-badge');

  // QR elements and state
  const qrSection = document.getElementById('qr-section');
  const qrCanvas = document.getElementById('qr-code');
  const downloadQrBtn = document.getElementById('download-qr-btn');
  let currentSlug = '';

  // Explicitly clear inputs on load to avoid browser Autofill interference
  longUrlInput.value = '';
  customSlugInput.value = '';
  if (qrSection) qrSection.style.display = 'none';
  if (downloadQrBtn) downloadQrBtn.disabled = true;
  currentSlug = '';
  if (qrCanvas) {
    const ctx = qrCanvas.getContext('2d');
    ctx.clearRect(0, 0, qrCanvas.width, qrCanvas.height);
  }

  // Load settings
  const { api_url, api_key } = await chrome.storage.local.get(['api_url', 'api_key']);
  
  if (api_url) {
    apiUrlInput.value = api_url;
  }
  
  if (api_key) {
    apiKeyInput.value = api_key;
    updateApiKeyLink();
    
    // Test saved connection in the background
    updateConnectionBadge('Checking...', 'Checking...');
    const result = await testConnection(api_url, api_key);
    updateConnectionBadge(result.status);
    
    if (result.success) {
      showPanel('main');
    } else {
      showPanel('settings');
      showStatus(result.message, 'error');
    }
  } else {
    updateConnectionBadge('Not configured');
    showPanel('settings');
    hideStatus(); // Do not show red error when nothing has been attempted yet
  }

  // Pre-fill active tab URL and suggest Base Site URL
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs?.[0]?.url) {
      // Don't pre-fill chrome:// or extension pages
      if (tabs[0].url.startsWith('http')) {
        longUrlInput.value = tabs[0].url;
        
        // Suggest Base URL if not configured yet
        if (!apiUrlInput.value) {
          try {
            const activeUrl = new URL(tabs[0].url);
            let suggestedUrl = activeUrl.origin;
            if (activeUrl.pathname.includes('/jkznetwork')) {
              suggestedUrl += '/jkznetwork';
            }
            apiUrlInput.value = suggestedUrl;
            updateApiKeyLink();
          } catch (e) {
            console.debug('Failed to pre-fill dynamic API URL:', e);
          }
        }
      }
    }
  });

  // Toggle settings panel
  toggleBtn.addEventListener('click', () => {
    if (mainPanel.classList.contains('hidden')) {
      showPanel('main');
    } else {
      showPanel('settings');
    }
  });

  // Update API Key link dynamically
  function updateApiKeyLink() {
    let url = apiUrlInput.value.trim();
    if (url) {
      if (url.endsWith('/')) {
        url = url.slice(0, -1);
      }
      apiKeyLink.href = `${url}/account-api`;
    } else {
      apiKeyLink.href = '#';
    }
  }

  apiUrlInput.addEventListener('input', updateApiKeyLink);

  // Allow links to open in new tab securely
  apiKeyLink.addEventListener('click', (e) => {
    e.preventDefault();
    const url = apiKeyLink.href;
    if (url && url !== '#') {
      chrome.tabs.create({ url });
    }
  });

  // Helper to update connection badge UI
  function updateConnectionBadge(status, text) {
    connectionBadge.textContent = text || status;
    connectionBadge.className = 'badge';
    if (status === 'Connected') {
      connectionBadge.classList.add('badge-success');
      shortenBtn.disabled = false;
    } else if (status === 'Invalid API key') {
      connectionBadge.classList.add('badge-error');
      shortenBtn.disabled = true;
    } else if (status === 'API unavailable') {
      connectionBadge.classList.add('badge-warning');
      shortenBtn.disabled = true;
    } else {
      connectionBadge.classList.add('badge-info');
      shortenBtn.disabled = true;
    }
  }

  // Test Connection Button click handler
  testConnectionBtn.addEventListener('click', async () => {
    const url = apiUrlInput.value.trim();
    const key = apiKeyInput.value.trim();
    
    if (!url || !key) {
      showStatus('Both Base URL and API Key are required.', 'error');
      updateConnectionBadge('Not configured');
      return;
    }
    
    testConnectionBtn.disabled = true;
    testConnectionBtn.textContent = 'Testing...';
    hideStatus();
    
    const result = await testConnection(url, key);
    updateConnectionBadge(result.status);
    showStatus(result.message, result.success ? 'success' : 'error');
    
    testConnectionBtn.disabled = false;
    testConnectionBtn.textContent = 'Test Connection';
  });

  // Save Settings click handler
  saveSettingsBtn.addEventListener('click', async () => {
    let url = apiUrlInput.value.trim();
    const key = apiKeyInput.value.trim();
    
    if (!url || !key) {
      showStatus('Both Base URL and API Key are required.', 'error');
      updateConnectionBadge('Not configured');
      return;
    }
    
    if (url.endsWith('/')) {
      url = url.slice(0, -1);
    }
    
    saveSettingsBtn.disabled = true;
    saveSettingsBtn.textContent = 'Saving...';
    hideStatus();
    
    const result = await testConnection(url, key);
    updateConnectionBadge(result.status);
    
    // Always update stored settings, even if offline, but show proper feedback
    await chrome.storage.local.set({ api_url: url, api_key: key });
    updateApiKeyLink();
    
    if (result.success) {
      showStatus('Settings saved and connected successfully!', 'success');
      setTimeout(() => {
        showPanel('main');
        hideStatus();
      }, 1200);
    } else {
      showStatus(`Settings saved, but connection failed: ${result.message}`, 'error');
    }
    
    saveSettingsBtn.disabled = false;
    saveSettingsBtn.textContent = 'Save Settings';
  });

  // Shorten URL click handler
  shortenBtn.addEventListener('click', async () => {
    const longUrl = longUrlInput.value.trim();
    const customSlug = customSlugInput.value.trim();

    if (!longUrl) {
      showStatus('Please enter a long URL.', 'error');
      return;
    }

    // Front-end Long URL format check
    try {
      new URL(longUrl);
      if (!longUrl.startsWith('http://') && !longUrl.startsWith('https://')) {
        throw new Error();
      }
    } catch (e) {
      showStatus('The destination URL is invalid. It must start with http:// or https://', 'error');
      return;
    }

    if (customSlug && !/^[a-zA-Z0-9-_]+$/.test(customSlug)) {
      showStatus('Custom alias must be a short slug, not a full URL.', 'error');
      return;
    }

    // Get current settings
    const config = await chrome.storage.local.get(['api_url', 'api_key']);
    if (!config.api_key || !config.api_url) {
      showPanel('settings');
      showStatus('API URL and Key are required to shorten links.', 'error');
      return;
    }

    shortenBtn.disabled = true;
    shortenBtn.textContent = 'Shortening...';
    hideStatus();
    resultBox.style.display = 'none';
    
    // Reset QR state
    if (qrSection) qrSection.style.display = 'none';
    if (downloadQrBtn) downloadQrBtn.disabled = true;
    currentSlug = '';
    if (qrCanvas) {
      const ctx = qrCanvas.getContext('2d');
      ctx.clearRect(0, 0, qrCanvas.width, qrCanvas.height);
    }

    try {
      const params = new URLSearchParams();
      params.append('type', 'link');
      params.append('location_url', longUrl);
      if (customSlug) {
        params.append('url', customSlug);
      }

      const response = await fetch(`${config.api_url}/api/links`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${config.api_key}`,
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        },
        body: params
      });

      if (response.status === 404) {
        throw new Error('Short link API endpoint not found.');
      }

      let data;
      try {
        data = await parseSafeJson(response);
      } catch (jsonErr) {
        throw new Error(jsonErr.message);
      }

      if (response.ok && data?.data?.url) {
        // Construct the full short URL from Base Site URL and returned slug
        const shortUrl = `${config.api_url}/${data.data.url}`;
        shortUrlInput.value = shortUrl;
        resultBox.style.display = 'block';
        showStatus('Link shortened successfully!', 'success');
        
        currentSlug = data.data.url;
        await saveRecentLink(longUrl, shortUrl, 'popup');
        
        // Generate QR code
        try {
          if (qrCanvas) {
            new QRious({
              element: qrCanvas,
              value: shortUrl,
              size: 180,
              level: 'H'
            });
            if (qrSection) qrSection.style.display = 'block';
            if (downloadQrBtn) downloadQrBtn.disabled = false;
          }
        } catch (qrErr) {
          console.error('QR code generation failed:', qrErr);
          if (qrSection) qrSection.style.display = 'none';
          if (downloadQrBtn) downloadQrBtn.disabled = true;
          showStatus('The short link was created, but the QR code could not be generated.', 'error');
        }
      } else {
        let errMsg = 'Failed to shorten link.';
        if (data?.errors?.[0]?.title) {
          errMsg = data.errors[0].title;
          
          // Map AltumCode standard errors to exact requested messages
          if (errMsg.includes('limits of your current plan')) {
            errMsg = 'You do not have permission to create more links on your current plan.';
          } else if (errMsg === 'This custom URL already exists.') {
            errMsg = 'This custom alias is already taken.';
          } else if (errMsg.includes("Maybe you're missing the https://") || errMsg.includes('invalid format')) {
            errMsg = 'The destination URL is invalid.';
          }
        }
        showStatus(errMsg, 'error');
        if (qrSection) qrSection.style.display = 'none';
        if (downloadQrBtn) downloadQrBtn.disabled = true;
        currentSlug = '';
      }
    } catch (err) {
      console.error('API Shorten error:', err);
      showStatus(err.message || 'Network error. Check your Base URL and connection.', 'error');
      if (qrSection) qrSection.style.display = 'none';
      if (downloadQrBtn) downloadQrBtn.disabled = true;
      currentSlug = '';
    } finally {
      shortenBtn.disabled = false;
      shortenBtn.textContent = 'Shorten Link';
    }
  });

  // Copy to clipboard with modern API and fallback
  copyBtn.addEventListener('click', async () => {
    try {
      await navigator.clipboard.writeText(shortUrlInput.value);
    } catch (err) {
      console.debug('Fallback to execCommand copy due to error:', err);
      shortUrlInput.select();
      document.execCommand('copy');
    }
    const originalText = copyBtn.textContent;
    copyBtn.textContent = 'Copied!';
    copyBtn.style.backgroundColor = '#059669';
    setTimeout(() => {
      copyBtn.textContent = originalText;
      copyBtn.style.backgroundColor = 'var(--accent)';
    }, 1500);
  });

  // Download QR code click handler
  downloadQrBtn.addEventListener('click', () => {
    if (!qrCanvas || !currentSlug) return;
    
    try {
      const dataUrl = qrCanvas.toDataURL('image/png');
      const safeSlug = currentSlug.replace(/[^a-zA-Z0-9-_]/g, '');
      const filename = `jkz-network-qr-${safeSlug || 'code'}.png`;
      
      const a = document.createElement('a');
      a.href = dataUrl;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
    } catch (err) {
      console.error('Failed to download QR code:', err);
      showStatus('Failed to download QR code image.', 'error');
    }
  });

  // Save recent links history (max 10)
  async function saveRecentLink(originalUrl, shortUrl, source) {
    const timestamp = Date.now();
    await chrome.storage.local.set({
      last_short_link: shortUrl,
      last_short_link_created_at: timestamp,
      last_short_link_original_url: originalUrl
    });

    let { recent_links } = await chrome.storage.local.get(['recent_links']);
    if (!Array.isArray(recent_links)) {
      recent_links = [];
    }
    recent_links.unshift({
      short_url: shortUrl,
      original_url: originalUrl,
      created_at: timestamp,
      source: source
    });
    if (recent_links.length > 10) {
      recent_links = recent_links.slice(0, 10);
    }
    await chrome.storage.local.set({ recent_links });
  }

  // Helper functions
  function showPanel(panel) {
    if (panel === 'settings') {
      mainPanel.classList.add('hidden');
      settingsPanel.classList.remove('hidden');
      toggleBtn.textContent = '✕';
    } else {
      settingsPanel.classList.add('hidden');
      mainPanel.classList.remove('hidden');
      toggleBtn.textContent = '⚙️';
    }
  }

  function showStatus(msg, type) {
    statusMsg.textContent = msg;
    statusMsg.style.display = 'block';
    if (type === 'error') {
      statusMsg.className = 'status-msg badge badge-error';
    } else {
      statusMsg.className = 'status-msg';
      statusMsg.style.color = 'var(--accent)';
    }
  }

  function hideStatus() {
    statusMsg.style.display = 'none';
  }
});
