<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Switch Games 2024</title>
    <style>
/* General Body Setup */
body {
    font-family: Arial, sans-serif;
    display: flex;
    background-color: #f3f4f6;
    margin: 0;
    margin-top: 90px; /* Adjust depending on the height of the search container */
    padding: 0;
    box-sizing: border-box;
	user-select: none;

}

/* Pane for Left and Right sections */
.pane {
    width: 50%;
    padding: 20px;
    border: 1px solid #ddd;
    box-sizing: border-box;
    overflow-y: auto;
    height: 90vh;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
}

.pane.left {
    margin-right: 10px;
}

.pane.right {
    margin-left: 10px;
}

/* Item Styling */
.item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #ddd;
    cursor: pointer;
    border-radius: 5px;
    transition: background-color 0.3s ease, transform 0.2s ease;
}
    .icon-img {
        width: auto; /* Adjust width as needed */
        height: 50px; /* Maintain aspect ratio */
        margin-right: 10px; /* Add spacing between icon and text */
    }
.item:hover {
    background-color: #f0f0f0;
}

.item.selected {
    background-color: #0f1d2b;
    color: white;
    transform: scale(1.05);
}

.item.selected:hover {
    background-color: #0070f3;
}

.item.highlight {
    background-color: #ffd966;
}

/* Controls Section */
.controls {
    margin-bottom: 20px;
    justify-content: space-between;
}

.button-group button {
    background-color: #0070f3;
    color: white;
    padding: 6px 25px; /* Smaller padding for smaller buttons */
    border: none;
    border-radius: 5px;
    font-size: 0.8rem; /* Smaller font size for compact design */
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.button-group button:hover {
    background-color: #005bb5;
}

.button-group button:disabled {
    background-color: #d3d3d3;
    cursor: not-allowed;
}

/* Input box for customer name and search */
input[type="text"] {
    padding: 5px;
    font-size: 1rem;
    width: 95%;
    border: 1px solid #ddd;
    border-radius: 2px;
    margin-bottom: 20px;
}

input[type="text"]:focus {
    border-color: #0070f3;
    outline: none;
}

/* Selected item wrapping off */
#selectedItems .item {
    white-space: nowrap;
}

/* Info Section */
#info {
    margin-top: 20px;
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

#info h3 {
    font-size: 1.2rem;
    font-weight: bold;
    margin: 0;
}

/* File List Section under selected folder */
.fileListContainer {
    margin-top: 20px;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}


/* copyButton */
#copyButton {
    background-color: #057822;
    padding: 12px 20px;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}


/* exportClient */
#exportClient {
    background-color: #f57c00;
    padding: 12px 20px;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}

/* uploadClient */
#uploadClient {
    background-color: #f57c00;
    padding: 12px 20px;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}

/* exportAdmin */
#exportAdmin {
    background-color: #f57c00;
    padding: 12px 20px;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}

/* importFile */
#importFile {
    background-color: #f57c00;
    padding: 12px 20px;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}

/* Reload Button */
#reloadButton {
    background-color: #f57c00;
    padding: 8px 8px;
    color: white;
    border: none;
    border-radius: 1px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}


/* toggleconfig Button */
#toggleconfig {
    background-color: #f57c00;
    padding: 12px 12px;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}


#reloadButton:hover {
    background-color: #e65100;
}

/* Floating Search Container */
.search-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 49%;
    padding: 5px;
    background-color: white;
    z-index: 1000; /* Ensures it's above other content */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* Optional: adds shadow for better visibility */
}

/* Controls Section Floating */
.controls {
    position: fixed;
    top: 0px;
    left: 50%;
    width: 50%;
    padding: 10px;
    background-color: white;
    z-index: 1000; /* Ensures it's above other content */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* Optional: adds shadow for better visibility */
}

/* Info Section Floating */
.infoz {
    position: fixed;
    top: 180px;
    left: 51%;
    width: 30;
    padding: 10px;
    background-color: white;
    z-index: 1000; /* Ensures it's above other content */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* Optional: adds shadow for better visibility */
}


