/**
 * ----------------------Start-of-list-view and grid-view--------------------------------------------
 */

const timerIds = {}; // Store timer IDs for each project box

document.addEventListener("DOMContentLoaded", function() {
    const rcListViewBtn = document.querySelector('#ReadyToPlan .list-view');
    const rcGridViewBtn = document.querySelector('#ReadyToPlan .grid-view');
    const planListViewBtn = document.querySelector('#PlannedProjects .list-view');
    const planGridViewBtn = document.querySelector('#PlannedProjects .grid-view');
    //const projectBoxes = document.querySelector('.project-boxes');
    const rcProjectBoxes = document.querySelector('#RCProjectBoxes');
    const planProjectBoxes = document.querySelector('#PlannedProjectBoxes');
    rcListViewBtn.addEventListener('click', function() {
        rcGridViewBtn.classList.remove('active');
        rcListViewBtn.classList.add('active');
        rcProjectBoxes.classList.remove('jsGridView');
        rcProjectBoxes.classList.add('jsListView');
    });
    rcGridViewBtn.addEventListener('click', function() {
        rcListViewBtn.classList.remove('active');
        rcGridViewBtn.classList.add('active');
        rcProjectBoxes.classList.remove('jsListView');
        rcProjectBoxes.classList.add('jsGridView');
    });
    planListViewBtn.addEventListener('click', function() {
        planGridViewBtn.classList.remove('active');
        planListViewBtn.classList.add('active');
        planProjectBoxes.classList.remove('jsGridView');
        planProjectBoxes.classList.add('jsListView');
    });
    planGridViewBtn.addEventListener('click', function() {
        planListViewBtn.classList.remove('active');
        planGridViewBtn.classList.add('active');
        planProjectBoxes.classList.remove('jsListView');
        planProjectBoxes.classList.add('jsGridView');
    });
    //---------------------------------------End-of-list-view and grid-view-----------------------------------------------------------
    var searchInput = document.getElementById('searchQuery');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                performSearch();
            });
        }
    //---------------------------------------Start of new project popup---------------------------------------------------------------

    const machineSelect = document.getElementById('machineNameSelect');
    const processSelect = document.getElementById('processSelect');
    // Load machine and process options from local storage
    function populateOptions() {
        const machineDataList = JSON.parse(localStorage.getItem('machineDataList')) || [];
        const processDataList = JSON.parse(localStorage.getItem('processDataList')) || [];

        // Populate machine options
        machineDataList.forEach(machine => {
        const option = document.createElement('option');
        option.value = machine;
        option.textContent = machine;
        machineSelect.appendChild(option);
        });

        // Populate process options
        processDataList.forEach(process => {
        const option = document.createElement('option');
        option.value = process;
        option.textContent = process;
        processSelect.appendChild(option);
        });
    }

        //Function to save project data
        function saveProjectData(projectData) {
            const projects = JSON.parse(localStorage.getItem('projectDataList')) || [];
            projects.push(projectData);
            localStorage.setItem('projectDataList', JSON.stringify(projects));
        }

    // Load and create project boxes from local storage
    function loadExistingProjects() {
        const projects = JSON.parse(localStorage.getItem('rcDataList')) || [];
        projects.forEach((projectData,index) => {
            rcProjectBox(projectData,index);
        });
        const plannedProjects = JSON.parse(localStorage.getItem("PlannedProjectsData")) || {};

        Object.entries(plannedProjects).forEach(([key, projectData], index) => {
            plannedProjectBox(projectData, index);
        });
    }
    // Event listener for form submission
    document.getElementById('newProjectSave').addEventListener('click', function (event) {
        event.preventDefault();
    
        // Gather form values
        const machineName = document.getElementById('machineNameSelect').value;
        const processName = document.getElementById('processSelect').value;
        const startDate = document.getElementById('startTime').value;
        const endDate = document.getElementById('endTime').value;
    
        const editingBoxId = this.dataset.editingBoxId;
        let projects = JSON.parse(localStorage.getItem('projectDataList')) || [];
    
        if (editingBoxId) {
        // Update existing project in localStorage
        const index = projects.findIndex(project => project.id == editingBoxId);
        if (index !== -1) {
            projects[index] = {
            ...projects[index],
            machineName,
            processName,
            date: startDate,
            deadline: endDate,
            };
            localStorage.setItem('projectDataList', JSON.stringify(projects));
    
            // Update the display of the existing project box
            updateProjectBox(projects[index]);
        }
    
        // Clear edit flag
        delete this.dataset.editingBoxId;
        } else {
        // Add new project if not in edit mode
        const projectData = {
            id: Date.now(),
            machineName,
            processName,
            date: startDate,
            deadline: endDate,
            progressStatus: 'Inactive',
            progressPercentage: 0,
            progressColor: '#fff',
        };
    
        // Save project data to local storage
        saveProjectData(projectData);
        rcProjectBox(projectData);
        plannedProjectBox(projectData);
        }
    
        // Reset form and close the popup
        resetForm();
        newProjectClosePopup();
    });
    
    // Initialize on page load
    populateOptions();
    loadExistingProjects();

    // Sort project boxes every seconds
    //   setInterval(sortProjectBoxesByRemainingTime, 1000);
        
});

