/**
 * Utility to fix display issues in development
 * - Removes grid overlay if accidentally enabled
 * - Clears offline queue if needed
 * 
 * NOTE: Les fixes pour "lignes verticales" ont été supprimés car le problème réel
 * était le style de focus des inputs, maintenant corrigé dans les composants Input.
 * Ce fichier est conservé pour les outils de diagnostic uniquement.
 */

export function fixDisplayIssues(): void {
  if (typeof window === 'undefined') return;

  // #region agent log
  const logData = { location: 'fixDisplayIssues.ts:8', message: 'fixDisplayIssues called', data: { readyState: document.readyState }, timestamp: Date.now(), sessionId: 'debug-session', runId: 'run1', hypothesisId: 'D' };
  console.log('[DEBUG]', logData);
  // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(logData)}).catch((e)=>console.error('[DEBUG] Log fetch failed:',e));
  // #endregion

  // FIX: Supprimer complètement la scrollbar visible en dev si elle cause des problèmes
  // Ajouter un style global pour masquer ou réduire la scrollbar
  const scrollbarFixId = 'fix-scrollbar-visibility';
  let scrollbarFix = document.getElementById(scrollbarFixId) as HTMLStyleElement | null;

  if (!scrollbarFix) {
    scrollbarFix = document.createElement('style');
    scrollbarFix.id = scrollbarFixId;
    scrollbarFix.textContent = `
      /* FIX: Réduire la visibilité de la scrollbar pour éviter les distractions visuelles */
      ::-webkit-scrollbar {
        width: 4px !important;
        height: 4px !important;
      }
      ::-webkit-scrollbar-track {
        background: transparent !important;
      }
      ::-webkit-scrollbar-thumb {
        background: rgba(0, 255, 247, 0.1) !important;
        border-radius: 2px !important;
      }
      ::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 255, 247, 0.2) !important;
      }
      /* Firefox */
      * {
        scrollbar-width: thin !important;
        scrollbar-color: rgba(0, 255, 247, 0.1) transparent !important;
      }
    `;
    // Ajouter le fix au début du head pour priorité maximale
    document.head.insertBefore(scrollbarFix, document.head.firstChild);
  }

  // FIX: Add a "clean mode" that disables ALL visual effects
  if (import.meta.env.DEV) {
    (window as any).__enableCleanMode = () => {
      console.log('[FixDisplay] Enabling CLEAN MODE - disabling all visual effects');
      const cleanStyle = document.createElement('style');
      cleanStyle.id = 'fix-display-clean-mode';
      cleanStyle.textContent = `
        /* CLEAN MODE: Disable all visual effects */
        body::before,
        body::after {
          display: none !important;
        }
        *::before,
        *::after {
          display: none !important;
        }
        /* Remove all borders */
        * {
          border-left: none !important;
          border-right: none !important;
        }
        /* Keep only essential borders for inputs */
        input, textarea, select {
          border: 1px solid rgba(255, 255, 255, 0.2) !important;
        }
      `;
      document.head.appendChild(cleanStyle);
      console.log('[FixDisplay] Clean mode enabled. All visual effects disabled.');
    };

    (window as any).__disableCleanMode = () => {
      const cleanStyle = document.getElementById('fix-display-clean-mode');
      if (cleanStyle) {
        cleanStyle.remove();
        console.log('[FixDisplay] Clean mode disabled.');
      }
    };

    // FIX: Add visual inspection helper to identify the source of vertical line
    // This will help us find the exact element causing the issue
    // Helper to find and highlight all suspicious vertical elements
    (window as any).__findVerticalLines = () => {
      console.log('[FixDisplay] Scanning for vertical lines...');
      const allElements = document.querySelectorAll('*');
      const suspicious: Array<{ element: HTMLElement, reason: string, styles: any }> = [];

      allElements.forEach((el) => {
        const htmlEl = el as HTMLElement;
        const computed = window.getComputedStyle(htmlEl);
        const rect = htmlEl.getBoundingClientRect();

        // Check for narrow vertical elements
        if (rect.width > 0 && rect.width < 10 && rect.height > window.innerHeight * 0.3) {
          suspicious.push({
            element: htmlEl,
            reason: `Narrow vertical element: ${rect.width}px x ${rect.height}px`,
            styles: {
              position: computed.position,
              zIndex: computed.zIndex,
              borderLeft: computed.borderLeftWidth,
              borderRight: computed.borderRightWidth,
              background: computed.background,
              backgroundImage: computed.backgroundImage?.substring(0, 100),
            }
          });
        }

        // Check for vertical borders
        const borderLeft = parseInt(computed.borderLeftWidth);
        const borderRight = parseInt(computed.borderRightWidth);
        if ((borderLeft > 0 || borderRight > 0) && rect.height > window.innerHeight * 0.5) {
          suspicious.push({
            element: htmlEl,
            reason: `Vertical border: left=${borderLeft}px, right=${borderRight}px`,
            styles: {
              position: computed.position,
              zIndex: computed.zIndex,
              width: rect.width,
              height: rect.height,
            }
          });
        }
      });

      console.log(`[FixDisplay] Found ${suspicious.length} suspicious elements:`, suspicious);
      suspicious.forEach((s, i) => {
        s.element.style.outline = `3px solid ${i % 2 === 0 ? 'red' : 'yellow'}`;
        s.element.style.outlineOffset = '2px';
        console.log(`[FixDisplay] ${i + 1}. ${s.reason}`, s.styles);
      });

      return suspicious;
    };

    (window as any).__inspectVerticalLine = () => {
      console.log('[FixDisplay] Inspecting all elements for vertical line source...');
      const allElements = document.querySelectorAll('*');
      const candidates: Array<{
        element: HTMLElement;
        tag: string;
        id: string;
        className: string;
        rect: DOMRect;
        styles: {
          position: string;
          zIndex: string;
          background: string;
          backgroundImage: string;
          borderLeft: string;
          borderRight: string;
          left: string;
          width: string;
        };
      }> = [];

      allElements.forEach((el) => {
        const htmlEl = el as HTMLElement;
        const computed = window.getComputedStyle(htmlEl);
        const rect = htmlEl.getBoundingClientRect();

        // Look for elements that could create a vertical line:
        // 1. Fixed/absolute positioned elements
        // 2. Elements with narrow width (< 20px) and full height
        // 3. Elements with vertical borders
        // 4. Elements with vertical gradients
        const isFixedOrAbsolute = computed.position === 'fixed' || computed.position === 'absolute';
        const isNarrowAndTall = rect.width < 20 && rect.width > 0 && rect.height > window.innerHeight * 0.5;
        const hasVerticalBorder = parseInt(computed.borderLeftWidth) > 0 || parseInt(computed.borderRightWidth) > 0;
        const hasVerticalGradient = (computed.backgroundImage || '').includes('90deg');
        const isCentered = Math.abs(rect.left + rect.width / 2 - window.innerWidth / 2) < 50;

        if ((isFixedOrAbsolute || isNarrowAndTall) && (hasVerticalBorder || hasVerticalGradient || isCentered)) {
          candidates.push({
            element: htmlEl,
            tag: el.tagName,
            id: el.id || '',
            className: el.className?.toString().substring(0, 100) || '',
            rect,
            styles: {
              position: computed.position,
              zIndex: computed.zIndex,
              background: computed.background.substring(0, 100),
              backgroundImage: computed.backgroundImage.substring(0, 100),
              borderLeft: computed.borderLeft,
              borderRight: computed.borderRight,
              left: computed.left,
              width: computed.width,
            },
          });
        }
      });

      // Sort by z-index (highest first) and log top candidates
      candidates.sort((a, b) => parseInt(a.styles.zIndex) - parseInt(b.styles.zIndex));
      console.log(`[FixDisplay] Found ${candidates.length} potential sources of vertical line:`, candidates.slice(0, 10));

      // Highlight top 5 candidates
      candidates.slice(0, 5).forEach((candidate, i) => {
        candidate.element.style.outline = `3px solid ${['red', 'orange', 'yellow', 'green', 'blue'][i]}`;
        candidate.element.style.outlineOffset = '2px';
        console.log(`[FixDisplay] Candidate ${i + 1} (${['red', 'orange', 'yellow', 'green', 'blue'][i]} outline):`, {
          tag: candidate.tag,
          id: candidate.id,
          className: candidate.className,
          position: candidate.styles.position,
          zIndex: candidate.styles.zIndex,
          rect: { left: candidate.rect.left, top: candidate.rect.top, width: candidate.rect.width, height: candidate.rect.height },
          styles: candidate.styles,
        });
      });

      return candidates;
    };
    console.log('[FixDisplay] Visual inspection helper available. Run __inspectVerticalLine() in console to find the source.');
  }

  // 1. Remove grid overlay if present
  const gridOverlay = document.getElementById('grid-overlay');
  // #region agent log
  // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:12',message:'Grid overlay check',data:{found:!!gridOverlay,exists:gridOverlay!==null},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
  // #endregion
  if (gridOverlay) {
    gridOverlay.remove();
    console.log('[FixDisplay] Grid overlay removed');
    // #region agent log
    // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:16',message:'Grid overlay removed',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
    // #endregion
  }

  // 1.5. Force remove repeating-linear-gradient from body::before (CSS cache issue)
  // HYPOTHESIS A: CSS gradient still present due to browser cache
  // HYPOTHESIS B: Another CSS file loads after and reapplies gradient
  // HYPOTHESIS C: body::after has a gradient that creates vertical line
  // HYPOTHESIS D: An element DOM with inline style creates the line
  if (typeof document !== 'undefined' && document.head) {
    const styleId = 'fix-display-override';
    let overrideStyle = document.getElementById(styleId) as HTMLStyleElement | null;
    // #region agent log
    // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:checkOverride',message:'Checking CSS override',data:{overrideExists:!!overrideStyle,headExists:!!document.head},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
    // #endregion

    // Check computed style of body::before to see if gradient is still present
    try {
      const bodyBefore = window.getComputedStyle(document.body, '::before');
      const bgImage = bodyBefore.backgroundImage || bodyBefore.background || '';
      const bg = bodyBefore.background || '';
      // #region agent log
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:checkBodyBefore',message:'Checking body::before computed style',data:{backgroundImage:bgImage.substring(0,150),background:bg.substring(0,150),hasGradient:bgImage.includes('repeating-linear-gradient')||bgImage.includes('linear-gradient')||bg.includes('repeating-linear-gradient')||bg.includes('linear-gradient'),display:bodyBefore.display,opacity:bodyBefore.opacity},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
      // #endregion
    } catch (e) {
      // #region agent log
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:checkBodyBeforeError',message:'Error checking body::before',data:{error:String(e)},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
      // #endregion
    }

    // Check body::after for vertical gradient (HYPOTHESIS C)
    try {
      const bodyAfter = window.getComputedStyle(document.body, '::after');
      const bgImageAfter = bodyAfter.backgroundImage || bodyAfter.background || '';
      // #region agent log
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:checkBodyAfter',message:'Checking body::after computed style',data:{backgroundImage:bgImageAfter.substring(0,150),hasGradient:bgImageAfter.includes('repeating-linear-gradient')||bgImageAfter.includes('linear-gradient'),display:bodyAfter.display,opacity:bodyAfter.opacity,zIndex:bodyAfter.zIndex},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
      // #endregion
    } catch (e) {
      // #region agent log
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:checkBodyAfterError',message:'Error checking body::after',data:{error:String(e)},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
      // #endregion
    }

    // Check for DOM elements with inline styles or computed styles that could create vertical line (HYPOTHESIS D, E)
    try {
      const allElements = document.querySelectorAll('*');
      const elementsWithVerticalGradients: Array<{ tag: string, id: string, className: string, computedBg: string, inlineStyle: string }> = [];
      allElements.forEach((el) => {
        const htmlEl = el as HTMLElement;
        const inlineStyle = htmlEl.style.cssText || '';
        const computedStyle = window.getComputedStyle(htmlEl);
        const computedBg = computedStyle.backgroundImage || computedStyle.background || '';

        // Check for vertical gradients (90deg) in both inline styles and computed styles
        const hasVerticalGradient =
          (inlineStyle.includes('90deg') && (inlineStyle.includes('linear-gradient') || inlineStyle.includes('repeating-linear-gradient'))) ||
          (computedBg.includes('90deg') && (computedBg.includes('linear-gradient') || computedBg.includes('repeating-linear-gradient')));

        if (hasVerticalGradient) {
          elementsWithVerticalGradients.push({
            tag: el.tagName,
            id: el.id || '',
            className: el.className?.toString().substring(0, 50) || '',
            computedBg: computedBg.substring(0, 150),
            inlineStyle: inlineStyle.substring(0, 100)
          });
        }
      });
      if (elementsWithVerticalGradients.length > 0) {
        // #region agent log
        const logData = { location: 'fixDisplayIssues.ts:checkVerticalGradients', message: 'Found elements with vertical gradients', data: { count: elementsWithVerticalGradients.length, elements: elementsWithVerticalGradients.slice(0, 10) }, timestamp: Date.now(), sessionId: 'debug-session', runId: 'run1', hypothesisId: 'D' };
        console.log('[DEBUG] Vertical gradients found:', logData);
        // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(logData)}).catch((e)=>console.error('[DEBUG] Log fetch failed:',e));
        // #endregion

        // FIX: Remove vertical gradients from found elements
        elementsWithVerticalGradients.forEach(({ tag, id, className }) => {
          const element = id ? document.getElementById(id) :
            className ? document.querySelector(`.${className.split(' ')[0]}`) : null;
          if (element) {
            const htmlEl = element as HTMLElement;
            const currentBg = htmlEl.style.backgroundImage || '';
            if (currentBg.includes('90deg')) {
              // Remove vertical gradient, keep only horizontal
              const newBg = currentBg.replace(/linear-gradient\(90deg[^)]+\)/g, '').replace(/,\s*,/g, ',').replace(/^,\s*|,\s*$/g, '');
              htmlEl.style.backgroundImage = newBg || 'none';
              console.log(`[FixDisplay] Removed vertical gradient from ${tag}${id ? `#${  id}` : ''}${className ? `.${  className.split(' ')[0]}` : ''}`);
            }
          }
        });
      }
    } catch (e) {
      // #region agent log
      const logData = { location: 'fixDisplayIssues.ts:checkVerticalGradientsError', message: 'Error checking vertical gradients', data: { error: String(e) }, timestamp: Date.now(), sessionId: 'debug-session', runId: 'run1', hypothesisId: 'D' };
      console.error('[DEBUG]', logData);
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(logData)}).catch(()=>{});
      // #endregion
    }

    // Always recreate the override to ensure it's applied (in case CSS loads after)
    if (overrideStyle) {
      overrideStyle.remove();
    }
    overrideStyle = document.createElement('style');
    overrideStyle.id = styleId;
    // FIX: Aggressively remove ALL gradients from body::before and body::after
    // This ensures no vertical lines appear even if CSS is cached or loads after
    // Remove any repeating-linear-gradient with 90deg (vertical) from body::before
    overrideStyle.textContent = `
      /* FIX: Aggressively remove ALL vertical lines and gradients */
      body::before {
        background: url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E") !important;
        background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E") !important;
        border-left: none !important;
        border-right: none !important;
        left: 0 !important;
        right: 0 !important;
        width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
      }
      body::after {
        display: none !important;
        border-left: none !important;
        border-right: none !important;
      }
      /* FIX: Remove any element on the right edge that could create a line */
      body > *:last-child {
        border-right: none !important;
      }
      html {
        border-right: none !important;
        overflow-x: hidden !important;
      }
      /* FIX: Hide .btn-premium::before shine effect that uses 90deg gradient */
      .btn-premium::before {
        display: none !important;
      }
      /* FIX: Remove ALL vertical gradients (90deg) from ALL elements and pseudo-elements */
      *,
      *::before,
      *::after {
        background-image: var(--bg-image-fixed, none) !important;
      }
      /* FIX: Remove vertical borders that could create lines */
      *[style*="border-left"],
      *[style*="border-right"] {
        border-left: none !important;
        border-right: none !important;
      }
      /* FIX: Hide any element that is very narrow and full height (likely a vertical line) */
      *[style*="width: 1px"],
      *[style*="width: 2px"],
      *[style*="width: 3px"],
      *[style*="width: 4px"] {
        display: none !important;
      }
    `;

    // FIX: Add a global style that filters out vertical gradients using CSS custom properties
    // We'll use JavaScript to process and remove 90deg gradients from computed styles
    const processBackgroundImage = (bgImage: string): string => {
      if (!bgImage || bgImage === 'none') return 'none';
      // Remove all linear-gradient and repeating-linear-gradient with 90deg
      let processed = bgImage;
      // Remove linear-gradient(90deg ...)
      processed = processed.replace(/linear-gradient\(90deg[^)]+\)/g, '');
      // Remove repeating-linear-gradient(90deg ...)
      processed = processed.replace(/repeating-linear-gradient\(90deg[^)]+\)/g, '');
      // Clean up commas
      processed = processed.replace(/,\s*,/g, ',').replace(/^,\s*|,\s*$/g, '');
      return processed || 'none';
    };

    // Apply fix to all existing elements
    const fixAllElements = () => {
      const allElements = document.querySelectorAll('*');
      let fixedCount = 0;
      allElements.forEach((el) => {
        const htmlEl = el as HTMLElement;
        const computed = window.getComputedStyle(htmlEl);
        const bgImage = computed.backgroundImage || '';
        const inlineBg = htmlEl.style.backgroundImage || '';
        const rect = htmlEl.getBoundingClientRect();

        // FIX: Remove elements that are very narrow and full height (vertical lines)
        // Also check if element is on the right edge of the screen
        const isOnRightEdge = rect.right >= window.innerWidth - 5 && rect.right <= window.innerWidth + 5;
        if (((computed.position === 'fixed' || computed.position === 'absolute') &&
          rect.width > 0 && rect.width < 5 &&
          rect.height > window.innerHeight * 0.5) ||
          (isOnRightEdge && rect.width < 10 && rect.height > window.innerHeight * 0.3)) {
          htmlEl.style.setProperty('display', 'none', 'important');
          fixedCount++;
          console.log(`[FixDisplay] Hidden narrow vertical element: ${el.tagName}${el.id ? `#${  el.id}` : ''} (${rect.width}px x ${rect.height}px, right: ${rect.right}px)`);
        }

        // FIX: Remove vertical borders that could create lines
        const borderLeft = computed.borderLeftWidth;
        const borderRight = computed.borderRightWidth;
        if (parseInt(borderLeft) > 0 && rect.width < 10 && rect.height > window.innerHeight * 0.5) {
          htmlEl.style.setProperty('border-left', 'none', 'important');
          fixedCount++;
        }
        if (parseInt(borderRight) > 0 && rect.width < 10 && rect.height > window.innerHeight * 0.5) {
          htmlEl.style.setProperty('border-right', 'none', 'important');
          fixedCount++;
        }

        // Check both computed and inline styles for vertical gradients
        if ((bgImage.includes('90deg') || inlineBg.includes('90deg')) &&
          (bgImage.includes('linear-gradient') || inlineBg.includes('linear-gradient') ||
            bgImage.includes('repeating-linear-gradient') || inlineBg.includes('repeating-linear-gradient'))) {
          const processed = processBackgroundImage(bgImage || inlineBg);
          htmlEl.style.setProperty('background-image', processed, 'important');
          fixedCount++;
        }

        // Also check pseudo-elements by trying to access them
        try {
          const beforeStyle = window.getComputedStyle(htmlEl, '::before');
          const afterStyle = window.getComputedStyle(htmlEl, '::after');
          if (beforeStyle.backgroundImage && beforeStyle.backgroundImage.includes('90deg')) {
            // We can't directly modify pseudo-elements, but we can add a class to hide them
            htmlEl.classList.add('fix-display-no-vertical-gradient');
          }
          if (afterStyle.backgroundImage && afterStyle.backgroundImage.includes('90deg')) {
            htmlEl.classList.add('fix-display-no-vertical-gradient');
          }
        } catch (e) {
          // Ignore errors accessing pseudo-elements
        }
      });
      if (fixedCount > 0) {
        console.log(`[FixDisplay] Fixed ${fixedCount} elements with vertical lines/gradients`);
      }
    };

    // Add CSS rule to hide elements with problematic pseudo-elements and narrow vertical elements
    const hideRuleId = 'fix-display-hide-pseudo';
    let hideRule = document.getElementById(hideRuleId) as HTMLStyleElement | null;
    if (!hideRule) {
      hideRule = document.createElement('style');
      hideRule.id = hideRuleId;
      hideRule.textContent = `
        .fix-display-no-vertical-gradient::before,
        .fix-display-no-vertical-gradient::after {
          display: none !important;
        }
        /* FIX: Hide any narrow vertical elements that could be lines */
        *[style*="width: 1px"]:not(script):not(style),
        *[style*="width: 2px"]:not(script):not(style),
        *[style*="width: 3px"]:not(script):not(style),
        *[style*="width: 4px"]:not(script):not(style),
        *[style*="width: 5px"]:not(script):not(style) {
          display: none !important;
        }
        /* FIX: Remove vertical borders from all elements EXCEPT form inputs */
        *:not(input):not(textarea):not(select):not(button):not([class*="input"]):not([class*="Input"]) {
          border-left: none !important;
          border-right: none !important;
        }
        /* FIX: Remove vertical borders from pseudo-elements */
        *::before,
        *::after {
          border-left: none !important;
          border-right: none !important;
        }
        /* FIX: Ensure body and html don't have right borders */
        body, html {
          border-right: none !important;
          margin-right: 0 !important;
          padding-right: 0 !important;
          overflow-x: hidden !important;
        }
        /* FIX: Hide any element positioned on the right edge with narrow width */
        * {
          box-sizing: border-box !important;
        }
      `;
      document.head.appendChild(hideRule);
    }

    // Run immediately and after delays
    fixAllElements();
    setTimeout(fixAllElements, 100);
    setTimeout(fixAllElements, 500);
    setTimeout(fixAllElements, 1000);
    // Insert at the beginning of head to ensure highest priority
    document.head.insertBefore(overrideStyle, document.head.firstChild);
    // #region agent log
    const logDataOverride = { location: 'fixDisplayIssues.ts:overrideStyle', message: 'Added CSS override to remove gradient', data: { styleId, textContentLength: overrideStyle.textContent.length, appended: !!overrideStyle.parentNode }, timestamp: Date.now(), sessionId: 'debug-session', runId: 'run1', hypothesisId: 'A' };
    console.log('[DEBUG]', logDataOverride);
    // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(logDataOverride)}).catch((e)=>console.error('[DEBUG] Log fetch failed:',e));
    // #endregion
  }

  // 2. Check offline queue status
  if (typeof localStorage !== 'undefined') {
    try {
      const queue = localStorage.getItem('veza_offline_queue');
      if (queue) {
        const parsed = JSON.parse(queue);
        if (parsed && Array.isArray(parsed) && parsed.length > 0) {
          console.log(`[FixDisplay] Offline queue has ${parsed.length} requests`);
          // Optionally clear the queue if it's stale (older than 5 minutes)
          const now = Date.now();
          const staleRequests = parsed.filter((req: any) => {
            if (!req.timestamp) return true;
            return now - req.timestamp > 5 * 60 * 1000; // 5 minutes
          });
          if (staleRequests.length > 0) {
            console.log(`[FixDisplay] Found ${staleRequests.length} stale requests`);
          }
        }
      }
    } catch (e) {
      console.error('[FixDisplay] Error checking offline queue:', e);
    }
  }
}

