CRM/src/core/common/header/index.tsx

1516 lines
57 KiB
TypeScript

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<any>("");
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<HTMLLIElement>(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<Notification[]>([]);
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<HTMLInputElement>) => {
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 */}
<div className="header">
{/* Logo */}
<div
className="header-left active"
onMouseEnter={toggleExpandMenu}
onMouseLeave={toggleExpandMenu2}
>
{/* LOGO (disabled for CLIENT role) */}
{logoRoute ? (
<>
<Link to={logoRoute} className="logo logo-normal mt-2 mb-2" style={{ textDecoration: 'none' }}>
<h3 style={{ color: '#8B5CF6', margin: 0, fontWeight: 'bold' }}>CRM</h3>
</Link>
<Link to={logoRoute} className="logo-small" style={{ textDecoration: 'none' }}>
<h3 style={{ color: '#8B5CF6', margin: 0, fontWeight: 'bold', fontSize: '18px' }}>CRM</h3>
</Link>
</>
) : (
<>
<div
className="logo logo-normal mt-2 mb-2"
style={{ cursor: "not-allowed", opacity: 0.6, textDecoration: 'none' }}
>
<h3 style={{ color: '#8B5CF6', margin: 0, fontWeight: 'bold' }}>CRM</h3>
</div>
<div
className="logo-small"
style={{ cursor: "not-allowed", opacity: 0.6, textDecoration: 'none' }}
>
<h3 style={{ color: '#8B5CF6', margin: 0, fontWeight: 'bold', fontSize: '18px' }}>CRM</h3>
</div>
</>
)}
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="tooltip-toggle">Toggle Sidebar</Tooltip>}
>
<Link id="toggle_btn" to="#" onClick={toggleMiniSidebar}>
<i className="ti ti-arrow-bar-to-left" />
</Link>
</OverlayTrigger>
</div>
{/* /Logo */}
<Link
id="mobile_btn"
className="mobile_btn"
to="#sidebar"
onClick={toggleMobileSidebar}
>
<span className="bar-icon">
<span />
<span />
<span />
</span>
</Link>
<div className="header-user">
<ul className="nav user-menu">
{/* Search */}
<li className="nav-item nav-search-inputs me-auto">
<div className="top-nav-search">
<Link to="#" className="responsive-search">
<i className="fa fa-search" />
</Link>
<form className="dropdown">
<div className="searchinputs" id="dropdownMenuClickable">
<span className="form-icon me-2">
<i className="ti ti-search" />
</span>
<input
type="text"
placeholder="Search"
value={searchValue}
onChange={handleSearchChange}
/>
{/* <div className="search-addon">
<button type="submit">
<i className="ti ti-command" />
</button>
</div> */}
</div>
</form>
</div>
</li>
{/* /Search */}
<li>
<div
className="sidebar sidebar-horizontal"
id="horizontal-single"
>
<div className="sidebar-menu">
<div className="main-menu">
<ul className="nav-menu">
<li className="menu-title">
<span>Main</span>
</li>
{HorizontalSidebarData?.map((mainMenu, index) => (
<React.Fragment key={`main-${index}`}>
{mainMenu?.menu
?.filter((data: any) => hasVisibleItem(data))
.map((data, i) => (
<li className="submenu" key={`menu-${i}`}>
<Link
to="#"
className={`
${data?.subMenus
?.map((link: any) => link?.route)
.includes(location.pathname)
? "active"
: ""
} ${subOpen === data.menuValue ? "subdrop" : ""}`}
onClick={() => toggleSidebar(data.menuValue)}
>
<i className={`ti ti-${data.icon}`}></i>
<span>{data.menuValue}</span>
<span className="menu-arrow"></span>
</Link>
{/* First-level Submenus */}
<ul
style={{
display:
subOpen === data.menuValue
? "block"
: "none",
}}
>
{data?.subMenus
?.filter((subMenu: any) => hasVisibleItem(subMenu))
.map((subMenu: any, j) => (
<li
key={`submenu-${j}`}
className={
subMenu?.customSubmenuTwo ? "submenu" : ""
}
>
<Link
to={subMenu?.route || "#"}
className={`${subMenu?.subMenusTwo
?.map((link: any) => link?.route)
.includes(location.pathname) ||
subMenu?.route === location.pathname
? "active"
: ""
} ${subsidebar === subMenu.menuValue
? "subdrop"
: ""
}`}
onClick={() =>
toggleSubsidebar(subMenu.menuValue)
}
>
<span>{subMenu?.menuValue}</span>
{subMenu?.customSubmenuTwo && (
<span className="menu-arrow"></span>
)}
</Link>
{/* Check if `customSubmenuTwo` exists */}
{subMenu?.customSubmenuTwo &&
subMenu?.subMenusTwo && (
<ul
style={{
display:
subsidebar === subMenu.menuValue
? "block"
: "none",
}}
>
{subMenu.subMenusTwo
.filter((subMenuTwo: any) =>
hasAccess(subMenuTwo.roles)
)
.map(
(subMenuTwo: any, k: number) => (
<li key={`submenu-two-${k}`}>
<Link
className={
subMenuTwo.route ===
location.pathname
? "active"
: ""
}
to={subMenuTwo.route}
>
{subMenuTwo.menuValue}
</Link>
</li>
)
)}
</ul>
)}
</li>
))}
</ul>
</li>
))}
</React.Fragment>
))}
</ul>
</div>
</div>
</div>
</li>
{/* Nav List */}
<li className="nav-item nav-list">
<ul className="nav">
<li>
<OverlayTrigger
placement="bottom"
overlay={
<Tooltip id="tooltip-fullscreen">Fullscreen</Tooltip>
}
>
<Link
to="#"
onClick={toggleFullscreen}
className="btn btn-icon border btn-menubar btnFullscreen"
onMouseEnter={(e) =>
e.currentTarget.classList.add(
"bg-primary",
"text-white"
)
}
onMouseLeave={(e) =>
e.currentTarget.classList.remove(
"bg-primary",
"text-white"
)
}
>
<i className="ti ti-maximize"></i>
</Link>
</OverlayTrigger>
</li>
<li className="dark-mode-list">
<Link
to="#"
className={`dark-mode-toggle ${layoutBs ? "" : "active"}`}
id="dark-mode-toggle"
>
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="tooltip-light">Light Mode</Tooltip>}
>
<i
className={`ti ti-sun light-mode ${layoutBs === "dark" ? "" : "active"
}`}
onClick={LayoutLight}
></i>
</OverlayTrigger>
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="tooltip-dark">Dark Mode</Tooltip>}
>
<i
className={`ti ti-moon dark-mode ${layoutBs === "dark" ? "active" : ""
}`}
onClick={LayoutDark}
></i>
</OverlayTrigger>
</Link>
</li>
{/* <li className="nav-item">
<Link to={route.faq} className="btn btn-help">
<i className="ti ti-help-hexagon" />
</Link>
</li> */}
<Dropdown align="end" className="nav-item">
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="tooltip-apps">Apps Menu</Tooltip>}
>
<Dropdown.Toggle
as="button"
className="btn btn-chart-pie border-0 d-flex align-items-center justify-content-center"
style={{
backgroundColor: "#cfe9e6",
color: "#108678ff",
transition: "all 0.3s ease",
width: "35px",
height: "35px",
padding: "0",
fontSize: "16px",
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "#108678ff";
e.currentTarget.style.color = "#fff";
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "#cfe9e6";
e.currentTarget.style.color = "#108678ff";
}}
>
<i className="ti ti-layout-grid-add" />
</Dropdown.Toggle>
</OverlayTrigger>
<Dropdown.Menu className="menus-info p-3">
<div className="row">
{/* LEFT COLUMN */}
<div className="col-md-6">
<ul className="menu-list">
{leftColumn.map((btn, index) => (
<li key={index}>
<Link to={btn.link} className="dropdown-item">
<div className="menu-details">
<span className={`menu-list-icon ${btn.bg}`}>
<i className={btn.icon} />
</span>
<div className="menu-details-content">
<p>{btn.label}</p>
<span>Open {btn.label}</span>
</div>
</div>
</Link>
</li>
))}
</ul>
</div>
{/* RIGHT COLUMN */}
<div className="col-md-6">
<ul className="menu-list">
{rightColumn.map((btn, index) => (
<li key={index}>
<Link to={btn.link} className="dropdown-item">
<div className="menu-details">
<span className={`menu-list-icon ${btn.bg}`}>
<i className={btn.icon} />
</span>
<div className="menu-details-content">
<p>{btn.label}</p>
<span>Open {btn.label}</span>
</div>
</div>
</Link>
</li>
))}
</ul>
</div>
</div>
</Dropdown.Menu>
</Dropdown>
{!isUser && !isSuperAdmin && !isClient && (
<Dropdown align="end" className="nav-item">
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="tooltip-reports">Reports</Tooltip>}
>
<Dropdown.Toggle
as="button"
className="btn btn-chart-pie border-0 d-flex align-items-center justify-content-center"
style={{
width: "35px",
height: "35px",
padding: "0",
fontSize: "16px",
backgroundColor: "#ffeca0ff",
color: "#d3ca1eff",
transition: "all 0.3s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "#f5d60eff";
e.currentTarget.style.color = "#fff";
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "#fff2beff";
e.currentTarget.style.color = "#f5d60eff";
}}
>
<i className="ti ti-chart-pie" />
</Dropdown.Toggle>
</OverlayTrigger>
<Dropdown.Menu className="menus-info p-3">
<ul className="menu-list">
{headerButtons
.filter((btn) => btn.type === "report")
.map((btn, index) => (
<li key={index}>
<Link to={btn.link} className="dropdown-item">
<div className="menu-details">
<span className={`menu-list-icon ${btn.bg}`}>
<i className={btn.icon} />
</span>
<div className="menu-details-content">
<p>{btn.label}</p>
<span>View {btn.label}</span>
</div>
</div>
</Link>
</li>
))}
</ul>
</Dropdown.Menu>
</Dropdown>
)}
</ul>
</li>
{/* /Nav List */}
{/* Email */}
{/* <li className="nav-item nav-item-email nav-item-box">
<Link to={route.email}>
<i className="ti ti-message-circle-exclamation" />
<span className="badge rounded-pill">14</span>
</Link>
</li> */}
{/* /Email */}
{!isSuperAdmin && (
<Dropdown
as="li"
className="nav-item nav-item-box p-1"
show={show}
onToggle={(isOpen) => setShow(isOpen)} // control dropdown
>
<OverlayTrigger
placement="bottom"
overlay={
<Tooltip id="tooltip-notifications">Notifications</Tooltip>
}
>
<Dropdown.Toggle
as={Link}
to="#"
className="nav-link d-flex align-items-center justify-content-center"
style={{
width: "35px",
height: "35px",
backgroundColor: "#f8d7da",
color: "#721b22ff",
transition: "all 0.3s ease", // 👈 smooth Bootstrap-friendly animation
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "#ac5259ff";
e.currentTarget.style.color = "#fff";
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "#e3acb1ff";
e.currentTarget.style.color = "#721b22ff";
}}
>
<i className="ti ti-bell" />
{notifications.some((n) => !n.is_read) && (
<span className="badge rounded-pill bg-danger position-absolute top-0 end-0">
{notifications.filter((n) => !n.is_read).length}
</span>
)}
</Dropdown.Toggle>
</OverlayTrigger>
<Dropdown.Menu className="dropdown-menu-end notification-dropdown">
{/* Header */}
<div className="topnav-dropdown-header d-flex justify-content-between align-items-center">
<h4 className="notification-title mb-0">
<i className="ti ti-bell me-1"></i>Notifications
</h4>
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="refresh-tooltip">Refresh</Tooltip>}
>
<a
href="#"
onClick={(e) => {
e.preventDefault();
fetchAndSetNotifications();
}}
className="text-dark d-inline-flex align-items-center justify-content-center"
style={{
width: "32px",
height: "32px",
borderRadius: "50%",
fontSize: "20px",
lineHeight: "1",
}}
>
<i className="ti ti-refresh-dot" />
</a>
</OverlayTrigger>
</div>
{/* Content */}
<div className="noti-content">
<ul className="notification-list">
{notifications.length === 0 ? (
<li className="notification-message text-center text-muted p-3">
<i className="ti ti-info-circle me-2" />
No notifications available
</li>
) : (
sortedNotifications.map((notification) => (
<li
className={`notification-message ${!notification.is_read ? "bg-light" : ""
}`}
key={notification.id}
>
<Link
to="#"
onClick={(e) => {
e.preventDefault();
handleNotificationClick(notification);
// ✅ close dropdown after click
setShow(false);
}}
style={{ textDecoration: "none" }}
>
<div className="media d-flex flex-column">
<div className="media-body">
<p className="noti-details mb-1 text-dark fw-semibold">
{!notification.is_read && (
<span className="unread-indicator me-2"></span>
)}
{notification.message}
</p>
<p className="noti-time text-muted small mb-0">
{new Date(
notification.created_at
).toLocaleString()}
</p>
</div>
</div>
</Link>
</li>
))
)}
</ul>
</div>
{/* Footer */}
<div className="topnav-dropdown-footer d-flex justify-content-between align-items-center">
<Link
to={route.activities}
className="view-link"
onClick={() => setShow(false)} // ✅ close when "View all" clicked
>
View all
</Link>
{notifications.some((n) => !n.is_read) && (
<Link
to="#"
className="clear-link text-primary"
onClick={async (e) => {
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
</Link>
)}
</div>
</Dropdown.Menu>
</Dropdown>
)}
{/* /Notifications */}
{/* /Notifications */}
{/* Profile Dropdown */}
<Dropdown align="end" className="nav-item main-drop p-1">
<OverlayTrigger
placement="bottom"
overlay={<Tooltip id="tooltip-profile">Profile</Tooltip>}
>
<Dropdown.Toggle
as="button"
className="btn btn-chart-pie d-flex align-items-center justify-content-center position-relative"
id="profileDropdown"
style={{
width: "40px",
height: "40px",
backgroundColor: "#fff",
border: "1px solid #ddd",
padding: 0,
}}
>
{getInitials(userName || "Unknown") ? (
<span
className="bg-primary text-white rounded-circle"
style={{
width: "30px",
height: "30px",
fontWeight: "bold",
display: "flex",
alignItems: "center",
justifyContent: "center",
textTransform: "uppercase",
fontSize: "14px",
}}
>
{getInitials(userName || "Unknown")}
</span>
) : (
<ImageWithBasePath
src="assets/img/profiles/avatar-20.jpg"
alt="Profile"
className="bg-primary rounded-circle"
style={{
width: "30px",
height: "30px",
objectFit: "cover",
}}
/>
)}
{/* Green active indicator dot */}
<span
className="position-absolute bottom-0 end-0 bg-success rounded-circle border border-white"
style={{
width: "12px",
height: "12px",
zIndex: 1,
}}
/>
</Dropdown.Toggle>
</OverlayTrigger>
<Dropdown.Menu className="p-3" style={{ minWidth: "240px" }}>
{/* User info header (fallback-safe) */}
<div className="text-center mb-3">
{userName || "Unknown" ? (
<>
{/* Avatar (re-use toggle logic) */}
<div className="text-center mb-2">
{/* Avatar */}
<div className="d-inline-flex align-items-center justify-content-center mb-2">
{getInitials(userName || "Unknown") ? (
<span
className="avatar avatar-md rounded-circle bg-primary text-white d-flex align-items-center justify-content-center"
style={{
width: "48px",
height: "48px",
fontSize: "18px",
fontWeight: 600,
}}
>
{getInitials(userName || "Unknown")}
</span>
) : (
<ImageWithBasePath
src="assets/img/profiles/avatar-20.jpg"
alt="Avatar"
className="avatar avatar-md rounded-circle"
style={{
width: "48px",
height: "48px",
objectFit: "cover",
}}
/>
)}
</div>
{/* Name */}
<h6 className="mb-1 fw-semibold text-dark">
{userName || "Unknown" || "—"}
</h6>
{/* Role Badge (only Admin/User) */}
<span
className="badge text-uppercase mb-1"
style={{
backgroundColor:
userRole?.toLowerCase() === "admin"
? "#ffe8e6"
: "#e6f4ff",
color:
userRole?.toLowerCase() === "admin"
? "#d93025"
: "#1a73e8",
fontSize: "10px",
padding: "3px 8px",
borderRadius: "6px",
letterSpacing: "0.3px",
}}
>
{userRole || "User"}
</span>
{/* Email - One line, no break, show tooltip if long */}
{/* <p
className="text-muted small mt-1 mb-0"
style={{
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
maxWidth: "180px",
margin: "0 auto",
}}
title={user?.email}
>
{user?.email || "—"}
</p> */}
<div className="d-flex justify-content-center mt-1">
<TextCopy text={userEmail || "—"} />
</div>
</div>
</>
) : (
<>
<div className="placeholder-glow mb-3">
<span className="placeholder avatar avatar-md rounded-circle col-12" />
</div>
<p className="placeholder-glow">
<span className="placeholder col-8" />
</p>
<p className="placeholder-glow">
<span className="placeholder col-6" />
</p>
</>
)}
</div>
<Dropdown.Divider className="my-2" />
<Dropdown.Item
as={Link}
to={route.profile}
className="d-flex align-items-center transition-all rounded-3" // <--- added
style={{ borderRadius: "8px" }} // <--- fallback
onMouseEnter={(e) => {
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
}
}}
>
<i className="ti ti-user-pin me-2 p-2 bg-light text-dark rounded-2" />{" "}
My Profile
</Dropdown.Item>
<Dropdown.Item
onClick={handleLockScreen}
className="d-flex align-items-center transition-all rounded-3"
style={{ borderRadius: "8px" }}
onMouseEnter={(e) => {
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");
}
}}
>
<i className="ti ti-lock me-2 p-2 bg-light text-dark rounded-2" />
Lock Screen
</Dropdown.Item>
{/* Logout */}
<Dropdown.Item
onClick={handleLogout}
className="d-flex align-items-center transition-all rounded-3"
style={{ borderRadius: "8px" }}
onMouseEnter={(e) => {
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
}
}}
>
<i className="ti ti-lock me-2 p-2 bg-light text-dark rounded-2" />{" "}
Logout
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
{/* /Profile Dropdown */}
</ul>
</div>
{/* Mobile Menu */}
<div className="dropdown mobile-user-menu">
<Link
to="#"
className="nav-link dropdown-toggle"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<i className="fa fa-ellipsis-v" />
</Link>
<div className="dropdown-menu">
{/* Dashboard */}
{/* <Link
className="dropdown-item d-flex align-items-center px-2 py-2 rounded-3"
style={{ borderRadius: "8px", transition: "all 0.3s ease" }}
to={route.leadsDashboard}
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
}
}}
>
<i className="ti ti-layout-2 me-2 bg-light text-dark p-1 rounded-2" />
Dashboard
</Link> */}
{/* My Profile */}
<Link
className="dropdown-item d-flex align-items-center px-2 py-2 rounded-3"
style={{ borderRadius: "8px", transition: "all 0.3s ease" }}
to={route.profile}
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
}
}}
>
<i className="ti ti-user-pin me-2 bg-light text-dark p-1 rounded-2" />
My Profile
</Link>
<Link
className="dropdown-item d-flex align-items-center px-2 py-2 rounded-3"
to="#"
onClick={(e) => {
e.preventDefault();
handleLockScreen();
}}
>
<i className="ti ti-lock me-2 bg-light text-dark p-1 rounded-2" />
Lock Screen
</Link>
{/* Logout */}
<Link
className="dropdown-item d-flex align-items-center px-2 py-2 rounded-3"
style={{ borderRadius: "8px", transition: "all 0.3s ease" }}
to="#"
onClick={(e) => {
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
}
}}
>
<i className="ti ti-lock me-2 bg-light text-dark p-1 rounded-2" />
Logout
</Link>
</div>
</div>
{/* /Mobile Menu */}
</div>
<ModalDeleteEffect />
{/* Logout Confirmation Modal */}
<Modal
show={showLogoutModal}
onHide={() => setShowLogoutModal(false)}
centered
className="effect-modal-show"
>
<div className="modal-header">
<h5 className="modal-title"><i className="ti ti-lock me-2" />Logout</h5>
<button
className="btn-close custom-btn-close border p-1 me-0 d-flex align-items-center justify-content-center rounded-circle"
aria-label="Close"
onClick={() => setShowLogoutModal(false)}
>
<i className="ti ti-x" />
</button>
</div>
<div className="modal-body text-center p-4">
<div className="success-popup-icon bg-light-warning mb-3">
<i className="ti ti-logout fs-36 text-warning effect-avatar-pulse" />
</div>
<h4 className="mb-2">Are you sure you want to logout?</h4>
<p className="mb-0 text-muted">
You will be logged out of your account.
</p>
<div className="d-flex justify-content-center gap-3 mt-4">
<button
className="btn btn-secondary"
onClick={() => setShowLogoutModal(false)}
>
No
</button>
<button
className="btn btn-primary"
onClick={confirmLogout}
>
Yes
</button>
</div>
</div>
</Modal>
</>
);
};
export default Header;