import type { Metadata, Viewport } from "next";
import type { ReactNode } from "react";
import "./globals.css";
import { getSessionUser } from "@/lib/auth";
import { getNotifications } from "@/lib/data";
import { SessionProvider } from "@/components/session-provider";
import { AppShell } from "@/components/app-shell";
import { ServiceWorker } from "@/components/service-worker";
import { CookieConsent } from "@/components/cookie-consent";
import { CATEGORIES } from "@/lib/constants";

export const metadata: Metadata = {
  title: {
    default: "PlayTube — watch, upload and go live",
    template: "%s · PlayTube",
  },
  description:
    "PlayTube is a full video platform: adaptive HLS streaming, shorts, live streams with real-time chat, playlists, creator analytics and monetization.",
  applicationName: "PlayTube",
  manifest: "/manifest.webmanifest",
  appleWebApp: {
    capable: true,
    title: "PlayTube",
    statusBarStyle: "black-translucent",
  },
  formatDetection: { telephone: false },
  icons: {
    icon: [
      { url: "/icons/icon-192.png", sizes: "192x192", type: "image/png" },
      { url: "/icons/icon-512.png", sizes: "512x512", type: "image/png" },
    ],
    apple: [{ url: "/icons/icon-192.png", sizes: "192x192", type: "image/png" }],
  },
  openGraph: {
    title: "PlayTube",
    description: "Watch, upload and go live on PlayTube.",
    type: "website",
    siteName: "PlayTube",
  },
  twitter: { card: "summary_large_image", title: "PlayTube" },
  keywords: ["video", "streaming", "shorts", "live", "PlayTube"],
};

export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  maximumScale: 5,
  viewportFit: "cover",
  themeColor: [
    { media: "(prefers-color-scheme: dark)", color: "#0f0f0f" },
    { media: "(prefers-color-scheme: light)", color: "#ffffff" },
  ],
};

const themeScript = `(() => {
  try {
    const stored = localStorage.getItem("playtube-theme");
    const theme = stored === "light" || stored === "dark"
      ? stored
      : (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
    document.documentElement.setAttribute("data-theme", theme);
    const lang = localStorage.getItem("playtube-lang") || "en";
    document.documentElement.setAttribute("lang", lang);
  } catch (e) {}
})();`;

export default async function RootLayout({ children }: { children: ReactNode }) {
  // Resilient on purpose: a fresh install has no DATABASE_URL / tables yet,
  // and the /setup wizard must still render.
  let session: Awaited<ReturnType<typeof getSessionUser>> = null;
  let unread = 0;
  try {
    session = await getSessionUser();
    if (session) {
      const items = await getNotifications(session.user.id, 40);
      unread = items.filter((n) => !n.isRead).length;
    }
  } catch {
    session = null;
  }

  return (
    <html lang="en" data-theme="dark" suppressHydrationWarning>
      <head>
        <script dangerouslySetInnerHTML={{ __html: themeScript }} />
      </head>
      <body className="bg-bg text-fg antialiased">
        <SessionProvider
          initialUser={
            session
              ? {
                  id: session.user.id,
                  email: session.user.email,
                  displayName: session.user.displayName,
                  handle: session.user.handle,
                  avatarUrl: session.user.avatarUrl,
                  role: session.user.role,
                  emailVerified: session.user.emailVerified,
                  language: session.user.language,
                  theme: session.user.theme,
                }
              : null
          }
          initialChannel={
            session?.channel
              ? {
                  id: session.channel.id,
                  name: session.channel.name,
                  handle: session.channel.handle,
                  avatarUrl: session.channel.avatarUrl,
                  bannerUrl: session.channel.bannerUrl,
                  isVerified: session.channel.isVerified,
                  isMonetized: session.channel.isMonetized,
                }
              : null
          }
          initialUnread={unread}
          categories={CATEGORIES}
        >
          <AppShell>{children}</AppShell>
          <CookieConsent />
          <ServiceWorker />
        </SessionProvider>
      </body>
    </html>
  );
}
