import App, { AppContext, AppProps } from "next/app";
import { NextIntlProvider } from "next-intl";
import { useRouter } from "next/router";
import cookies from "next-cookies";

const twMessages = require(`../public/h5_assets/messages/zh_TW/common.json`);
const cnMessages = require(`../public/h5_assets/messages/zh_CN/common.json`);

const MyApp = ({ Component, pageProps }: AppProps) => {

  let router = useRouter();
  
  return (
    <NextIntlProvider
      messages={(pageProps.lang ?? router.locale) === "zh_CN" ? { ...cnMessages } : { ...twMessages }}
    >
      <Component {...pageProps} />
    </NextIntlProvider>
  );
};

MyApp.getInitialProps = async (props: AppContext) => {
  const NEXT_LOCALE = cookies(props.ctx)["NEXT_LOCALE"];
  const appProps = await App.getInitialProps(props);
  
  appProps.pageProps = {
    ...appProps.pageProps,
    lang: NEXT_LOCALE,
  };

  return { ...appProps };
};

export default MyApp;