"use client";

import React, { useEffect, useState, useCallback } from "react";
import Sidebar from "@/components/Sidebar/Sidebar";
import Navbar from "@/components/Navbar/Navbar";
import { useRouter } from "next/navigation";
import { ClientNotificationProvider } from "@/lib/api/hooks/useClientNotifications";

// 🔧 PORTAL-FIX: How often to check if the client is still allowed in (in ms).
//    30 seconds is a good balance — fast enough that a disabled user gets kicked
//    within 30 seconds, but not so fast that it hammers the server.
const SESSION_CHECK_INTERVAL = 30_000;

export default function ClientDashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  // Start in a "checking" state so we NEVER redirect before we've actually
  // read localStorage on the client. This removes the race where the layout
  // redirected during hydration before the token was readable.
  const [authState, setAuthState] = useState<"checking" | "ok">("checking");

  // 🔧 PORTAL-FIX: Centralized logout — clears tokens, redirects to login.
  //    Called when token is missing, expired, or server returns 401.
  const forceLogout = useCallback(() => {
    localStorage.removeItem("clientPortalToken");
    localStorage.removeItem("clientUser");
    router.replace("/client/login");
  }, [router]);

  // 🔧 PORTAL-FIX: Lightweight session check — pings a protected endpoint.
  //    If the guard returns 401 (disabled user), clientFetch auto-redirects.
  //    If fetch fails for network reasons, we don't log out (just retry next cycle).
  const checkSession = useCallback(async () => {
    const token = localStorage.getItem("clientPortalToken");
    if (!token) {
      forceLogout();
      return;
    }

    try {
      const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3008/api";
      const res = await fetch(`${API_BASE}/client-portal/company`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      });

      if (res.status === 401) {
        // 🔧 Server said unauthorized — admin disabled this user.
        //    Clear everything and redirect to login.
        forceLogout();
      }
      // Any other status (200, 500, etc.) — session is still valid, do nothing.
    } catch {
      // Network error — don't log out, just retry next cycle.
    }
  }, [forceLogout]);

  useEffect(() => {
    const token = localStorage.getItem("clientPortalToken");
    if (!token) {
      // genuinely no token → go to client login
      router.replace("/client/login");
      return;
    }
    // token present → render the dashboard
    setAuthState("ok");

    // 🔧 PORTAL-FIX: Start the periodic session check.
    //    Every 30 seconds, ping the server to verify the client is still allowed.
    //    If admin disabled them, the guard returns 401 → auto-logout.
    const interval = setInterval(checkSession, SESSION_CHECK_INTERVAL);

    // Cleanup on unmount
    return () => clearInterval(interval);
  }, [router, checkSession]);

  // While we haven't confirmed the token yet, render nothing (no redirect,
  // no flash). This is the key: we only redirect INSIDE the effect, after
  // actually reading localStorage — never during the first render.
  if (authState === "checking") {
    return (
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "center",
        height: "100vh", color: "#94a3b8", fontFamily: "Inter, system-ui, sans-serif",
      }}>
        Loading your portal…
      </div>
    );
  }

  return (
    <div style={{ display: "flex", height: "100vh", background: "#f8fafc" }}>
      <ClientNotificationProvider />
      <Sidebar isClientPortal={true} />
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <Navbar isClientPortal={true} />
        <main style={{ flex: 1, overflow: "auto", padding: "20px" }}>
          {children}
        </main>
      </div>
    </div>
  );
}