<div id="instruction-guide">
    <div class="instruction-row">
        <div class="instruction-col">
            <div class="instruction-title">Paste Your Text</div>
            <div class="instruction-description">Paste your text in the textarea provided. You can paste any text you wish to humanize.</div>
        </div>
        <div class="instruction-col">
            <div class="instruction-title">Click Humanize</div>
            <div class="instruction-description">Click the "Humanize" button to transform your text into a more natural, readable format.</div>
        </div>
        <div class="instruction-col">
            <div class="instruction-title">Copy or Download</div>
            <div class="instruction-description">Once the text is humanized, you can copy it to your clipboard or download it to your device.</div>
        </div>
    </div>
</div>

<style>
    /* Scoped styles for instruction guide */
    #instruction-guide {
        width: 100%;
        height: 100%;  /* Ensure full height */
        background-color: #f5f5f5;  /* Light background */
        padding: 20px;  /* Reduced padding for less space around content */
        box-sizing: border-box;
        margin-bottom: 20px;
        margin-top: 10px; /* Spacing between the guide and tool */
        display: flex;  /* Enable Flexbox */
        justify-content: center;  /* Center horizontally */
        align-items: center;  /* Center vertically */
        border-radius: 10px;
    }

    /* Instruction row with three columns */
    #instruction-guide .instruction-row {
        display: flex;
        justify-content: space-between;
        gap: 20px; /* Adds space between the columns, reducing unwanted margin behavior */
        max-width: 1200px;  /* Optional: Limit the maximum width */
        width: 100%;  /* Full width of the container */
    }

    /* Individual instruction columns */
    #instruction-guide .instruction-col {
        flex: 1;  /* Allow columns to grow equally */
        text-align: center;
        padding: 15px;  /* Adjusted padding inside each column */
        background-color: #ffffff;  /* Optional: Background for columns to make it stand out */
        border-radius: 8px;  /* Optional: Round the corners of the columns */
        transition: all 0.3s ease;  /* Smooth transition for hover effect */
    }

    /* Title for each instruction point (in red) */
    #instruction-guide .instruction-title {
        font-size: 18px;
        font-weight: bold;
        color: #870205;
        margin-bottom: 10px;
    }

    /* Description text (black) */
    #instruction-guide .instruction-description {
        font-size: 14px;
        color: #1e232b;
        line-height: 1.4;
    }

    /* Hover effect for instruction columns */
    #instruction-guide .instruction-col:hover {
        background: linear-gradient(90deg, #870205, #210101);  /* Apply linear gradient */
        color: white;  /* Change text color to white */
    }

    /* Ensure that the title and description remain properly styled on hover */
    #instruction-guide .instruction-col:hover .instruction-title,
    #instruction-guide .instruction-col:hover .instruction-description {
        color: white;  /* Ensure the title and description text are white on hover */
    }

    /* Mobile responsiveness */
    @media (max-width: 768px) {
        #instruction-guide .instruction-row {
            flex-direction: column; /* Stack instructions vertically on small screens */
            gap: 15px; /* Reduce gap between columns */
        }

        #instruction-guide .instruction-col {
            margin-bottom: 15px; /* Reduce space between columns on mobile */
        }
    }
</style>


