import React, { useEffect } from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import './i18n' // Initialize i18n
import { registerSW } from 'virtual:pwa-register'
import twemoji from 'twemoji'

// Only register service worker when not in Electron (file:// protocol doesn't support SW)
const isElectron = window.location.protocol === 'file:'
if (!isElectron) {
  registerSW({
    onNeedRefresh() {
      if (confirm('New version available! Reload to update?')) {
        window.location.reload()
      }
    },
    onOfflineReady() {
      console.log('App ready to work offline')
    },
  })
}

// Initialize Twemoji after React renders
const initTwemoji = () => {
  twemoji.parse(document.body, {
    folder: 'svg',
    ext: '.svg',
    base: 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/'
  });
};

// Create a wrapper component that initializes Twemoji
const TwemojiWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  useEffect(() => {
    // Initial parse
    initTwemoji();

    // Set up MutationObserver to re-parse when DOM changes
    const observer = new MutationObserver(() => {
      initTwemoji();
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    return () => observer.disconnect();
  }, []);

  return <>{children}</>;
};

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <TwemojiWrapper>
      <App />
    </TwemojiWrapper>
  </React.StrictMode>,
)
