/**
 * 8px Grid Overlay Utility (Dev Only)
 * 
 * Action 11.2.1.4: Visual grid overlay tool for development
 * 
 * Usage:
 * - Press Ctrl+G (or Cmd+G on Mac) to toggle the grid overlay
 * - Only works in development mode
 * - Helps visualize 8px grid alignment
 */

let overlayElement: HTMLDivElement | null = null;
let isEnabled = false;

/**
 * Creates the grid overlay element
 */
function createOverlay(): HTMLDivElement {
  const overlay = document.createElement('div');
  overlay.id = 'grid-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 9999;
    background-image: 
      linear-gradient(to right, rgba(102, 252, 241, 0.1) 1px, transparent 1px),
      linear-gradient(to bottom, rgba(102, 252, 241, 0.1) 1px, transparent 1px);
    background-size: 8px 8px;
    opacity: 0.5;
  `;
  return overlay;
}

/**
 * Toggles the grid overlay on/off
 */
function toggleOverlay(): void {
  if (!import.meta.env.DEV) {
    console.warn('[Grid Overlay] Only available in development mode');
    return;
  }

  if (isEnabled) {
    // Disable overlay
    if (overlayElement && overlayElement.parentNode) {
      overlayElement.parentNode.removeChild(overlayElement);
    }
    overlayElement = null;
    isEnabled = false;
    console.log('[Grid Overlay] Disabled');
  } else {
    // Enable overlay
    overlayElement = createOverlay();
    document.body.appendChild(overlayElement);
    isEnabled = true;
    console.log('[Grid Overlay] Enabled - Press Ctrl+G (Cmd+G on Mac) to toggle');
    // #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:'gridOverlay.ts:59',message:'Grid overlay enabled',data:{isEnabled:true},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
    // #endregion
  }
}

/**
 * Initializes the grid overlay utility
 * Sets up keyboard shortcut listener
 */
export function initGridOverlay(): void {
  if (!import.meta.env.DEV) {
    // Don't initialize in production
    return;
  }

  // Listen for keyboard shortcut: Ctrl+G (or Cmd+G on Mac)
  document.addEventListener('keydown', (e) => {
    // Check for Ctrl+G (Windows/Linux) or Cmd+G (Mac)
    if ((e.ctrlKey || e.metaKey) && e.key === 'g') {
      e.preventDefault();
      toggleOverlay();
    }
  });

  console.log('[Grid Overlay] Initialized - Press Ctrl+G (Cmd+G on Mac) to toggle');
}

/**
 * Manually enable the grid overlay (for programmatic use)
 */
export function enableGridOverlay(): void {
  if (!import.meta.env.DEV) {
    console.warn('[Grid Overlay] Only available in development mode');
    return;
  }

  if (!isEnabled) {
    toggleOverlay();
  }
}

/**
 * Manually disable the grid overlay (for programmatic use)
 */
export function disableGridOverlay(): void {
  if (isEnabled) {
    toggleOverlay();
  }
}