<!doctype html>


    
    
    Text Humanizer
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <style>
        #humanize-tool {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            position: relative;
        }

        #humanize-tool .container {
            width: 100%;
            max-width: 1920px;
            margin: 0 auto;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
            background-color: #eeeeee;
            box-sizing: border-box;
            padding-top: 10px;
            padding-bottom: 20px;
            position: relative;
            overflow: hidden;
        }

        .usage-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(0.5px);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }

        .usage-overlay.active {
            opacity: 1;
            pointer-events: all;
        }

        .usage-message {
            background: linear-gradient(135deg, #1a1a1a, #2d2d2d);
            padding: 25px 35px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(8px);
        }

        .usage-message h3 {
            margin: 0 0 0 0;
            font-size: 1.4em;
            color: #fff;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 600;
        }

        .usage-message p {
            margin: 0;
            font-size: 1.1em;
            color: #fff;
            opacity: 0.9;
        }

        #cooldownTimer {
            display: inline-block;
            padding: 15px 27px;
            margin-top: 10px;
            background: linear-gradient(135deg, #870205, #210101);
            border-radius: 50px;
            font-family: 'Arial', sans-serif;
            font-size: 2em;
            font-weight: bold;
            color: #fff;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            box-shadow: 
                0 4px 15px rgba(135, 2, 5, 0.3),
                inset 0 2px 2px rgba(255, 255, 255, 0.1),
                inset 0 -2px 2px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
            animation: timerPulse 2s infinite;
        }

        @keyframes timerPulse {
            0% {
                transform: scale(1);
                box-shadow: 
                    0 4px 15px rgba(135, 2, 5, 0.3),
                    inset 0 2px 2px rgba(255, 255, 255, 0.1),
                    inset 0 -2px 2px rgba(0, 0, 0, 0.2);
            }
            50% {
                transform: scale(1.02);
                box-shadow: 
                    0 8px 25px rgba(135, 2, 5, 0.4),
                    inset 0 2px 2px rgba(255, 255, 255, 0.1),
                    inset 0 -2px 2px rgba(0, 0, 0, 0.2);
            }
            100% {
                transform: scale(1);
                box-shadow: 
                    0 4px 15px rgba(135, 2, 5, 0.3),
                    inset 0 2px 2px rgba(255, 255, 255, 0.1),
                    inset 0 -2px 2px rgba(0, 0, 0, 0.2);
            }
        }

        .beta-tag {
            position: absolute;
            top: 10px;
            right: -35px;
            padding: 6px 40px;
            font-weight: bold;
            font-size: 12px;
            transform: rotate(45deg);
            transform-origin: center;
            text-transform: uppercase;
            letter-spacing: 1px;
            z-index: 5;
            background: linear-gradient(90deg, #e87c15, #f9cd33, white, #f9cd33, #e87c15);
            background-size: 200% 100%;
            animation: shimmer 3s linear infinite;
            border: 1px solid rgba(232, 124, 21, 0.3);
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }

        @keyframes shimmer {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }

        #humanize-tool .header-container {
            text-align: center;
            margin-bottom: 20px;
            width: 100%;
            height: auto;
            overflow: visible;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: -5px;
            margin-right: -25px;
        }

        .typing-animation {
            display: inline-block;
            color: black;
            font-size: 25px;
            font-weight: medium;
            white-space: nowrap;
            line-height: 1.2;
            letter-spacing: 1px;
            transition: opacity 0.5s ease;
            min-height: 30px;
            margin-top: 10px;
        }

        #humanize-tool .textarea-container {
            display: flex;
            justify-content: space-between;
            gap: 20px;
            flex-wrap: wrap;
        }

        #humanize-tool .textarea-container > div {
            flex: 1;
            min-width: 300px;
            display: flex;
            flex-direction: column;
        }

        #humanize-tool textarea,
        #humanize-tool #humanizedParagraph {
            width: 100%;
            height: 300px;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
            white-space: pre-wrap;
            overflow-y: auto;
            resize: none;
            font-family: 'Arial', sans-serif;
        }

        #humanize-tool textarea {
            color: #1e232b;
        }

        #humanize-tool textarea::placeholder {
            color: #ccc;
        }

        #humanize-tool #humanizedParagraph {
            background: linear-gradient(90deg, #870205, #210101);
            color: white;
            height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
            font-family: 'Arial', sans-serif;
            word-wrap: break-word;
        }

        #humanize-tool .controls {
            flex-direction: row;
            height: 40px;
            margin-top: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;
            gap: 10px;
        }

        #humanize-tool .gen-counter-container {
            margin-top: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;
            height: 40px;
        }

        #humanize-tool .controls .left-section,
        #humanize-tool .gen-counter-container .left-section {
            flex: 1;
            text-align: left;
            font-size: 14px;
            color: #870205;
            display: flex;
            align-items: center;
            gap: 10px;
            width: 150px;
        }

        #humanize-tool .controls .right-section,
        #humanize-tool .gen-counter-container .right-section {
            flex: 1;
            text-align: right;
        }

