import type { ReactNode } from 'react';
import type { Viewport } from 'next';
import { headers } from 'next/headers';

import './globals.css';
import MetaPageView from './MetaPageView';
import { ToastProvider } from './context/ToastContext';
import ToastContainer from './components/ToastContainer';

export const metadata = {
  title: 'Ayatique — Audio Quranic Stories',
  description: 'Discover peace and spiritual growth through audio Quranic stories.',
};

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  maximumScale: 1,
  viewportFit: 'cover',
};

const pixelId = process.env.NEXT_PUBLIC_META_PIXEL_ID?.trim();
const tiktokPixelId = process.env.NEXT_PUBLIC_TIKTOK_PIXEL_ID?.trim();

const ttqSnippet = tiktokPixelId
  ? `!function (w, d, t) {
      w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie","holdConsent","revokeConsent","grantConsent"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(
      var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var r="https://analytics.tiktok.com/i18n/pixel/events.js",o=n&&n.partner;ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=r,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};n=document.createElement("script")
      ;n.type="text/javascript",n.async=!0,n.src=r+"?sdkid="+e+"&lib="+t;e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(n,e)};
      ttq.load('${tiktokPixelId}');
      ttq.page();
    }(window, document, 'ttq');`
  : undefined;

const fbqSnippet = pixelId
  ? `!function(f,b,e,v,n,t,s){
      if(f.fbq)return;
      n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;
      n.push=n;
      n.loaded=!0;
      n.version='2.0';
      n.queue=[];
      t=b.createElement(e);
      t.async=!0;
      t.src=v;
      s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s);
    }(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '${pixelId}');`
  : undefined;

export default function RootLayout({ children }: { children: ReactNode }) {
  const pathname = headers().get('x-pathname') ?? '';
  const skipAnalytics = pathname.startsWith('/dashboard_aya');

  return (
    <html lang="en">
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <link
          href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Inter:wght@400;700;900&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap"
          rel="stylesheet"
        />
        {!skipAnalytics && fbqSnippet ? (
          <>
            <script dangerouslySetInnerHTML={{ __html: fbqSnippet }} />
            <noscript>
              <img
                height="1"
                width="1"
                style={{ display: 'none' }}
                src={`https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1`}
                alt=""
              />
            </noscript>
          </>
        ) : null}
        {!skipAnalytics && ttqSnippet ? (
          <script dangerouslySetInnerHTML={{ __html: ttqSnippet }} />
        ) : null}
        {!skipAnalytics && (
        <script
          type="text/javascript"
          dangerouslySetInnerHTML={{
            __html: `
              (function(c,l,a,r,i,t,y){
                c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
                t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
                y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
              })(window, document, "clarity", "script", "wey87rk90i");
            `,
          }}
        />
        )}
      </head>
      <body className="app-body">
        <ToastProvider>
          {!skipAnalytics && <MetaPageView />}
          <ToastContainer />
          {children}
        </ToastProvider>
      </body>
    </html>
  );
}