/* configuration Section Floating */
.configurationz {
    position: fixed;
    top: 210px;
    left: 70%;
    width: 19%;
	
    padding: 5px;
    background-color: white;
    z-index: 1000; /* Ensures it's above other content */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* Optional: adds shadow for better visibility */
}


/* Selected Items Section */
.selecteds {
    margin-top: 230px;
    left: 50%;
    width: 80%;
    padding: 10px;
    background-color: white;
    z-index: 1000; /* Ensures it's above other content */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* Optional: adds shadow for better visibility */
}

/* Media Queries for Mobile Responsiveness */
@media (max-width: 768px) {
    body {
        flex-direction: column;
        margin-top: 150px; /* Adjust based on header sizes */
    }

    /* Adjust the left and right panes for mobile */
    .pane {
        width: 100%;
        margin: 260px 0;
    }

    /* Adjust Search Bar for Mobile */
    .search-container {
        width: 100%;
        padding: 10px;
    }

    /* Adjust Controls for Mobile */
    .controls {
        width: 100%;
        left: 0;
        top: 50px; /* Adjust to avoid overlap with search */
        padding: 10px;
    }

    /* Adjust Info Section for Mobile */
    .infoz {
        width: 100%;
        left: 0;
        top: 250px; /* Adjust based on previous sections */
		font-size: 10px;
    }
	
    /* Adjust Info Section for Mobile */
	.configurationz {
			width: 40%;
			left: 50%;
			top: 280px; /* Adjust based on previous sections */
		}


    /* Adjust Selected Items Section for Mobile */
    .selecteds {
        width: 100%;
        left: 0;
        margin-top: 250px; /* Adjust if needed */
    }

    /* Adjust button sizes for mobile */
    .button-group button {
        width: 100%;
        padding: 8px 12px;
        font-size: 1rem;
    }
}

/* Further customizations for smaller devices can be added here (e.g., @media for 480px or less) */

    </style>
</head>
<body>
    <div class="pane" id="leftPane">
        <div class="controls">
            <strong>Available Items</strong>
            <!--  <input type="text" id="searchBar" placeholder="Search items..." oninput="filterItems()"> -->
        </div>
		<div class="search-container" id="searchContainer">
			<input type="text" id="searchBar" placeholder="Search items..." oninput="filterItems()" maxlength="50">
			<button id="clearSearchBtn" onclick="clearSearch()">Clear</button>
		</div>
        <!-- Items will be populated here -->
    </div>



    <div class="pane" id="rightPane">
    <div id="info" class="infoz">

        <p>Total games: <span id="totalGames">0</span></p>
        <p>Total size of: <b><span id="totalSize">0</span> <i>GB</i></b></p>
        <p>Estimated install duration: <span id="installDuration">0</span> </p>


<div id="configuration" class="configurationz" style="display: none;">
    <form id="storageForm">
        <label for="consoleType">Console:</label>
        <select id="consoleType" onchange="calculateStorage()" style="font-size: 10px;">>
            <option value="29">V1(32GB)</option>
            <option value="29">V2 (32GB)</option>
            <option value="29">Lite (32GB)</option>
            <option value="58">OLED (64GB)</option>
        </select>
		<br>
        <label for="sdCardSize">SD Card:</label>
        <select id="sdCardSize" onchange="calculateStorage()" style="font-size: 10px;">>
            <option value="119">128GB</option>
            <option value="238">256GB</option>
            <option value="476">512GB</option>
            <option value="952">1TB</option>
        </select>
		<label for="customspaceOptions">custom</label>
            <select id="customspace" onchange="calculateStorage()" value="0" style="font-size: 10px;">
