/**
 * Accessibility Utilities
 * WCAG 2.1 compliance helpers for the chat widget
 */

/**
 * Announce message to screen readers
 * Uses aria-live region for dynamic content updates
 */
export function announce(message: string, priority: 'polite' | 'assertive' = 'polite') {
  // Find or create the live region
  let liveRegion = document.getElementById('boostbot-live-region');
  
  if (!liveRegion) {
    liveRegion = document.createElement('div');
    liveRegion.id = 'boostbot-live-region';
    liveRegion.setAttribute('role', 'status');
    liveRegion.setAttribute('aria-live', priority);
    liveRegion.setAttribute('aria-atomic', 'true');
    liveRegion.className = 'sr-only'; // Visually hidden
    liveRegion.style.cssText = `
      position: absolute;
      width: 1px;
      height: 1px;
      padding: 0;
      margin: -1px;
      overflow: hidden;
      clip: rect(0, 0, 0, 0);
      white-space: nowrap;
      border: 0;
    `;
    document.body.appendChild(liveRegion);
  }
  
  // Update the aria-live attribute if priority changed
  liveRegion.setAttribute('aria-live', priority);
  
  // Clear and set new message (triggers announcement)
  liveRegion.textContent = '';
  
  // Small delay to ensure screen readers catch the change
  setTimeout(() => {
    liveRegion!.textContent = message;
  }, 100);
}

/**
 * Focus trap for modal dialogs
 * Keeps focus within the container when using Tab/Shift+Tab
 */
export function createFocusTrap(container: HTMLElement) {
  const focusableSelectors = [
    'button:not([disabled])',
    '[href]',
    'input:not([disabled])',
    'select:not([disabled])',
    'textarea:not([disabled])',
    '[tabindex]:not([tabindex="-1"])',
  ].join(', ');
  
  const getFocusableElements = () => {
    return Array.from(container.querySelectorAll(focusableSelectors)) as HTMLElement[];
  };
  
  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key !== 'Tab') return;
    
    const focusableElements = getFocusableElements();
    if (focusableElements.length === 0) return;
    
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
    
    if (e.shiftKey) {
      // Shift+Tab: if on first element, go to last
      if (document.activeElement === firstElement) {
        e.preventDefault();
        lastElement.focus();
      }
    } else {
      // Tab: if on last element, go to first
      if (document.activeElement === lastElement) {
        e.preventDefault();
        firstElement.focus();
      }
    }
  };
  
  // Add listener
  container.addEventListener('keydown', handleKeyDown);
  
  // Focus first element
  const focusableElements = getFocusableElements();
  if (focusableElements.length > 0) {
    focusableElements[0].focus();
  }
  
  // Return cleanup function
  return () => {
    container.removeEventListener('keydown', handleKeyDown);
  };
}

/**
 * Get unique ID for ARIA attributes
 */
let idCounter = 0;
export function generateId(prefix = 'boostbot'): string {
  return `${prefix}-${++idCounter}`;
}

/**
 * Check if user prefers reduced motion
 */
export function prefersReducedMotion(): boolean {
  return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}

/**
 * Get color contrast ratio
 * Useful for ensuring text readability
 */
export function getContrastRatio(color1: string, color2: string): number {
  const getLuminance = (hex: string) => {
    const rgb = parseInt(hex.slice(1), 16);
    const r = ((rgb >> 16) & 0xff) / 255;
    const g = ((rgb >> 8) & 0xff) / 255;
    const b = (rgb & 0xff) / 255;
    
    const [R, G, B] = [r, g, b].map(c => {
      return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
    });
    
    return 0.2126 * R + 0.7152 * G + 0.0722 * B;
  };
  
  const l1 = getLuminance(color1);
  const l2 = getLuminance(color2);
  
  const lighter = Math.max(l1, l2);
  const darker = Math.min(l1, l2);
  
  return (lighter + 0.05) / (darker + 0.05);
}

/**
 * Keyboard event helpers
 */
export const Keys = {
  Enter: 'Enter',
  Space: ' ',
  Escape: 'Escape',
  Tab: 'Tab',
  ArrowUp: 'ArrowUp',
  ArrowDown: 'ArrowDown',
  ArrowLeft: 'ArrowLeft',
  ArrowRight: 'ArrowRight',
  Home: 'Home',
  End: 'End',
} as const;

/**
 * Handle keyboard events for interactive elements
 */
export function handleKeyboardClick(
  e: React.KeyboardEvent,
  onClick: () => void
) {
  if (e.key === Keys.Enter || e.key === Keys.Space) {
    e.preventDefault();
    onClick();
  }
}








