"use client";

import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Bell } from "lucide-react";

import { UserSidebar } from "@/components/layout/user-sidebar";
import { useAuthStore } from "@/stores/auth-store";

const PAGE_TITLES: Record<string, string> = {
  "/dashboard": "Dashboard",
  "/dashboard/reports": "My Reports",
  "/dashboard/subscription": "Subscription & Billing",
  "/dashboard/profile": "My Profile",
};

function getPageTitle(pathname: string): string {
  // Exact match first
  if (PAGE_TITLES[pathname]) return PAGE_TITLES[pathname];
  // Report detail
  if (pathname.startsWith("/dashboard/reports/")) return "Report Viewer";
  return "Dashboard";
}

export default function UserLayout({ children }: { children: ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const { isAuthenticated, loadFromStorage } = useAuthStore();
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    loadFromStorage();
    setChecked(true);
  }, [loadFromStorage]);

  useEffect(() => {
    if (checked && !isAuthenticated) {
      router.replace("/auth/login");
    }
  }, [checked, isAuthenticated, router]);

  if (!checked || !isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="flex flex-col items-center gap-3">
          <div className="w-10 h-10 rounded-full border-4 border-teal-600 border-t-transparent animate-spin" />
          <p className="text-gray-500 text-sm">Loading…</p>
        </div>
      </div>
    );
  }

  const pageTitle = getPageTitle(pathname);

  return (
    <div className="min-h-screen bg-gray-50 flex">
      {/* Sidebar */}
      <UserSidebar />

      {/* Main content */}
      <div className="flex-1 flex flex-col lg:pl-64 min-w-0">
        {/* Top header */}
        <header className="bg-white border-b border-gray-100 px-4 sm:px-6 lg:px-8 h-14 flex items-center justify-between sticky top-0 z-20 shadow-sm">
          {/* Left spacer for mobile hamburger */}
          <div className="w-10 lg:w-0" />
          <h1 className="text-base font-semibold text-gray-900 lg:text-left absolute left-1/2 -translate-x-1/2 lg:static lg:translate-x-0">
            {pageTitle}
          </h1>
          <button className="h-8 w-8 rounded-lg flex items-center justify-center hover:bg-gray-100 transition-colors relative">
            <Bell className="h-4.5 w-4.5 text-gray-500" style={{ width: "18px", height: "18px" }} />
            <span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-teal-600" />
          </button>
        </header>

        {/* Page content */}
        <main className="flex-1 px-4 sm:px-6 lg:px-8 py-6 max-w-5xl w-full mx-auto">
          {children}
        </main>
      </div>
    </div>
  );
}
