"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Sidebar from "@/components/Sidebar/Sidebar";
import Navbar from "@/components/Navbar/Navbar";
import styles from "./layout.module.css";
import NotificationProvider from "@/components/NotificationProvider";
import { AppToaster } from "@/components/AppToaster";
import ChatBubble from "@/components/Chat/ChatBubble"; // ✅ ADD

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const [isAuthorized, setIsAuthorized] = useState(false);

  useEffect(() => {
    // ✅ Client-side auth check — replaces proxy.ts route protection
    const token =
      sessionStorage.getItem("access_token") ||
      localStorage.getItem("access_token");

    if (!token) {
      // ❌ No token → redirect to login
      router.replace("/login");
    } else {
      // ✅ Token exists → allow access
      setIsAuthorized(true);
    }
  }, [router]);

  // While checking auth, show nothing (prevents flash before redirect)
  if (!isAuthorized) {
    return null;
  }

  return (
    <div className={styles.shell}>
      <NotificationProvider />
      <AppToaster />
      <Sidebar />
      <div className={styles.right}>
        <Navbar />
        <main className={styles.main}>{children}</main>
      </div>

      {/* ✅ WhatsApp-style floating chat bubble — appears on ALL pages */}
      <ChatBubble />
    </div>
  );
}