function updateProjectBox(projectData) {
  const projectBox = document.querySelector(`.project-box[data-box-id="${projectData.id}"]`);

  if (projectBox) {
    // Update fields in the project box
    projectBox.querySelector('.box-content-header').textContent = projectData.machineName;
    projectBox.querySelector('.box-content-subheader').textContent = projectData.processName;
    projectBox.querySelector('.project-date').textContent = formatDate(projectData.date);

    const countdownDisplay = projectBox.querySelector(`#countdown-${projectData.id}`);
    startCountdownTimer(projectData.date, projectData.deadline, countdownDisplay, projectData.id);
  }
}

// Function to set up edit listener on a specific pencil icon by boxId
function viewRCDetails(boxId) {
    const rcData = JSON.parse(localStorage.getItem('rcDataList')) || [];
    const rcId1 = rcData[boxId];

    sessionStorage.setItem('viewRCId', rcId1.rcId);

    // Redirect to the form page for editing details
    window.location.href = 'route-card.html';
}
// Function to set up edit listener on a specific pencil icon by boxId
function initializeEditListener(boxId) {
    // const planData = JSON.parse(localStorage.getItem('PlannedProjectsData')) || [];
    // const planId1 = planData[boxId];

    // sessionStorage.setItem('editPlanId', planId1.rcId);
    sessionStorage.setItem('editPlanId', boxId);

    // Redirect to the form page for editing details
    window.location.href = 'project-planning.html';
}
function initializeViewListener(boxId) {

    sessionStorage.setItem('viewPlanId', boxId);

    // Redirect to the form page for editing details
    window.location.href = 'project-planning.html';
}

/**
 * ------------------------------projectbox popup validation-------------------------------------
 */

// Function to handle the selection of an option
function selectOption(option, percentage, color, boxId) {
    // Use the boxId to find the specific project box
    const boxProgressWrapper = document.querySelector(`.box-progress-wrapper[data-box-id="${boxId}"]`);

    // Check if the boxProgressWrapper exists
    if (boxProgressWrapper) {
        boxProgressWrapper.querySelector('.box-progress-header').textContent = option;
        // boxProgressWrapper.querySelector('.box-progress').style.width = percentage;
        boxProgressWrapper.querySelector('.box-progress').style.backgroundColor = color;

        const progressPercentage = boxProgressWrapper.querySelector('.box-progress-percentage');

        if (option === 'Cancelled') {
            const iconCancel = '<i class="fas fa-ban" style="color: #ff0000;"></i>';
            progressPercentage.innerHTML = iconCancel;
        } else if (option === 'Hold') {
            const iconHold = '<i class="fas fa-pause" style="color: #A020F0;"></i>';
            progressPercentage.innerHTML = iconHold;
        } else {
            progressPercentage.textContent = '';
        }
    }

    closePopup(boxId);
}

