import type { Metadata, Viewport } from 'next';
import './globals.css';
import './hayat.css';
import { siteConfig } from '@/config/site';
import { CartProvider } from '@/context/CartContext';
import { SizeProvider } from '@/context/SizeContext';
import { getStoreSettings } from '@/lib/settings';
import { getWooCommerceCategories } from '@/lib/wpgraphql';
import { headers } from 'next/headers';
import { isLandingSlug } from '@/lib/landing';
import Header from '@/components/layout/Header';
import Footer from '@/components/layout/Footer';
import CartDrawer from '@/components/layout/CartDrawer';
import FloatingCart from '@/components/layout/FloatingCart';
import FloatingCartTab from '@/components/layout/FloatingCartTab';
import MobileTabBar from '@/components/layout/MobileTabBar';
import Toast from '@/components/layout/Toast';
import FloatingActions from '@/components/layout/FloatingActions';
import TrackingScripts from '@/components/tracking/TrackingScripts';
import ViewportLock from '@/components/layout/ViewportLock';

// NOTE: no `dynamic = 'force-dynamic'` here on purpose. The layout reads
// headers() for landing detection (still dynamic per request), but data
// fetches use `revalidate: 60` + on-demand tag purges, so TTFB stays low.

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

function getVerificationData(settings: any) {
  let fbVerification = (settings?.tracking?.facebook_domain_verification || '').trim();
  const headerScript = settings?.tracking?.header_script || '';

  if (!fbVerification && headerScript) {
    const fbMatch =
      headerScript.match(/facebook-domain-verification[\s\S]*?content=["']([^"']+)["']/i) ||
      headerScript.match(/content=["']([^"']+)["'][\s\S]*?facebook-domain-verification/i);
    if (fbMatch) {
      fbVerification = fbMatch[1].trim();
    }
  }

  let googleVerification = '';
  if (headerScript) {
    const gMatch =
      headerScript.match(/google-site-verification[\s\S]*?content=["']([^"']+)["']/i) ||
      headerScript.match(/content=["']([^"']+)["'][\s\S]*?google-site-verification/i);
    if (gMatch) {
      googleVerification = gMatch[1].trim();
    }
  }

  const otherMetas: Record<string, string> = {};
  if (fbVerification) {
    otherMetas['facebook-domain-verification'] = fbVerification;
  }
  if (headerScript) {
    const metaRegex = /<meta\s+([^>]+)>/gi;
    let m;
    while ((m = metaRegex.exec(headerScript)) !== null) {
      const attrs = m[1];
      const nameM = attrs.match(/name=["']([^"']+)["']/i);
      const propM = attrs.match(/property=["']([^"']+)["']/i);
      const contentM = attrs.match(/content=["']([^"']+)["']/i);
      const key = nameM?.[1] || propM?.[1];
      if (key && contentM && key !== 'facebook-domain-verification' && key !== 'google-site-verification') {
        otherMetas[key] = contentM[1];
      }
    }
  }

  return { fbVerification, googleVerification, otherMetas };
}

