/**
 * Diagnostic script for sidebar loading
 * Runs before sidebar.js to help debug loading issues
 */

// === DIAGNOSTIC 1: HTML LOADED ===
console.log('='.repeat(80));
console.log('[Sidebar Diagnostics] Script loaded');
console.log('[Sidebar Diagnostics] Current URL:', window.location.href);
console.log('[Sidebar Diagnostics] Document title:', document.title);
console.log('[Sidebar Diagnostics] Chrome runtime available:', !!chrome?.runtime);
console.log('[Sidebar Diagnostics] Chrome runtime ID:', chrome?.runtime?.id);
console.log('='.repeat(80));

// Add global error handlers to catch any module loading errors
window.addEventListener('error', (event) => {
  console.error('[Sidebar Diagnostics] ❌ Global error caught:', {
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
    error: event.error
  });
});

window.addEventListener('unhandledrejection', (event) => {
  console.error('[Sidebar Diagnostics] ❌ Unhandled promise rejection:', {
    reason: event.reason,
    promise: event.promise
  });
});

// === DIAGNOSTIC 2: MANUAL CONNECTION TEST ===
console.log('[Sidebar Diagnostics] Testing chrome.runtime messaging...');

if (chrome?.runtime) {
  console.log('[Sidebar Diagnostics] chrome.runtime available, attempting GET_AUTH_STATE...');
  chrome.runtime.sendMessage({ type: 'GET_AUTH_STATE' })
    .then(response => {
      console.log('[Sidebar Diagnostics] ✅ Message successful! Response:', response);
      console.log('[Sidebar Diagnostics] Authenticated:', response?.authenticated);
      console.log('[Sidebar Diagnostics] Auth data:', response?.auth);

      if (response?.authenticated) {
        console.log('[Sidebar Diagnostics] ✅ Authentication is working!');
        console.log('[Sidebar Diagnostics] Org ID:', response.auth?.orgId);
        console.log('[Sidebar Diagnostics] User ID:', response.auth?.userId);
      } else {
        console.log('[Sidebar Diagnostics] ⚠️ Not authenticated');
      }
    })
    .catch(error => {
      console.error('[Sidebar Diagnostics] ❌ Message failed:', error);
    });
} else {
  console.error('[Sidebar Diagnostics] ❌ chrome.runtime not available!');
}

// === DIAGNOSTIC 3: CHECK MODULE LOADING ===
setTimeout(() => {
  console.log('='.repeat(80));
  console.log('[Sidebar Diagnostics] Module loading check (after 2 seconds)');
  console.log('[Sidebar Diagnostics] Document ready state:', document.readyState);

  // Check for script elements
  const scripts = document.querySelectorAll('script');
  console.log('[Sidebar Diagnostics] Found', scripts.length, 'script tags');
  scripts.forEach((script, i) => {
    if (script.src) {
      console.log(`[Sidebar Diagnostics] Script ${i}:`, {
        src: script.src.split('/').pop(),
        type: script.type,
        loaded: script.readyState === 'complete' || !script.readyState
      });
    }
  });
  console.log('='.repeat(80));
}, 2000);