// Close the popup when clicking outside of it
document.addEventListener('click', function(event) {
    const openPopups = document.querySelectorAll('.popup-container');

    openPopups.forEach(popup => {
        // Check if the click happened outside the popup and the "More" button
        if (!popup.contains(event.target) && !event.target.closest('.project-btn-more')) {
            popup.style.display = 'none';
        }
    });
});

// Function to open the popup at the position of the clicked project box
function openPopup(event, boxId) {
    // Close any open popups
    const openPopups = document.querySelectorAll('.popup-container');
    openPopups.forEach(popup => {
        popup.style.display = 'none'; // Hide all open popups
    });

    // Show the popup for the clicked box
    const popupToOpen = document.querySelector(`#status-popup-${boxId}`);
    if (popupToOpen) {
        // Get the position of the button that triggered the popup
        const rect = event.currentTarget.getBoundingClientRect();

        // Position the popup within the project box
        popupToOpen.style.position = 'absolute';
        popupToOpen.style.left = `${rect.left + window.scrollX - 280}px`; // Adjust the X position
        popupToOpen.style.top = `${rect.top + window.scrollY - 30}px`; // Adjust the Y position
        popupToOpen.style.display = 'block'; // Make the popup visible
        popupToOpen.style.zIndex = '1000'; // Ensure the popup appears above other elements
    }
}

// Function to close a specific popup
function closePopup(boxId) {
    const popup = document.querySelector(`#status-popup-${boxId}`);
    if (popup) {
        popup.style.display = 'none'; // Hide the popup
    }
}

/**
 * -----------------------------End-of-popup validation-------------------------------------
 */

/**
 * ----------------------------Start of search bar Query for project boxes-------------------------------------
 */
// document.getElementById('searchQuery').addEventListener('input', function(){
//   performSearch();
// });
// Modify the event listener for the checkboxes to unselect all others when one is selected
document.querySelectorAll('.filter-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        // Uncheck all checkboxes except the one that was clicked
        if (this.checked) {
        document.querySelectorAll('.filter-checkbox').forEach(cb => {
            if (cb !== this) cb.checked = false;
        });
        }

        // Perform the search after updating the checkbox states
        performSearch();
    });
});

function performSearch() {  
    const searchQuery = document.getElementById('searchQuery').value.toLowerCase();
    const selectedFilters = Array.from(document.querySelectorAll('.filter-checkbox:checked')).map(cb => cb.value.toLowerCase());

    // Get all project boxes to hide/show
    const projectBoxes = document.querySelectorAll('.project-box-wrapper');


    // Loop through each project box
    projectBoxes.forEach(projectBox => {
        const header = projectBox.querySelector('.box-content-header');
        const subHeader = projectBox.querySelector('.box-content-subheader');
        const dateElement = projectBox.querySelector('.project-date');
        const progressHeader = projectBox.querySelector('.box-progress-header');

        // Get text content for comparison
        const headerContent = header ? header.textContent.toLowerCase() : '';
        const subHeaderContent = subHeader ? subHeader.textContent.toLowerCase() : '';
        const dateContent = dateElement ? dateElement.textContent.toLowerCase() : '';
        const progressHeaderContent = progressHeader ? progressHeader.textContent.toLowerCase() : '';

        // Basic search match
        const matchesSearch = headerContent.includes(searchQuery) ||
                            subHeaderContent.includes(searchQuery) ||
                            dateContent.includes(searchQuery) ||
                            progressHeaderContent.includes(searchQuery);

        // Filter match
        let matchesFilter = true;
        if (selectedFilters.length > 0) {
        matchesFilter = selectedFilters.every(filter => 
            headerContent.includes(filter) ||
            subHeaderContent.includes(filter) ||
            progressHeaderContent.includes(filter)
        );
    }

    // Show or hide based on both search and filter
    if (matchesSearch && matchesFilter) {
        projectBox.style.display = 'block';
    } else {
        projectBox.style.display = 'none';
    }
});
}