.usage-counter {
    background: linear-gradient(90deg, #e87c15, #f9cd33, white, #f9cd33, #e87c15);
    background-size: 200% 100%;
    animation: shimmer 3s linear infinite;
    color: #343434;
    padding: 0; /* Remove padding */
    width: 28px; /* Set a fixed width */
    height: 28px; /* Set a fixed height */
    line-height: 28px; /* Center the number vertically */
    border-radius: 50%; /* Make the element circular */
    font-size: 1em; /* Adjust font size if needed */
    font-weight: bold;
    border: 1.5px solid rgba(232, 124, 21, 0.3);
    text-shadow: 0 1px 2px rgba(255,255,255,0.3);
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    white-space: nowrap;
    display: inline-block;
    text-align: center; /* Center the number horizontally */
}

.credit-text {
    margin-left: -3px; /* Move the "Credit Left" text slightly to the left */
    vertical-align: middle; /* Align with the circle */
}

@media (max-width: 768px) {
    .credit-text {
        margin-left: -8px; /* Keep the margin for tablets and mobile */
		vertical-align: middle; /* Align with the circle */
    }
}

@media (max-width: 480px) {
    .credit-text {
        margin-left: -10px; /* Adjust margin for smaller mobile devices */
        vertical-align: middle; /* Align with the circle */
    }
}


        #humanize-tool #toggleBtn,
        #humanize-tool #downloadBtn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            color: #870205;
            transition: transform 0.3s ease;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #humanize-tool #toggleBtn i,
        #humanize-tool #downloadBtn i {
            font-size: 20px;
        }

        #humanize-tool #toggleBtn:hover,
        #humanize-tool #downloadBtn:hover {
            transform: scale(1.1);
        }

        #humanize-tool #toggleBtn:disabled,
        #humanize-tool #downloadBtn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        #humanize-tool #humanizeBtn,
        #humanize-tool #copyBtn {
            padding: 12px 24px;
            font-size: 14px;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            background: linear-gradient(90deg, #870205, #210101);
            color: white;
            transition: all 0.3s ease;
            white-space: nowrap;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            justify-content: center;
            width: 120px;
            height: 40px;
            position: relative;
            overflow: hidden;
        }

        #humanize-tool #copyBtn i {
            opacity: 0;
            position: absolute;
            transform: scale(0);
            transition: all 0.3s ease;
        }

        #humanize-tool #copyBtn span {
            transition: all 0.3s ease;
        }

        #humanize-tool #copyBtn.success {
            background: linear-gradient(90deg, #210101, #870205);
        }

        #humanize-tool #copyBtn.success span {
            opacity: 0;
            transform: translateY(20px);
        }

        #humanize-tool #copyBtn.success i {
            opacity: 1;
            transform: scale(1);
        }

        #humanize-tool #humanizeBtn:hover,
        #humanize-tool #copyBtn:hover {
            background: linear-gradient(90deg, #210101, #870205);
        }

        #humanize-tool #copyBtn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        @media (max-width: 768px) {
            #humanize-tool .container {
                width: 95%;
                padding: 15px;
            }

            #humanize-tool .textarea-container {
                flex-direction: column;
            }

            #humanize-tool .controls {
                flex-wrap: wrap;
                height: auto;
                gap: 15px;
            }

            .beta-tag {
                top: 10px;
                right: -30px;
                padding: 4px 35px;
                font-size: 0.75rem;
            }

            .usage-message {
                padding: 20px 30px;
            }

            .usage-message h3 {
                font-size: 1.2em;
            }

            #cooldownTimer {
                font-size: 1.8em;
                padding: 12px 20px;
            }
        }

        @media (max-width: 480px) {
            #humanize-tool .container {
                padding: 10px;
            }

            #humanize-tool textarea,
            #humanize-tool #humanizedParagraph {
                height: 250px;
            }

            #humanize-tool #humanizeBtn,
            #humanize-tool #copyBtn {
                width: 100px;
                padding: 10px 20px;
            }

            #humanize-tool #toggleBtn,
            #humanize-tool #downloadBtn {
                width: 35px;
                height: 35px;
            }

            #humanize-tool #toggleBtn i,
            #humanize-tool #downloadBtn i {
                font-size: 18px;
            }

            .beta-tag {
                top: 8px;
                right: -28px;
                padding: 3px 30px;
                font-size: 0.7rem;
            }

            .usage-message {
                padding: 15px 25px;
            }

            .usage-message h3 {
                font-size: 1.1em;
            }

            #cooldownTimer {
                font-size: 1.5em;
                padding: 10px 18px;
            }
        }
    </style>


    <div id="humanize-tool">
        <div class="container">
            <div class="usage-overlay" id="usageOverlay">
                <div class="usage-message">
                    <h3>Usage Limit Reached</h3>
                    <p>Wait until: <span id="cooldownTimer">00:60:00</span></p>
                </div>
            </div>
            <div class="beta-tag"><a href="https://www.aitohuman.net">Beta</a></div>
            <div class="header-container">
                <div class="typing-animation" id="headerText"></div>
            </div>
            <div class="textarea-container">
                <div>
                    <textarea id="inputText" placeholder="Paste your text here..."></textarea>
                    <div class="controls">
                        <div class="left-section">
                            <div class="word-count" id="inputWordCount">0 words</div>
                            <button id="toggleBtn" title="Delete all text">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </div>
                        <div class="usage-counter">
                            <span id="remainingUses">15</span>
                        </div><span class="credit-text">Credits Left</span>
                        <div class="right-section">
                            <button id="humanizeBtn">Humanize</button>
                        </div>
                    </div>
                </div>
                <div id="outputText" style="display: none;">
                    <div id="humanizedParagraph">Humanized text will appear here...</div>
                    <div class="gen-counter-container">
                        <div class="left-section">
                            <span id="genCounter">Gen: 0</span>
                            <button id="downloadBtn" title="Download text" disabled>
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                        <div class="right-section">
                            <button id="copyBtn" disabled>
                                <i class="fas fa-check"></i>
                                <span>Copy Result</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Constants
            const USAGE_LIMIT = 15;
            const COOLDOWN_HOURS = 1;
            const COOLDOWN_MS = COOLDOWN_HOURS * 60 * 60 * 1000;
            const TYPING_SPEED = 50;
            
            // State variables
            let genCount = 0;
            let copyTimeout;
            let isTyping = false;
            let typingTimeout;
            const phrases = [
                "Humanize Your Text...",
                "Unlimited Access...",
                "Privacy Guaranteed...",
                "No Login Required..."
            ];
            let currentPhraseIndex = 0;

            // Load synonyms for text processing
