/**
 * JTZL_WebIRC_Chat - React Entry Point
 *
 * @package   JTZL_WebIRC_Chat
 * @copyright Copyright (c) 2025, JT. G.
 * @license   GPL-3.0+
 * @since     3.0.0
 */

import { createRoot } from 'react-dom/client';
import { IRCChat } from './components/chat/IRCChat';
import { ThemeProvider } from './components/providers/ThemeProvider';
import { readConfig } from './config';
import { initializeTheme } from './lib/theme-script';
import { performanceMonitor, BundleSizeAnalyzer } from './lib/performance';
import type { Config } from './types';

/**
 * Initialize the React-based WebIRC Chat interface.
 *
 * @since 3.0.0
 */
function initWebIRCChat(): void {
	// Start performance monitoring
	performanceMonitor.markStart();

	const root = document.querySelector('.chat-webirc') as HTMLElement | null;
	if (!root) {
		// eslint-disable-next-line no-console
		console.warn('WebIRC Chat: No .chat-webirc element found');
		return;
	}

	// Initialize theme to prevent FOUC
	initializeTheme();

	// Get configuration from WordPress localized script and data attributes
	const config: Config = readConfig(root);

	// Mark load end
	performanceMonitor.markLoadEnd();

	// Create React root and render the IRC chat component with theme provider
	const reactRoot = createRoot(root);
	reactRoot.render(
		<ThemeProvider
			defaultTheme={config.ui?.defaultTheme || 'light'}
			storageKey="webirc-ui-theme"
		>
			<IRCChat config={config} />
		</ThemeProvider>
	);

	// Mark render end and log metrics
	setTimeout(() => {
		performanceMonitor.markRenderEnd();
		performanceMonitor.measureMemoryUsage();
		performanceMonitor.logMetrics();
		BundleSizeAnalyzer.logBundleSize();
	}, 100);
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
	document.addEventListener('DOMContentLoaded', initWebIRCChat);
} else {
	initWebIRCChat();
}
