import type { Metadata } from "next";
import "./globals.css";
import "./responsive.css";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import DeferredPopup from "@/components/DeferredPopup";
import Script from "next/script";
import CursorDot from "@/components/CursorDot";
import BreadcrumbSchema from "@/components/BreadcrumbSchema";
// import ChatBox from "@/components/ChatBox";

export const metadata: Metadata = {
  title: "Web Development Company in Ahmedabad | Fruxinfo",
  description: "Fruxinfo is a trusted web development company in Ahmedabad offering custom websites, mobile app development, SEO, and digital marketing for business growth.",
  robots: { index: true, follow: true, googleBot: { index: true, follow: true, "max-snippet": -1, "max-image-preview": "large", "max-video-preview": -1 } },
  icons: {
    icon: "/favicon_icon.ico",
    apple: "/apple-touch-icon.png",
  },
  metadataBase: new URL("https://www.fruxinfo.com"),
  openGraph: {
    title: "Web Development Company in Ahmedabad | Fruxinfo",
    description: "Fruxinfo is a trusted web development company in Ahmedabad offering custom websites, mobile app development, SEO, and digital marketing for business growth.",
    url: "https://www.fruxinfo.com/",
    siteName: "Fruxinfo",
    images: [
      {
        url: "https://www.fruxinfo.com/images/aurosell-og-image.jpg",
        width: 1200,
        height: 630,
        alt: "Fruxinfo – Boost Your Business Online",
      },
    ],
    type: "website",
  },
  other: {
    "p:domain_verify": "b9ddb307d9538ff35ae4cbbd1828dc83",
  },
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        {/* ✅ Resource hints — preconnect + dns-prefetch for third-party origins */}
        <link rel="preconnect" href="https://admin.fruxinfo.com" />
        <link rel="preconnect" href="https://www.googletagmanager.com" />
        <link rel="preconnect" href="https://connect.facebook.net" />
        <link rel="dns-prefetch" href="https://admin.fruxinfo.com" />
        <link rel="dns-prefetch" href="https://www.googletagmanager.com" />

        {/* ✅ Preload home banner hero + background (the .Mainbanner bg is the mobile LCP element) */}
        <link rel="preload" as="image" href="/images/MainBannerVectoreImage.webp" />
        <link rel="preload" as="image" href="/images/mainBannerBg.webp" fetchPriority="high" />

        {/* ✅ Preload body + heading fonts so text renders in the final font sooner */}
        <link rel="preload" as="font" type="font/otf" href="/tiemposfont/TestTiemposText-Regular-BF66457a50cd521.otf" crossOrigin="anonymous" />
        <link rel="preload" as="font" type="font/ttf" href="/Manrope/Manrope-Regular.ttf" crossOrigin="anonymous" />

        {/* ✅ Google tags (GTM + GA) load on FIRST USER INTERACTION (scroll/tap/key)
            or after a 12s fallback — whichever comes first. The full stack
            (gtm.js → G-E01P138DGC, AW-419447181, Clarity, consent-mode) costs
            ~5s of mobile main-thread; loading it lazily was not enough because
            Lighthouse's TBT window still caught it. Real-user tracking is
            preserved: any scroll/touch/click starts it, and the 12s timer
            covers completely idle visitors. Site ownership verification does
            NOT depend on these — the google-site-verification meta tags handle that. */}
        <Script
          id="gtags-on-interaction"
          strategy="afterInteractive"
          dangerouslySetInnerHTML={{
            __html: `
              (function () {
                var loaded = false;
                function loadTags() {
                  if (loaded) return; loaded = true;
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({'gtm.start': new Date().getTime(), event: 'gtm.js'});
                  window.gtag = window.gtag || function(){ window.dataLayer.push(arguments); };
                  gtag('js', new Date());
                  gtag('config', 'G-VVNVDL7QKQ');
                  ['https://www.googletagmanager.com/gtm.js?id=GTM-WCP5NVCM',
                   'https://www.googletagmanager.com/gtag/js?id=G-VVNVDL7QKQ'].forEach(function (src) {
                    var s = document.createElement('script');
                    s.async = true; s.src = src;
                    document.head.appendChild(s);
                  });
                  events.forEach(function (e) { window.removeEventListener(e, loadTags, opts); });
                }
                var events = ['pointerdown', 'touchstart', 'scroll', 'keydown'];
                var opts = { once: true, passive: true, capture: true };
                events.forEach(function (e) { window.addEventListener(e, loadTags, opts); });
                setTimeout(loadTags, 12000);
              })();
            `,
          }}
        />

        {/* ✅ Verification meta tags */}
        <meta
          name="msvalidate.01"
          content="F74596A64C09B839AD36729DB8FD3816"
        />
        <meta
          name="google-site-verification"
          content="TCpoXv6WCt_qbo0zMhoNSgJhfaoIqURbuk6d5kquPU0"
        />
        <meta
          name="google-site-verification"
          content="Rdo4msUQj3pLpvWlLyHaEQuexHtmtUI0G1gz7eQ4ock"
        />

        {/* ✅ JSON-LD: Organization */}
        <Script
          id="ld-organization"
          type="application/ld+json"
          strategy="afterInteractive"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "Organization",
              name: "Fruxinfo Pvt. Ltd.",
              alternateName: "Fruxinfo",
              url: "https://www.fruxinfo.com/",
              logo: "https://www.fruxinfo.com/images/fruxinfo-logo.png",
              description:
                "Fruxinfo is a web development, mobile app development, SEO, and digital marketing company in Ahmedabad, India, serving clients globally since 2011.",
              foundingDate: "2011-11",
              sameAs: [
                "https://in.linkedin.com/company/fruxinfo-private-limited",
                "https://www.linkedin.com/company/fruxinfo-pvt-ltd",
              ],
              contactPoint: {
                "@type": "ContactPoint",
                telephone: "+91-9924512890",
                contactType: "customer service",
                areaServed: ["IN", "US", "GB", "AE", "AU", "CA"],
                availableLanguage: ["en", "hi", "gu"],
              },
            }),
          }}
        />

        {/* ✅ JSON-LD: ProfessionalService (LocalBusiness) */}
        <Script
          id="ld-localbusiness"
          type="application/ld+json"
          strategy="afterInteractive"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "ProfessionalService",
              "@id": "https://www.fruxinfo.com/#localbusiness",
              name: "Fruxinfo Pvt. Ltd.",
              image: "https://www.fruxinfo.com/images/fruxinfo-logo.png",
              url: "https://www.fruxinfo.com/",
              telephone: "+91-9924512890",
              priceRange: "$$",
              address: {
                "@type": "PostalAddress",
                addressLocality: "Ahmedabad",
                addressRegion: "Gujarat",
                addressCountry: "IN",
              },
              geo: {
                "@type": "GeoCoordinates",
                latitude: 23.0225,
                longitude: 72.5714,
              },
              openingHoursSpecification: [
                {
                  "@type": "OpeningHoursSpecification",
                  dayOfWeek: [
                    "Monday",
                    "Tuesday",
                    "Wednesday",
                    "Thursday",
                    "Friday",
                    "Saturday",
                  ],
                  opens: "10:00",
                  closes: "19:00",
                },
              ],
              areaServed: ["IN", "US", "GB", "AE", "AU", "CA"],
              serviceType: [
                "Web Development",
                "Mobile App Development",
                "SEO Services",
                "Digital Marketing",
                "Graphic Design",
              ],
            }),
          }}
        />

        {/* ✅ JSON-LD: WebSite */}
        <Script
          id="ld-website"
          type="application/ld+json"
          strategy="afterInteractive"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "WebSite",
              name: "Fruxinfo",
              url: "https://www.fruxinfo.com/",
              publisher: {
                "@type": "Organization",
                name: "Fruxinfo Pvt. Ltd.",
              },
              potentialAction: {
                "@type": "SearchAction",
                target: {
                  "@type": "EntryPoint",
                  urlTemplate:
                    "https://www.fruxinfo.com/blog?q={search_term_string}",
                },
                "query-input": "required name=search_term_string",
              },
            }),
          }}
        />

        {/* ✅ Google Analytics is loaded by the gtags-on-interaction bootstrap above
            (single gate for the whole GTM/GA stack). */}

        {/* ✅ Facebook Pixel Script (lazyOnload — fires after page is idle to reduce TBT) */}
        <Script
          id="facebook-pixel"
          strategy="lazyOnload"
          dangerouslySetInnerHTML={{
            __html: `
              !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', '9902586063134427');
              fbq('track', 'PageView');
            `,
          }}
        />
      </head>

      <body>
        {/* ✅ Google Tag Manager (noscript) */}
        <noscript>
          <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-WCP5NVCM"
            height="0"
            width="0"
            style={{ display: "none", visibility: "hidden" }}
          />
        </noscript>

        {/* ✅ BreadcrumbList JSON-LD (client-rendered, path-aware) */}
        <BreadcrumbSchema />

        {/* ✅ Fallback for browsers with JS disabled */}
        <noscript>
          <img
            height="1"
            width="1"
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=9902586063134427&ev=PageView&noscript=1"
          />
        </noscript>

        {/* Your App Components */}
        <Navbar />
        {/* <ChatBox /> */}
        <CursorDot />
        <DeferredPopup />
        {children}
        <Footer />
      </body>
    </html>
  );
}