const synonyms = new Map();

// Helper function to remove duplicates from an array
function deduplicateArray(arr) {
    return [...new Set(arr)];
}

// Helper function to merge synonym lists for the same word
function mergeSynonymLists(existingSynonyms, newSynonyms) {
    const allSynonyms = [...existingSynonyms, ...newSynonyms];
    return deduplicateArray(allSynonyms);
}

// Retry logic with extended backoff
async function fetchWithRetry(url, retries = 5, delay = 1000) { // Increased retries
    let attempt = 0;
    while (attempt < retries) {
        try {
            const response = await fetch(url);
            if (response.ok) {
                return response; // Return the valid response if successful
            } else {
                throw new Error(`Response not OK (Status: ${response.status})`);
            }
        } catch (error) {
            attempt++;
            const backoffDelay = delay * Math.pow(2, attempt - 1); // Exponential backoff
            console.warn(`Attempt ${attempt} failed for ${url}. Error: ${error.message}. Retrying in ${backoffDelay}ms...`);
            if (attempt < retries) {
                await new Promise(resolve => setTimeout(resolve, backoffDelay)); // Exponential delay
            } else {
                console.error(`Failed to fetch ${url} after ${retries} attempts`);
                return null; // Return null after max attempts
            }
        }
    }
}

// Function to load synonyms from a single external API
async function loadSynonyms() {
    try {
        const url = 'https://usc-01-api.jsonsilo.com/public/48fadc3f-e5fc-41b9-adf0-428256660a6d'; // Example URL

        // Fetch the API response with retry mechanism
        const response = await fetchWithRetry(url);

        if (response && response.ok) {
            const data = await response.json();

            // Ensure the data structure is valid
            if (data && typeof data === 'object') {
                // Only process data if it's valid
                for (let [word, synonymList] of Object.entries(data)) {
                    word = word.toLowerCase(); // Normalize word to lowercase

                    // Validate synonymList to ensure it's an array
                    if (Array.isArray(synonymList)) {
                        if (synonyms.has(word)) {
                            const existingSynonyms = synonyms.get(word);
                            const mergedSynonyms = mergeSynonymLists(existingSynonyms, deduplicateArray(synonymList));
                            synonyms.set(word, mergedSynonyms);
                        } else {
                            synonyms.set(word, deduplicateArray(synonymList));
                        }
                    } else {
                        console.error(`Invalid data for word ${word}: expected array but got ${typeof synonymList}`);
                    }
                }

                console.log('Synonyms loaded and merged successfully');
            } else {
                console.error('API response format is invalid.');
            }
        } else {
            console.error('Failed to load synonyms from the API.');
        }
    } catch (error) {
        console.error('Error loading synonyms:', error);
    }
}





            loadSynonyms();

            // URL and domain processing
            const urlRegex = /(?:https?:\/\/|www\.)\S+\.\S+|\S+@\S+\.\S+|\S+\.\S+/g;
            let domainPartsSet = new Set();

            function extractDomainParts(domain) {
                const domainParts = domain.split('.');
                domainParts.forEach(part => {
                    domainPartsSet.add(part.toLowerCase());
                });
            }

            // Text processing function
            function processText(text) {
                const placeholders = [];
                let match;

                domainPartsSet.clear();

                // Extract URLs and domains
                while ((match = urlRegex.exec(text)) !== null) {
                    const fullUrl = match[0];

                    if (fullUrl.includes('@')) {
                        const emailDomain = fullUrl.split('@')[1];
                        extractDomainParts(emailDomain);
                    } else {
                        const urlDomain = fullUrl.replace(/^https?:\/\//, '').split('/')[0];
                        extractDomainParts(urlDomain);
                    }

                    placeholders.push(fullUrl);
                    text = text.replace(fullUrl, `{{URL_PLACEHOLDER_${placeholders.length - 1}}}`);
                }

                function applyCase(originalWord, synonym) {
                    if (originalWord === originalWord.toUpperCase()) {
                        return synonym.toUpperCase();
                    } else if (originalWord === originalWord.charAt(0).toUpperCase() + originalWord.slice(1).toLowerCase()) {
                        return synonym.charAt(0).toUpperCase() + synonym.slice(1).toLowerCase();
                    }
                    return synonym.toLowerCase();
                }

                const words = text.split(/\b/);
                const processedText = words.map(word => {
                    const lowerWord = word.toLowerCase();

                    if (domainPartsSet.has(lowerWord)) {
                        return word;
                    }

                    if (synonyms.has(lowerWord)) {
                        const synonymList = synonyms.get(lowerWord);
                        const randomSynonym = synonymList[Math.floor(Math.random() * synonymList.length)];
                        return applyCase(word, randomSynonym);
                    }

                    return word;
                }).join('');

                let resultText = processedText;
                placeholders.forEach((placeholder, index) => {
                    resultText = resultText.replace(`{{URL_PLACEHOLDER_${index}}}`, placeholder);
                });

                return resultText;
            }

            // Usage tracking functions
            function initializeUsageData() {
                const storedData = localStorage.getItem('humanizer_usage');
                let data;
                
                try {
                    data = storedData ? JSON.parse(storedData) : {
                        count: 0,
                        lastReset: Date.now(),
                        isBlocked: false
                    };
                } catch (e) {
                    console.error('Error parsing stored data:', e);
                    data = {
                        count: 0,
                        lastReset: Date.now(),
                        isBlocked: false
                    };
                }

                const now = Date.now();
                if (data.isBlocked && now - data.lastReset >= COOLDOWN_MS) {
                    data = {
                        count: 0,
                        lastReset: now,
                        isBlocked: false
                    };
                } else if (data.count >= USAGE_LIMIT && !data.isBlocked) {
                    data.isBlocked = true;
                    data.lastReset = now;
                }

                localStorage.setItem('humanizer_usage', JSON.stringify(data));
                return data;
            }

            let usageData = initializeUsageData();

            function updateUsageDisplay() {
                const remainingUsesElement = document.getElementById('remainingUses');
                if (remainingUsesElement) {
                    const remainingUses = Math.max(0, USAGE_LIMIT - usageData.count);
                    remainingUsesElement.textContent = remainingUses;
                }
            }

            function checkAndResetUsage() {
                const now = Date.now();
                if (usageData.isBlocked && now - usageData.lastReset >= COOLDOWN_MS) {
                    usageData = {
                        count: 0,
                        lastReset: now,
                        isBlocked: false
                    };
                    localStorage.setItem('humanizer_usage', JSON.stringify(usageData));
                    updateUsageDisplay();
                    toggleOverlay(false);
                    return true;
                }
                return !usageData.isBlocked;
            }

            function updateCooldownTimer() {
                if (!usageData.isBlocked) return;

                const now = Date.now();
                const timeLeft = Math.max(0, COOLDOWN_MS - (now - usageData.lastReset));
                
                if (timeLeft === 0) {
                    checkAndResetUsage();
                    return;
                }

                const hours = Math.floor(timeLeft / (60 * 60 * 1000));
                const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
                const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);

                const timerDisplay = `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                const timerElement = document.getElementById('cooldownTimer');
                if (timerElement) {
                    timerElement.textContent = timerDisplay;
                }
            }

            function toggleOverlay(show) {
                const overlay = document.getElementById('usageOverlay');
                if (overlay) {
                    if (show) {
                        overlay.classList.add('active');
                    } else {
                        overlay.classList.remove('active');
                    }
                }
            }

            function incrementUsage() {
                if (!checkAndResetUsage()) return false;

                const inputText = document.getElementById('inputText').value.trim();
                const humanizeBtn = document.getElementById('humanizeBtn');
                
                if (inputText && humanizeBtn.textContent === 'Humanize') {
                    usageData.count++;
                    
                    if (usageData.count >= USAGE_LIMIT) {
                        usageData.isBlocked = true;
                        usageData.lastReset = Date.now();
                        toggleOverlay(true);
                        localStorage.setItem('humanizer_usage', JSON.stringify(usageData));
                        return false;
                    }

                    localStorage.setItem('humanizer_usage', JSON.stringify(usageData));
                    updateUsageDisplay();
                }
                
                return true;
            }

            // Header animation functions
            async function displayTypingEffect(element, text) {
                if (!element) return;
                
                return new Promise((resolve) => {
                    let index = 0;
                    element.textContent = '';

                    function type() {
                        if (index < text.length) {
                            element.textContent += text.charAt(index);
                            index++;
                            setTimeout(type, TYPING_SPEED);
                        } else {
                            setTimeout(resolve, 500);
                        }
                    }
                    type();
                });
            }

            async function animateHeaderText() {
                const headerElement = document.getElementById('headerText');
                if (!headerElement) return;

                while (true) {
                    await displayTypingEffect(headerElement, phrases[currentPhraseIndex]);
                    headerElement.style.opacity = '0';
                    await new Promise(resolve => setTimeout(resolve, 300));
                    headerElement.textContent = '';
                    headerElement.style.opacity = '1';
                    currentPhraseIndex = (currentPhraseIndex + 1) % phrases.length;
                }
            }

            // Text output functions
            function typeOutText(element, text, speed) {
                if (!element) return;

                const copyBtn = document.getElementById('copyBtn');
                const downloadBtn = document.getElementById('downloadBtn');
                if (copyBtn) copyBtn.disabled = true;
                if (downloadBtn) downloadBtn.disabled = true;

                if (isTyping) {
                    clearTimeout(typingTimeout);
                    element.textContent = '';
                    isTyping = false;
                }

                isTyping = true;
                let index = 0;
                element.textContent = '';

                function type() {
                    if (index < text.length) {
                        element.textContent += text.charAt(index);
                        index++;
                        element.scrollTop = element.scrollHeight;
                        typingTimeout = setTimeout(type, speed);
                    } else {
                        isTyping = false;
                        smoothScrollBackToTop();
                        if (copyBtn) copyBtn.disabled = false;
                        if (downloadBtn) downloadBtn.disabled = false;
                    }
                }
                type();
            }

            function smoothScrollBackToTop() {
                const outputElement = document.getElementById('humanizedParagraph');
                if (outputElement) {
                    outputElement.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                }
            }

            function updateToggleButton() {
                const inputText = document.getElementById('inputText');
                const toggleBtn = document.getElementById('toggleBtn');
                if (!inputText || !toggleBtn) return;

                const hasText = inputText.value.trim().length > 0;
                if (hasText) {
                    toggleBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
                    toggleBtn.title = 'Delete all text';
                } else {
                    toggleBtn.innerHTML = '<i class="fas fa-paste"></i>';
                    toggleBtn.title = 'Paste text';
                }
            }

            function updateWordCount(text) {
                const wordCountElement = document.getElementById('inputWordCount');
                if (wordCountElement) {
                    const wordCount = text.trim().split(/\s+/).filter(word => word.length > 0).length;
                    wordCountElement.textContent = `${wordCount} words`;
                }
            }

            // Event listeners
            const inputText = document.getElementById('inputText');
            const toggleBtn = document.getElementById('toggleBtn');
            const humanizeBtn = document.getElementById('humanizeBtn');
            const copyBtn = document.getElementById('copyBtn');
            const downloadBtn = document.getElementById('downloadBtn');

            if (toggleBtn) {
                toggleBtn.addEventListener('click', async () => {
                    if (!inputText) return;
                    
                    const hasText = inputText.value.trim().length > 0;
                    
                    if (hasText) {
                        inputText.value = '';
                        updateToggleButton();
                        updateWordCount('');
                        const outputText = document.getElementById('outputText');
                        if (outputText) outputText.style.display = 'none';
                        if (humanizeBtn) humanizeBtn.textContent = 'Humanize';
                        if (copyBtn) copyBtn.disabled = true;
                        if (downloadBtn) downloadBtn.disabled = true;
                        genCount = 0;
                        const genCounter = document.getElementById('genCounter');
                        if (genCounter) genCounter.textContent = `Gen: ${genCount}`;
                    } else {
                        try {
                            const text = await navigator.clipboard.readText();
                            inputText.value = text;
                            updateToggleButton();
                            updateWordCount(text);
                        } catch (err) {
                            console.error('Failed to read clipboard:', err);
                        }
                    }
                });
            }

            if (downloadBtn) {
                downloadBtn.addEventListener('click', () => {
                    const outputText = document.getElementById('humanizedParagraph');
                    if (!outputText) return;

                    const blob = new Blob([outputText.textContent], { type: 'text/plain' });
                    const link = document.createElement('a');
                    const fileName = 'aitohuman-net.txt';
                    link.href = URL.createObjectURL(blob);
                    link.download = fileName;
                    link.click();
                });
            }

            if (humanizeBtn) {
                humanizeBtn.addEventListener('click', () => {
                    if (!incrementUsage()) return;
                    if (!inputText) return;

                    if (copyBtn) {
                        copyBtn.classList.remove('success');
                        if (copyTimeout) clearTimeout(copyTimeout);
                    }

                    const inputTextValue = inputText.value;
                    if (!inputTextValue.trim()) {
                        alert("Please enter text to Humanize");
                        return;
                    }

                     const processedText = processText(inputTextValue);
                    const outputElement = document.getElementById('humanizedParagraph');
                    const outputText = document.getElementById('outputText');
                    
                    if (outputText) outputText.style.display = 'block';
                    if (copyBtn) copyBtn.disabled = false;
                    genCount++;
                    const genCounter = document.getElementById('genCounter');
                    if (genCounter) genCounter.textContent = `Gen: ${genCount}`;
                    if (humanizeBtn) humanizeBtn.textContent = 'Enhance';
                    if (outputElement) typeOutText(outputElement, processedText, 1);
                    updateWordCount(inputTextValue);
                });
            }

            if (copyBtn) {
                copyBtn.addEventListener('click', async () => {
                    const outputText = document.getElementById('humanizedParagraph');
                    if (!outputText) return;
                    
                    try {
                        await navigator.clipboard.writeText(outputText.textContent);
                        if (copyTimeout) clearTimeout(copyTimeout);
                        copyBtn.classList.add('success');
                        copyTimeout = setTimeout(() => {
                            copyBtn.classList.remove('success');
                        }, 500);
                    } catch (err) {
                        console.error('Failed to copy text:', err);
                    }
                });
            }

            if (inputText) {
                inputText.addEventListener('input', () => {
                    updateToggleButton();
                    const outputText = document.getElementById('outputText');
                    if (outputText) outputText.style.display = 'none';
                    if (humanizeBtn) humanizeBtn.textContent = 'Humanize';
                    if (copyBtn) copyBtn.disabled = true;
                    if (downloadBtn) downloadBtn.disabled = true;
                    genCount = 0;
                    const genCounter = document.getElementById('genCounter');
                    if (genCounter) genCounter.textContent = `Gen: ${genCount}`;
                    updateWordCount(inputText.value);
                });
            }

            // Initialize
            function initializeBlockState() {
                if (usageData.isBlocked) {
                    toggleOverlay(true);
                    updateCooldownTimer();
                }
                updateUsageDisplay();
            }

            updateToggleButton();
            initializeBlockState();
            animateHeaderText();
            setInterval(updateCooldownTimer, 1000);
        });
    </script>

</!doctype>