// ==UserScript==
// @name         CSGOROLL Daily Script
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  A script that opens boxes every 24h for csgoroll.com to save time (recommended to put it in RDP)
// @author       itumi#3587
// @match        https://www.csgoroll.com/*/boxes/world/daily-free
// @icon         https://pbs.twimg.com/profile_images/1610084878720049154/n0j4nld9_400x400.png
// @grant        none
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
// ==/UserScript==

window.onload = function () {
    "use strict";
    console.clear();

    // Create a <div> element to display logs
    const logContainer = document.createElement("div");
    logContainer.setAttribute("id", "log-container");
    logContainer.style.cssText = "position: fixed; top: 100px; right: 10px; background-color: rgba(30, 30, 30, 0.8); padding: 10px; border-radius: 5px; z-index: 9999; max-width: 300px; overflow-y: auto;";
    document.body.appendChild(logContainer);

	// Load existing log from storage
	const storedLogs = JSON.parse(localStorage.getItem('logs')) || []
	storedLogs.forEach((msg) => addLog(msg))

	function addLog(message) {
		const logElement = document.createElement('div')
		logElement.innerHTML = `<div style="text-align: center;">${message}</div>`;
		// logElement.innerText = message
		logContainer.append(logElement)

		// Check if 'logs' exist in localStorage before attempting to retrieve them
		const retrievedLogs = localStorage.getItem('logs')
		if (retrievedLogs !== null && typeof retrievedLogs === 'string') {
		  try {
			  // Assign parsed result to a temporary variable
			  var tempSavedLogs = JSON.parse(retrievedLogs)

			  // Spread into an array using the temporary variable
			  const savedLogs = [...tempSavedLogs, message];

			  // Update localStorage with newly added log entry
			  localStorage.setItem('logs', JSON.stringify(savedLogs))
		  } catch (e) {}
		} else {
		  // No prior logs detected, create one now
		  localStorage.setItem('logs', JSON.stringify([message]));
		}
	}

    // Log initial message
    addLog("************<br>CSGOROLL Daily Script<br>Coded By: ITUMI#3587<br>ID: 209612826464092160<br>************");

    let lastCloseTime; // Variable to store the time when the last box was closed
    let totalOpened = 0; // Variable to store total opened boxes
	let totalValue = 0;
    const caseLevel = "Level 2";

    // Rest of your script goes here...

    async function openbox() {
        const sleep = (time) => {
            return new Promise((resolve) => setTimeout(resolve, time));
        }
        for (let boxnum = 0; boxnum < 11; boxnum++) {
            const caseLevel = $(".name.ng-star-inserted").eq(boxnum).text();
            const OpenBtn = $(".open-btn").eq(boxnum);
            const DisableClass = "mat-button-disabled";
            if (OpenBtn) {
                if (OpenBtn.hasClass(DisableClass)) {
                    consoleLog();
                    addLog("Log: You can't open case - " + caseLevel);
                    await sleep(5000);
                } else {
                    consoleLog();
                    addLog("Log: Opening case - " + caseLevel);
                    await sleep(3000);
                    OpenBtn.click();
                    await sleep(3000);
                    const OpenCaseBtn = $(".open-btn").eq(11);
                    if (OpenCaseBtn) {
                        await sleep(3000);
                        consoleLog();
                        addLog("Log: Rolling case - " + caseLevel);
                        OpenCaseBtn.click();
                        await sleep(3000);
                        const CloseCaseBtn = $(".close").eq(1);
                        if (CloseCaseBtn) {
                            consoleLog();
                            addLog("Log: Closing case - " + caseLevel);
                            lastCloseTime = new Date(); // Store the current time
                            await sleep(3000);
							totalOpened++;
                            const SellBtn = $(".sell-btn").eq(boxnum); // Assuming you're targeting the same box here
                            if (SellBtn) {
                                await sleep(3000);
                                consoleLog();
                                const sellValue = $(".currency-value").eq(boxnum).text();
                                totalValue += parseFloat(sellValue);
                                // addLog("Log: Sold case for - " + sellValue);
                                // SellBtn.click();
                                await sleep(3000);
                            } else {
                                addLog("Can't find SellBtn");
                                location.reload();
                            }
                            CloseCaseBtn.click();
                            await sleep(3000);
                        } else {
                            addLog("Can't find CloseCaseBtn");
							location.reload();
                        }
                    } else {
                        addLog("Can't find OpenCaseBtn");
						location.reload();
                    }
                }
            } else {
                addLog("Can't find OpenBtn");
				location.reload();
            }
        }
        openbox();
    }

    function formatTime(date) {
        if (date) {
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${hours}:${minutes}:${seconds}`;
        } else {
            return "N/A"; // If date is undefined, return "N/A"
        }
    }

    function consoleLog() {
        // Instead of console clearing, update log container content
        logContainer.innerHTML = ""; // Clear previous logs
        addLog("************<br>CSGOROLL Daily Script<br>Coded By: ITUMI#3587<br>ID: 209612826464092160<br>************");
		addLog("Last case opened at : " + formatTime(lastCloseTime));
        addLog("Total cases opened  : " + totalOpened);
		addLog("Total value opened  : " + totalValue);
    }

	function closeChat() {
		const closeButton = $(".close.clip-bl.mat-icon-button.mat-button-base");
		if (closeButton.length > 0) {
			console.log("Closing the chat...");
			closeButton.click();
		} else {
			// If closeButton is not found, wait for a short interval and then retry
			setTimeout(closeChat, 1000);
		}
	}

    async function startAutoOpen() {
        console.log("Started!");
        await openbox();
    }

    setInterval(() => {
        console.log("Reloading page...");
        location.reload();
    }, 360000);

	setTimeout(closeChat, 3000);
    setTimeout(startAutoOpen, 3000);
};

my code seems to freeze the webpage