<option value="0">NA</option>
<option value="32">32GB</option>
<option value="64">64GB</option>
<option value="96">96GB</option>
<option value="128">128GB</option>
<option value="160">160GB</option>
<option value="192">192GB</option>
<option value="224">224GB</option>
<option value="256">256GB</option>
<option value="288">288GB</option>
<option value="320">320GB</option>
<option value="352">352GB</option>
<option value="384">384GB</option>
<option value="416">416GB</option>
<option value="448">448GB</option>
<option value="480">480GB</option>
<option value="512">512GB</option>
<option value="544">544GB</option>
<option value="576">576GB</option>
<option value="608">608GB</option>
<option value="640">640GB</option>
<option value="672">672GB</option>
<option value="704">704GB</option>
<option value="736">736GB</option>
<option value="768">768GB</option>
<option value="800">800GB</option>
<option value="832">832GB</option>
<option value="864">864GB</option>
<option value="896">896GB</option>
<option value="928">928GB</option>
<option value="952">1TB</option>
            </select> <br>
        <div id="extraboot" >
		<label for="androidOptions">Android</label>
            <select id="androidSize" onchange="calculateStorage()" value="0" style="font-size: 10px;">
                <option value="0"> NA</option>
                <option value="16">16GB</option>
                <option value="32">32GB</option>
                <option value="64">64GB</option>
            </select>

		<label for="linuxOptions">Linux</label>
             <select id="linuxSize" onchange="calculateStorage()" value="0" style="font-size: 10px;">
                <option value="0">NA</option>
                <option value="16">16GB</option>
                <option value="32">32GB</option>
                <option value="64">64GB</option>
            </select>

        </div>
    </form>
    <div id="result"></div>
</div>
		
		
    </div>
	
        <div class="controls">
            <strong>Selected Items</strong>
            <button onclick="sortBy('name')">(↑)Name</button>
            <button onclick="sortBy('size')">(↑)Size</button>
			<button onclick="resetSorting()">Rst</button>

            <!--<button onclick="clearSelection()">Clear All</button>(↑)(↓)
            <label for="shareableLink">Shareable Link:</label>   -->

		<input type="text" id="shareableLink" readonly style="width: 20%; padding: 8px; font-size: 14px;"><button id="copyButton" style="padding: 8px 12px; font-size: 14px; cursor: pointer;">COPY Link</button><br>
		
<input type="text" id="customerName" placeholder="Enter customer name (required) / use Underscore for spaces" required maxlength="50" style="width: 50%; padding: 8px; font-size: 14px;"/> 			
						<button onclick="reloadPage()" id="reloadButton">Reload</button><button onclick="toggleConfiguration()" id="toggleconfig">Config</button>
            <button onclick="uploadForClient()" id="uploadClient">Upload LIST</button>
			


        </div>
        <div id="selectedItems" class="selecteds"></div>
    </div>



    <script>
        const leftPane = document.getElementById("leftPane");
        const rightPane = document.getElementById("selectedItems");
        const infoTotalGames = document.getElementById("totalGames");
        const infoTotalSize = document.getElementById("totalSize");
        const infoInstallDuration = document.getElementById("installDuration");
        const customerNameInput = document.getElementById("customerName");

        let selectedItems = [];
        let originalOrder = [];
        let lastMovedIndex = null;

        function convertSizeToBytes(size) {
            const sizeRegex = /(\d+\.?\d*)\s*(GiB|MiB|KiB|B)/i;
            const match = size.match(sizeRegex);
            if (match) {
                const value = parseFloat(match[1]);
                const unit = match[2].toUpperCase();

                switch (unit) {
                    case 'B':
                        return value;
                    case 'KIB':
                        return value * 1024 ;
                    case 'MIB':
                        return value * 1024 * 1024 ;
                    case 'GIB':
                        return value * 1024 * 1024 * 1024 ;
                }
            }
            return 0;
        }


let folderMatchingData = null;

// Load folderMatching.json
fetch('./cache.json') // Ensure the path is correct
    .then(response => response.json())
    .then(data => {
        folderMatchingData = data;
        console.log('Folder matching JSON loaded successfully.');
    })
    .catch(error => console.error('Error loading folder matching JSON:', error));

	
function getIconUrlForFolder(folderName) {
    // Ensure the JSON dataset is loaded
    if (!folderMatchingData) {
        console.error("Folder matching data is not loaded.");
        //return { iconUrl: null, resolvedName: folderName };
        return { iconUrl: './ico32.png', resolvedName: folderName };
    }

    // Find the matching folder name in folderMatchingData
    const match = folderMatchingData.matched.find(item => item.folderName === folderName);
    if (!match) {
        console.warn(`No match found for folder: ${folderName}`);
        return { iconUrl: './ico32.png', resolvedName: folderName };
    }

    // Return both iconUrl and resolvedName
    return {
        iconUrl: match.iconUrl || './ico32.png',
        resolvedName: match.resolvedName || folderName
    };
}


