// Main entry point for the Restaurant Booking Widget
import { RestaurantBookingWidget } from './RestaurantBookingWidget';
import { defaultConfig } from '@core/config';
import { DOM_IDS } from '@core/constants';
import type { WidgetOptions } from './RestaurantBookingWidget';

// CSS imports - will be processed by Vite
import '@styles/base.css';
import '@styles/components.css';
import '@styles/themes.css';

// Export the main widget class
export { RestaurantBookingWidget };

// Export types for external use
export type { WidgetOptions };
export type { WidgetConfig } from '@core/types';

// Extend Window interface for TypeScript
declare global {
  interface Window {
    RBW_NO_AUTO_INIT?: boolean;
    restaurantBookingWidget?: RestaurantBookingWidget;
  }
  
  interface ImportMeta {
    hot?: {
      accept: (deps: string | string[], callback: (module: any) => void) => void;
    };
  }
}

// Default initialization function
export function init(options: WidgetOptions = {}): RestaurantBookingWidget {
  return new RestaurantBookingWidget(options);
}

// Auto-initialization when DOM is ready
function autoInit(): void {
  // Check if auto-init is disabled
  if (window.RBW_NO_AUTO_INIT) {
    return;
  }

  // Look for existing widget container
  const container = document.getElementById(DOM_IDS.WIDGET_ROOT);
  if (!container) {
    return;
  }

  // Check if widget is already initialized
  if (container.classList.contains('rbw-initialized')) {
    return;
  }

  try {
    // Get configuration from data attributes
    const config = getConfigFromAttributes(container);
    
    // Initialize widget
    const widget = init({
      container,
      config,
      autoInit: true
    });

    // Mark as initialized
    container.classList.add('rbw-initialized');

    // Store widget instance for external access
    (window as any).restaurantBookingWidget = widget;

    console.log('Restaurant Booking Widget initialized automatically');
  } catch (error) {
    console.error('Failed to auto-initialize Restaurant Booking Widget:', error);
  }
}

// Helper function to extract config from data attributes
function getConfigFromAttributes(element: HTMLElement): Partial<import('@core/types').WidgetConfig> {
  const config: any = {};
  
  // Map data attributes to config properties
  const attributeMap = {
    'data-sheet-url': 'googleSheetUrl',
    'data-max-guests': 'maxGuests',
    'data-default-guests': 'defaultGuests',
    'data-timezone': 'timezone',
    'data-waitlist-url': 'waitlistUrl',
    'data-reservation-selector': 'reservationSelector',
    'data-cache-timeout': 'cacheTimeout'
  };

  Object.entries(attributeMap).forEach(([attr, prop]) => {
    const value = element.getAttribute(attr);
    if (value) {
      // Convert numeric values
      if (prop === 'maxGuests' || prop === 'defaultGuests' || prop === 'cacheTimeout') {
        config[prop] = parseInt(value, 10);
      } else {
        config[prop] = value;
      }
    }
  });

  return config;
}

// DOM ready handler
function domReady(fn: () => void): void {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', fn);
  } else {
    fn();
  }
}

// Initialize when DOM is ready
domReady(autoInit);

// Handle hot module replacement in development
if (import.meta.hot) {
  import.meta.hot.accept('./RestaurantBookingWidget', (newModule) => {
    if (newModule) {
      console.log('Hot reloading Restaurant Booking Widget...');
      // Force re-initialization in development
      const existingWidget = (window as any).restaurantBookingWidget;
      if (existingWidget) {
        existingWidget.destroy();
      }
      
      setTimeout(() => {
        autoInit();
      }, 100);
    }
  });
}

// Global error handler for widget-related errors
window.addEventListener('error', (event) => {
  if (event.filename && event.filename.includes('booking-widget')) {
    console.error('Restaurant Booking Widget error:', event.error);
  }
});

// Global unhandled promise rejection handler
window.addEventListener('unhandledrejection', (event) => {
  if (event.reason && event.reason.message && event.reason.message.includes('RBW')) {
    console.error('Restaurant Booking Widget promise rejection:', event.reason);
  }
});

// Expose widget for debugging in development
if (process.env.NODE_ENV === 'development') {
  (window as any).RBW_DEBUG = {
    RestaurantBookingWidget,
    init,
    defaultConfig,
    DOM_IDS
  };
}

// Export default for direct import
export default RestaurantBookingWidget;