import './lib/intl-polyfill';
import { PropsWithChildren, useRef } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import WechatShareBootstrap from './components/WechatShareBootstrap';
import { patchTaroH5Hooks } from './lib/patch-taro-h5-hooks';
import { handleWechatOrderConfirmShow } from './lib/wechat-order-confirm';
import { installClientErrorReporting } from './lib/client-error';
import { prefetchShareBrandAssets } from './lib/wechat-share';
import './app.css';

// H5：在首屏 page hooks 执行前，把 Taro.useDidShow 等绑到与 createReactApp 同一份 runtime
patchTaroH5Hooks();
installClientErrorReporting();
prefetchShareBrandAssets();

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

  useDidShow((options?: {
    referrerInfo?: {
      appId?: string;
      extraData?: { status?: string; errormsg?: string; req_extradata?: Record<string, string> };
    };
  }) => {
    if (process.env.TARO_ENV !== 'weapp') return;
    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 (
    <>
      <WechatShareBootstrap />
      {children}
    </>
  );
}

export default App;
