// 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) {
    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);
      }
    }
    
    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
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.' };
  }
}

// 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 });
}

document.addEventListener('DOMContentLoaded', async () => {
  const connectionBadge = document.getElementById('connection-badge');
  const destinationUrlInput = document.getElementById('destination-url');
  const customSlugInput = document.getElementById('custom-slug');
  const checkGenerateQr = document.getElementById('check-generate-qr');
  const checkOpenDashboard = document.getElementById('check-open-dashboard');
  const shortenBtn = document.getElementById('shorten-btn');
  
  const resultBox = document.getElementById('result-box');
  const shortUrlInput = document.getElementById('short-url');
  const copyBtn = document.getElementById('copy-btn');
  const qrSection = document.getElementById('qr-section');
  const qrCanvas = document.getElementById('qr-code');
  const downloadQrBtn = document.getElementById('download-qr-btn');
  const statusMsg = document.getElementById('status-msg');

  let currentSlug = '';

  // Helper to show/hide status messages
  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';
  }

  // 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;
    }
  }

  // Read URL query parameters
  const urlParams = new URLSearchParams(window.location.search);
  const paramUrl = urlParams.get('url');
  const paramAuto = urlParams.get('auto') === '1';
  const paramQr = urlParams.get('qr') === '1';

  if (paramUrl) {
    destinationUrlInput.value = paramUrl;
  }
  if (paramQr) {
    checkGenerateQr.checked = true;
  }

  // Clear inputs and canvases initial state
  if (qrSection) qrSection.style.display = 'none';
  if (downloadQrBtn) downloadQrBtn.disabled = true;
  currentSlug = '';

  // Get and verify configurations
  const config = await chrome.storage.local.get(['api_url', 'api_key']);
  if (config.api_url && config.api_key) {
    updateConnectionBadge('Checking...', 'Checking...');
    const result = await testConnection(config.api_url, config.api_key);
    updateConnectionBadge(result.status);
    
    if (!result.success) {
      showStatus(result.message, 'error');
    } else if (paramAuto) {
      // Auto shorten if parameter is set and connected
      shortenBtn.click();
    }
  } else {
    updateConnectionBadge('Not configured');
    showStatus('API URL and Key are required. Please configure settings in popup first.', 'error');
  }

  // Shorten Button Click
  shortenBtn.addEventListener('click', async () => {
    const longUrl = destinationUrlInput.value.trim();
    const customSlug = customSlugInput.value.trim();

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

    try {
      new URL(longUrl);
      if (!longUrl.startsWith('http://') && !longUrl.startsWith('https://')) {
        throw new Error();
      }
    } catch (_) {
      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;
    }

    shortenBtn.disabled = true;
    shortenBtn.textContent = 'Shortening...';
    hideStatus();
    resultBox.style.display = 'none';
    if (qrSection) qrSection.style.display = 'none';
    if (downloadQrBtn) downloadQrBtn.disabled = true;
    currentSlug = '';

    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) {
        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, 'advanced_context');

        // Copy to clipboard
        try {
          await navigator.clipboard.writeText(shortUrl);
        } catch (_) {
          shortUrlInput.select();
          document.execCommand('copy');
        }

        // Generate QR code
        if (checkGenerateQr.checked && qrCanvas) {
          try {
            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);
            showStatus('The short link was created, but the QR code could not be generated.', 'error');
          }
        }

        // Open Dashboard
        if (checkOpenDashboard.checked) {
          chrome.tabs.create({ url: `${config.api_url}/dashboard` });
        }
      } else {
        let errMsg = 'Failed to shorten link.';
        if (data?.errors?.[0]?.title) {
          errMsg = data.errors[0].title;
          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');
      }
    } catch (err) {
      console.error('Options window shortening error:', err);
      showStatus(err.message || 'Network error. Check your Base URL and connection.', 'error');
    } finally {
      shortenBtn.disabled = false;
      shortenBtn.textContent = 'Shorten Link';
    }
  });

  // Copy button listener
  copyBtn.addEventListener('click', async () => {
    try {
      await navigator.clipboard.writeText(shortUrlInput.value);
    } catch (_) {
      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 listener
  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');
    }
  });
});
