"use client";

import React from "react";
import { usePathname } from "next/navigation";
import { Sidebar } from "@/components/dashboard/Sidebar";
import { TopNav } from "@/components/dashboard/TopNav";
import { DashboardShellProvider, useDashboardShell } from "@/components/dashboard/DashboardShellContext";
import { PaywallModal } from "@/components/paywall/PaywallModal";
import { ToastStack } from "@/components/dashboard/ToastStack";

/** Single PaywallModal instance for the dashboard shell, opened via useDashboardShell().openPaywall() — used by Pro-gated nav items (e.g. Projects). */
function GlobalPaywallModal() {
  const { isPaywallOpen, closePaywall } = useDashboardShell();
  return <PaywallModal isOpen={isPaywallOpen} onClose={closePaywall} onSuccessUpgrade={closePaywall} />;
}

function GlobalToasts() {
  const { toasts, dismissToast } = useDashboardShell();
  return <ToastStack toasts={toasts} onDismiss={dismissToast} />;
}

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();

  // Onboarding is optional — never block the scanner behind a wizard.
  if (pathname === "/dashboard/onboarding") {
    return <>{children}</>;
  }

  return (
    <DashboardShellProvider>
      <div
        data-testid="dashboard-layout-root"
        className="min-h-screen bg-[#F6F9FF] flex flex-row overflow-x-clip w-full relative selection:bg-black selection:text-white"
      >
        <Sidebar />

        <div className="flex-1 flex flex-col min-w-0 overflow-x-hidden w-full">
          <TopNav />
          <main
            data-testid="dashboard-main-content"
            className="flex-1 p-4 sm:p-6 lg:p-8 max-w-[1440px] w-full mx-auto overflow-x-hidden"
          >
            {children}
          </main>
        </div>
      </div>

      <GlobalPaywallModal />
      <GlobalToasts />
    </DashboardShellProvider>
  );
}