/**
 * -----------------------------End-of-search bar query-------------------------------------
 */
/**
 * -----------------------------Start of making project box dynamic-------------------------------------
 */
// Array of background colors to cycle through for each new project box
const projectBoxColors = ['#dbf6fd', '#ffdeeb','#f0e3bf','#d9e3bf','#f0d9bf','#f0bfe3','#e3bfe3', '#e6f4ea', '#fdeedc',
    '#bfe3c8', '#fcefe6','#bfd2e3','#e3bfc2','#e3d9bf', '#f0e3bf','#d9e3bf','#f0d9bf','#f0bfe3','#e3bfe3','#e3d9e3'];
let colorIndex = 0;


// Function to create a new project box
function rcProjectBox(projectData,index) {

    let plannedProjects = JSON.parse(localStorage.getItem("PlannedProjectsData")) || {};
    if (projectData.rcId){
        for (let n in plannedProjects) {
            if (plannedProjects[n].rcId === projectData.rcId) {
                return;
            }
        }
    }

    const projectBoxContainer = document.querySelector('#RCProjectBoxes'); // Reference the new container
    // Get the next background color and increment the index for the next box
    const backgroundColor = projectBoxColors[colorIndex];
    colorIndex = (colorIndex + 1) % projectBoxColors.length; // Cycle through the colors
    // Generate a unique box ID
    const boxId = index;
    // const boxId = Date.now();
    // Create a new project box
    const newProjectBox = document.createElement('div');
    newProjectBox.classList.add('project-box-wrapper'); // Same class as existing box wrapper
    newProjectBox.innerHTML = `
        <div class="project-box" data-box-id="${boxId}" style="background-color: ${backgroundColor};">
            <div class="project-box-header">
                <span class="project-date">RC Date: ${projectData.rcDate}</span>
                <div class="more-wrapper">
                    <button class="project-btn-edit" onclick="event.stopPropagation(); viewRCDetails(${boxId})">
                    <i class="fas fa-eye edit-project-box" id ="edit-project-${boxId}" title="View Route Card Details"></i>
                    </button>
                    <button class="project-btn-more" onclick="event.stopPropagation(); openPopup(event, ${boxId})">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                        viewBox="0 0 24 24" fill="none" stroke="currentColor"
                        stroke-width="2" stroke-linecap="round"
                        stroke-linejoin="round" class="feather feather-more-vertical">
                        <circle cx="12" cy="12" r="1" />
                        <circle cx="12" cy="5" r="1" />
                        <circle cx="12" cy="19" r="1" />
                    </svg>
                    </button>
                </div>
            </div>
            <div class="project-box-content-header">
                <p class="box-content-header">${projectData.rcId}</p>
                <p class="box-content-subheader">${projectData.companyName}</p>
            </div>
            <div class="box-progress-wrapper" data-box-id="${boxId}">
                <p class="box-progress-header">Ready to plan</p>
                <div class="box-progress-bar">
                    <span class="box-progress" style="width: 100%; background-color: #4287f5;"></span>
                </div>
                <p class="box-progress-percentage"></p>
            </div>
            ${projectData.approvedBy ? `<p class="box-approval-status">Appoved By: ${projectData.approvedBy} | On: ${projectData.approvedBy}</p>`
                : `<p class="box-approval-status">Appoved By: Admin | On: ${currentDate()}</p>`}
            <div class="project-box-footer">
                <div class="participants">
                    <button class="add-participant" onclick="event.stopPropagation();" style="color: #ff942e;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"
                                viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                stroke-width="3" stroke-linecap="round"
                                stroke-linejoin="round" class="feather feather-plus">
                            <path d="M12 5v14M5 12h14" />
                        </svg>
                    </button>
                </div>
                <div class="convertBtn days-left" style="color: #ff942e;" onclick="redirectToProjectPage(${boxId})">Create Plan</div>
            </div>
        </div>
        <!-- Status Popup Container -->
        <div class="popup-container" id="status-popup-${boxId}" data-box-id="${boxId}">
            <div class="popup-item Assigned" onclick="selectOption('Ready To Plan', '100%', '#4287f5', ${boxId})">
                <i class="fas fa-pencil-alt"></i>
                <span>Ready To Plan</span>
            </div>
            <div class="popup-item Inprogress" onclick="selectOption('Waiting For Approval', '100%', '#fa6b05', ${boxId})">
                <i class="fas fa-exclamation"></i>
                <span>Waiting For Approval</span>
            </div>
            <div class="popup-item WorkDone" onclick="selectOption('Reschedule', '100%', '#faee05', ${boxId})">
                <i class="fas fa-sync-alt"></i>
                <span>Reschedule</span>
            </div>
            <div class="popup-item Approved" onclick="selectOption('Ready For Production', '100%', '#0a6905', ${boxId})">
                <i class="fas fa-thumbs-up"></i>
                <span>Ready For Production</span>
            </div>
            <div class="popup-item Cancelled" onclick="selectOption('Cancelled', '100%', '#ff0000', ${boxId})">
                <i class="fas fa-ban"></i>
                <span>Cancelled</span>
            </div>
            <div class="popup-item Hold" onclick="selectOption('Hold', '100%', '#A020F0', ${boxId})">
                <i class="fas fa-pause"></i>
                <span>Hold</span>
            </div>
        </div>
    `;
    // Append the new project box to the new container
    projectBoxContainer.appendChild(newProjectBox);
}

