import { createRoot } from 'react-dom/client';
import React from 'react';
import App from './App.tsx';
import './index.css';

// Capacitor初期化
import { Capacitor } from '@capacitor/core';
import { initPushNotifications } from './lib/pushNotificationClient';

// ErrorBoundary
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; error: Error | null }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error('App crashed:', error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 32, fontFamily: 'sans-serif', color: '#333' }}>
          <h2>エラーが発生しました</h2>
          <pre style={{ fontSize: 12, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
            {this.state.error?.message}
          </pre>
        </div>
      );
    }
    return this.props.children;
  }
}

// Capacitor用の初期化処理
if (Capacitor.isNativePlatform()) {
  // ネイティブプラットフォーム用の初期化
  import('@capacitor/status-bar').then(({ StatusBar, Style }) => {
    // iOS: 透過設定でセーフエリアを有効化
    // Android: 背景色を設定（必要に応じて調整）
    if (Capacitor.getPlatform() === 'ios') {
      StatusBar.setStyle({ style: Style.Default });
      StatusBar.setOverlaysWebView({ overlay: true });
    } else {
      StatusBar.setStyle({ style: Style.Default });
      StatusBar.setBackgroundColor({ color: '#ffffff' });
    }
  });

  import('@capacitor/splash-screen').then(({ SplashScreen }) => {
    SplashScreen.hide();
  });

  // プッシュ通知初期化（Flutter版initOneSignal相当）
  void initPushNotifications();
}

createRoot(document.getElementById('root')!).render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>
);