export async function generateMetadata(): Promise<Metadata> {
  const settings = await getStoreSettings().catch(() => null);
  const { fbVerification, googleVerification, otherMetas } = getVerificationData(settings);

  let rawBrand = settings?.header?.brand_name?.trim();
  if (!rawBrand || rawBrand.toLowerCase().includes('ros') || rawBrand.toLowerCase().includes('digital store') || rawBrand.toLowerCase().includes('royal macaw')) {
    rawBrand = 'Hayat Supplements';
  }
  const brandName = rawBrand;
  const siteTitle = `${brandName} — খাঁটি মধু, ভেষজ ও বাদাম`;
  const logoUrl = settings?.header?.logo_url || siteConfig.brand.logoUrl;
  const shareImageUrl = siteConfig.brand.shareImageUrl || '/images/share.png';

  return {
    title: {
      default: siteTitle,
      template: `%s | ${brandName}`,
    },
    description: siteConfig.seo.defaultDescription,
    metadataBase: new URL(siteConfig.seo.siteUrl),
    alternates: {
      canonical: '/',
    },
    verification: {
      google: googleVerification || undefined,
      other: otherMetas,
    },
    openGraph: {
      title: siteTitle,
      description: siteConfig.seo.defaultDescription,
      url: siteConfig.seo.siteUrl,
      siteName: brandName,
      locale: 'en_US',
      type: 'website',
      images: [
        {
          url: shareImageUrl,
          width: 1200,
          height: 630,
          alt: `${brandName} — Shoes that fit the first time`,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image',
      title: siteTitle,
      description: siteConfig.seo.defaultDescription,
      images: [shareImageUrl],
    },
    icons: {
      icon: [
        { url: '/images/favicon.png', sizes: '32x32', type: 'image/png' },
        { url: '/images/favicon.png', sizes: '192x192', type: 'image/png' },
        { url: '/favicon.ico' },
      ],
      apple: [
        { url: '/images/favicon.png', sizes: '180x180', type: 'image/png' },
      ],
      shortcut: ['/images/favicon.png'],
    },
  };
}

interface ParsedHtmlTag {
  type: 'meta' | 'link' | 'script' | 'style' | 'noscript';
  attrs: Record<string, string>;
  content?: string;
}

function parseRawHtmlTags(rawHtml?: string): ParsedHtmlTag[] {
  if (!rawHtml || !rawHtml.trim()) return [];
  const trimmed = rawHtml.trim();

  // If user pasted raw JavaScript snippet without wrapping in <script> tags
  if (
    !trimmed.startsWith('<') &&
    (trimmed.includes('function') ||
      trimmed.includes('window.') ||
      trimmed.includes('fbq(') ||
      trimmed.includes('dataLayer') ||
      trimmed.includes('var ') ||
      trimmed.includes('let ') ||
      trimmed.includes('const '))
  ) {
    return [
      {
        type: 'script',
        attrs: {},
        content: trimmed,
      },
    ];
  }

  const items: ParsedHtmlTag[] = [];
  const tagRegex = /<(script|style|meta|link|noscript)([\s\S]*?)>(?:([\s\S]*?)<\/\1>)?/gi;
  let match;
  while ((match = tagRegex.exec(trimmed)) !== null) {
    const tagName = match[1].toLowerCase() as ParsedHtmlTag['type'];
    const attrString = match[2] || '';
    const innerContent = match[3];

    const attrs: Record<string, string> = {};
    const attrRegex = /([a-zA-Z0-9_\-:]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
    let a;
    while ((a = attrRegex.exec(attrString)) !== null) {
      const name = a[1].toLowerCase();
      const val = a[2] !== undefined ? a[2] : (a[3] !== undefined ? a[3] : (a[4] !== undefined ? a[4] : 'true'));
      attrs[name] = val;
    }

    items.push({
      type: tagName,
      attrs,
      content: innerContent,
    });
  }

  return items;
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const settings = await getStoreSettings();
  const categories = await getWooCommerceCategories().catch(() => []);
  const brandName = settings.header?.brand_name || 'Hayat Supplements';
  const socialLinks = [
    settings.footer?.facebook,
    settings.footer?.instagram,
    settings.footer?.tiktok,
    settings.footer?.youtube,
  ].filter(Boolean);
  const unifiedWhatsApp = settings.header?.whatsapp || settings.footer?.whatsapp || '8801325202214';
  const { fbVerification, googleVerification } = getVerificationData(settings);
  const headCustomTags = parseRawHtmlTags(settings?.tracking?.header_script);
  const bodyCustomTags = parseRawHtmlTags(settings?.tracking?.body_script);

  // Landing pages (e.g. /linglong) render their OWN header/footer — skip the
  // site-wide chrome there. Static routes always win over /[slug] in the App
  // Router, so guard the reserved top-level segments explicitly.
  const pathname = (await headers()).get('x-pathname') || '';
  const pathSegs = pathname.split('/').filter(Boolean);
  const RESERVED_TOP_SEGMENTS = new Set([
    'about', 'api', 'brand', 'brands', 'cart', 'category', 'checkout',
    'clear2029', 'collection', 'concern', 'contact', 'contact-us',
    'how-we-price', 'landing', 'loader', 'order-received', 'page',
    'policies', 'pricing', 'product', 'shipping', 'shop', 'size-guide',
    'track-order',
  ]);
  const isLandingPage =
    pathSegs.length === 1 &&
    !RESERVED_TOP_SEGMENTS.has(pathSegs[0].toLowerCase()) &&
    (await isLandingSlug(pathSegs[0]).catch(() => false));

  return (
    <html lang="bn">
      <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=Jost:wght@300;400;500;600;700&family=Hind+Siliguri:wght@400;500;600;700&display=swap"
          rel="stylesheet"
        />

        {/* Favicon Icons */}
        <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png" />
        <link rel="icon" type="image/png" sizes="192x192" href="/images/favicon.png" />
        <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png" />
        <link rel="shortcut icon" href="/images/favicon.png" />

        {/* PixelFly, Stape.io & GTM DataLayer Initialization in <head> */}
        <script
          id="pixelfly-gtm-datalayer-init"
          dangerouslySetInnerHTML={{
            __html: 'window.dataLayer = window.dataLayer || [];',
          }}
        />

        {/*  Server-rendered Tags from Custom Header Scripts (Scripts, Styles, Links, Noscripts) */}
        {headCustomTags.map((item, idx) => {
          if (item.type === 'link') {
            return <link key={`h-link-${idx}`} {...item.attrs} />;
          }
          if (item.type === 'style') {
            return (
              <style
                key={`h-style-${idx}`}
                {...item.attrs}
                dangerouslySetInnerHTML={{ __html: item.content || '' }}
              />
            );
          }
          if (item.type === 'script') {
            if (item.attrs.src) {
              return <script key={`h-script-${idx}`} {...item.attrs} />;
            }
            return (
              <script
                key={`h-script-${idx}`}
                {...item.attrs}
                dangerouslySetInnerHTML={{ __html: item.content || '' }}
              />
            );
          }
          if (item.type === 'noscript') {
            return (
              <noscript
                key={`h-noscript-${idx}`}
                dangerouslySetInnerHTML={{ __html: item.content || '' }}
              />
            );
          }
          return null;
        })}
      </head>
      <body>
        {/* Device Scale & Zoom Lock */}
        <ViewportLock />

        {/* 🚀 Server-rendered Tags from Custom Body Scripts (e.g. GTM Noscript iframe, custom tracking body tags) */}
        {bodyCustomTags.map((item, idx) => {
          if (item.type === 'script') {
            if (item.attrs.src) {
              return <script key={`b-script-${idx}`} {...item.attrs} />;
            }
            return (
              <script
                key={`b-script-${idx}`}
                {...item.attrs}
                dangerouslySetInnerHTML={{ __html: item.content || '' }}
              />
            );
          }
          if (item.type === 'noscript') {
            return (
              <noscript
                key={`b-noscript-${idx}`}
                dangerouslySetInnerHTML={{ __html: item.content || '' }}
              />
            );
          }
          return null;
        })}

        {/* Global Google Tag Manager & Meta Pixel Tracking */}
        <TrackingScripts
          gtmId={settings?.tracking?.gtm_id}
          pixelId={settings?.tracking?.pixel_id}
        />

        {/* 🌟 Structured Data / JSON-LD Schema for Organization & WebSite */}
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              '@context': 'https://schema.org',
              '@graph': [
                {
                  '@type': 'Organization',
                  '@id': `${siteConfig.seo.siteUrl}/#organization`,
                  name: brandName,
                  url: siteConfig.seo.siteUrl,
                  logo: {
                    '@type': 'ImageObject',
                    url: `${siteConfig.seo.siteUrl}/images/logo.png`,
                  },
                  sameAs: socialLinks,
                  contactPoint: [
                    {
                      '@type': 'ContactPoint',
                      telephone: '+8801325202214',
                      contactType: 'customer service',
                      areaServed: 'BD',
                      availableLanguage: ['Bengali', 'English'],
                    },
                  ],
                },
                {
                  '@type': 'WebSite',
                  '@id': `${siteConfig.seo.siteUrl}/#website`,
                  url: siteConfig.seo.siteUrl,
                  name: brandName,
                  description: siteConfig.seo.defaultDescription,
                  publisher: {
                    '@id': `${siteConfig.seo.siteUrl}/#organization`,
                  },
                  inLanguage: 'bn',
                  potentialAction: {
                    '@type': 'SearchAction',
                    target: `${siteConfig.seo.siteUrl}/shop?q={search_term_string}`,
                    'query-input': 'required name=search_term_string',
                  },
                },
              ],
            }),
          }}
        />

        <SizeProvider>
          <CartProvider>
            {/* Master Site-Wide Header (skipped on landing pages — they render their own) */}
            {!isLandingPage && (
              <Header
                settings={settings.header}
                categories={categories}
              />
            )}

            {/* Dynamic Page Content */}
            <main id="app">{children}</main>

            {/* Master Site-Wide Footer (skipped on landing pages — they render their own) */}
            {!isLandingPage && (
              <Footer
                settings={settings.footer}
                brandName={brandName}
                categories={categories}
              />
            )}

            {/* Global Floating Components (site chrome hidden on landing pages — they have their own) */}
            <CartDrawer />
            {!isLandingPage && <FloatingCart />}
            <Toast />
            {!isLandingPage && <FloatingActions whatsappNumber={unifiedWhatsApp} />}
            {!isLandingPage && <MobileTabBar />}
          </CartProvider>
        </SizeProvider>
      </body>
    </html>
  );
}