function plannedProjectBox(projectData,index) {
    const projectBoxContainer = document.querySelector('#PlannedProjectBoxes');
    // Get the next background color and increment the index for the next box
    const backgroundColor = projectBoxColors[colorIndex];
    colorIndex = (colorIndex + 1) % projectBoxColors.length;
    // Generate a unique box ID
    const boxId = index;
    // const boxId = Date.now();
    // Create a new project box
    const newProjectBox = document.createElement('div');
    newProjectBox.classList.add('project-box-wrapper'); // Same class as existing box wrapper
    newProjectBox.innerHTML = `
        <div class="project-box" data-box-id="${boxId}" style="background-color: ${backgroundColor};">
            <div class="project-box-header">
                <div>
                    <span class="project-date">Planned Date: ${projectData.planDate || currentDate()}</span><br>
                    <span class="project-date">Planned By: ${projectData.planBy || 'User'}</span>
                </div>
                <div class="more-wrapper">
                    ${projectData.approvedBy ? 
                    `<button class="project-btn-edit" onclick="event.stopPropagation(); initializeViewListener(${boxId})">
                        <i class="fas fa-eye edit-project-box" id ="edit-project-${boxId}" title="View Planned Data"></i>
                    </button>` : 
                    `<button class="project-btn-edit" onclick="event.stopPropagation(); initializeEditListener(${boxId})">
                        <i class="fas fa-pencil-alt edit-project-box" id ="edit-project-${boxId}" title="Edit Planned Data"></i>
                    </button>`}
                    <button class="project-btn-more" onclick="event.stopPropagation(); openPopup(event, ${boxId})">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                            viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" stroke-linecap="round"
                            stroke-linejoin="round" class="feather feather-more-vertical">
                            <circle cx="12" cy="12" r="1" />
                            <circle cx="12" cy="5" r="1" />
                            <circle cx="12" cy="19" r="1" />
                        </svg>
                    </button>
                </div>
            </div>
            <div class="project-box-content-header">
                <p class="box-content-header">${projectData.rcId}</p>
                <p class="box-content-subheader">${projectData.companyName}</p>
            </div>
            <div class="box-progress-wrapper" data-box-id="${boxId}">
                <p class="box-progress-header">${projectData.status || 'Waiting For Approval'}</p>
                <div class="box-progress-bar">
                    <span class="box-progress" style="width: 100%; background-color: #fa6b05;"></span>
                </div>
                <p class="box-progress-percentage"></p>
            </div>
            ${projectData.approvedBy ? `<p class="box-approval-status">Appoved By: ${projectData.approvedBy} | On: ${projectData.approvedBy}</p>`
                : ``}
            <div class="project-box-footer">
                <div class="participants">
                    <button class="add-participant" onclick="event.stopPropagation();" style="color: #ff942e;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"
                                viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                stroke-width="3" stroke-linecap="round"
                                stroke-linejoin="round" class="feather feather-plus">
                            <path d="M12 5v14M5 12h14" />
                        </svg>
                    </button>
                </div>
                <div class="convertBtn days-left" style="color: #ff942e; ${projectData.approvedBy ? '':'cursor:not-allowed;'}" 
                ${projectData.approvedBy ? `onclick="redirectToProductionPage(${boxId})"`:'title="Not approved yet"'}>Convert To Production</div>
            </div>
        </div>
        <!-- Status Popup Container -->
        <div class="popup-container" id="status-popup-${boxId}" data-box-id="${boxId}">
            <div class="popup-item Inprogress" onclick="selectOption('Waiting For Approval', '100%', '#fa6b05', ${boxId})">
                <i class="fas fa-exclamation"></i>
                <span>Waiting For Approval</span>
            </div>
            <div class="popup-item WorkDone" onclick="selectOption('Reschedule', '100%', '#faee05', ${boxId})">
                <i class="fas fa-sync-alt"></i>
                <span>Reschedule</span>
            </div>
            <div class="popup-item Approved" onclick="selectOption('Ready For Production', '100%', '#0a6905', ${boxId})">
                <i class="fas fa-thumbs-up"></i>
                <span>Ready For Production</span>
            </div>
            <div class="popup-item Cancelled" onclick="selectOption('Cancelled', '100%', '#ff0000', ${boxId})">
                <i class="fas fa-ban"></i>
                <span>Cancelled</span>
            </div>
            <div class="popup-item Hold" onclick="selectOption('Hold', '100%', '#A020F0', ${boxId})">
                <i class="fas fa-pause"></i>
                <span>Hold</span>
            </div>
        </div>
    `;

    // Append the new project box to the new container
    projectBoxContainer.appendChild(newProjectBox);
}

