import './lib/intl-polyfill';
import { PropsWithChildren, useEffect, useRef } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { handleWechatOrderConfirmShow } from './lib/wechat-order-confirm';
import { installClientErrorReporting } from './lib/client-error';
import { prefetchShareBrandAssets } from './lib/wechat-share';
import { prefetchJiuzuSplashAssets } from './lib/jiuzu-splash';
import { capturePromoSceneAndTouchScan } from './lib/promo';
import { initClientVersionChecks } from './lib/client-version';
import './app.css';

installClientErrorReporting();
prefetchShareBrandAssets();
prefetchJiuzuSplashAssets();

function App({ children }: PropsWithChildren) {
  const handlingRef = useRef(false);

  useEffect(() => {
    void capturePromoSceneAndTouchScan();
    initClientVersionChecks();
  }, []);

  useDidShow((options?: {
    referrerInfo?: {
      appId?: string;
      extraData?: { status?: string; errormsg?: string; req_extradata?: Record<string, string> };
    };
  }) => {
    if (handlingRef.current) return;

    const referrerInfo =
      options?.referrerInfo ||
      (typeof Taro.getEnterOptionsSync === 'function'
        ? (
            Taro.getEnterOptionsSync() as {
              referrerInfo?: {
                appId?: string;
                extraData?: {
                  status?: string;
                  errormsg?: string;
                  req_extradata?: Record<string, string>;
                };
              };
            }
          ).referrerInfo
        : undefined);
    if (!referrerInfo?.appId) return;

    handlingRef.current = true;
    void handleWechatOrderConfirmShow({ referrerInfo })
      .then((result) => {
        if (result.redirectUrl) {
          Taro.redirectTo({ url: result.redirectUrl }).catch(() => {
            Taro.reLaunch({ url: result.redirectUrl! });
          });
          return;
        }
        if (!result.handled || !result.orderId) return;
        const pages = Taro.getCurrentPages();
        const cur = pages[pages.length - 1] as { route?: string } | undefined;
        const route = cur?.route || '';
        if (route.includes('pickup-receive')) {
          Taro.redirectTo({ url: '/pages/orders/index?tab=all' }).catch(() => {});
        }
      })
      .finally(() => {
        handlingRef.current = false;
      });
  });

  return <>{children}</>;
}

export default App;
