/**
 * Content Script - Dynamic Favicon with Session Badge
 * Overlays session badge color onto site's favicon
 */

(function() {
  'use strict';

  // Skip execution on extension pages and local HTML files
  const isExtensionProtocol = window.location.protocol === 'chrome-extension:' ||
                              window.location.protocol === 'edge-extension:';
  const isFileProtocol = window.location.protocol === 'file:';
  const isExtensionHTML = window.location.href.includes('storage-diagnostics.html') ||
                          window.location.href.includes('popup-license.html') ||
                          window.location.href.includes('license-details.html');
  const isPopup = window.location.href.includes('/popup.html');

  if ((isExtensionProtocol && !isPopup) || isFileProtocol || (isExtensionHTML && !isPopup)) {
    console.log('[Favicon] Skipping execution on extension/local page');
    return;
  }

  console.log('[Favicon] Script loaded');

  let sessionColor = null;
  let isInitialized = false;
  let shouldStopRetrying = false; // Flag to stop retry logic

  /**
   * Get session ID and color from background script
   */
  async function getSessionColor() {
    try {
      // Check if chrome.runtime is available
      if (!chrome || !chrome.runtime) {
        console.error('[Favicon] chrome.runtime not available');
        return false;
      }

      console.log('[Favicon] Requesting session ID from background...');

      // Use Promise wrapper for better error handling
      const response = await new Promise((resolve, reject) => {
        chrome.runtime.sendMessage({ action: 'getSessionId' }, (response) => {
          if (chrome.runtime.lastError) {
            console.error('[Favicon] Runtime error:', chrome.runtime.lastError);
            reject(chrome.runtime.lastError);
          } else {
            resolve(response);
          }
        });
      });

      console.log('[Favicon] Session ID response:', response);

      if (response?.success && response.sessionId) {
        console.log('[Favicon] Got session ID:', response.sessionId);

        // Now get the session color
        const colorResponse = await new Promise((resolve, reject) => {
          chrome.runtime.sendMessage({
            action: 'getSessionColor',
            sessionId: response.sessionId
          }, (response) => {
            if (chrome.runtime.lastError) {
              console.error('[Favicon] Runtime error:', chrome.runtime.lastError);
              reject(chrome.runtime.lastError);
            } else {
              resolve(response);
            }
          });
        });

        console.log('[Favicon] Session color response:', colorResponse);

        if (colorResponse?.success && colorResponse.color) {
          sessionColor = colorResponse.color;
          console.log('[Favicon] ✓ Got session color:', sessionColor);
          return true;
        } else {
          console.log('[Favicon] Failed to get session color');
          return false;
        }
      } else {
        console.log('[Favicon] Tab has no session, skipping favicon overlay');
        return false;
      }
    } catch (error) {
      console.error('[Favicon] Error getting session color:', error);
      return false;
    }
  }

  /**
   * Create a canvas with the extension icon and colored badge overlay
   * @param {HTMLImageElement} img - Extension icon image
   * @param {string} color - Hex color code for badge
   * @returns {string} Data URL of badged icon
   */
  function createBadgedIcon(img, color) {
    const canvas = document.createElement('canvas');
    const size = 32; // Standard favicon size
    canvas.width = size;
    canvas.height = size;

    const ctx = canvas.getContext('2d');

    // Draw extension icon
    ctx.drawImage(img, 0, 0, size, size);

    // Draw colored badge in bottom-right corner
    const badgeSize = 12;
    const badgeX = size - badgeSize - 2;
    const badgeY = size - badgeSize - 2;

    // Draw badge background (white circle with slight shadow)
    ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
    ctx.shadowBlur = 2;
    ctx.shadowOffsetX = 1;
    ctx.shadowOffsetY = 1;

    ctx.fillStyle = '#FFFFFF';
    ctx.beginPath();
    ctx.arc(badgeX + badgeSize/2, badgeY + badgeSize/2, badgeSize/2, 0, Math.PI * 2);
    ctx.fill();

    // Reset shadow
    ctx.shadowColor = 'transparent';
    ctx.shadowBlur = 0;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;

    // Draw colored badge
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(badgeX + badgeSize/2, badgeY + badgeSize/2, badgeSize/2 - 1, 0, Math.PI * 2);
    ctx.fill();

    return canvas.toDataURL('image/png');
  }

  /**
   * Apply extension icon with colored badge
   */
  function applyBadgedFavicon() {
    if (!sessionColor) {
      console.log('[Favicon] No session color, skipping');
      return;
    }

    console.log('[Favicon] Applying extension icon with colored badge...');

    // Load extension icon
    const extensionIconUrl = chrome.runtime.getURL('icons/icon48.png');
    const iconImg = new Image();

    iconImg.onload = function() {
      console.log('[Favicon] Extension icon loaded, creating badged version');

      // Create badged favicon using extension icon
      const badgedDataUrl = createBadgedIcon(iconImg, sessionColor);

      // Remove existing favicons (including temporary placeholder)
      const existingLinks = document.querySelectorAll('link[rel*="icon"]');
      existingLinks.forEach(link => link.remove());

      // Add badged extension icon
      const newLink = document.createElement('link');
      newLink.rel = 'icon';
      newLink.type = 'image/png';
      newLink.href = badgedDataUrl;
      newLink.dataset.sessionFavicon = 'true'; // Mark as our favicon
      document.head.appendChild(newLink);

      console.log('[Favicon] ✓ Extension icon with badge applied (replaced temporary favicon)');
    };

    iconImg.onerror = function() {
      console.error('[Favicon] Failed to load extension icon');
    };

    // Load extension icon
    iconImg.src = extensionIconUrl;
  }

  /**
   * Initialize the favicon overlay
   */
  async function initialize() {
    if (isInitialized) {
      return;
    }

    console.log('[Favicon] Initializing session favicon...');

    // Get session color
    const hasSession = await getSessionColor();

    if (!hasSession) {
      console.log('[Favicon] No session assigned to this tab, skipping favicon change');
      return;
    }

    isInitialized = true;

    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', applyBadgedFavicon);
    } else {
      // DOM already loaded
      applyBadgedFavicon();
    }

    console.log('[Favicon] ✓ Session favicon initialized');
  }

  // Start initialization with retry logic
  let retryCount = 0;
  const maxRetries = 5;
  const retryDelays = [100, 500, 1000, 2000, 3000];

  async function initWithRetry() {
    // Check if we should stop retrying (e.g., clearSessionFavicon was called)
    if (shouldStopRetrying) {
      console.log('[Favicon] Retry logic stopped (clearSessionFavicon called)');
      return;
    }

    console.log('[Favicon] Init attempt', retryCount + 1, 'of', maxRetries + 1);
    const hasSession = await getSessionColor();

    if (hasSession) {
      console.log('[Favicon] Session found, initializing...');
      initialize();
    } else if (retryCount < maxRetries) {
      console.log('[Favicon] No session yet, retrying in', retryDelays[retryCount], 'ms');
      // Retry after delay
      setTimeout(() => {
        retryCount++;
        initWithRetry();
      }, retryDelays[retryCount]);
    } else {
      console.log('[Favicon] Max retries reached, tab has no session - restoring original site favicon');

      // Remove temporary placeholder and let browser fetch original favicon
      const tempFavicons = document.querySelectorAll('link[data-temporary="true"]');
      tempFavicons.forEach(link => link.remove());

      // Add original site favicon with cache-busting to force fresh fetch
      const originalFavicon = document.createElement('link');
      originalFavicon.rel = 'icon';
      originalFavicon.type = 'image/x-icon';
      originalFavicon.href = '/favicon.ico?' + Date.now(); // Cache-busting
      document.head.appendChild(originalFavicon);

      console.log('[Favicon] ✓ Original site favicon restored for non-session tab');
    }
  }

  /**
   * Remove session favicon and restore original favicon
   */
  function clearSessionFavicon() {
    console.log('[Favicon] Clearing session favicon...');

    // Stop any ongoing retry logic
    shouldStopRetrying = true;

    // Remove our custom favicon
    const sessionFavicons = document.querySelectorAll('link[data-session-favicon="true"]');
    sessionFavicons.forEach(link => {
      console.log('[Favicon] Removing session favicon:', link.href);
      link.remove();
    });

    // Remove temporary placeholders
    const tempFavicons = document.querySelectorAll('link[data-temporary="true"]');
    tempFavicons.forEach(link => link.remove());

    // Force browser to reload the original site favicon by removing ALL favicon links
    // and letting the browser re-fetch the default favicon from the site
    const allFaviconLinks = document.querySelectorAll('link[rel*="icon"]');
    allFaviconLinks.forEach(link => {
      link.remove();
    });

    // Add a cache-busting favicon link to force the browser to fetch the original
    // This prevents browser from using cached session favicon
    const faviconLink = document.createElement('link');
    faviconLink.rel = 'icon';
    faviconLink.type = 'image/x-icon';
    faviconLink.href = '/favicon.ico?' + Date.now(); // Cache-busting query parameter
    document.head.appendChild(faviconLink);

    // Reset state
    sessionColor = null;
    isInitialized = false;

    console.log('[Favicon] ✓ Session favicon cleared (original favicon restored with cache-bust)');
  }

  // Listen for session color changes and clear requests
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'sessionColorChanged' && message.color) {
      console.log('[Favicon] Session color changed to:', message.color);
      sessionColor = message.color;

      // Reapply favicon with new color
      applyBadgedFavicon();

      sendResponse({ success: true });
    } else if (message.action === 'clearSessionFavicon') {
      console.log('[Favicon] Received clear session favicon request');
      clearSessionFavicon();
      sendResponse({ success: true });
    }
  });

  // CRITICAL: Immediately clear ALL favicons on load to prevent browser favicon cache
  // from showing session-colored favicons on non-session tabs
  (function clearAllFaviconsImmediately() {
    console.log('[Favicon] Clearing ALL favicons immediately on load to prevent cache issues...');

    // Remove ALL favicon links (session and original)
    // This forces the browser to re-fetch the favicon after we determine if this is a session tab
    const allFaviconLinks = document.querySelectorAll('link[rel*="icon"]');
    if (allFaviconLinks.length > 0) {
      allFaviconLinks.forEach(link => link.remove());
      console.log(`[Favicon] Removed ${allFaviconLinks.length} favicon link(s) to clear cache`);
    }

    // Add a temporary neutral favicon to prevent browser from using its cache
    // This will be replaced by either:
    // - Session favicon (if session is found)
    // - Original site favicon (if no session)
    const tempFavicon = document.createElement('link');
    tempFavicon.rel = 'icon';
    tempFavicon.type = 'image/x-icon';
    tempFavicon.href = 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; // 1x1 transparent pixel
    tempFavicon.dataset.temporary = 'true';
    document.head.appendChild(tempFavicon);

    console.log('[Favicon] Added temporary placeholder favicon');
  })();

  // Start initialization
  console.log('[Favicon] Starting initialization...');
  initWithRetry();

})();