// Fetch and parse XML file
fetch('file_tree_output.xml')
    .then(response => response.text())
    .then(data => {
        const parser = new DOMParser();
        const xml = parser.parseFromString(data, 'application/xml');
        const folders = xml.querySelectorAll('folder');

        folders.forEach(folder => {
            if (folder.getAttribute('name') === 'NSP 2021') return;

            const name = folder.getAttribute('name');
            const size = folder.getAttribute('size');
            const div = document.createElement('div');
            const { iconUrl, resolvedName } = getIconUrlForFolder(name);

            div.className = 'item';
            div.dataset.name = name;
            div.dataset.size = size;

            div.innerHTML = `
                <span>
                    <img src="${iconUrl}" class="icon-img" title="${resolvedName}">
					<button onclick="showFiles('${name}')">?</button>
                    ${name}
                </span>
                <span>${size}</span>
            `;

            leftPane.appendChild(div);
        });
    })
    .catch(error => console.error('Error loading XML file:', error));

let currentModal = null; // Global reference to the currently open modal

function showFiles(folderName) {
    fetch('file_tree_output.xml')
        .then(response => response.text())
        .then(data => {
            const parser = new DOMParser();
            const xml = parser.parseFromString(data, 'application/xml');
            const folder = Array.from(xml.querySelectorAll('folder')).find(f => f.getAttribute('name') === folderName);

            if (folder) {
                const files = Array.from(folder.querySelectorAll('file')).map(file => file.getAttribute('name'));
                const folderSize = folder.getAttribute('size');
                const fileCount = files.length;
                const maxVisibleFiles = 10; // Limit the number of items shown initially

                // Close the current modal if one exists
                if (currentModal) {
                    currentModal.remove();
                }

                // Create a modal container
                const modal = document.createElement('div');
                modal.innerHTML = `
                    <div style="
                        position: fixed;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        background: white;
                        padding: 20px;
                        border: 1px solid #ccc;
                        border-radius: 8px;
                        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
                        z-index: 1000;
                        width: 350px;
                    ">
                        <div style="font-size: 12px; margin-bottom: 10px; color: #555;">
                            <strong>Folder:</strong> ${folderName}<br>
                            <strong>Total Size:</strong> ${folderSize}<br>
                            <strong>Total Files:</strong> ${fileCount}
                        </div>
                        <div id="file-list" style="max-height: 300px; overflow-y: auto; margin-bottom: 10px; font-size: 8px">
                            ${files.slice(0, maxVisibleFiles).join('<br>')}
                        </div>
                        ${files.length > maxVisibleFiles ? '<button id="more-button">More</button>' : ''}
                        <button style="margin-top: 10px;" onclick="this.parentElement.remove(); currentModal = null;">Close</button>
                    </div>
                `;

                document.body.appendChild(modal);
                currentModal = modal; // Update the global reference

                // Handle the "More" button
                if (files.length > maxVisibleFiles) {
                    const moreButton = modal.querySelector('#more-button');
                    const fileList = modal.querySelector('#file-list');
                    let currentIndex = maxVisibleFiles;

                    moreButton.addEventListener('click', () => {
                        const nextFiles = files.slice(currentIndex, currentIndex + maxVisibleFiles).join('<br>');
                        fileList.innerHTML += `<br>${nextFiles}`;
                        currentIndex += maxVisibleFiles;

                        // Remove the "More" button if all files are displayed
                        if (currentIndex >= files.length) {
                            moreButton.remove();
                        }
                    });
                }
            } else {
                alert(`No files found for folder: ${folderName}`);
            }
        })
        .catch(error => console.error('Error showing files:', error));
}



        leftPane.addEventListener("click", (e) => {
            const item = e.target.closest(".item");
            if (!item) return;

            item.classList.toggle("selected");
            const itemName = item.getAttribute("data-name");
            const itemSize = item.getAttribute("data-size");

            if (item.classList.contains("selected")) {
                selectedItems.push({ name: itemName, size: itemSize });
                originalOrder.push({ name: itemName, size: itemSize });
            } else {
                selectedItems = selectedItems.filter(i => i.name !== itemName);
                originalOrder = originalOrder.filter(i => i.name !== itemName);
            }
            updateRightPane();
        });

        function updateRightPane() {
            rightPane.innerHTML = "";
            selectedItems.forEach((item, index) => {
                const div = document.createElement("div");
                div.className = "item";
                if (index === lastMovedIndex) {
                    div.classList.add("highlight");
                }
                div.dataset.index = index;
			div.innerHTML = `
									
									<div class="button-group">
									
									<button onclick="moveUp(${index})">Up</button>
									<button onclick="moveDown(${index})">Down</button>
									
									
							 <span><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button onclick="removeItem(${index})">X</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>${item.size}</b>
							 </span><br>${index+1} - &nbsp;&nbsp;&nbsp;${item.name}</span> </div>

							`;
                rightPane.appendChild(div);
            });
            updateInfo();
        }

