import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
    ActionIcon,
    Breadcrumbs,
    Button, Card,
    Flex, Grid,
    Group,
    Popover,
    ScrollArea,
    Text, TextInput,
    Title, Drawer,
    Tooltip, Select, Menu,
    ThemeIcon,
    Divider,
    Modal, List,
    Tabs, Badge
} from '@mantine/core';
import { useDisclosure, useHotkeys, useDebouncedCallback } from '@mantine/hooks';
import { useLocation, useParams, useNavigate } from 'react-router-dom';
import {
    IconCaretDownFilled,
    IconChevronRight,
    IconFilter,
    IconRefresh, IconSearch,
    IconX, IconSettings, IconArchive,
    IconGauge, IconFingerprint, IconActivity,
    IconSettings2,
    IconArchiveFilled,
    IconArchiveOff,
    IconLayoutNavbarCollapse,
    IconLayoutNavbarExpand,
    IconCodeVariablePlus,
    IconAdjustmentsHorizontal,
    IconCheck,
    IconPlaylistX,
    IconArrowBarRight, IconArrowBarLeft,
    IconLayoutColumns,
    IconInfoCircle, IconGripVertical, IconArrowsHorizontal, IconCalendarEvent, IconEye, IconSubtask,
    IconList, IconLayoutKanban, IconCalendar, IconTimeline, IconPencil,
    IconLayoutDashboard, IconDeviceMobile, IconWorldWww, IconBell,
    IconShieldCheck, IconTag, IconFolderOpen, IconCircleCheck, IconStopwatch
} from '@tabler/icons-react';
import UsersAvatarGroup from "../../ui/UsersAvatarGroup";
import {
    changeGanttViewMode, fetchGanttTasksByProject,
    fetchTasksByProject,
    archiveProject,
    updateIsLoading,
    unarchiveProject,
    createTaskSection,
    updateExpandedItems,
    clearLoadedSections,
    fetchTasksSectionWise,
    fetchArchiveTasks, setDrawerContext, fetchClosedTasks,
    editSectionSortOrder,
    updateOrdered,
    updateFilterValues,
    resetFilterValues
} from "../../Settings/store/taskSlice";
import { hasPermission, useProjectPermissions } from "../../ui/permissions";
import ViewArchive from './ViewArchive';
import FilterTasksPopover from './FilterTasksPopover';
import ShortcutPopover from './ShortcutPopover';
import MemberAddRemovePopover from './MemberAddRemovePopover';
import { translate } from '../../../utils/i18n';
import AddonInstallationModal from '../../Settings/AddonInstallationModal';
import ProjectConfigureModal from './ProjectConfigureModal';
import { showNotification, updateNotification } from '@mantine/notifications';
import { modals } from '@mantine/modals';
import { updateInputFieldFocus } from "../../../store/base/commonSlice";
import { fetchAllCompanies } from "../../Settings/store/companySlice";
import ProjectSettingsModal from './ProjectSettingsModal';
import ProjectAddTaskSnippet from './ProjectAddTaskSnippet';

const T = {
    border:   '#E2E8F0',
    text:     '#1A202C',
    icon:     '#6B7280',
    teal:     '#39758D',
    radius:   '12px',
};

const menuStyles = {
    dropdown: {
        padding: 0,
        border: `1px solid ${T.border}`,
        borderRadius: T.radius,
        boxShadow: '0 8px 32px rgba(0,0,0,.12)',
        overflow: 'hidden',
        '--menu-item-hover': '#EBF1F4',
    },
    item: {
        borderRadius: 0,
        fontSize: '12px',
        color: T.text,
        padding: '7px 12px',
    },
    label: {
        padding: '10px 14px 8px',
        borderBottom: `1px solid ${T.border}`,
        fontSize: '12px',
        fontWeight: 700,
        color: T.text,
        marginBottom: 0,
    },
    divider: {
        borderColor: T.border,
        margin: 0,
    },
};

