import React, { useCallback, useEffect, useMemo, useRef, useState, } from "react"; import { Link, useLocation } from "react-router-dom"; import ImageWithBasePath from "../imageWithBasePath"; import { all_routes } from "../../../feature-module/router/all_routes"; import { useDispatch, useSelector } from "react-redux"; import { Dropdown } from "react-bootstrap"; import { setExpandMenu, setMiniSidebar, setMobileSidebar, setSidebarSearch, } from "../../data/redux/commonSlice"; import { HorizontalSidebarData } from "../../data/json/horizontalSidebar"; import { logout } from "../../data/redux/authSlice"; import { useNavigate } from "react-router-dom"; import { RootState } from "../../data/redux/store"; import { fetchNotificationsByUserId, Notification, markNotificationAsRead, markNotificationsAsRead, } from "../../../api/notification"; import { OverlayTrigger, Tooltip, Modal } from "react-bootstrap"; import { toast } from "react-toastify"; import { HeaderButtons } from "../../data/json/headerButton"; import TextCopy from "../textcopy"; import { logoutUser } from "../../../api/authService"; import { stopAutoLockWatcher } from "../../../api/autolock"; import ModalDeleteEffect from "../ModalDeleteEffect"; const Header = () => { const [subOpen, setSubopen] = useState(""); const [subsidebar, setSubsidebar] = useState(""); const [isFullscreen, setIsFullscreen] = useState(false); const [open, setOpen] = useState(false); const [show, setShow] = useState(false); const [showLogoutModal, setShowLogoutModal] = useState(false); const dropdownRef = useRef(null); const route = all_routes; const location = useLocation(); const dispatch = useDispatch(); const navigate = useNavigate(); const [searchValue, setSearchValue] = useState(""); const mobileSidebar = useSelector((state: any) => state.common.mobileSidebar); const miniSidebar = useSelector((state: any) => state.common.miniSidebar); const userId = useSelector((state: RootState) => state.auth.user_id); const token = localStorage.getItem("authToken") || ""; const [notifications, setNotifications] = useState([]); const [isLoading, setIsLoading] = useState(true); // or from from props/context const fetchAndSetNotifications = useCallback(async () => { try { if (!userId) return; const data = await fetchNotificationsByUserId(userId); setNotifications(data); } catch (err) { console.error("Failed to load notifications", err); } finally { setIsLoading(false); } }, [userId]); useEffect(() => { fetchAndSetNotifications(); // Initial fetch // ๐Ÿ” Poll every 60 seconds (adjust as needed) const interval = setInterval(() => { fetchAndSetNotifications(); }, 100000); return () => clearInterval(interval); }, [fetchAndSetNotifications]); useEffect(() => { const handleClickOutside = (e: MouseEvent) => { if ( dropdownRef.current && !dropdownRef.current.contains(e.target as Node) ) { setOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); useEffect(() => { dispatch(setSidebarSearch("")); // โœ… clear on route change }, [dispatch, location.pathname]); // Make logout modal draggable useEffect(() => { const setupModalDraggable = (modalElement: HTMLElement) => { if (modalElement.hasAttribute('data-draggable-setup')) return; modalElement.setAttribute('data-draggable-setup', 'true'); const modalDialog = modalElement.querySelector('.modal-dialog') as HTMLElement; const modalHeader = modalElement.querySelector('.modal-header') as HTMLElement; if (!modalDialog || !modalHeader) return; let isDragging = false; let initialX = 0; let initialY = 0; let startX = 0; let startY = 0; const resetPosition = () => { isDragging = false; modalDialog.style.position = ''; modalDialog.style.top = ''; modalDialog.style.left = ''; modalDialog.style.transform = ''; modalDialog.style.margin = ''; modalDialog.style.transition = ''; modalDialog.style.width = ''; modalDialog.style.maxWidth = ''; if (!modalDialog.classList.contains('modal-dialog-centered')) { modalDialog.classList.add('modal-dialog-centered'); } }; const dragStart = (e: MouseEvent) => { const target = e.target as HTMLElement; if (target.closest('.btn-close') || target.closest('button') || target.closest('input') || target.closest('select')) { return; } if (e.target === modalHeader || modalHeader.contains(e.target as Node)) { isDragging = true; modalHeader.style.cursor = 'move'; const rect = modalDialog.getBoundingClientRect(); startX = rect.left; startY = rect.top; const computedStyle = getComputedStyle(modalDialog); const currentWidth = computedStyle.width; const currentMaxWidth = computedStyle.maxWidth; const currentMinWidth = computedStyle.minWidth; modalDialog.classList.remove('modal-dialog-centered'); modalDialog.style.position = 'fixed'; modalDialog.style.top = `${startY}px`; modalDialog.style.left = `${startX}px`; modalDialog.style.margin = '0'; modalDialog.style.transform = 'none'; modalDialog.style.transition = 'none'; if (currentWidth && currentWidth !== 'auto' && currentWidth !== '0px') { modalDialog.style.width = currentWidth; } if (currentMaxWidth && currentMaxWidth !== 'none' && currentMaxWidth !== '0px') { modalDialog.style.maxWidth = currentMaxWidth; } if (currentMinWidth && currentMinWidth !== '0px' && currentMinWidth !== 'auto') { modalDialog.style.minWidth = currentMinWidth; } initialX = e.clientX - startX; initialY = e.clientY - startY; } }; const drag = (e: MouseEvent) => { if (!isDragging) return; e.preventDefault(); const newX = e.clientX - initialX; const newY = e.clientY - initialY; const rect = modalDialog.getBoundingClientRect(); const maxX = window.innerWidth - rect.width; const maxY = window.innerHeight - rect.height; const constrainedX = Math.max(0, Math.min(newX, maxX)); const constrainedY = Math.max(0, Math.min(newY, maxY)); modalDialog.style.left = `${constrainedX}px`; modalDialog.style.top = `${constrainedY}px`; }; const dragEnd = () => { if (isDragging) { isDragging = false; modalHeader.style.cursor = 'move'; modalDialog.style.transition = ''; } }; modalHeader.style.cursor = 'move'; modalHeader.style.userSelect = 'none'; modalHeader.addEventListener('mousedown', dragStart); document.addEventListener('mousemove', drag); document.addEventListener('mouseup', dragEnd); const handleHidden = () => { resetPosition(); modalElement.removeAttribute('data-draggable-setup'); }; modalElement.addEventListener('hidden.bs.modal', handleHidden); }; const checkAndSetup = () => { const modals = document.querySelectorAll('.modal.show'); modals.forEach((modal) => { const modalEl = modal as HTMLElement; const title = modalEl.querySelector('.modal-title')?.textContent || ''; if (title.includes('Logout') && !modalEl.hasAttribute('data-draggable-setup')) { setTimeout(() => setupModalDraggable(modalEl), 50); } }); }; const interval = setInterval(checkAndSetup, 100); return () => { clearInterval(interval); }; }, [showLogoutModal]); const getInitials = useCallback((name?: string): string | null => { if (!name) return null; const parts = name.trim().split(" "); if (parts.length === 1) return parts[0][0].toUpperCase(); return (parts[0][0] + parts[1][0]).toUpperCase(); }, []); const userName = useSelector((state: RootState) => state.auth.username); const userRole = useSelector((state: RootState) => state.auth.role); const userEmail = useSelector((state: RootState) => state.auth.e_mail); const handleNotificationClick = useCallback( async (clickedNotification: Notification) => { try { if (!clickedNotification.is_read) { await markNotificationsAsRead(clickedNotification.id); } // Optimistically update just the clicked one setNotifications((prev) => prev.map((n) => n.id === clickedNotification.id ? { ...n, is_read: true } : n ) ); navigate(`${route.activities}?highlight=${clickedNotification.id}`); } catch (err) { console.error("Failed to mark notification as read", err); } }, [navigate, route.activities] ); const toggleMobileSidebar = useCallback(() => { dispatch(setMobileSidebar(!mobileSidebar)); }, [dispatch, mobileSidebar]); const toggleMiniSidebar = useCallback(() => { dispatch(setMiniSidebar(!miniSidebar)); }, [dispatch, miniSidebar]); const toggleExpandMenu = useCallback(() => { dispatch(setExpandMenu(true)); }, [dispatch]); const toggleExpandMenu2 = useCallback(() => { dispatch(setExpandMenu(false)); }, [dispatch]); const [layoutBs, setLayoutBs] = useState(localStorage.getItem("dataTheme")); const role = (userRole?.toLowerCase() || "user") as | "user" | "admin" | "superadmin" | "client"; const headerButtons = HeaderButtons[role]; const appButtons = headerButtons.filter((btn) => btn.type === "app"); const mid = Math.ceil(appButtons.length / 2); const leftColumn = appButtons.slice(0, mid); const rightColumn = appButtons.slice(mid); const isUser = role === "user"; const isAdmin = role === "admin"; const isSuperAdmin = role === "superadmin"; const isClient = role === "client"; const LayoutDark = useCallback(() => { localStorage.setItem("dataTheme", "dark"); document.documentElement.setAttribute("data-theme", "dark"); setLayoutBs("dark"); }, []); const LayoutLight = useCallback(() => { localStorage.setItem("dataTheme", "light"); document.documentElement.setAttribute("data-theme", "light"); setLayoutBs("light"); }, []); const toggleSidebar = useCallback( (title: any) => { localStorage.setItem("menuOpened", title); if (title === subOpen) { setSubopen(""); } else { setSubopen(title); } }, [subOpen] ); const toggleSubsidebar = useCallback( (subitem: any) => { if (subitem === subsidebar) { setSubsidebar(""); } else { setSubsidebar(subitem); } }, [subsidebar] ); const toggleFullscreen = useCallback(() => { if (!isFullscreen) { if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen().catch((err) => { }); setIsFullscreen(true); } } else { if (document.exitFullscreen) { if (document.fullscreenElement) { document.exitFullscreen().catch((err) => { }); } setIsFullscreen(false); } } }, [isFullscreen]); const handleLogout = useCallback(() => { setShowLogoutModal(true); }, []); const confirmLogout = useCallback(async () => { try { // ๐Ÿ” Call backend logout API await logoutUser(); stopAutoLockWatcher(); } catch (err) { console.error("Logout API failed โ€” proceeding with local logout."); } // ๐Ÿงน Clear Redux dispatch(logout()); // ๐Ÿšซ REMOVE history + go fresh to login navigate(all_routes.login, { replace: true }); toast.success("Logged out successfully"); setShowLogoutModal(false); }, [dispatch, navigate]); const handleLockScreen = useCallback(() => { // โœ… Mark app as locked (DO NOT remove token) localStorage.setItem("isLocked", "true"); // Optional: close dropdowns/modals if open setShow(false); // ๐Ÿ” Navigate to lock screen navigate(all_routes.lockScreen); }, [navigate]); const handleSearchChange = useCallback( (e: React.ChangeEvent) => { const value = e.target.value; setSearchValue(value); dispatch(setSidebarSearch(value.toLowerCase())); // case insensitive }, [dispatch] ); const sortedNotifications = useMemo(() => { return [...notifications] .sort( (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() ) .slice(0, 10); }, [notifications]); const logoRoute = useMemo(() => { if (!userRole) return route.leadsDashboard; switch (userRole.toLowerCase()) { case "superadmin": return route.superadminDashboard; case "admin": return route.dealsDashboard; case "client": return null; // ๐Ÿ”’ CLIENT โ†’ logo disabled case "user": default: return route.leadsDashboard; } }, [ userRole, route.superadminDashboard, route.dealsDashboard, route.leadsDashboard, ]); const isLockScreen = location.pathname === "/lock-screen"; if (isLockScreen) { return null; } const hasAccess = (roles?: string[]) => { if (!roles || roles.length === 0) return true; if (!userRole) return false; return roles.includes(userRole); }; const hasVisibleItem = (item: any): boolean => { if (hasAccess(item.roles)) return true; if (item.subMenus?.length) { return item.subMenus.some((sub: any) => hasVisibleItem(sub)); } if (item.subMenusTwo?.length) { return item.subMenusTwo.some((inner: any) => hasAccess(inner.roles) ); } return false; }; return ( <> {/* Header */}
{/* Logo */}
{/* LOGO (disabled for CLIENT role) */} {logoRoute ? ( <>

CRM

CRM

) : ( <>

CRM

CRM

)} Toggle Sidebar} >
{/* /Logo */}
    {/* Search */}
  • {/* /Search */}
    • Main
    • {HorizontalSidebarData?.map((mainMenu, index) => ( {mainMenu?.menu ?.filter((data: any) => hasVisibleItem(data)) .map((data, i) => (
    • link?.route) .includes(location.pathname) ? "active" : "" } ${subOpen === data.menuValue ? "subdrop" : ""}`} onClick={() => toggleSidebar(data.menuValue)} > {data.menuValue} {/* First-level Submenus */}
        {data?.subMenus ?.filter((subMenu: any) => hasVisibleItem(subMenu)) .map((subMenu: any, j) => (
      • link?.route) .includes(location.pathname) || subMenu?.route === location.pathname ? "active" : "" } ${subsidebar === subMenu.menuValue ? "subdrop" : "" }`} onClick={() => toggleSubsidebar(subMenu.menuValue) } > {subMenu?.menuValue} {subMenu?.customSubmenuTwo && ( )} {/* Check if `customSubmenuTwo` exists */} {subMenu?.customSubmenuTwo && subMenu?.subMenusTwo && (
          {subMenu.subMenusTwo .filter((subMenuTwo: any) => hasAccess(subMenuTwo.roles) ) .map( (subMenuTwo: any, k: number) => (
        • {subMenuTwo.menuValue}
        • ) )}
        )}
      • ))}
    • ))}
      ))}
  • {/* Nav List */}
    • Fullscreen } > e.currentTarget.classList.add( "bg-primary", "text-white" ) } onMouseLeave={(e) => e.currentTarget.classList.remove( "bg-primary", "text-white" ) } >
    • Light Mode} > Dark Mode} >
    • {/*
    • */} Apps Menu} > { e.currentTarget.style.backgroundColor = "#108678ff"; e.currentTarget.style.color = "#fff"; }} onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = "#cfe9e6"; e.currentTarget.style.color = "#108678ff"; }} >
      {/* LEFT COLUMN */}
        {leftColumn.map((btn, index) => (
      • {btn.label}

        Open {btn.label}
      • ))}
      {/* RIGHT COLUMN */}
        {rightColumn.map((btn, index) => (
      • {btn.label}

        Open {btn.label}
      • ))}
      {!isUser && !isSuperAdmin && !isClient && ( Reports} > { e.currentTarget.style.backgroundColor = "#f5d60eff"; e.currentTarget.style.color = "#fff"; }} onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = "#fff2beff"; e.currentTarget.style.color = "#f5d60eff"; }} >
        {headerButtons .filter((btn) => btn.type === "report") .map((btn, index) => (
      • {btn.label}

        View {btn.label}
      • ))}
      )}
  • {/* /Nav List */} {/* Email */} {/*
  • 14
  • */} {/* /Email */} {!isSuperAdmin && ( setShow(isOpen)} // control dropdown > Notifications } > { e.currentTarget.style.backgroundColor = "#ac5259ff"; e.currentTarget.style.color = "#fff"; }} onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = "#e3acb1ff"; e.currentTarget.style.color = "#721b22ff"; }} > {notifications.some((n) => !n.is_read) && ( {notifications.filter((n) => !n.is_read).length} )} {/* Header */} {/* Content */}
      {notifications.length === 0 ? (
    • No notifications available
    • ) : ( sortedNotifications.map((notification) => (
    • { e.preventDefault(); handleNotificationClick(notification); // โœ… close dropdown after click setShow(false); }} style={{ textDecoration: "none" }} >

      {!notification.is_read && ( )} {notification.message}

      {new Date( notification.created_at ).toLocaleString()}

    • )) )}
    {/* Footer */}
    setShow(false)} // โœ… close when "View all" clicked > View all {notifications.some((n) => !n.is_read) && ( { e.preventDefault(); const unreadIds = notifications .filter((n) => !n.is_read) .map((n) => n.id); if (unreadIds.length > 0) { try { await markNotificationsAsRead(unreadIds); setNotifications((prev) => prev.map((n) => unreadIds.includes(n.id) ? { ...n, is_read: true } : n ) ); toast.success("Marked all notifications as read"); } catch (err) { console.error("Failed to mark all as read", err); } } // โœ… close after marking all as read setShow(false); }} > Mark all as read )}
    )} {/* /Notifications */} {/* /Notifications */} {/* Profile Dropdown */} Profile} > {getInitials(userName || "Unknown") ? ( {getInitials(userName || "Unknown")} ) : ( )} {/* Green active indicator dot */} {/* User info header (fallback-safe) */}
    {userName || "Unknown" ? ( <> {/* Avatar (re-use toggle logic) */}
    {/* Avatar */}
    {getInitials(userName || "Unknown") ? ( {getInitials(userName || "Unknown")} ) : ( )}
    {/* Name */}
    {userName || "Unknown" || "โ€”"}
    {/* Role Badge (only Admin/User) */} {userRole || "User"} {/* Email - One line, no break, show tooltip if long */} {/*

    {user?.email || "โ€”"}

    */}
    ) : ( <>

    )}
    { e.currentTarget.classList.add( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold", "rounded-3" // keep corners rounded on hover ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-light", "text-dark"); // <-- remove white bg icon.classList.add("bg-dark", "text-white"); // <-- add black bg } }} onMouseLeave={(e) => { e.currentTarget.classList.remove( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold", "rounded-3" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-dark", "text-white"); // <-- remove black icon.classList.add("bg-light", "text-dark"); // <-- restore white } }} > {" "} My Profile { e.currentTarget.classList.add( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold", "rounded-3" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-light", "text-dark"); icon.classList.add("bg-dark", "text-white"); } }} onMouseLeave={(e) => { e.currentTarget.classList.remove( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold", "rounded-3" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-dark", "text-white"); icon.classList.add("bg-light", "text-dark"); } }} > Lock Screen {/* Logout */} { e.currentTarget.classList.add( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold", "rounded-3" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-light", "text-dark"); // <-- remove white bg icon.classList.add("bg-dark", "text-white", "rounded-2"); // <-- add black bg } }} onMouseLeave={(e) => { e.currentTarget.classList.remove( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold", "rounded-3" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove( "bg-dark", "text-white", "rounded-2" ); // <-- remove black icon.classList.add("bg-light", "text-dark", "rounded-2"); // <-- restore white } }} > {" "} Logout
    {/* /Profile Dropdown */}
{/* Mobile Menu */}
{/* Dashboard */} {/* { e.currentTarget.classList.add( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-light", "text-dark"); // <-- remove white bg icon.classList.add("bg-dark", "text-white"); // <-- add black bg } }} onMouseLeave={(e) => { e.currentTarget.classList.remove( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-dark", "text-white"); // <-- remove black icon.classList.add("bg-light", "text-dark"); // <-- restore white } }} > Dashboard */} {/* My Profile */} { e.currentTarget.classList.add( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-light", "text-dark"); // <-- remove white bg icon.classList.add("bg-dark", "text-white"); // <-- add black bg } }} onMouseLeave={(e) => { e.currentTarget.classList.remove( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-dark", "text-white"); // <-- remove black icon.classList.add("bg-light", "text-dark"); // <-- restore white } }} > My Profile { e.preventDefault(); handleLockScreen(); }} > Lock Screen {/* Logout */} { e.preventDefault(); handleLogout(); }} onMouseEnter={(e) => { e.currentTarget.classList.add( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-light", "text-dark"); // <-- remove white bg icon.classList.add("bg-dark", "text-white"); // <-- add black bg } }} onMouseLeave={(e) => { e.currentTarget.classList.remove( "bg-grey", "bg-opacity-25", "text-dark", "fw-semibold" ); const icon = e.currentTarget.querySelector("i"); if (icon) { icon.classList.remove("bg-dark", "text-white"); // <-- remove black icon.classList.add("bg-light", "text-dark"); // <-- restore white } }} > Logout
{/* /Mobile Menu */}
{/* Logout Confirmation Modal */} setShowLogoutModal(false)} centered className="effect-modal-show" >
Logout

Are you sure you want to logout?

You will be logged out of your account.

); }; export default Header;