import React from 'react';
import ReactDOM from 'react-dom/client';
import {App as AntdApp} from 'antd';

import App from './App';
import {ThemeProvider} from './providers/ThemeProvider';
import {AppProvider} from './providers/AppProvider';
import {SettingsProvider} from './providers/SettingsProvider';
import CanvasApp from '@/modules/canvas/views/CanvasApp';
// 全局样式（包含 Tailwind 指令 + 主题扩展 + 重置）
import '@/shared/theme/globals.css';

/** 判断当前是否为画布窗口（通过 URL hash 区分） */
const isCanvasMode = window.location.hash.startsWith('#/canvas');

ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
        {isCanvasMode ? (
            // Canvas 模式：轻量级 Provider，无 Auth/Storage/Settings 依赖
            <ThemeProvider>
                <AntdApp>
                    <CanvasApp />
                </AntdApp>
            </ThemeProvider>
        ) : (
            // 正常模式：完整的 AppProvider 链
            <AppProvider>
                <ThemeProvider>
                    <SettingsProvider>
                        <AntdApp>
                            <App />
                        </AntdApp>
                    </SettingsProvider>
                </ThemeProvider>
            </AppProvider>
        )}
    </React.StrictMode>,
);

// 仅在 Electron 环境中监听主进程消息（浏览器预览时跳过）
import { safeIpcOn } from '@/shared/utils/bus';
safeIpcOn('main-process-message', (_event: unknown, message: unknown) => {
    console.log('[Main Process Message]:', message);
});

// 渲染进程全局未捕获错误（兜底记录到日志文件）
import {logger} from '@/shared/utils/bus';

window.addEventListener('error', (event) => {
    logger.error('ui', 'Uncaught error (renderer)', event.error, {
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
    });
});

window.addEventListener('unhandledrejection', (event) => {
    const error =
        event.reason instanceof Error
            ? event.reason
            : new Error(String(event.reason));
    logger.error('ui', 'Unhandled promise rejection (renderer)', error);
});