const data = [
    { icon: IconGauge, label: 'Day', description: 'Item with description' },
    {
        icon: IconFingerprint,
        label: 'Week',
        rightSection: <IconChevronRight size={16} stroke={1.5} />,
    },
    { icon: IconActivity, label: 'Month' },
];
const ProjectDetailsNav = () => {
    const location = useLocation();
    const navigate = useNavigate()
    const dispatch = useDispatch();

    const { loggedUserId } = useSelector((state) => state.auth.user);
    const { loggedInUser } = useSelector((state) => state.auth.session);
    const userId = loggedInUser ? loggedInUser.loggedUserId : loggedUserId;

    const usersData = useSelector((state) => state.users);

    const { whiteboardAddonState } = useSelector((state) => state.settings.setting);
    const { projectInfo, ganttViewMode, ganttListIsVisible, ordered, filterValues, taskListSections, projectNavbar, loadedSections, tasks, boardMembers } = useSelector((state) => state.settings.task);
    const projectPermissions = useProjectPermissions(projectInfo?.id);
    const { projectSections, projectPriorities, projectStatuses } = useSelector((state) => state.settings.project);
    const { companies } = useSelector((state) => state.settings.company);
    const [settingDrawerOpened, { open: settingDrawerOpen, close: settingDrawerClose }] = useDisclosure(false);
    const [projectPopoverOpened, setProjectPopoverOpened] = useState(false);
    const [addonModalOpened, setAddonModalOpened] = useState(false);
    const [projectNavConfigureModalOpen, setProjectNavConfigureModalOpen] = useState(false);
    const [projectSettingsModalOpen, setProjectSettingsModalOpen] = useState(false);
    const [isOpenedMemberPopover, setIsOpenedMemberPopover] = useState(false);
    const [helpGuideModalOpened, setHelpGuideModalOpened] = useState(false);
    const [isAddingSection, setIsAddingSection] = useState(false);
    const [drawerContext, setDrawerContext] = useState('archive');
    const [currentActiveTab, setCurrentActiveTab] = useState('tasks');

    const { id } = useParams();
    const listPagePathName = `/project/task/list/${id}`;
    const boardPagePathName = `/project/task/board/${id}`;
    const calendarPagePathName = `/project/task/calendar/${id}`;
    const ganttChartPagePathName = `/project/task/gantt/${id}`;
    const reportPagePathName = `/project/task/report/${id}`;
    const whiteboardPagePathName = `/project/whiteboard/${id}`;

    const listPageSectionByPriorityPathName = `/project/task/list/section/by/priority/${id}`;
    const listPageSectionByStatusPathName = `/project/task/list/section/by/status/${id}`;
    const listPageSectionByMemberPathName = `/project/task/list/section/by/member/${id}`;
    const listPageSectionByDueDatePathName = `/project/task/list/section/by/duedate/${id}`;

    const boardPageSectionByPriorityPathName = `/project/task/board/section/by/priority/${id}`;
    const boardPageSectionByStatusPathName   = `/project/task/board/section/by/status/${id}`;
    const boardPageSectionByMemberPathName   = `/project/task/board/section/by/member/${id}`;
    const boardPageSectionByDueDatePathName  = `/project/task/board/section/by/duedate/${id}`;

    const activeFilterCount = Object.values(filterValues || {}).filter(
        v => v !== null && v !== ''
    ).length;

    const dueDateLabels = { today: 'Today', overdue: 'Over Due', upcoming: 'Upcoming', 'no-date': 'No Date' };
    const activeFilterPills = [
        filterValues?.name               && { key: 'name',               label: `Title: "${filterValues.name}"` },
        filterValues?.section_id         && { key: 'section_id',         label: `Section: ${projectSections?.find(s => String(s.id) === String(filterValues.section_id))?.name || filterValues.section_id}` },
        filterValues?.assigned_to        && { key: 'assigned_to',        label: `Assigned: ${boardMembers?.find(m => String(m.id) === String(filterValues.assigned_to))?.name || filterValues.assigned_to}` },
        filterValues?.priority_id        && { key: 'priority_id',        label: `Priority: ${projectPriorities?.find(p => String(p.id) === String(filterValues.priority_id))?.name || filterValues.priority_id}` },
        filterValues?.internal_status_id && { key: 'internal_status_id', label: `Status: ${projectStatuses?.find(s => String(s.id) === String(filterValues.internal_status_id))?.name || filterValues.internal_status_id}` },
        filterValues?.date_type          && { key: 'date_type',          label: `Due: ${dueDateLabels[filterValues.date_type] || filterValues.date_type}` },
    ].filter(Boolean);

    const reloadSections = () => {
        if (ordered && ordered.length > 0 && projectInfo?.id) {
            dispatch(fetchTasksSectionWise({
                projectId: projectInfo.id,
                limit: 10,
                offset: 0,
                search: '',
                userId: userId
            }));
        }
    };

    // Reset filters whenever the user navigates to a different view/tab
    const isFirstPathRender = useRef(true);
    useEffect(() => {
        if (isFirstPathRender.current) {
            isFirstPathRender.current = false;
            return;
        }
        dispatch(resetFilterValues());
    }, [location.pathname]);

    const searchInputRef = useRef(null);
    useHotkeys([
        ['alt+F', () => {
            if (searchInputRef.current) {
                searchInputRef.current.focus();
            }
        }],
        ['alt+P', () => setProjectPopoverOpened(true)],
        ['Escape', () => setProjectPopoverOpened(false)],
        ['alt+K', () => toggoleView()]
    ]);

    const [searchInputValue, setSearchInputValue] = useState('');

    const toggoleView = () => {
        if (location.pathname === listPagePathName) {
            navigate(boardPagePathName);
        } else if (location.pathname === boardPagePathName) {
            navigate(calendarPagePathName);
        } else if (location.pathname === calendarPagePathName) {
            navigate(ganttChartPagePathName);
        } else if (location.pathname === ganttChartPagePathName) {
            navigate(listPagePathName);
        }
    }



    const goToTasksList = useCallback((projectId) => {
        // Only clear sections if switching to a different project
        if (Number(projectInfo?.id) !== Number(projectId)) {
            dispatch(clearLoadedSections())
        }
        navigate(`/project/task/list/${projectId}`);
        setProjectPopoverOpened(false);
    }, [navigate, projectInfo?.id, dispatch]);
    //searchHandler
    const searchHandler = (e) => {

        const searchValue = e.target.value;
        // searchValue length is greater than 2
        setSearchInputValue(searchValue);
        debouncedSearch(searchValue);
        // if (location.pathname === ganttChartPagePathName) {
        //     dispatch(fetchGanttTasksByProject({ id: id, data: { search: searchValue } }))
        // } else {
        //     dispatch(fetchTasksByProject({ id: id, data: { search: searchValue } }))
        // }

    }

    const debouncedSearch = useDebouncedCallback((value) => {
        if (location.pathname === ganttChartPagePathName) {
            dispatch(fetchGanttTasksByProject({ id, data: { search: value } }));
        } else {
            dispatch(fetchTasksByProject({ id, data: { search: value }, userId }));
        }
    }, 1000);


    const handleClearSearch = () => {
        setSearchInputValue('');
        dispatch(fetchTasksByProject({ id: id, data: { search: '' } }));
        dispatch(fetchGanttTasksByProject({ id: id, data: { search: '' } }));
    };

    const handleRefresh = () => {
        // Only trigger a reload when there are sections to reload
        if (ordered?.length > 0 && projectInfo?.id) {
            // Clear old data before fetching fresh data
            dispatch(clearLoadedSections());
            dispatch(updateIsLoading(true));
            reloadSections();
        } else {
            // Ensure loading state is not left true when there's nothing to reload
            dispatch(updateIsLoading(false));
        }
    }

    const projectCount = projectInfo?.parent?.projects?.length || 0;
    const cardHeight = 80;
    const maxVisibleCards = 3;

    const scrollAreaHeight = projectCount > maxVisibleCards
        ? cardHeight * maxVisibleCards
        : 'auto';

    //handleGanttViewMode
    const handleGanttViewMode = (mode) => {
        dispatch(changeGanttViewMode(mode));
    }

    const handleViewSwitch = (view) => {
        dispatch(updateIsLoading(true));

        switch (view) {
            case 'list':
                navigate(`/project/task/list/${id}`);
                break;
            case 'board':
                navigate(`/project/task/board/${id}`);
                break;
            case 'calendar':
                navigate(`/project/task/calendar/${id}`);
                break;
            case 'gantt':
                navigate(`/project/task/gantt/${id}`);
                break;
            case 'whiteboard':
                navigate(`/project/whiteboard/${id}`);
                break;
            case 'report':
                navigate(`/project/task/report/${id}`);
                break;
        }
    };

    const handleArchiveProject = () => {
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconArchive size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Archive Project')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        {translate('Are you sure you want to archive this project?')}
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes', cancel: 'Cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Project',
                    message: "Archiving The Project...",
                    disallowClose: true,
                    color: 'green',
                });
                dispatch(archiveProject({
                    id: id,
                    data: {
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error completing subtask:', error);
                    });
            },
        });
    }

    const handleUnarchiveProject = () => {
        modals.openConfirmModal({
            title: (
                <Group spacing="xs">
                    <ThemeIcon color="orange" radius="xl" size="lg" variant="filled">
                        <IconArchive size={24} />
                    </ThemeIcon>
                    <Text size="md" weight={500}>
                        {translate('Unarchive Project')}
                    </Text>
                </Group>
            ),
            centered: true,
            children: (
                <>
                    <Divider size="xs" mb={24} className='!-ml-4 w-[calc(100%+2rem)]' />
                    <Text size="md" mb={30}>
                        {translate('Are you sure you want to unarchive this project?')}
                    </Text>
                </>
            ),
            labels: { confirm: 'Yes', cancel: 'Cancel' },
            confirmProps: { color: 'orange' },
            onConfirm: () => {
                showNotification({
                    id: 'load-data',
                    loading: true,
                    title: 'Project',
                    message: "Unarchiving The Project...",
                    disallowClose: true,
                    color: 'green',
                });
                dispatch(unarchiveProject({
                    id: id,
                    data: {
                        updated_by: loggedInUser?.loggedUserId ?? loggedUserId,
                    }
                }))
                    .then((response) => {
                        if (response.payload && response.payload.status && response.payload.status === 200) {
                            updateNotification({
                                id: 'load-data',
                                loading: true,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'green',
                            });
                        } else {
                            updateNotification({
                                id: 'load-data',
                                loading: false,
                                title: 'Subtask',
                                message: response.payload && response.payload.message && response.payload.message,
                                autoClose: 2000,
                                disallowClose: true,
                                color: 'red',
                            });
                        }
                    })
                    .catch((error) => {
                        console.error('Error completing subtask:', error);
                    });
            },
        });
    }

    useEffect(() => {
        const permissions = ['whiteboard-access', 'whiteboard-manage', 'whiteboard-comments', 'edit-whiteboard-comments', 'delete-whiteboard-comments', 'create-edit-whiteboard-page', 'delete-whiteboard-page'];
        const init = () => {
            if (window.lazytasksWhiteboard && projectNavbar?.whiteboard && hasPermission(loggedInUser, permissions, projectPermissions, 'project')) {
                window.lazytasksProjectPermissions = window.lazytasksProjectPermissions || {};
                window.lazytasksProjectPermissions[id] = projectPermissions;
                window.dispatchEvent(new CustomEvent('lazytasksProjectPermissionsReady', { detail: { project_id: id, permissions: projectPermissions } }));
                window.lazytasksWhiteboard.whiteboardTabButton(id);
            }
        };
        if (window.lazytasksWhiteboard) {
            init();
        } else {
            window.addEventListener('lazytasksWhiteboardReady', init);
            return () => window.removeEventListener('lazytasksWhiteboardReady', init);
        }
    }, [projectNavbar, id]);

    useEffect(() => {
        if (!companies || companies.length === 0) {
            dispatch(fetchAllCompanies());
        }
    }, []);

    useEffect(() => {
        if (window.lazytasksWhiteboard && (projectNavbar && projectNavbar.whiteboard) && hasPermission(loggedInUser,
            ['whiteboard-access', 'whiteboard-manage', 'whiteboard-comments', 'edit-whiteboard-comments', 'delete-whiteboard-comments', 'create-edit-whiteboard-page', 'delete-whiteboard-page'],
            projectPermissions, 'project')) {
            window.lazytasksProjectPermissions = window.lazytasksProjectPermissions || {};
            window.lazytasksProjectPermissions[id] = projectPermissions;
            window.dispatchEvent(new CustomEvent('lazytasksProjectPermissionsReady', { detail: { project_id: id, permissions: projectPermissions } }));
            window.lazytasksWhiteboard.whiteboardTabButton(id);
        }
    }, [location, projectNavbar, id]);

    const [expandedItems, setExpandedItems] = useState([]);
    const [accordionItems, setAccordionItems] = useState([]);

    const handleAddSection = () => {
        setIsAddingSection(true);
        const newItemValue = `untitle-section-${accordionItems.length + 1}`;
        const newItem = {
            value: newItemValue,
            title: `Type section name here`,
        };
        setAccordionItems([newItem, ...accordionItems]);
        setExpandedItems([newItemValue, ...expandedItems]);

        const newSection = {
            name: 'Type section name here',
            project_id: projectInfo.id,
            sort_order: 0,
            position: 'beginning',
            created_by: loggedInUser ? loggedInUser.loggedUserId : loggedUserId
        }

        dispatch(createTaskSection(newSection))
            .then((response) => {
                setIsAddingSection(false);
                // Persist the new order to the backend
                if (response.payload?.data?.taskSections) {
                    const newSectionSlug = response.payload.data.taskSections;
                    const newOrdered = [newSectionSlug, ...ordered];
                    const submittedData = {
                        orderedList: newOrdered,
                        project_id: projectInfo.id,
                        updated_by: loggedInUser ? loggedInUser.loggedUserId : loggedUserId
                    };
                    dispatch(editSectionSortOrder({ data: submittedData }));
                }
            })
            .catch(() => {
                setIsAddingSection(false);
            });
        dispatch(updateInputFieldFocus(true));
    };

    useEffect(() => {
        if (tasks && taskListSections) {
            const transformedItems = Object.entries(taskListSections).map(([key, value]) => ({
                value: key,
                title: value.name,
            })
            );
            setAccordionItems(transformedItems);
            // Set all accordion items as expanded
            setExpandedItems(transformedItems.map(item => item.value));
        }

    }, [taskListSections, ordered]);

    const handleExpandCollapseSections = () => {
        if (expandedItems.length === accordionItems.length) {
            // Collapse all
            setExpandedItems([]);
            dispatch(updateExpandedItems([]));
        } else {
            // Expand all
            setExpandedItems(accordionItems.map(item => item.value));
            dispatch(updateExpandedItems(accordionItems.map((item) => item.value)));
        }

    }

    const activePaths = [
        listPagePathName,
        boardPagePathName,

        listPageSectionByPriorityPathName,
        listPageSectionByStatusPathName,
        listPageSectionByMemberPathName,
        listPageSectionByDueDatePathName,

        boardPageSectionByPriorityPathName,
        boardPageSectionByStatusPathName,
        boardPageSectionByMemberPathName,
        boardPageSectionByDueDatePathName,
    ];

    const isActive = activePaths.includes(location.pathname);

    const isListActive = [
        listPagePathName,
        listPageSectionByPriorityPathName,
        listPageSectionByStatusPathName,
        listPageSectionByMemberPathName,
        listPageSectionByDueDatePathName,
    ].includes(location.pathname);

    const [defaultSelectValue, setDefaultSelectValue] = useState('section');
    const [sectionByValue, setSectionByValue] = useState(null);
    useEffect(() => {
        switch (location.pathname) {
            case listPagePathName:
            case boardPagePathName:
                setDefaultSelectValue('section');
                setSectionByValue(null);
                break;

            case listPageSectionByPriorityPathName:
            case boardPageSectionByPriorityPathName:
                setDefaultSelectValue('section');
                setSectionByValue('priority');
                break;
            case listPageSectionByStatusPathName:
            case boardPageSectionByStatusPathName:
                setDefaultSelectValue('section');
                setSectionByValue('status');
                break;
            case listPageSectionByMemberPathName:
            case boardPageSectionByMemberPathName:
                setDefaultSelectValue('section');
                setSectionByValue('member');
                break;
            case listPageSectionByDueDatePathName:
            case boardPageSectionByDueDatePathName:
                setDefaultSelectValue('section');
                setSectionByValue('duedate');
                break;
            default:
                setDefaultSelectValue(null);
                setSectionByValue(null);
        }
    }, [location.pathname]);



    const handleSectionBy = (value) => {
        const isBoardTab = [
            boardPagePathName,
            boardPageSectionByPriorityPathName,
            boardPageSectionByStatusPathName,
            boardPageSectionByMemberPathName,
            boardPageSectionByDueDatePathName,
        ].includes(location.pathname);

        const base = isBoardTab ? 'board' : 'list';

        switch (value) {
            case 'section':
                navigate(`/project/task/${base}/${id}`);
                break;
            case 'priority':
                navigate(`/project/task/${base}/section/by/priority/${id}`);
                break;
            case 'status':
                navigate(`/project/task/${base}/section/by/status/${id}`);
                break;
            case 'member':
                navigate(`/project/task/${base}/section/by/member/${id}`);
                break;
            case 'duedate':
                navigate(`/project/task/${base}/section/by/duedate/${id}`);
                break;
        }
    };

    const menuPermissions = [
        ['config-project'],
        ['manage-project'],
        ['manage-section'],
        ['manage-section']
    ];

    const userHasAnyPermission = menuPermissions.some((perm) =>
        hasPermission(loggedInUser?.llc_permissions, perm)
    );

    return (
        <>
            <Grid className='mt-2 mb-3'>
                <Grid.Col span={9}>
                    <Flex align="center" gap={6}>
                        {/* Workspace Name */}
                        <Flex
                            align="center"
                            gap={6}
                            className="px-2.5 py-1 rounded-full cursor-default"
                            style={{
                                backgroundColor: '#EBF1F4',
                            }}
                        >
                            <Text
                                fw={600}
                                size="sm"
                                c="#39758D"
                                className="whitespace-nowrap"
                            >
                                {projectInfo && projectInfo.parent && projectInfo.parent.name}
                            </Text>
                        </Flex>

                        {/* Separator */}
                        <IconChevronRight size={16} stroke={2} color="#9CA3AF" />

                        {/* Project Selector */}
                        <Popover width={300} position="bottom-start" withArrow shadow="md" zIndex={1000}
                            opened={projectPopoverOpened}
                            onChange={setProjectPopoverOpened}
                        >
                            <Popover.Target>
                                <Flex
                                    className="px-3 py-1 rounded-full cursor-pointer hover:bg-gray-50 transition-colors"
                                    gap={8}
                                    align="center"
                                    onClick={() => setProjectPopoverOpened((o) => !o)}
                                    style={{
                                        border: '1px solid #D1D5DB',
                                        backgroundColor: projectPopoverOpened ? '#F9FAFB' : '#ffffff',
                                    }}
                                >
                                    <Text fw={600} size="sm" c="#202020" className="whitespace-nowrap">
                                        {projectInfo && projectInfo.name}
                                    </Text>
                                    <IconCaretDownFilled
                                        size={14}
                                        color="#6B7280"
                                        style={{
                                            transform: projectPopoverOpened ? 'rotate(180deg)' : 'rotate(0deg)',
                                            transition: 'transform 0.2s ease',
                                        }}
                                    />
                                </Flex>
                            </Popover.Target>
                            <Popover.Dropdown>
                                <ScrollArea h={scrollAreaHeight} offsetScrollbars scrollbarSize={4}>

                                    {projectInfo && projectInfo.parent && projectInfo.parent.projects && projectInfo.parent.projects.length > 0 && (() => {
                                        // Sort sibling projects using the ordered list from companies Redux state
                                        // (which reflects the custom drag-and-drop order from settings)
                                        const currentCompany = companies?.find(c => String(c.id) === String(projectInfo.parent.id));
                                        const sortedProjects = currentCompany?.projects
                                            ? [...projectInfo.parent.projects].sort((a, b) => {
                                                const aIdx = currentCompany.projects.findIndex(p => String(p.id) === String(a.id));
                                                const bIdx = currentCompany.projects.findIndex(p => String(p.id) === String(b.id));
                                                return (aIdx === -1 ? 9999 : aIdx) - (bIdx === -1 ? 9999 : bIdx);
                                            })
                                            : projectInfo.parent.projects;
                                        return sortedProjects.map((project, index) => (
                                        <Card key={`${project.id}-${index}`} className='mb-2 mt-0 cursor-pointer' shadow="sm" radius="sm"
                                            withBorder
                                            bg={location && (location.pathname === '/project/task/list/' + project.id ||
                                                location.pathname === '/project/task/board/' + project.id ||
                                                location.pathname === '/project/task/calendar/' + project.id) ? '#F5F9FB' : 'white'}
                                            onClick={() => goToTasksList(project.id)}
                                            style={{ borderColor: '#39758d' }}
                                        >
                                            <div className="flex justify-between items-center -mt-1">
                                                <Text size="sm" weight={700}>{project.name}</Text>
                                                <UsersAvatarGroup users={project.members} size={30} maxCount={2} />
                                            </div>

                                            <Group position="apart">
                                                <Flex align="center" gap="4">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8" fill="none">
                                                        <circle cx="4" cy="4" r="4" fill="#F1975A" />
                                                    </svg>
                                                    <Text size="xs">{translate('%d users engaged').replace('%d', project.members && project.members.length)}</Text>
                                                </Flex>
                                                <Flex align="center" gap="4">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 8 8" fill="none">
                                                        <circle cx="4" cy="4" r="4" fill="#39758D" />
                                                    </svg>
                                                    <Text size="xs">{translate('%d task').replace('%d', project?.total_tasks)}</Text>
                                                </Flex>
                                            </Group>
                                        </Card>
                                    ));
                                    })()}

                                </ScrollArea>

                            </Popover.Dropdown>
                        </Popover>
                    </Flex>
                </Grid.Col>
                <Grid.Col span={3}>

                    <Flex className={`cursor-pointer`} justify="flex-end" align="center" gap="xs">
                        <TextInput
                            ref={searchInputRef}
                            leftSection={<IconSearch size={22} stroke={1.5} className="text-gray-500" />}
                            value={searchInputValue}
                            rightSectionPointerEvents="auto"
                            rightSection={
                                searchInputValue && (
                                    <IconX
                                        size={24}
                                        stroke={1.5}
                                        className="cursor-pointer text-gray-500"
                                        onClick={handleClearSearch}
                                    />
                                )
                            }
                            style={{ width: '255px' }}
                            onChange={(e) => { searchHandler(e) }}
                            placeholder={translate("Search...")} />

                        <Menu shadow={false} width={240} position="bottom-end" zIndex={30} styles={menuStyles}>
                            <Menu.Target>
                                <ActionIcon variant="filled" color="#EBF1F4" c="#39758D" size={36} aria-label="Settings" radius={"lg"}>
                                    <IconSettings size={24} stroke={1.5} />
                                </ActionIcon>
                            </Menu.Target>

                            <Menu.Dropdown>
                                <Menu.Label>
                                    <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                        <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: T.teal, flexShrink: 0 }} />
                                        {translate('Project')}
                                    </span>
                                </Menu.Label>
                                {hasPermission(loggedInUser, ['config-project', 'manage-project-members', 'remove-project-member'], projectPermissions, 'project') && (
                                    <Menu.Item
                                        leftSection={<IconSettings2 size={16} stroke={1.5} color={T.icon} />}
                                        onClick={() => setProjectSettingsModalOpen(true)}
                                    >
                                        {translate('Project Settings')}
                                    </Menu.Item>
                                )}
                                {window.lazytasksTimeTracker &&
                                 hasPermission(loggedInUser, ['timetracker-access'], projectPermissions, 'project') && (
                                    <Menu.Item
                                        leftSection={<IconStopwatch size={16} stroke={1.5} color={T.icon} />}
                                        onClick={() => window.lazytasksTimeTracker.openProjectLogs(id, projectInfo?.name)}
                                    >
                                        {translate('View Time Log')}
                                    </Menu.Item>
                                )}
                                <>
                                    {expandedItems.length === accordionItems.length ? (
                                        <Menu.Item
                                            leftSection={<IconLayoutNavbarCollapse size={16} stroke={1.5} color={T.icon} />}
                                            onClick={handleExpandCollapseSections}
                                        >
                                            {translate('Collapse All Sections')}
                                        </Menu.Item>
                                    ) : (
                                        <Menu.Item
                                            leftSection={<IconLayoutNavbarExpand size={16} stroke={1.5} color={T.icon} />}
                                            onClick={handleExpandCollapseSections}
                                        >
                                            {translate('Expand All Sections')}
                                        </Menu.Item>
                                    )}
                                </>
                                {(hasPermission(loggedInUser, ['manage-section'], projectPermissions, 'project') ||
                                  hasPermission(loggedInUser, ['close-task'], projectPermissions, 'project') ||
                                  hasPermission(loggedInUser, ['manage-project'], null, 'global')) &&
                                    <Menu.Divider />
                                }
                                {hasPermission(loggedInUser, ['manage-section', 'create-task'], projectPermissions, 'project') && (
                                    <Menu.Item
                                        leftSection={<IconArchive size={16} stroke={1.5} color={T.icon} />}
                                        onClick={() => {
                                            setDrawerContext('tasks');
                                            setCurrentActiveTab('tasks');
                                            settingDrawerOpen();
                                        }}
                                    >
                                        {translate('View Archived Tasks')}
                                    </Menu.Item>
                                )}
                                {hasPermission(loggedInUser, ['close-task'], projectPermissions, 'project') && (
                                    <Menu.Item
                                        leftSection={<IconPlaylistX size={16} stroke={1.5} color={T.icon} />}
                                        onClick={() => {
                                            setDrawerContext('closed-tasks');
                                            setCurrentActiveTab('closed-tasks');
                                            settingDrawerOpen();
                                        }}
                                    >
                                        {translate('View Closed Tasks')}
                                    </Menu.Item>
                                )}
                                {hasPermission(loggedInUser, ['manage-section'], projectPermissions, 'project') && (
                                    <Menu.Item
                                        leftSection={<IconArchiveFilled size={16} stroke={1.5} color={T.icon} />}
                                        onClick={() => {
                                            setDrawerContext('sections');
                                            setCurrentActiveTab('sections');
                                            settingDrawerOpen();
                                        }}
                                    >
                                        {translate('View Archived Sections')}
                                    </Menu.Item>
                                )}
                                {hasPermission(loggedInUser, ['manage-project'], null, 'global') && projectInfo && (
                                    <>
                                        {projectInfo.status_name === 'active' && (
                                            <Menu.Item
                                                leftSection={<IconArchive size={16} stroke={1.5} color={T.icon} />}
                                                onClick={handleArchiveProject}
                                            >
                                                {translate('Archive Project')}
                                            </Menu.Item>
                                        )}
                                        {projectInfo.status_name === 'archived' && (
                                            <Menu.Item
                                                leftSection={<IconArchiveOff size={16} stroke={1.5} color={T.icon} />}
                                                onClick={handleUnarchiveProject}
                                            >
                                                {translate('Unarchive Project')}
                                            </Menu.Item>
                                        )}
                                    </>
                                )}
                            </Menu.Dropdown>
                        </Menu>

                        <Tooltip withinPortal={false} label={translate('Help Guide')} position="top" withArrow>
                            <ActionIcon
                                onClick={() => setHelpGuideModalOpened(true)}
                                variant="filled"
                                color="#EBF1F4"
                                c="#39758D"
                                size={36}
                                radius="lg"
                                aria-label="Help Guide"
                            >
                                <IconInfoCircle size={24} stroke={1.5} />
                            </ActionIcon>
                        </Tooltip>

                    </Flex>
                </Grid.Col>
            </Grid>


            <div className="relative flex justify-between items-center">
                <div className="relative flex mb-3 space-x-3">

                    {projectNavbar && projectNavbar.list && (
                        <Button
                            className="nav-link" activeClassName="active-link"
                            onClick={() => handleViewSwitch('list')}
                            size="sm"
                            color={isListActive ? "#39758D" : "#EBF1F4"}
                            styles={{
                                label: {
                                    color: isListActive ? "#fff" : "#000"
                                }
                            }}
                        >
                            {translate("List")}
                        </Button>
                    )}

                    {projectNavbar && projectNavbar.board && (
                        <Button
                            onClick={() => handleViewSwitch('board')}
                            className="nav-link" activeClassName="active-link"
                            size="sm"
                            color={[boardPagePathName, boardPageSectionByPriorityPathName, boardPageSectionByStatusPathName, boardPageSectionByMemberPathName, boardPageSectionByDueDatePathName].includes(location.pathname) ? "#39758D" : "#EBF1F4"}
                            styles={{
                                label: {
                                    color: [boardPagePathName, boardPageSectionByPriorityPathName, boardPageSectionByStatusPathName, boardPageSectionByMemberPathName, boardPageSectionByDueDatePathName].includes(location.pathname) ? "#fff" : "#000"
                                }
                            }}
                        >
                            {translate("Board")}
                        </Button>
                    )}

                    {projectNavbar && projectNavbar.calendar && (
                        <Button
                            onClick={() => handleViewSwitch('calendar')}
                            className="nav-link" activeClassName="active-link"
                            size="sm"
                            color={location.pathname === calendarPagePathName ? "#39758D" : "#EBF1F4"}
                            styles={{
                                label: {
                                    color: location.pathname === calendarPagePathName ? "#fff" : "#000"
                                }
                            }}
                        >
                            {translate("Calendar")}
                        </Button>
                    )}

                    {!window?.appLocalizer?.whiteboardInstalled && projectNavbar && projectNavbar.whiteboard && (
                        <Tooltip withinPortal={false} className="!py-0 !text-[10px] !z-10" label={translate("Addons")} opened position="top" offset={{ mainAxis: -8, crossAxis: 20 }} color={"#ED7D31"} size="xs"
                            onClick={() => setAddonModalOpened(true)}
                        >
                            <Button
                                onClick={() => setAddonModalOpened(true)}
                                className="!text-sm" activeClassName="active-link" size="sm" color={"#EBF1F4"} styles={{ label: { color: "#c2c2c2" } }}>
                                {translate("Whiteboard")}
                            </Button>
                        </Tooltip>
                    )}
                    <AddonInstallationModal opened={addonModalOpened} onClose={() => setAddonModalOpened(false)} />

                    {(projectNavbar && projectNavbar.whiteboard) && (whiteboardAddonState && whiteboardAddonState == 'installed_active') && hasPermission(
                        loggedInUser,
                        ['whiteboard-access', 'whiteboard-manage', 'whiteboard-comments', 'edit-whiteboard-comments', 'delete-whiteboard-comments',
                            'create-edit-whiteboard-page', 'delete-whiteboard-page'
                        ],
                        projectPermissions, 'project'
                    )
                        && (
                            <div id="lazytasks_whiteboard_tab_button">
                                {/* for whiteboard */}
                            </div>
                        )
                    }

                    {/*<Button className="!text-sm" size="sm" color={"#EBF1F4"} styles={{ label: { color: "#c2c2c2" } }}>
                            Gantt chart
                        </Button>*/}
                    {projectNavbar && projectNavbar.gantt && (
                        <Button
                            onClick={() => handleViewSwitch('gantt')}
                            className="!text-sm"
                            activeClassName="active-link"
                            size="sm"
                            color={location.pathname === ganttChartPagePathName ? "#39758D" : "#EBF1F4"}
                            styles={{
                                label: {
                                    color: location.pathname === ganttChartPagePathName ? "#fff" : "#000"
                                }
                            }}
                        >
                            {translate("Gantt chart")}
                        </Button>
                    )}
                    {projectNavbar && projectNavbar.swimlane && (
                        <Tooltip withinPortal={false} className="!py-0 !text-[10px] !z-10" label={translate("Coming Soon")} opened position="top" offset={-8} color={"#ED7D31"} size="xs">
                            <Button className="!text-sm" activeClassName="active-link" size="sm" color={"#EBF1F4"} styles={{ label: { color: "#c2c2c2" } }} disabled>
                                {translate("Swimlane")}
                            </Button>
                        </Tooltip>
                    )}

                    {(projectNavbar?.report !== false) && (
                        <Button
                            onClick={() => handleViewSwitch('report')}
                            className="!text-sm"
                            activeClassName="active-link"
                            size="sm"
                            color={location.pathname === reportPagePathName ? "#39758D" : "#EBF1F4"}
                            styles={{
                                label: {
                                    color: location.pathname === reportPagePathName ? "#fff" : "#000"
                                }
                            }}
                        >
                            {translate("Report")}
                        </Button>
                    )}

                </div>

                <div className="relative filterandusers flex flex-wrap items-center gap-2.5 mb-3">
                    {location && location.pathname === ganttChartPagePathName &&
                        <>
                            <Select
                                style={{ maxWidth: '100px' }}
                                size="xs"
                                value={ganttViewMode}
                                data={[
                                    { value: 'Day', label: translate('Day') },
                                    { value: 'Week', label: translate('Week') },
                                    { value: 'Month', label: translate('Month') },
                                ]}
                                onChange={(value) => dispatch(changeGanttViewMode(value))}
                                allowDeselect={false}
                            />
                        </>
                    }
                    <Tooltip withinPortal={false} label={translate('Refresh')} position="top" withArrow>
                        <ActionIcon onClick={() => handleRefresh()} variant="filled" size={36} color="#FDF2EA" c="#ED7D31" radius="xl" aria-label="Refresh">
                            <IconRefresh size={24} stroke={1.5} />
                        </ActionIcon>
                    </Tooltip>



                    {isActive && (
                        <Menu shadow={false} width={200} position="bottom-center" styles={menuStyles}>
                            <Menu.Target>
                                <Tooltip withinPortal={false} label={translate('Group by')} position="top" withArrow>
                                    <ActionIcon
                                        variant="light"
                                        size={36}
                                        radius="xl"
                                        color="#39758D"
                                        c={sectionByValue ? '#39758D' : '#4D4D4D'}
                                        aria-label="Section By"
                                        style={sectionByValue ? { backgroundColor: '#D6E8EE' } : {}}
                                    >
                                        <IconLayoutColumns size={24} stroke={1.5} />
                                    </ActionIcon>
                                </Tooltip>
                            </Menu.Target>

                            <Menu.Dropdown>
                                <Menu.Label>
                                    <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                        <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: T.teal, flexShrink: 0 }} />
                                        {translate('Group By')}
                                    </span>
                                </Menu.Label>
                                <Menu.Item
                                    rightSection={!sectionByValue ? <IconCheck size={14} stroke={1.5} color={T.teal} /> : null}
                                    onClick={() => handleSectionBy('section')}
                                >
                                    {translate('Section')}
                                </Menu.Item>
                                <Menu.Item
                                    rightSection={sectionByValue === 'priority' ? <IconCheck size={14} stroke={1.5} color={T.teal} /> : null}
                                    onClick={() => handleSectionBy('priority')}
                                >
                                    {translate('Priority')}
                                </Menu.Item>
                                <Menu.Item
                                    rightSection={sectionByValue === 'status' ? <IconCheck size={14} stroke={1.5} color={T.teal} /> : null}
                                    onClick={() => handleSectionBy('status')}
                                >
                                    {translate('Status')}
                                </Menu.Item>
                                <Menu.Item
                                    rightSection={sectionByValue === 'member' ? <IconCheck size={14} stroke={1.5} color={T.teal} /> : null}
                                    onClick={() => handleSectionBy('member')}
                                >
                                    {translate('Assigned To')}
                                </Menu.Item>
                                <Menu.Item
                                    rightSection={sectionByValue === 'duedate' ? <IconCheck size={14} stroke={1.5} color={T.teal} /> : null}
                                    onClick={() => handleSectionBy('duedate')}
                                >
                                    {translate('Due Date')}
                                </Menu.Item>
                            </Menu.Dropdown>
                        </Menu>
                    )}

                    <FilterTasksPopover project_id={id} reloadSections={reloadSections} />
                    {location && (location.pathname === listPagePathName || location.pathname === boardPagePathName) && (() => {
                        const canAddSection = hasPermission(loggedInUser, ['manage-section'], projectPermissions, 'project');
                        return (
                            <Tooltip withinPortal={false} label={translate('Add Section')} position="top" withArrow>
                                <ActionIcon
                                    onClick={() => canAddSection && !isAddingSection && handleAddSection()}
                                    variant="light" size={36} radius="xl" color="#39758D" c="#4D4D4D" aria-label="Section"
                                    loading={isAddingSection}
                                    disabled={!canAddSection || isAddingSection}
                                    className={!canAddSection ? 'opacity-50 !cursor-not-allowed' : ''}
                                    loaderProps={{ type: 'dots' }}
                                >
                                    <IconCodeVariablePlus size={24} stroke={1.5} />
                                </ActionIcon>
                            </Tooltip>
                        );
                    })()}
                    {/* <ShortcutPopover /> */}
                    {location && (location.pathname === listPagePathName || activePaths.includes(location.pathname)) && (
                        <div className="flex items-center">
                            <ProjectAddTaskSnippet
                                projectId={id}
                                disabled={!hasPermission(loggedInUser, ['create-task'], projectPermissions, 'project')}
                            />
                        </div>
                    )}
                    <div className="flex gap-2">
                        <MemberAddRemovePopover
                            isOpened={isOpenedMemberPopover}
                            setIsOpened={setIsOpenedMemberPopover}
                        />
                    </div>



                </div>
            </div>

            {activeFilterPills.length > 0 && (
                <div className="flex flex-wrap justify-end items-center gap-2 px-1 pb-2">
                    {activeFilterPills.map((pill) => (
                        <Badge
                            key={pill.key}
                            color="cyan"
                            variant="light"
                            size="sm"
                            rightSection={
                                <ActionIcon
                                    size="xs"
                                    color="cyan"
                                    radius="xl"
                                    variant="transparent"
                                    onClick={() => {
                                        const updated = { ...filterValues, [pill.key]: pill.key === 'name' ? '' : null };
                                        dispatch(updateFilterValues(updated));
                                        dispatch(fetchTasksByProject({ id, data: updated, userId }));
                                    }}
                                >
                                    <IconX size={10} />
                                </ActionIcon>
                            }
                        >
                            {pill.label}
                        </Badge>
                    ))}
                </div>
            )}

            <div className="drawer mt-[16]">

                <Drawer
                    opened={settingDrawerOpened}
                    onClose={settingDrawerClose}
                    position="right"
                    withCloseButton={false}
                    size="lg"
                    overlayProps={{ backgroundOpacity: 0.3, blur: 1 }}
                    zIndex={1000}
                    styles={{
                        inner: {
                            transform: appLocalizer?.is_admin ? 'translateX(0px)' : 'translateX(0px)',
                        }
                    }}
                >
                    <Drawer.Body>
                        <Card padding="lg" withBorder radius="md" shadow="sm">
                            <Card.Section withBorder inheritPadding py="xs" className="bg-[#FDFDFD] mb-4 border-b border-[#E0E0E0]">
                                <Group justify="space-between" align="center">
                                    <Text fw={600} size="md">
                                        {currentActiveTab === 'closed-tasks'
                                            ? translate('Closed Tasks')
                                            : currentActiveTab === 'sections'
                                                ? translate('Archived Sections')
                                                : translate('Archived Tasks')}
                                    </Text>
                                    <ActionIcon variant="subtle" onClick={settingDrawerClose} color="gray">
                                        <IconX style={{ height: "70%", width: "70%" }} stroke={1.5} />
                                    </ActionIcon>
                                </Group>
                            </Card.Section>

                            {settingDrawerOpened && <ViewArchive onCloseDrawer={settingDrawerClose} drawerContext={drawerContext} onTabChange={setCurrentActiveTab} />}

                        </Card>
                    </Drawer.Body>
                </Drawer>

            </div>


            <ProjectConfigureModal project_id={id} opened={projectNavConfigureModalOpen} onClose={() => setProjectNavConfigureModalOpen(false)} />
            <ProjectSettingsModal project_id={id} opened={projectSettingsModalOpen} onClose={() => setProjectSettingsModalOpen(false)} />

            <Modal
                opened={helpGuideModalOpened}
                onClose={() => setHelpGuideModalOpened(false)}
                title={
                    <Group spacing="xs">
                        <ThemeIcon color="#39758D" variant="light" radius="md" size="lg">
                            <IconInfoCircle size={22} stroke={1.5} />
                        </ThemeIcon>
                        <Text fw={600} size="lg">{translate('Project Guide')}</Text>
                    </Group>
                }
                size="xl"
                centered
                radius="md"
                overlayProps={{ backgroundOpacity: 0.4, blur: 2 }}
            >
                <Divider mb="md" />

                <Tabs defaultValue="overview">
                    <Tabs.List>
                        <Tabs.Tab value="overview" leftSection={<IconLayoutDashboard size={14} />}>
                            {translate('Overview')}
                        </Tabs.Tab>
                        {projectNavbar && projectNavbar.list && (
                            <Tabs.Tab value="list" leftSection={<IconList size={14} />}>
                                {translate('List')}
                            </Tabs.Tab>
                        )}
                        {projectNavbar && projectNavbar.board && (
                            <Tabs.Tab value="board" leftSection={<IconLayoutKanban size={14} />}>
                                {translate('Board')}
                            </Tabs.Tab>
                        )}
                        {projectNavbar && projectNavbar.calendar && (
                            <Tabs.Tab value="calendar" leftSection={<IconCalendar size={14} />}>
                                {translate('Calendar')}
                            </Tabs.Tab>
                        )}
                        {projectNavbar && projectNavbar.gantt && (
                            <Tabs.Tab value="gantt" leftSection={<IconTimeline size={14} />}>
                                {translate('Gantt Chart')}
                            </Tabs.Tab>
                        )}
                        {projectNavbar && projectNavbar.whiteboard && (
                            <Tabs.Tab value="whiteboard" leftSection={<IconPencil size={14} />}>
                                {translate('Whiteboard')}
                            </Tabs.Tab>
                        )}
                        <Tabs.Tab value="settings" leftSection={<IconSettings2 size={14} />}>
                            {translate('Settings')}
                        </Tabs.Tab>
                        <Tabs.Tab value="mobile" leftSection={<IconDeviceMobile size={14} />}>
                            {translate('Mobile App')}
                        </Tabs.Tab>
                    </Tabs.List>

                    {/* Overview */}
                    <Tabs.Panel value="overview" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconLayoutDashboard size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Switching views')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the view tabs at the top (List, Board, Calendar, Gantt Chart, Whiteboard) to see your tasks in different ways. Enable or disable views for this project from Project Settings.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconSettings2 size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Configure your project')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Access Project Settings via the \u2699 icon to configure views, custom statuses, custom priorities, member permissions, and notification templates — all per project.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="teal" variant="light" radius="md" size="md">
                                        <IconWorldWww size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Frontend view')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Your project can be published as a public-facing page, allowing clients or guests to view project progress without needing access to the admin panel.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconDeviceMobile size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Mobile app')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Access your tasks from anywhere using the LazyTasks mobile app. Available on iOS and Android.')}
                                </Text>
                            </div>
                        </div>
                    </Tabs.Panel>

                    {/* List */}
                    <Tabs.Panel value="list" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconList size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Task list by section')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Tasks are grouped into sections. Collapse or expand sections using the arrow, drag sections to reorder them, and create new sections inline at the bottom of the list.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconGripVertical size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Add & reorder tasks')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Add tasks with the "+ Add Task" button inside any section. Drag task rows to reorder them within or across sections.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconLayoutColumns size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Section By (Group By)')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the "Section By" control to regroup tasks by a different parameter — such as status, priority, or assignee — for a different perspective on your work.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconAdjustmentsHorizontal size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Filters & search')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the filter icon and search bar to narrow down visible tasks by assignee, priority, status, date, and more.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="gray" variant="light" radius="md" size="md">
                                        <IconFolderOpen size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Archive sections')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the Settings (\u2699) menu to archive entire sections, keeping your workspace clean. Archived sections can be restored at any time.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="teal" variant="light" radius="md" size="md">
                                        <IconCircleCheck size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Complete & close tasks')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Once a task is marked as complete, you can then formally "close" it as a separate step. This two-step flow helps track the gap between task completion and official closure for efficiency reporting.')}
                                </Text>
                            </div>
                        </div>
                    </Tabs.Panel>

                    {/* Board */}
                    <Tabs.Panel value="board" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconLayoutKanban size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Tasks as cards')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('The board shows tasks grouped into columns by status. Each card displays key information at a glance — assignee, priority, due date, and more.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconGripVertical size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Drag between columns')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Drag a card to a different column to instantly update the task status. The task status updates in real time.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconLayoutColumns size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Section By (Group By)')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the "Section By" control to switch the grouping axis — for example, group by assignee or priority instead of status.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconCheck size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Add tasks from the board')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Click "+ Add Task" at the bottom of any column to create a task directly in that status.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconTag size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Custom statuses')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Board columns reflect your project\'s custom statuses. Add, rename, or reorder statuses from Project Settings.')}
                                </Text>
                            </div>
                        </div>
                    </Tabs.Panel>

                    {/* Calendar */}
                    <Tabs.Panel value="calendar" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconCalendar size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Tasks with due dates')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('The calendar displays tasks that have a due date assigned. Tasks without a due date do not appear on the calendar.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconCalendarEvent size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Click a date to create a task')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Click any date cell to quickly create a new task with that date pre-filled as the due date.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconArrowsHorizontal size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Navigate months')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the previous and next arrows at the top of the calendar to move between months.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconLayoutColumns size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Section By (Group By)')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the "Section By" control to filter which grouping of tasks is shown on the calendar.')}
                                </Text>
                            </div>
                        </div>
                    </Tabs.Panel>

                    {/* Gantt Chart */}
                    <Tabs.Panel value="gantt" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconEye size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Which tasks appear here?')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Only tasks marked as visible on the Gantt chart are shown. You can toggle visibility from the task list using the Gantt icon on each task row. Tasks must have start or end dates to display a bar on the timeline.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconSubtask size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Parent & Subtask grouping')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('If a subtask is visible on the Gantt chart, its parent task will automatically appear as a group header — even if the parent itself is not marked visible. Tasks are ordered by section, just like the list view.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconGripVertical size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Move tasks')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Drag a task bar horizontally to shift both its start and end dates while keeping the same duration. Connected dependent tasks will automatically shift along with it.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconArrowsHorizontal size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Resize duration')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Drag the left or right edge of a task bar to change its start or end date independently. This lets you extend or shorten the task duration.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconCalendarEvent size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('View modes')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Switch between Day, Week, and Month views using the dropdown to zoom in or out on the timeline. Use Day view for detailed scheduling and Month view for a high-level overview.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="red" variant="light" radius="md" size="md">
                                        <IconX size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Remove from Gantt')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Hover over a task name in the side panel and click the X icon to remove it from the Gantt chart. The task itself is not deleted — it is only hidden from this view.')}
                                </Text>
                            </div>
                        </div>
                        <Divider mt="md" mb="sm" />
                        <Text size="xs" c="dimmed" ta="center">
                            {translate('Double-click any task bar or row to open the task details drawer.')}
                        </Text>
                    </Tabs.Panel>

                    {/* Whiteboard */}
                    <Tabs.Panel value="whiteboard" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconPencil size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Visual freeform canvas')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('The whiteboard is a free-form space to sketch ideas, diagrams, and flows related to your project. Everything is saved automatically.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconAdjustmentsHorizontal size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Drawing tools')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use shapes, text, lines, and freehand drawing to build your canvas. Select and move elements freely.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconLayoutColumns size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Multiple pages')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Organize your content across multiple whiteboard pages within the same project.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="red" variant="light" radius="md" size="md">
                                        <IconCodeVariablePlus size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Addon required')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('The Whiteboard feature requires the LazyTasks Whiteboard addon to be installed and activated. Access it from the Addons panel if not yet installed.')}
                                </Text>
                            </div>
                        </div>
                    </Tabs.Panel>

                    {/* Settings */}
                    <Tabs.Panel value="settings" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="#39758D" variant="light" radius="md" size="md">
                                        <IconTag size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Custom statuses')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Define your own task statuses per project (e.g., In Review, Blocked). Manage them under Project Settings \u2192 Statuses.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="orange" variant="light" radius="md" size="md">
                                        <IconArrowBarRight size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Custom priorities')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Add or remove priority levels per project to match your workflow. Manage them under Project Settings \u2192 Priorities.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="grape" variant="light" radius="md" size="md">
                                        <IconShieldCheck size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Permissions')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Control what each role can do within this project. Configure per-project permissions under Project Settings \u2192 Permissions.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="teal" variant="light" radius="md" size="md">
                                        <IconBell size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Notification templates')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Customize the email and notification templates sent for project events. Manage them under Project Settings \u2192 Notifications.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="gray" variant="light" radius="md" size="md">
                                        <IconFolderOpen size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Archive project or sections')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Use the Settings (\u2699) menu to archive the entire project or individual sections. Archived items are hidden from the main view but can be restored at any time.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="teal" variant="light" radius="md" size="md">
                                        <IconCircleCheck size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Complete & close tasks')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('After marking a task as complete, a separate "Close" action formally records the closure date. This two-step flow helps measure the time between task completion and official closure for efficiency reporting.')}
                                </Text>
                            </div>
                            <div>
                                <Group spacing="xs" mb={6}>
                                    <ThemeIcon color="cyan" variant="light" radius="md" size="md">
                                        <IconWorldWww size={16} stroke={1.5} />
                                    </ThemeIcon>
                                    <Text fw={600} size="sm">{translate('Frontend view')}</Text>
                                </Group>
                                <Text size="sm" c="dimmed" ml={42}>
                                    {translate('Enable a public-facing frontend page for your project so clients or guests can view project progress without needing admin panel access.')}
                                </Text>
                            </div>
                        </div>
                    </Tabs.Panel>

                    {/* Mobile App */}
                    <Tabs.Panel value="mobile" pt="md">
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '48px 24px', gap: '12px' }}>
                            <ThemeIcon color="gray" variant="light" radius="xl" size={56}>
                                <IconDeviceMobile size={30} stroke={1.5} />
                            </ThemeIcon>
                            <Text fw={600} size="md" c="dimmed">{translate('Mobile App Guide')}</Text>
                            <Badge color="orange" variant="light" size="lg">{translate('Coming Soon')}</Badge>
                            <Text size="sm" c="dimmed" ta="center" style={{ maxWidth: 320 }}>
                                {translate('Mobile app documentation will be available here soon.')}
                            </Text>
                        </div>
                    </Tabs.Panel>
                </Tabs>
            </Modal>

        </>

    );
}

export default ProjectDetailsNav;