// JavaScript function to handle the redirect onclick projectbox
function redirectToProjectPage(boxId) {

    // Get the project data from localStorage using the boxId
    const projects = JSON.parse(localStorage.getItem('rcDataList')) || [];
    const projectData = projects[boxId];
    scheduleTasks(projectData);
    const projectId = projectData.rcId;
    // const projectId = boxId;

    sessionStorage.setItem('newPlanRCid', projectId);

    window.location.href = `project-planning.html`;
}
// JavaScript function to handle the redirect onclick projectbox
function redirectToProductionPage(boxId) {

    const projectId = boxId;

    sessionStorage.setItem('planToProductionid', projectId);

    window.location.href = `#`;
}

// Function to format date as 'dd-mm-yyyy hh:mm'
function formatDate(dateString) {
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based, so add 1
    const year = date.getFullYear();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${day}-${month}-${year} | ${hours}:${minutes}`;
}

// Function to start the countdown timer with timer IDs included
function startCountdownTimer(startTimeString, deadlineString, displayElement, boxId) {
    const startTime = new Date(startTimeString);
    const deadline = new Date(deadlineString);
    let timeLeft = deadline - startTime; // Calculate remaining time from startTime to deadline

    // Clear any existing timer for this project box to avoid duplicates
    if (timerIds[boxId]) {
        clearInterval(timerIds[boxId]);
    }

    updateDisplay(timeLeft, displayElement); // Update display immediately

    // Update the timer every second and save the interval ID in timerIds
    timerIds[boxId] = setInterval(() => {
        timeLeft -= 1000; // Decrease timeLeft by 1 second
        if (timeLeft <= 0) {
            displayElement.textContent = 'Task Completed';
            clearInterval(timerIds[boxId]);
            delete timerIds[boxId]; // Clean up the timer ID
        } else {
            updateDisplay(timeLeft, displayElement);
        }
    }, 1000);
}

// Function to update the display
function updateDisplay(timeLeft, displayElement) {
    if (timeLeft > 0) {
        const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60));
        const minutesLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
        const secondsLeft = Math.floor((timeLeft % (1000 * 60)) / 1000);
        displayElement.textContent = `${hoursLeft} h ${minutesLeft} m ${secondsLeft} s`;
    }
}

/**
 * -----------------------------End of making project box dynamic-------------------------------------------------------------------------
 */

//Function to sort project boxes
function sortProjectBoxesByRemainingTime() {
    const projectContainer = document.querySelector('.project-boxes.jsGridView , .project-boxes.jsListView');
    const projectBoxes = Array.from(projectContainer.getElementsByClassName('project-box-wrapper'));

    // Sort project boxes by remaining time in the countdown
    projectBoxes.sort((a, b) => {
        const countdownA = a.querySelector('.days-left').textContent;
        const countdownB = b.querySelector('.days-left').textContent;

        const timeA = parseCountdownText(countdownA);
        const timeB = parseCountdownText(countdownB);

        return timeA - timeB; // Ascending order
    });

    // Reorder boxes in the DOM
    projectBoxes.forEach(box => projectContainer.appendChild(box));
}

// Helper function to parse countdown text (e.g., "1 h 20 m 30 s" to total milliseconds)
function parseCountdownText(countdownText) {
    const timeParts = countdownText.match(/(\d+)\s*h\s*(\d+)\s*m\s*(\d+)\s*s/);

    if (timeParts) {
        const hours = parseInt(timeParts[1], 10);
        const minutes = parseInt(timeParts[2], 10);
        const seconds = parseInt(timeParts[3], 10);

        // Convert to total milliseconds
        return (hours * 3600 + minutes * 60 + seconds) * 1000;
    } else {
        return Infinity; // If "Calculating time..." or invalid format, push to end
    }
}

// Sort every 10 seconds
//populate machine name dropdown
const machineData = JSON.parse(localStorage.getItem('MachineData')) || [];
const machineNameSelect = document.getElementById("machineNameSelect");
machineData.forEach(machine => {
    const option = document.createElement("option");
    option.value = machine.machineId;
    option.textContent = machine.machineId;
    machineNameSelect.appendChild(option);
});

// ----------------------- start of planning------------------------------


// localStorage.removeItem('rcDataList');
// localStorage.removeItem('PlannedProjectsData');

sessionStorage.removeItem('newPlanRCid');
sessionStorage.removeItem('editPlanId');
sessionStorage.removeItem('viewPlanId');

console.log('PlannedProjectsData',JSON.parse(localStorage.getItem('PlannedProjectsData')));


function formatDateWithCustomLocale(dateStr) {
    const date = new Date(dateStr);
  
    const options = {
      weekday: 'short',   // 'short' is optional; you can remove it if you don't want the weekday name
      year: 'numeric',
      month: '2-digit',   // '2-digit' ensures the month and day are always two digits
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true        // Ensures 12-hour format with AM/PM
    };
  
    // Format using toLocaleString and specify the 'en-GB' locale for DD/MM/YYYY format
    return date.toLocaleString('en-GB', options).replace(',', '').replace(/\//g, '/');
}
function currentDate() {
    const now = new Date(Date.now());
    const day = String(now.getDate()).padStart(2, '0');
    const month = String(now.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
    const year = now.getFullYear();
    return `${day}-${month}-${year}`;
}

// ----------------------------------------------------------------------

function createProcessBox(projectData, index) {
    const projectBoxContainer = document.querySelector('.project-boxes.jsGridView , .project-boxes.jsListView');
    const backgroundColor = projectBoxColors[colorIndex];
    colorIndex = (colorIndex + 1) % projectBoxColors.length;
    const boxId = index;

    const newProjectBox = document.createElement('div');
    newProjectBox.classList.add('project-box-wrapper');

    // Get first process (assuming only one for now, you can loop if needed)
    const processKey = Object.keys(projectData.productProcesses)[0];
    const processData = projectData.productProcesses[processKey];

    // Format dates nicely
    const start = new Date(processData.startDate).toLocaleString();
    const end = new Date(processData.endDate).toLocaleString();

    newProjectBox.innerHTML = `
        <div class="project-box" data-box-id="${boxId}" style="background-color: ${backgroundColor};">
            <div class="project-box-header">
                <span class="project-date">Start: ${start}</span>
                <div class="more-wrapper">
                    <button class="project-btn-edit" onclick="event.stopPropagation(); initializeEditListener(${boxId})">
                        <i class="fas fa-eye edit-project-box" id="edit-project-${boxId}" title="View Process Details"></i>
                    </button>
                    <button class="project-btn-more" onclick="event.stopPropagation(); openPopup(event, ${boxId})">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                             viewBox="0 0 24 24" fill="none" stroke="currentColor"
                             stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                             class="feather feather-more-vertical">
                            <circle cx="12" cy="12" r="1"/>
                            <circle cx="12" cy="5" r="1"/>
                            <circle cx="12" cy="19" r="1"/>
                        </svg>
                    </button>
                </div>
            </div>
            <div class="project-box-content-header">
                <p class="box-content-header">${projectData.rcId}</p>
                <p class="box-content-subheader">${processData.process} - ${processData.machine}</p>
            </div>
            <div class="box-progress-wrapper" data-box-id="${boxId}">
                <p class="box-progress-header">Cycle Time</p>
                <div class="box-progress-bar">
                    <span class="box-progress" style="width: 100%; background-color: #4287f5;"></span>
                </div>
                <p class="box-progress-percentage">${processData.ctHours}h ${processData.ctMinutes}m</p>
            </div>

            <p class="box-approval-status">Operator: ${processData.operator}</p>
            <p class="box-approval-status">End: ${end}</p>

            <div class="project-box-footer">
                <div class="participants">
                    <button class="add-participant" onclick="event.stopPropagation();" style="color: #ff942e;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"
                             viewBox="0 0 24 24" fill="none" stroke="currentColor"
                             stroke-width="3" stroke-linecap="round"
                             stroke-linejoin="round" class="feather feather-plus">
                            <path d="M12 5v14M5 12h14"/>
                        </svg>
                    </button>
                </div>
                <div class="convertBtn days-left" style="color: #ff942e;" onclick="redirectToProjectPage(${boxId})">Details</div>
            </div>
        </div>
        <div class="popup-container" id="status-popup-${boxId}" data-box-id="${boxId}">
            <div class="popup-item Assigned" onclick="selectOption('Pending', '100%', '#4287f5', ${boxId})">
                <i class="fas fa-hourglass-half"></i>
                <span>Pending</span>
            </div>
            <div class="popup-item Inprogress" onclick="selectOption('In Progress', '100%', '#fa6b05', ${boxId})">
                <i class="fas fa-cogs"></i>
                <span>In Progress</span>
            </div>
            <div class="popup-item WorkDone" onclick="selectOption('Completed', '100%', '#0a6905', ${boxId})">
                <i class="fas fa-check-circle"></i>
                <span>Completed</span>
            </div>
        </div>
    `;

    projectBoxContainer.appendChild(newProjectBox);
}
