import { useEffect, PropsWithChildren } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import ErrorBoundary from './components/ErrorBoundary';
import { flushEvents } from './services/analytics';
import { useAuthStore } from './stores/auth';
import { useUIStore } from './stores/ui';
import './app.scss';

function App({ children }: PropsWithChildren<Record<string, unknown>>) {
  const restoreAuth = useAuthStore((s) => s.restore);
  const restoreUI = useUIStore((s) => s.restore);

  useDidShow(() => {
    restoreAuth();
    restoreUI();
  });

  useEffect(() => {
    const timer = setInterval(() => {
      flushEvents();
    }, 30000);
    const onHide = () => { flushEvents(); };
    Taro.eventCenter.on('appHide', onHide);
    return () => {
      clearInterval(timer);
      Taro.eventCenter.off('appHide', onHide);
    };
  }, []);

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

export default App;