function updateInfo() {
    infoTotalGames.textContent = selectedItems.length;

    const totalSize = selectedItems.reduce((sum, item) => sum + convertSizeToBytes(item.size), 0);
    const totalSizeGB = (totalSize / (1024 * 1024 * 1024)).toFixed(2); // Convert to GB
    infoTotalSize.textContent = totalSizeGB;

    const bloatedSize = totalSize * 1.2; // 20% increase
    const installSpeedBytesPerSecond = 14 * 1024 * 1024; // 14 MB/sec converted to bytes/sec

    const totalInstallDurationSeconds = bloatedSize / installSpeedBytesPerSecond;
    const hours = Math.floor(totalInstallDurationSeconds / 3600); // Calculate hours
    const minutes = Math.floor((totalInstallDurationSeconds % 3600) / 60); // Calculate remaining minutes

    infoInstallDuration.textContent = `${hours}h ${minutes}m`;

    // Check if total size exceeds available space
    if (parseFloat(totalSizeGB) > availableSpace) {
        infoTotalSize.style.color = "red"; // Change font color to red
    } else {
        infoTotalSize.style.color = ""; // Reset font color to default
    }
}

let lastExportTime = 0; // Track the last export timestamp

function exportForAdmin() {
    const now = Date.now();

    // Prevent double-click or triggering within 2 seconds
    if (now - lastExportTime < 2000) {
        alert("Please wait 2 seconds before trying again.");
        return;
    }

    // Update the last export time
    lastExportTime = now;

    // Check if customer name is entered
    let customerName = document.getElementById("customerName").value.trim();
    if (!customerName) {
        alert("Please enter a customer name before exporting.");
        return;
    }

    // Replace special characters with underscores
    customerName = customerName.replace(/[^a-zA-Z0-9]/g, "_");

    // Create filename with current date and time
    const nowDate = new Date();
    const timestamp = `${nowDate.getFullYear()}${String(nowDate.getMonth() + 1).padStart(2, '0')}${String(nowDate.getDate()).padStart(2, '0')}_${String(nowDate.getHours()).padStart(2, '0')}${String(nowDate.getMinutes()).padStart(2, '0')}`;
    const filename = `${customerName}_${timestamp}.PRMZ`;

    // Base directory path
    const baseDirectory = "K:\\NSP 2021\\";

    // Fetch and parse the XML file
    fetch('file_tree_output.xml')
        .then(response => response.text())
        .then(data => {
            const parser = new DOMParser();
            const xml = parser.parseFromString(data, 'application/xml');
            let content = "";

            // Loop through each selected item in the selectedItems array
            selectedItems.forEach(selected => {
                const folder = Array.from(xml.querySelectorAll('folder')).find(f => f.getAttribute('name') === selected.name);

                if (folder) {
                    // Construct full path for each file in the selected folder
                    const folderPath = `${baseDirectory}${folder.getAttribute('name')}`;
                    folder.querySelectorAll('file').forEach(file => {
                        const fileName = file.getAttribute('name');
                        content += `${folderPath}\\${fileName}\n`;
                    });
                }
            });

            // Create a blob and trigger download
            const blob = new Blob([content], { type: 'text/plain' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            link.click();
            URL.revokeObjectURL(link.href);
        })
        .catch(error => console.error('Error loading XML file:', error));
}



let lastExportClientTime = 0; // Track the last export timestamp for the client function

function exportForClient() {
    const now = Date.now();

    // Prevent double-click or triggering within 2 seconds
    if (now - lastExportClientTime < 2000) {
        alert("Please wait 2 seconds before trying again.");
        return;
    }

    // Update the last export time
    lastExportClientTime = now;

    if (selectedItems.length === 0) return;

    const customerNameInput = document.getElementById("customerName");
    let customerName = customerNameInput.value.trim();

    if (!customerName) {
        alert("Customer name is required!");
        return;
    }

    // Replace special characters with underscores
    customerName = customerName.replace(/[^a-zA-Z0-9]/g, "_");

    const fileName = `${customerName}_${new Date().toISOString().slice(0, 19).replace(/[-T]/g, "").replace(/:/g, "")}.CLI_PRMZ`;
    const selectedFiles = selectedItems.map(item => item.name);

    const blob = new Blob([selectedFiles.join("\n")], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.click();

    // Clean up the URL object
    URL.revokeObjectURL(url);
}


let lastUploadTime = 0; // Track the last upload timestamp

async function uploadForClient() {
    // Check if the function was clicked within the last 15 seconds
    const now = Date.now();
    if (now - lastUploadTime < 15000) {
        alert("You must wait 15 seconds before attempting another upload.");
        return;
    }

    if (selectedItems.length === 0) {
        alert("List cannot be empty");
        return;
    }

    const customerNameInput = document.getElementById("customerName");
    let customerName = customerNameInput.value.trim();

    if (!customerName) {
        alert("Customer name is required!");
        return;
    }

    // Replace special characters with underscores
    customerName = customerName.replace(/[^a-zA-Z0-9]/g, "_");

    const confirmUpload = confirm(
        `Are you sure you want to upload the file with customer name: "${customerName}"?`
    );

    if (!confirmUpload) {
        alert("Upload canceled.");
        return;
    }

    const binName = "CLI_PRMZ"; // Fixed bin name as per requirements
    const fileName = `${customerName}_${new Date().toISOString().slice(0, 19).replace(/[-T]/g, "").replace(/:/g, "")}.CLI_PRMZ`;

    const selectedFiles = selectedItems.map(item => item.name);

    // Create the file content
    const blob = new Blob([selectedFiles.join("\n")], { type: 'text/plain' });

    // Define Filebin upload URL
    const uploadUrl = `https://filebin.net/${binName}/${fileName}`;

    try {
        // Perform the upload (raw file content)
        const response = await fetch(uploadUrl, {
            method: "POST",
            headers: {
                "Content-Type": "text/plain", // Ensure correct MIME type
            },
            body: blob, // Send the raw file content directly
        });

        if (response.status === 201) {
            // File uploaded successfully
            lastUploadTime = now; // Update the last upload time
            const shareableLink = `https://filebin.net/${binName}/${fileName}`;
            const linkInput = document.getElementById("shareableLink");
            linkInput.value = shareableLink;
            alert(`File uploaded successfully!\n\nThe link is shown in the input box.`);
        } else {
            const error = await response.json();
            alert(`Upload failed: ${error.message || "Unknown error."}`);
        }
    } catch (error) {
        alert(`Upload failed: ${error.message}`);
    }
}




        function sortBy(field) {
            selectedItems.sort((a, b) => a[field].localeCompare(b[field]));
            updateRightPane();
        }

        function resetSorting() {
            selectedItems = [...originalOrder];
            updateRightPane();
        }

        function clearSelection() {
            selectedItems = [];
            originalOrder = [];
            document.querySelectorAll(".item").forEach(item => item.classList.remove("selected"));
            updateRightPane();
        }

function reloadPage() {
    // Show a confirmation prompt
    const userConfirmed = confirm("Are you sure you want to refresh the page? Any unsaved changes will be lost.");
    
    // If the user clicks "OK" (yes), proceed with the refresh
    if (userConfirmed) {
        location.href = location.href.split('?')[0] + '?forceRefresh=' + new Date().getTime();
    }
		
		/*
    const searchBar = document.getElementById("searchBar");
    const customerName = document.getElementById("customerName");
    const shareableLink = document.getElementById("shareableLink");
const importFileElement = document.getElementById("importFile");

if (importFileElement) {
    const importFile = importFileElement; // Safely declare importFile if it exists
    importFile.value = ""; // Clear the importFile field
}
	            
	
    searchBar.value = "";  // Clear the search field
    customerName.value = "";  // Clear the customerName field

    shareableLink.value = "";  // Clear the shareableLink field
	
	filterItems();
            //location.reload();*/

}

function filterItems() {
    const query = document.getElementById("searchBar").value.toLowerCase();
    document.querySelectorAll("#leftPane .item").forEach(item => {
        // Check if the item's name matches the query
        const itemName = item.dataset.name.toLowerCase();
        
        // If the item matches the query, show it; otherwise, hide it
        if (itemName.includes(query)) {
            item.style.display = "flex"; // Assuming you're using flexbox or a similar layout for items
        } else {
            item.style.display = "none"; // Hide the item without disturbing the layout
        }
    });
}


        function moveUp(index) {
            if (index === 0) return;
            [selectedItems[index - 1], selectedItems[index]] = [selectedItems[index], selectedItems[index - 1]];
			lastMovedIndex = index - 1;
            updateRightPane();
        }

        function moveDown(index) {
            if (index === selectedItems.length - 1) return;
            [selectedItems[index + 1], selectedItems[index]] = [selectedItems[index], selectedItems[index + 1]];
            lastMovedIndex = index + 1;
            updateRightPane();
        }

        function removeItem(index) {
            const item = selectedItems[index];
            selectedItems.splice(index, 1);
            originalOrder = originalOrder.filter(i => i.name !== item.name);

            // Uncheck the item in the left pane
            const leftItem = Array.from(leftPane.getElementsByClassName("item"))
                .find(i => i.dataset.name === item.name);
            if (leftItem) leftItem.classList.remove("selected");

            lastMovedIndex = null;
            updateRightPane();
        }
		
// Function to clear the search input
function clearSearch() {
    const searchBar = document.getElementById("searchBar");
    searchBar.value = "";  // Clear the search field
	filterItems();
}

document.onkeydown = function(e) {
    if (e.keyCode === 123) {  // F12 key
        e.preventDefault();
        alert("Developer tools are disabled.");
    }
};
document.addEventListener("contextmenu", function(event) {
    event.preventDefault();
});

        const searchBar = document.getElementById("searchBar");
        const customerName = document.getElementById("customerName");

        searchBar.focus();

document.addEventListener("click", (event) => {
    // Check if the device is a mobile device
    const isMobile = window.innerWidth <= 768;

    // Define a set of exceptions where focus should not be forced back to the search bar
    const exceptions = [customerName, searchBar, ...document.querySelectorAll(".configurationz")];

    // If not a mobile device and the clicked element is not an exception
    if (!isMobile && !exceptions.some(el => el.contains(event.target))) {
        // Refocus the search bar and select its content
        searchBar.focus();
        searchBar.select();
    }
});

// Prevent overriding focus for customerName when it is clicked
customerName.addEventListener("focus", () => {
    customerName.addEventListener(
        "blur",
        () => {
            // Refocus the search bar when leaving the customerName field
            searchBar.focus();
            searchBar.select();
        },
        { once: true } // Ensure this blur listener runs only once
    );
});

function importFromFile(event) {
    const file = event.target.files[0];
    if (file) {
        // Remove timestamp from the file name during import
        let customerName = file.name.split('.').slice(0, -1).join('.'); // Remove file extension
        customerName = customerName.replace(/_\d{14}$/, ""); // Remove trailing _YYYYMMDDHHMMSS if it exists
        customerName = customerName.replace(/[^a-zA-Z0-9]/g, "_"); // Sanitize for valid characters
        document.getElementById("customerName").value = customerName;

        const reader = new FileReader();
        reader.onload = function (e) {
            const importedTitles = e.target.result.split('\n').map(line => line.trim());

            // Clear existing selectedItems to avoid duplicates
            selectedItems = [];

            // Iterate over imported titles to preserve file order
            importedTitles.forEach(title => {
                const item = document.querySelector(`#leftPane .item[data-name="${title}"]`);
                if (item) {
                    item.classList.add("selected");
                    const itemName = item.getAttribute("data-name");
                    const itemSize = item.getAttribute("data-size");
                    selectedItems.push({ name: itemName, size: itemSize });
                }
            });

            updateRightPane();
        };
        reader.readAsText(file);
    }
}


		
document.getElementById("copyButton").addEventListener("click", () => {
    const shareableLink = document.getElementById("shareableLink");
    
    if (shareableLink.value) {
        // Select the text and copy to clipboard
        shareableLink.select();
        shareableLink.setSelectionRange(0, 99999); // For mobile devices
        navigator.clipboard.writeText(shareableLink.value).then(() => {
            alert("Link copied to clipboard!");
        }).catch(err => {
            alert("Failed to copy link. Please try manually.");
            console.error(err);
        });
    } else {
        alert("No link to copy!");
    }
});


//code for toggle
toggleConfiguration();
   function toggleConfiguration() {
        const configDiv = document.getElementById('configuration');
        configDiv.style.display = configDiv.style.display === 'none' ? 'block' : 'none';
    }
   function toggleadmin() {
        const configDiv = document.getElementById('admintoolz');
        configDiv.style.display = configDiv.style.display === 'none' ? 'block' : 'none';
    }
	
let availableSpace = 0;
calculateStorage();
function calculateStorage() {


 
		
    // Get selected values
    const consoleTypeElement = document.getElementById('consoleType');
    const sdCardSizeElement = document.getElementById('sdCardSize');
    const androidSizeElement = document.getElementById('androidSize');
    const linuxSizeElement = document.getElementById('linuxSize');
    const customSpaceElement = document.getElementById('customspace');
	

		
    const consoleType = parseInt(consoleTypeElement.value);
    const sdCardSize = parseInt(sdCardSizeElement.value); 
    const androidSize = parseInt(androidSizeElement.value);
    const linuxSize = parseInt(linuxSizeElement.value);
    const customspaceSize = parseInt(customSpaceElement.value);

    // Calculate reserved storage
    const jvfile = 1;
    const emuMMCSize = consoleType; // 32GB for V1/V2/Lite, 64GB for OLED
    const buffa = Math.floor(emuMMCSize / 3);
    const totalReserved = emuMMCSize + androidSize + linuxSize + jvfile + buffa;
    const extraUSR = Math.floor(emuMMCSize / 2);
	

	
    // Update availableSpace and availableSpacemin based on customSpace
	//availableSpace = customspaceSize > 0 ? customspaceSize : (availableSpacemin + extraUSR);
	//availableSpacemin = customspaceSize > 0 ? customspaceSize : (sdCardSize - totalReserved);
	availableSpace = customspaceSize > 0 ? customspaceSize : ((sdCardSize - totalReserved)+extraUSR);
    availableSpacemin = customspaceSize > 0 ? customspaceSize : (sdCardSize - totalReserved);

	
    // Disable or enable inputs based on customSpace value
    const isCustomSpace = customspaceSize > 0;
    consoleTypeElement.disabled = isCustomSpace;
    sdCardSizeElement.disabled = isCustomSpace;
    androidSizeElement.disabled = isCustomSpace;
    linuxSizeElement.disabled = isCustomSpace;

    // Display result
    const resultDiv = document.getElementById('result');
    if (availableSpacemin >= 0) {
        resultDiv.innerHTML = `<p><b>Space for games: ${availableSpace} GB</b></p>`;
    } else {
        resultDiv.innerHTML = `<p>Insufficient storage. You are over by ${-availableSpace} GB.</p>`;
    }
        /*resultDiv.innerHTML = `
		${sdCardSize}  #sdCardSize		<br>
		${emuMMCSize}  #emuMMCSize		<br>
		
		${availableSpace} #availableSpace		<br>
		${availableSpacemin}  #availableSpacemin		<br>
		${extraUSR}  #extraUSR		<br>
		
		${totalReserved}  #totalReserved		<br>
		${customspaceSize}  #customspaceSize		<br>
		${availableSpace}  #availableSpace		<br>
		`;*/

    updateInfo();
}
		



    </script>
</body>
</html>
