import { ClerkProvider } from '@clerk/nextjs';
import { dark } from '@clerk/themes';
import type { Metadata, ResolvingMetadata } from 'next';
import { cookies, headers } from 'next/headers';
import Image from 'next/image';
import Script from 'next/script';

import AnalyticsScripts from '@/components/ga4/AnalyticsScripts';
import PwaInstallSuppressionScript from '@/components/pwa/PwaInstallSuppressionScript';
import { isAndroid, isIOS } from '@/utils/device';
import { staticAssetUrl } from '@/utils/staticAssetUrl';

import { AppProviders } from './AppProviders';
import ClientLayout from './ClientLayout';
import './globals.css';

export const fetchCache = 'force-no-store';

export async function generateMetadata(
  _props: any,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const pathname = '/';
  const headersList = await headers();
  const host = headersList.get('host') || 'suno.com';
  const canonicalUrl = `https://${host}${pathname}`;
  const parentMetadata = await parent;

  return {
    title: parentMetadata.title ?? 'Suno | AI Music',
    description:
      parentMetadata.description ??
      'Create stunning original music for free in seconds using AI. Make your own masterpieces, share with friends, and discover music from artists worldwide.',
    openGraph: {
      type: 'website',
      url: 'https://suno.com',
      siteName: 'Suno',
      locale: 'en_US',
      images: [
        {
          url: 'https://cdn-o.suno.com/meta-preview.jpg',
          width: 2468,
          height: 800,
          type: 'image/jpeg',
          alt: 'Suno AI Music Generator',
        },
      ],
    },
    alternates: {
      canonical: parentMetadata.alternates?.canonical ?? canonicalUrl,
    },

    // PWA config
    appleWebApp: {
      capable: true,
      statusBarStyle: 'black-translucent',
      title: 'Suno',
    },
    applicationName: 'Suno',
  };
}

