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

import { AppProviders } from '@/app/(root)/AppProviders';
import ClientLayout from '@/app/(root)/ClientLayout';
import '@/app/(root)/globals.css';
import AnalyticsScripts from '@/components/ga4/AnalyticsScripts';
import PwaInstallSuppressionScript from '@/components/pwa/PwaInstallSuppressionScript';
import { isAndroid, isIOS } from '@/utils/device';
import { staticAssetUrl } from '@/utils/staticAssetUrl';

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

export async function generateMetadata(): Promise<Metadata> {
  return {
    title: 'Suno',
    description: 'Suno',

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

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 />

          {/* 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> */}
          <script type='application/ld+json'>
            {JSON.stringify({
              '@context': 'https://schema.org',
              '@type': 'WebSite',
              name: 'Suno',
              url: 'https://suno.com/',
              potentialAction: {
                '@type': 'SearchAction',
                target: 'https://suno.com/search?q=Suno',
                'query-input': 'required name=search_term_string',
              },
            })}
          </script>
          <script type='application/ld+json'>
            {JSON.stringify({
              '@context': 'https://schema.org',
              '@type': 'Organization',
              name: 'Suno',
              url: 'https://suno.com/',
              logo: 'https://cdn-o.suno.com/Logo-7.svg',
              description:
                'Suno is building a future where anyone can make great music. From shower singers to chart-topping artists, we empower imagination and creativity.',
              address: {
                '@type': 'PostalAddress',
                addressLocality: 'Cambridge',
                addressRegion: 'MA',
                addressCountry: 'US',
              },
              sameAs: [
                'https://twitter.com/sunomusic',
                'https://www.instagram.com/sunomusic/',
                'https://www.tiktok.com/@sunomusic',
                'https://discord.com/invite/suno',
              ],
            })}
          </script>
          <PwaInstallSuppressionScript />
        </head>
        <body style={{ overflowY: 'hidden' }} className='chakra-ui-dark'>
          {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-slate-800'>
                  Suno will be right back
                </h1>
                <div className='max-w-[600px] text-center font-sans text-lg text-slate-600'>
                  <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}
                hideSidebars={true}
                hideMobileNav={true}
              >
                {/* as part of making the url bar collapsable, we removed the height restriction on the body & html tags.
                 however, the landing page components are positioned with the assumption that the body & html tags have height 100%.
                 so we add this div to maintain the height restriction / overflow container until we can refactor it

                 TODO: refactor it to also collapse the url bar*/}
                <div className='h-dvh w-full overflow-x-hidden'>{children}</div>
              </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>
  );
}
