import type { Metadata } from "next";
import { Suspense } from "react";
import "./app.css";
import AppShell from "@/components/layout/AppShell";
import { ThemeProvider } from "@/components/layout/ThemeProvider";
import { brand } from "@/lib/brand";
import { getCurrentUser } from "@/lib/currentUser";
import { startDailyOptimizerAgentScheduler } from "@/lib/profitOptimizer/agentScheduler";

export const metadata: Metadata = {
  title: { default: brand.productName, template: `%s · ${brand.name}` },
  description: brand.description,
  metadataBase: new URL(brand.url),
};

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  // Start the in-process daily agent on real server requests. The scheduler is
  // guarded by a global singleton so navigation/dev reloads cannot duplicate it.
  startDailyOptimizerAgentScheduler();
  const account = await getCurrentUser().catch(() => null);
  const currentUser = account ? { id: account.id, username: account.username, role: account.role } : null;
  return (
    <html lang="id">
      <body>
        <ThemeProvider>
          <Suspense fallback={<main className="min-h-dvh bg-slate-100">{children}</main>}>
            <AppShell currentUser={currentUser}>{children}</AppShell>
          </Suspense>
        </ThemeProvider>
      </body>
    </html>
  );
}
