import 'server-only';
import '@theme/assets/globals.scss';

import { withSegmentDefaults } from '@akinon/next/hocs/server';
import Footer from '@theme/views/footer';
import Header from '@theme/views/header';
import RootModal from '@theme/views/root-modal';
import ClientRoot from './client-root';
import { ResolvedRootLayoutProps, Metadata } from '@akinon/next/types';
import { getSeoData } from '@akinon/next/data/server';
import PzRoot from '@akinon/next/components/pz-root';
import MobileAppToggler from '@akinon/next/components/mobile-app-toggler';
import pwaTags from '@theme/components/pwa-tags';
import { OfflineFallback } from '@theme/components/offline-fallback';
import { InstallPrompt } from '@theme/components/install-prompt';
import type { Viewport } from 'next';
import settings from '@theme/settings';
import RouteHandler from '@theme/components/route-handler';

export const viewport: Viewport = {
  width: 'device-width',
  height: 'device-height',
  initialScale: 1,
  maximumScale: 1,
  userScalable: false
};

export async function generateMetadata() {
  const { locales } = settings.localization;

  const languages = locales.map(({ localePath }) => ({
    [localePath]: `/${localePath}`
  }));

  let result: Metadata = {
    alternates: {
      languages: languages.reduce((acc, cur) => ({ ...acc, ...cur }), {})
    }
  };

  const response = await getSeoData('/');

  result = { ...result, ...pwaTags, ...response };

  return result;
}

async function RootLayout({
  locale,
  translations,
  children
}: ResolvedRootLayoutProps) {
  return (
    <html lang={locale.isoCode} {...(locale.rtl ? { dir: 'rtl' } : {})}>
      <head />
      <body className="overflow-x-hidden">
        <PzRoot translations={translations} locale={locale.value}>
          <ClientRoot>
            <div className="overflow-x-clip">
              <MobileAppToggler>
                <Header />
              </MobileAppToggler>
              <main>
                <OfflineFallback>{children}</OfflineFallback>
                <RouteHandler />
                <RootModal />
              </main>
              <MobileAppToggler>
                <Footer />
              </MobileAppToggler>
              <MobileAppToggler>
                <InstallPrompt />
              </MobileAppToggler>
            </div>
          </ClientRoot>
        </PzRoot>
      </body>
    </html>
  );
}

export default withSegmentDefaults(RootLayout, {
  segmentType: 'root-layout'
});
