import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { invoke } from '@tauri-apps/api/core';
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
import App from './App';
import './styles/variables.css';
import './styles/global.css';
import { loadAppConfig } from './api/modules/config';

async function bootstrap() {
  // 加载运行模式配置
  let appEnvironment = 'production';
  try {
    const config = await loadAppConfig();
    appEnvironment = config.environment;
  } catch {
    // 加载失败时默认为生产模式
  }
  (window as unknown as Record<string, unknown>).__APP_ENV__ = appEnvironment;

  // 右键菜单：生产模式受限，调试模式开放
  // 生产模式：非输入框/文本区且未按 Shift 时阻止默认右键（不支持刷新）
  // 调试模式：不拦截，WebView 默认右键菜单可用（含刷新/检查元素）
  document.addEventListener('contextmenu', (e) => {
    const env = (window as unknown as Record<string, unknown>).__APP_ENV__ as string;
    if (env === 'production') {
      const target = e.target as HTMLElement;
      const tag = target.tagName.toLowerCase();
      const isInput = tag === 'input' || tag === 'textarea' || target.isContentEditable;
      if (!isInput && !e.shiftKey) {
        e.preventDefault();
      }
    }
    // 调试模式：不拦截，放行默认右键菜单
  });

  // 全局快捷键：仅 F12 打开 DevTools
  // 生产模式禁用，调试模式开放（macOS 需 Fn+F12）
  document.addEventListener('keydown', (e) => {
    if (e.key === 'F12') {
      const env = (window as unknown as Record<string, unknown>).__APP_ENV__ as string;
      if (env === 'production') {
        e.preventDefault();
        return;
      }
      e.preventDefault();
      invoke('open_devtools').catch(() => {
        // 非 Tauri 环境忽略
      });
    }
  });

  const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);

  root.render(
    <BrowserRouter>
      <App />
    </BrowserRouter>
  );

  // 前端渲染完成后，通知 Tauri 显示主窗口
  // 使用 requestIdleCallback 确保首帧已绘制
  const showWindow = () => {
    const win = getCurrentWebviewWindow();
    win.show().catch(() => {
      // 非 Tauri 环境忽略
    });
    win.setFocus().catch(() => {
      // 非 Tauri 环境忽略
    });
  };

  if ('requestIdleCallback' in window) {
    requestIdleCallback(showWindow, { timeout: 500 });
  } else {
    setTimeout(showWindow, 100);
  }
}

bootstrap();
