import { NgModule, ModuleWithProviders, inject, APP_INITIALIZER } from '@angular/core';
import { CommonModule } from '@angular/common';

// Services
import { LiveAnnouncerService } from './services/live-announcer';
import { FocusMonitorService } from './services/focus-monitor';
import { KeyboardManagerService } from './services/keyboard-manager';
import { HighContrastService } from './services/high-contrast';
import { A11yConfigService, A11yConfiguration, A11Y_CONFIG } from './services/a11y-config';

// Directives
import { FocusTrapDirective } from './directives/focus-trap';
import { ArrowNavigationDirective } from './directives/arrow-navigation';

// Components
import { SkipLinksComponent } from './components/skip-links';
import { ScreenReaderOnlyComponent } from './components/screen-reader-only';

const DIRECTIVES = [
  FocusTrapDirective,
  ArrowNavigationDirective
];

const COMPONENTS = [
  SkipLinksComponent,
  ScreenReaderOnlyComponent
];

/**
 * Initialize accessibility features based on configuration
 */
export function initializeA11y(
  config: A11yConfigService,
  highContrast: HighContrastService
): () => void {
  return () => {
    // Apply body classes for accessibility preferences
    if (config.isEnabled('accessibility.addBodyClasses')) {
      highContrast.applyPreferencesToBody();
    }

    // Inject accessibility styles
    if (config.isEnabled('accessibility.injectAccessibilityStyles')) {
      highContrast.injectReducedMotionStyles();
    }

    // Log initialization
    config.log('UI Accessibility module initialized', config.getConfig());
  };
}

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    ...DIRECTIVES,
    ...COMPONENTS
  ],
  exports: [
    ...DIRECTIVES,
    ...COMPONENTS
  ]
})
export class UiAccessibilityModule {
  static forRoot(config?: Partial<A11yConfiguration>): ModuleWithProviders<UiAccessibilityModule> {
    return {
      ngModule: UiAccessibilityModule,
      providers: [
        // Core services
        LiveAnnouncerService,
        FocusMonitorService,
        KeyboardManagerService,
        HighContrastService,
        A11yConfigService,
        
        // Configuration
        {
          provide: A11Y_CONFIG,
          useValue: config || {}
        },
        
        // Initialize accessibility features
        {
          provide: APP_INITIALIZER,
          useFactory: initializeA11y,
          deps: [A11yConfigService, HighContrastService],
          multi: true
        }
      ]
    };
  }

  static forChild(): ModuleWithProviders<UiAccessibilityModule> {
    return {
      ngModule: UiAccessibilityModule,
      providers: []
    };
  }

  constructor() {
    // Module loaded
    if (typeof console !== 'undefined') {
      console.log('🔍 UI Accessibility module loaded');
    }
  }
}