import type { Metadata, Viewport } from "next";
import nextDynamic from "next/dynamic";
import { DISCORD_INVITE_URL, SITE_NAME } from "@/lib/constants";
import { getSiteUrl } from "@/lib/site-url";
import ToastProvider from "@/components/Toast";
import "./globals.css";

const BugReportWidget = nextDynamic(() => import("@/components/BugReportWidget"));
const SuggestWidget = nextDynamic(() => import("@/components/SuggestWidget"));
const DiscordDropClaimPopup = nextDynamic(() => import("@/components/DiscordDropClaimPopup"));
const DiscordActivityBridge = nextDynamic(() => import("@/components/DiscordActivityBridge"));

const themeInit = `try{var t=localStorage.getItem("profile-theme");if(t==="light"||t==="dark")document.documentElement.dataset.theme=t;}catch(e){}`;

const recoveryRedirectInit = `try{
  var h=window.location.hash;
  if(h){
    var isRecovery=h.indexOf("type=recovery")!==-1;
    var isExpired=h.indexOf("error_code=otp_expired")!==-1||(h.indexOf("error=")!==-1&&h.indexOf("recovery")!==-1);
    if(isRecovery&&window.location.pathname!=="/reset-password"){
      window.location.replace("/reset-password"+h);
    }else if(isExpired&&window.location.pathname!=="/login"){
      window.location.replace("/login?error="+encodeURIComponent("Your password reset link is invalid or has expired. Please request a new one."));
    }
  }
}catch(e){}`;

const acquisitionInit = "try{if(!document.cookie.includes('sinss_acq=')){var r=document.referrer||'';var p=window.location.pathname||'/';var q=new URLSearchParams(window.location.search);var s=q.get('utm_source')||'';var cp=q.get('utm_campaign')||'';var ref=q.get('ref')||'';var d='';if(r){try{d=new URL(r).hostname.toLowerCase().replace(/^www\\./,'');}catch(_){}}var data={r:r?r.slice(0,500):undefined,d:d||undefined,p:p.slice(0,100),s:s||undefined,c:cp||undefined,ref:ref||undefined};document.cookie='sinss_acq='+encodeURIComponent(JSON.stringify(data))+';path=/;max-age=2592000;SameSite=Lax';}}catch(e){}";

const websiteJsonLd = {
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "WebSite",
      "@id": "https://www.sinss.lol/#website",
      name: SITE_NAME,
      url: "https://www.sinss.lol",
      description: "Customizable bio link pages for your music, Discord presence, socials, and online identity.",
      potentialAction: {
        "@type": "SearchAction",
        target: "https://www.sinss.lol/{search_term_string}",
        "query-input": "required name=search_term_string",
      },
    },
    {
      "@type": "Organization",
      "@id": "https://www.sinss.lol/#organization",
      name: SITE_NAME,
      url: "https://www.sinss.lol",
      logo: "https://www.sinss.lol/sinss-mark.svg",
      sameAs: [DISCORD_INVITE_URL],
    },
    {
      "@type": "WebApplication",
      "@id": "https://www.sinss.lol/#software",
      name: SITE_NAME,
      url: "https://www.sinss.lol",
      applicationCategory: "SocialNetworkingApplication",
      operatingSystem: "Web, iOS, Android",
      description: "Customizable bio link platform featuring animated video backgrounds, multi-track audio with synced lyrics, custom cursor effects, and real-time Discord presence.",
      browserRequirements: "Requires JavaScript. Requires HTML5.",
      offers: [
        {
          "@type": "Offer",
          name: "Free Plan",
          price: "0.00",
          priceCurrency: "USD",
          description: "Free customizable bio link profile with audio player, visual effects, and analytics.",
        },
        {
          "@type": "Offer",
          name: "Lifetime Premium",
          price: "6.99",
          priceCurrency: "USD",
          description: "One-time lifetime upgrade with 5 profiles, video backgrounds, custom badges, image hosting, and priority showcase.",
        },
      ],
      featureList: [
        "Six customizable profile layouts (classic, portfolio, scroll, compact, minimal, banner)",
        "Real-time Discord presence, status syncing, and guild clan tags",
        "Multi-track background audio player with synchronized lyrics",
        "Custom video backgrounds, animated gradients, and visual particle effects",
        "Custom cursor upload and particle trails",
        "Real-time visitor analytics and outbound link click tracking",
        "Community leaderboard and custom badge verification",
      ],
    },
  ],
};

const pageTitle = `${SITE_NAME} — Customizable Bio Link & Discord Profiles`;
const pageDescription = "Create a customizable bio link page for your links, music, Discord presence, and socials. Fast, free, and fully personal.";

export const metadata: Metadata = {
  metadataBase: new URL(getSiteUrl()),
  title: {
    default: pageTitle,
    template: `%s | ${SITE_NAME}`,
  },
  description: pageDescription,
  keywords: [
    "bio link",
    "link in bio",
    "discord bio link",
    "custom bio page",
    "sinss.lol",
    "discord presence bio",
    "linktree alternative",
    "social links profile",
  ],
  authors: [{ name: SITE_NAME, url: "https://www.sinss.lol" }],
  creator: SITE_NAME,
  publisher: SITE_NAME,
  openGraph: {
    type: "website",
    url: "/",
    siteName: SITE_NAME,
    title: pageTitle,
    description: pageDescription,
    locale: "en_US",
  },
  twitter: {
    card: "summary_large_image",
    title: pageTitle,
    description: pageDescription,
  },
  icons: {
    icon: [
      { url: "/sinss-mark.svg", type: "image/svg+xml" },
      { url: "/favicon.ico", sizes: "any", type: "image/x-icon" },
    ],
    shortcut: "/sinss-mark.svg",
    apple: "/apple-touch-icon.png",
  },
  verification: {
    other: {
      "msvalidate.01": ["0332A24A2A5F5CAD0C9BD89394594ABE"],
    },
  },
};

export const viewport: Viewport = {
  themeColor: "#f8e3e3",
};

const FONTS_HREF =
  "https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Sans:wght@400;500;600;700&family=Fira+Code:wght@400;500;600;700&family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600;700&family=Manrope:wght@400;500;600;700;800&family=Merriweather:wght@400;700;900&family=Oswald:wght@400;500;600;700&family=Outfit:wght@400;500;600;700;800&family=Playfair+Display:wght@400;500;600;700;800&family=Poppins:wght@400;500;600;700;800&family=Rubik:wght@400;500;600;700;800&family=Source+Sans+3:wght@400;500;600;700;800&family=Space+Grotesk:wght@400;500;600;700&display=swap";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <meta name="darkreader-lock" />
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <link rel="preload" as="style" href={FONTS_HREF} />
        <link rel="stylesheet" href={FONTS_HREF} />
        <script dangerouslySetInnerHTML={{ __html: themeInit }} />
        <script dangerouslySetInnerHTML={{ __html: recoveryRedirectInit }} />
        <script dangerouslySetInnerHTML={{ __html: acquisitionInit }} />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(websiteJsonLd) }}
        />
      </head>
      <body suppressHydrationWarning>
        <ToastProvider>
          {children}
          <DiscordDropClaimPopup />
          <BugReportWidget />
          <SuggestWidget />
          <DiscordActivityBridge />
        </ToastProvider>
      </body>
    </html>
  );
}