const clerkLocalizationOverrides = {
  footerPageLink__privacy: 'By continuing, you accept our Privacy Policy and',
  footerPageLink__terms: 'Terms of Use',
  signUp: {
    start: {
      actionText: '',
    },
  },
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const headers_obj = await headers();
  const customCountry = headers_obj.get('country');
  const vercelCountry = headers_obj.get('x-vercel-ip-country');
  const country = customCountry || vercelCountry;

  // Get additional geolocation headers
  const postalCode = headers_obj.get('x-vercel-ip-postal-code');
  const latitude = headers_obj.get('x-vercel-ip-latitude');
  const longitude = headers_obj.get('x-vercel-ip-longitude');
  const city = headers_obj.get('x-vercel-ip-city');
  const region = headers_obj.get('x-vercel-ip-country-region');
  const forwardedFor = headers_obj.get('x-forwarded-for');

  // User agent for Chrome and Firefox is CriOS and FxiOS
  const isOnIos = isIOS();
  const isOnAndroid = isAndroid();
  const supportedBrowser = isOnIos || isOnAndroid;

  console.debug('Location Alpha:', country);
  console.debug('Location Alpha (custom):', customCountry);
  console.debug('Location Alpha (auto):', vercelCountry);
  console.debug('Zone Beta:', postalCode);
  console.debug('Coord X:', latitude);
  console.debug('Coord Y:', longitude);
  console.debug('Metro:', city);
  console.debug('District:', region);
  console.debug('Origin:', forwardedFor);

  // Override Clerk publishable key for staff
  const cookieStore = await cookies();
  const sunoAuthOverride = cookieStore.get('suno_auth')?.value;

  return (
    <ClerkProvider
      publishableKey={sunoAuthOverride || undefined}
      localization={clerkLocalizationOverrides}
      appearance={{
        baseTheme: dark,
        layout: {
          termsPageUrl: 'https://suno.ai/legal/terms',
          privacyPageUrl: 'https://suno.ai/legal/privacy',
        },
      }}
    >
      <html lang='en' data-theme='dark' style={{ colorScheme: 'dark' }}>
        <head>
          <link
            rel='icon'
            type='image/x-icon'
            href='https://cdn-o.suno.com/favicon.ico'
            sizes='any'
          />
          <link
            rel='icon'
            type='image/png'
            href='https://cdn-o.suno.com/favicon-192x192.png'
            sizes='192x192'
          />
          <link
            rel='icon'
            type='image/png'
            href='https://cdn-o.suno.com/favicon-512x512.png'
            sizes='512x512'
          />
          <link
            rel='apple-touch-icon'
            href='https://cdn-o.suno.com/apple-touch-icon.png'
          />

          {/* Critical font preloading - Other fonts load progressively via @font-face */}
          <link
            rel='preload'
            href={staticAssetUrl('PPNeueMontreal-Regular.woff')}
            as='font'
            type='font/woff'
            crossOrigin='anonymous'
            fetchPriority='high'
          />
          <link
            rel='preload'
            href={staticAssetUrl('PPNeueMontreal-Medium.woff')}
            as='font'
            type='font/woff'
            crossOrigin='anonymous'
          />
          {/* Maze for user testing */}
          <Script id='maze'>
            {`(function(m,a,z,e){var s,t;try{t=m.sessionStorage.getItem('maze-us');}catch(err){}if(!t){t=new Date().getTime();try{m.sessionStorage.setItem('maze-us',t);}catch(err){}}s=a.createElement('script');s.src=z+'?apiKey='+e;s.async=true;a.getElementsByTagName('head')[0].appendChild(s);m.mazeUniversalSnippetApiKey=e;})(window,document,'https://snippet.maze.co/maze-universal-loader.js','a964c763-8fae-4629-b2aa-2df4f0d2c15d');`}
          </Script>
          {/* Do not add an hcaptcha script tag to this file. See the comment at the top of (root)/Captcha.tsx. */}

          <AnalyticsScripts />

          {/* Stripe.js */}
          <Script
            id='stripe-js'
            src='https://js.stripe.com/v3'
            strategy='lazyOnload'
            async
            defer
          />
          {/* End Stripe.js */}
          {/* Cloudflare Analytics */}
          <Script
            id='cloudflare-analytics'
            src='https://static.cloudflareinsights.com/beacon.min.js'
            data-cf-beacon='{"token": "ab1dff532cc64f0da79eb9c4070ee1e7"}'
            strategy='lazyOnload'
            defer
            async
          />
          {/* End Cloudflare Analytics */}
          {/* Uncomment this to enable react-scan to profile re-renders */}
          {/* <script src='https://unpkg.com/react-scan/dist/auto.global.js'></script> */}
          <PwaInstallSuppressionScript />
        </head>
        <body className='chakra-ui-dark bg-background-primary'>
          {process.env.NEXT_PUBLIC_MAINTENANCE === 'true' ? (
            <div className='mt-[120px] flex justify-center'>
              <div className='flex flex-col items-center'>
                <Image
                  width={240}
                  height={240}
                  className='mb-8 w-60 rounded-3xl'
                  src='https://cdn-o.suno.com/suno-app-icon.webp'
                  alt='Suno'
                />
                <h1 className='mb-4 font-serif text-3xl text-foreground-secondary'>
                  Suno will be right back
                </h1>
                <div className='max-w-[600px] text-center font-sans text-lg text-foreground-tertiary'>
                  <strong>Scheduled Maintenance:</strong> Our site is undergoing
                  planned maintenance today (11/14/2024) from 10:00 PM to 11:00
                  PM ET. During this time, features will be temporarily
                  unavailable. Thank you for your patience!
                </div>
              </div>
            </div>
          ) : (
            <AppProviders
              app={{
                geolocation: {
                  country,
                  postalCode,
                  latitude,
                  longitude,
                  city,
                  region,
                  forwardedFor,
                },
              }}
            >
              <ClientLayout supportedBrowser={supportedBrowser}>
                {children}
              </ClientLayout>
            </AppProviders>
          )}
          <noscript>
            <iframe
              src='https://www.googletagmanager.com/ns.html?id=GTM-NQ9L4VGG'
              height='0'
              width='0'
              style={{ display: 'none', visibility: 'hidden' }}
              title='Google Tag Manager'
            ></iframe>
          </noscript>
        </body>
      </html>
    </ClerkProvider>
  );
}