// Auto-fix on import in development
if (import.meta.env.DEV) {
  if (typeof window !== 'undefined') {
    // Function to apply fix with delay to ensure CSS is loaded
    const applyFixWithDelay = () => {
      // Run immediately
      fixDisplayIssues();
      // Also run after a short delay to catch any CSS that loads asynchronously
      setTimeout(() => {
        fixDisplayIssues();
        console.log('[FixDisplay] Applied CSS override (delayed)');
      }, 100);
      // Run again after stylesheets are loaded
      setTimeout(() => {
        fixDisplayIssues();
        console.log('[FixDisplay] Applied CSS override (after stylesheets)');
      }, 500);
    };

    // Run after DOM is ready
    if (document.readyState === 'loading') {
      // #region agent log
      const logData = { location: 'fixDisplayIssues.ts:DOM loading', message: 'DOM loading, adding listener', data: { readyState: document.readyState }, timestamp: Date.now(), sessionId: 'debug-session', runId: 'run1', hypothesisId: 'D' };
      console.log('[DEBUG]', logData);
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(logData)}).catch((e)=>console.error('[DEBUG] Log fetch failed:',e));
      // #endregion
      document.addEventListener('DOMContentLoaded', applyFixWithDelay);
    } else {
      // #region agent log
      const logData = { location: 'fixDisplayIssues.ts:DOM ready', message: 'DOM ready, calling immediately', data: { readyState: document.readyState }, timestamp: Date.now(), sessionId: 'debug-session', runId: 'run1', hypothesisId: 'D' };
      console.log('[DEBUG]', logData);
      // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(logData)}).catch((e)=>console.error('[DEBUG] Log fetch failed:',e));
      // #endregion
      applyFixWithDelay();
    }

    // FIX: Use MutationObserver to detect and fix new elements with vertical gradients as they're added
    const removeVerticalGradients = (element: HTMLElement) => {
      const computed = window.getComputedStyle(element);
      const bgImage = computed.backgroundImage || '';
      const inlineBg = element.style.backgroundImage || '';

      if ((bgImage.includes('90deg') || inlineBg.includes('90deg')) &&
        (bgImage.includes('linear-gradient') || inlineBg.includes('linear-gradient') ||
          bgImage.includes('repeating-linear-gradient') || inlineBg.includes('repeating-linear-gradient'))) {
        // Remove vertical gradient
        if (inlineBg.includes('90deg')) {
          const newBg = inlineBg.replace(/linear-gradient\(90deg[^)]+\)/g, '').replace(/repeating-linear-gradient\(90deg[^)]+\)/g, '').replace(/,\s*,/g, ',').replace(/^,\s*|,\s*$/g, '');
          element.style.backgroundImage = newBg || 'none';
        }
        // Force remove via inline style
        element.style.setProperty('background-image', element.style.backgroundImage?.replace(/linear-gradient\(90deg[^)]+\)/g, '').replace(/repeating-linear-gradient\(90deg[^)]+\)/g, '') || 'none', 'important');
        console.log(`[FixDisplay] Removed vertical gradient from newly added element: ${element.tagName}${element.id ? `#${  element.id}` : ''}`);
      }
    };

    // Observe DOM changes and fix new elements
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            const element = node as HTMLElement;
            removeVerticalGradients(element);
            // Also check children
            element.querySelectorAll('*').forEach((child) => {
              removeVerticalGradients(child as HTMLElement);
            });
          }
        });
      });
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['style', 'class'],
    });

    // Also check periodically in case overlay is added later or CSS is reloaded
    setInterval(() => {
      const overlay = document.getElementById('grid-overlay');
      if (overlay) {
        // #region agent log
        // fetch('http://127.0.0.1:7242/ingest/09c5ea5e-2380-4cc3-92aa-d26f3b3d26f6',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'fixDisplayIssues.ts:interval',message:'Grid overlay found in interval check',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
        // #endregion
        overlay.remove();
      }
      // Reapply CSS fix periodically to ensure it's not overridden
      const overrideStyle = document.getElementById('fix-display-override');
      if (!overrideStyle || !overrideStyle.parentNode) {
        fixDisplayIssues();
      }

      // FIX: Periodically scan and remove all vertical gradients from all elements
      // Also check for other sources of vertical lines (borders, pseudo-elements, etc.)
      try {
        const allElements = document.querySelectorAll('*');
        let fixedCount = 0;
        const suspiciousElements: Array<{ tag: string, id: string, className: string, reason: string }> = [];

        allElements.forEach((el) => {
          const htmlEl = el as HTMLElement;
          const computedStyle = window.getComputedStyle(htmlEl);
          const bgImage = computedStyle.backgroundImage || '';
          const inlineBg = htmlEl.style.backgroundImage || '';
          const position = computedStyle.position;
          const zIndex = parseInt(computedStyle.zIndex) || 0;
          const rect = htmlEl.getBoundingClientRect();

          // Check for vertical gradients (90deg) in computed or inline styles
          if ((bgImage.includes('90deg') || inlineBg.includes('90deg')) &&
            (bgImage.includes('linear-gradient') || inlineBg.includes('linear-gradient') ||
              bgImage.includes('repeating-linear-gradient') || inlineBg.includes('repeating-linear-gradient'))) {
            // AGGRESSIVE FIX: Remove vertical gradient from both inline and force via CSS
            if (inlineBg.includes('90deg')) {
              const newBg = inlineBg.replace(/linear-gradient\(90deg[^)]+\)/g, '').replace(/repeating-linear-gradient\(90deg[^)]+\)/g, '').replace(/,\s*,/g, ',').replace(/^,\s*|,\s*$/g, '');
              htmlEl.style.backgroundImage = newBg || 'none';
              // Also set a data attribute to mark it for CSS override
              htmlEl.setAttribute('data-vertical-gradient-removed', 'true');
            }
            // Force remove via inline style override
            htmlEl.style.setProperty('background-image', htmlEl.style.backgroundImage?.replace(/linear-gradient\(90deg[^)]+\)/g, '').replace(/repeating-linear-gradient\(90deg[^)]+\)/g, '') || 'none', 'important');
            fixedCount++;
            suspiciousElements.push({
              tag: el.tagName,
              id: el.id || '',
              className: el.className?.toString().substring(0, 50) || '',
              reason: 'vertical-gradient-90deg'
            });
            console.log(`[FixDisplay] Removed vertical gradient from ${el.tagName}${el.id ? `#${  el.id}` : ''}${el.className ? `.${  el.className.toString().split(' ')[0]}` : ''} (z-index: ${zIndex})`);
          }

          // Check for suspicious elements that could create vertical lines
          // Elements that are fixed/absolute, cover full height, and have narrow width
          if ((position === 'fixed' || position === 'absolute') &&
            rect.height > window.innerHeight * 0.8 &&
            rect.width < 10 && rect.width > 0) {
            const borderLeft = computedStyle.borderLeftWidth;
            const borderRight = computedStyle.borderRightWidth;
            if (parseInt(borderLeft) > 0 || parseInt(borderRight) > 0) {
              suspiciousElements.push({
                tag: el.tagName,
                id: el.id || '',
                className: el.className?.toString().substring(0, 50) || '',
                reason: `narrow-vertical-element (${rect.width}px wide, ${rect.height}px tall, border: ${borderLeft}/${borderRight})`
              });
            }
          }

          // Check pseudo-elements for vertical gradients
          try {
            const beforeStyle = window.getComputedStyle(htmlEl, '::before');
            const afterStyle = window.getComputedStyle(htmlEl, '::after');
            const beforeBg = beforeStyle.backgroundImage || '';
            const afterBg = afterStyle.backgroundImage || '';

            if (beforeBg.includes('90deg') && (beforeBg.includes('linear-gradient') || beforeBg.includes('repeating-linear-gradient'))) {
              suspiciousElements.push({
                tag: `${el.tagName  }::before`,
                id: el.id || '',
                className: el.className?.toString().substring(0, 50) || '',
                reason: 'vertical-gradient-in-before'
              });
            }
            if (afterBg.includes('90deg') && (afterBg.includes('linear-gradient') || afterBg.includes('repeating-linear-gradient'))) {
              suspiciousElements.push({
                tag: `${el.tagName  }::after`,
                id: el.id || '',
                className: el.className?.toString().substring(0, 50) || '',
                reason: 'vertical-gradient-in-after'
              });
            }
          } catch (e) {
            // Ignore errors accessing pseudo-elements
          }
        });

        if (suspiciousElements.length > 0) {
          console.log(`[FixDisplay] Found ${suspiciousElements.length} suspicious elements:`, suspiciousElements.slice(0, 10));
        }
        if (fixedCount > 0) {
          console.log(`[FixDisplay] Fixed ${fixedCount} elements with vertical gradients`);
        }
      } catch (e) {
        console.error('[FixDisplay] Error scanning for vertical gradients:', e);
      }
    }, 1000);
  }
}
