<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <title>Rscripts Ultimate Experience</title>
    <!-- Tailwind CSS via CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Canvas Confetti Library -->
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.5.1/dist/confetti.browser.min.js"></script>
    <!-- Tailwind Dark Mode and Extended Config -->
    <script>
      tailwind.config = {
        darkMode: 'class',
        theme: {
          extend: {
            colors: {
              primary: "#90EE90",       // Soft Light Green
              secondary: "#006400",     // Dark Green
              accent: "#228B22",        // Forest Green
              bgLight: "#ffffff",       // White background for light mode
              bgDark: "#000000",        // Black background for dark mode
            },
            animation: {
              fadeIn: 'fadeIn 0.5s ease-in-out',
              fadeOut: 'fadeOut 0.5s ease-in-out',
              slideIn: 'slideIn 0.5s ease-out',
              bounceSlow: 'bounce 2s infinite',
            },
            keyframes: {
              fadeIn: {
                '0%': { opacity: 0 },
                '100%': { opacity: 1 }
              },
              fadeOut: {
                '0%': { opacity: 1 },
                '100%': { opacity: 0 }
              },
              slideIn: {
                '0%': { transform: 'translateX(100%)' },
                '100%': { transform: 'translateX(0)' }
              }
            },
          },
        },
      };
    </script>
    <!-- Custom Styles -->
    <style>
      html {
        transition: background-color 0.3s, color 0.3s;
      }
      .transition-theme {
        transition: background-color 0.3s, color 0.3s;
      }
      /* Scroll-to-top button styling */
      #scrollTopBtn {
        position: fixed;
        bottom: 2rem;
        right: 2rem;
        background-color: #90EE90;
        color: black;
        padding: 0.75rem;
        border-radius: 50%;
        display: none;
        z-index: 50;
      }
      /* Carousel controls styling */
      .carousel-btn {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 0.5rem;
        border-radius: 9999px;
        cursor: pointer;
      }
      .carousel-btn:hover {
        background: rgba(0, 0, 0, 0.7);
      }
      /* Scroll progress bar */
      #progressBarContainer {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 5px;
        background: rgba(0, 0, 0, 0.1);
        z-index: 100;
      }
      #progressBar {
        height: 5px;
        background: #90EE90;
        width: 0%;
      }
      /* Video background styling for hero */
      #heroVideo {
        position: absolute;
        top: 0;
        left: 0;
        min-width: 100%;
        min-height: 100%;
        object-fit: cover;
        z-index: -1;
        opacity: 0.5;
      }
      /* Timeline styling */
      .timeline-item {
        position: relative;
        padding-left: 2rem;
        margin-bottom: 2rem;
      }
      .timeline-item::before {
        content: "";
        position: absolute;
        top: 0.5rem;
        left: 0;
        width: 1rem;
        height: 1rem;
        background-color: #90EE90;
        border: 3px solid #006400;
        border-radius: 50%;
      }
      .timeline-item::after {
        content: "";
        position: absolute;
        top: 1.5rem;
        left: 0.5rem;
        width: 3px;
        height: calc(100% - 1.5rem);
        background-color: #90EE90;
      }
      /* Modal styling */
      .modal {
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.5);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 100;
        transition: opacity 0.3s;
      }
      .modal.active {
        display: flex;
      }
    </style>
  </head>
  <body class="bg-bgLight text-black transition-theme dark:bg-bgDark dark:text-white">
    <!-- ================== SCROLL PROGRESS BAR ================== -->
    <div id="progressBarContainer">
      <div id="progressBar"></div>
    </div>

    <!-- ================== HEADER ================== -->
    <header class="bg-white dark:bg-gray-800 shadow sticky top-0 z-50 transition-theme">
      <div class="max-w-7xl mx-auto px-4 py-4 flex flex-col md:flex-row md:items-center md:justify-between">
        <div class="flex items-center justify-between">
          <a href="#" class="text-3xl font-bold">Flames Scripts</a>
          <!-- Upload Script Button in Header -->
          <button id="uploadBtn" class="hidden md:inline-block ml-4 bg-accent hover:bg-secondary text-white px-4 py-2 rounded transition-colors">
            Upload Script
          </button>
          <button id="menu-toggle" class="md:hidden text-gray-600 dark:text-gray-300 focus:outline-none">
            <svg class="h-6 w-6 fill-current" viewBox="0 0 24 24">
              <path d="M4 5h16M4 12h16M4 19h16"/>
            </svg>
          </button>
        </div>
        <nav id="nav-menu" class="mt-4 md:mt-0 hidden md:block">
          <ul class="flex flex-col md:flex-row md:space-x-6">
            <li><a href="#hero" class="hover:text-primary transition-colors">Home</a></li>
            <li><a href="#content" class="hover:text-primary transition-colors">Scripts</a></li>
            <li><a href="#featured" class="hover:text-primary transition-colors">Featured</a></li>
            <li><a href="#features" class="hover:text-primary transition-colors">Features</a></li>
            <li><a href="#process" class="hover:text-primary transition-colors">Our Process</a></li>
            <li><a href="#news" class="hover:text-primary transition-colors">Latest News</a></li>
            <li><a href="#top-liked" class="hover:text-primary transition-colors">Top Liked</a></li>
          </ul>
        </nav>
        <!-- Search Input -->
        <div class="mt-4 md:mt-0">
          <input type="text" id="searchInput" placeholder="Search scripts..."
            class="px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary dark:bg-gray-700 dark:border-gray-600" />
        </div>
        <!-- Dark/Light Mode Toggle -->
        <div class="mt-4 md:mt-0">
          <button id="theme-toggle"
            class="flex items-center justify-center p-2 bg-gray-200 dark:bg-gray-700 rounded focus:outline-none">
            <svg id="theme-icon" class="w-6 h-6 text-gray-800 dark:text-gray-200" fill="currentColor"
              viewBox="0 0 20 20">
              <!-- Icon set dynamically -->
            </svg>
          </button>
        </div>
      </div>
    </header>

    <!-- ================== UPLOAD SCRIPT MODAL ================== -->
    <div id="upload-modal" class="modal">
      <div class="bg-white dark:bg-gray-800 rounded-lg max-w-3xl w-full p-6 relative shadow-lg">
        <button id="upload-modal-close" class="absolute top-2 right-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white focus:outline-none">
          <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M6 18L18 6M6 6l12 12"/>
          </svg>
        </button>
        <h2 class="text-3xl font-bold text-center mb-8">Upload Script</h2>
        <form id="uploadForm" class="space-y-4">
          <div>
            <label class="block font-semibold mb-1" for="uploadTitle">Script Title *</label>
            <input id="uploadTitle" type="text" required placeholder="My hub, new auto farm, infinite money..."
              class="w-full p-2 border rounded dark:bg-gray-800" />
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadGameLink">Game Link (Optional)</label>
            <input id="uploadGameLink" type="url" placeholder="https://www.roblox.com/games/2753915549/..."
              class="w-full p-2 border rounded dark:bg-gray-800" />
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadDiscord">Discord Invite Link</label>
            <input id="uploadDiscord" type="url" placeholder="https://discord.gg/3C9TbYKZJC"
              class="w-full p-2 border rounded dark:bg-gray-800" />
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadDescription">Script Description *</label>
            <textarea id="uploadDescription" required placeholder="Enter a description for your script..."
              class="w-full p-2 border rounded dark:bg-gray-800" rows="3"></textarea>
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadCode">Script Code *</label>
            <textarea id="uploadCode" required placeholder='loadstring(game:HttpGet("https://raw.githubusercontent.com/EdgeIY/infiniteyield/master/source",true))()'
              class="w-full p-2 border rounded dark:bg-gray-800" rows="5"></textarea>
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadFeatures">Features (Hit enter after each)</label>
            <textarea id="uploadFeatures" placeholder="Aimbot&#10;ESP&#10;Auto Farm" class="w-full p-2 border rounded dark:bg-gray-800" rows="3"></textarea>
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadKeywords">Keywords (Hit enter after each)</label>
            <textarea id="uploadKeywords" placeholder="Jailbreak Script&#10;Jailbreak Auto Rob" class="w-full p-2 border rounded dark:bg-gray-800" rows="3"></textarea>
          </div>
          <div>
            <label class="block font-semibold mb-1">Mobile Compatible?</label>
            <div class="flex items-center space-x-4">
              <label><input type="radio" name="mobile" value="yes" required class="mr-1" /> Yes</label>
              <label><input type="radio" name="mobile" value="no" class="mr-1" /> No</label>
            </div>
          </div>
          <div>
            <label class="block font-semibold mb-1">Contains a Key-System?</label>
            <div class="flex items-center space-x-4">
              <label><input type="radio" name="keySystem" value="yes" required class="mr-1" /> Yes</label>
              <label><input type="radio" name="keySystem" value="no" class="mr-1" /> No</label>
            </div>
          </div>
          <div>
            <label class="block font-semibold mb-1">Is the Script Paid?</label>
            <div class="flex items-center space-x-4">
              <label><input type="radio" name="paid" value="yes" required class="mr-1" /> Yes</label>
              <label><input type="radio" name="paid" value="no" class="mr-1" /> No</label>
            </div>
          </div>
          <div>
            <label class="block font-semibold mb-1" for="uploadImage">Upload Image (Optional)</label>
            <input id="uploadImage" type="file" accept="image/*" class="w-full p-2 border rounded dark:bg-gray-800" />
          </div>
          <div>
            <button type="submit" class="w-full bg-accent hover:bg-secondary text-white font-semibold py-3 rounded transition-colors">
              Upload Script
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- ================== HERO SECTION WITH VIDEO BACKGROUND ================== -->
    <section id="hero" class="relative h-screen flex items-center justify-center text-center transition-theme">
      <!-- Background Video -->
      <video id="heroVideo" autoplay loop muted>
        <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4">
      </video>
      <div class="relative z-10 max-w-3xl mx-auto space-y-6 px-4">
        <h2 class="text-5xl font-extrabold drop-shadow-lg">Discover Roblox Scripts</h2>
        <p class="text-xl drop-shadow-md">
          Enjoy a modern, immersive experience exploring the latest and trending Roblox scripts.
        </p>
        <a href="#content"
          class="inline-block bg-accent hover:bg-secondary text-white font-semibold py-3 px-6 rounded shadow transition-colors">
          Explore Now
        </a>
      </div>
    </section>

    <!-- ================== TABS (Latest / Trending) ================== -->
    <section id="tabs" class="max-w-7xl mx-auto px-4 py-6 transition-theme">
      <div class="flex justify-center border-b border-gray-200 dark:border-gray-700">
        <button id="latest-tab"
          class="py-2 px-4 font-semibold border-b-4 border-transparent hover:border-primary focus:outline-none">
          Latest Scripts
        </button>
        <button id="trending-tab"
          class="py-2 px-4 font-semibold border-b-4 border-transparent hover:border-primary focus:outline-none">
          Trending Scripts
        </button>
      </div>
    </section>

    <!-- ================== SCRIPTS CONTENT ================== -->
    <section id="content" class="max-w-7xl mx-auto px-4 py-6 transition-theme">
      <div id="scripts-container" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        <!-- Script cards injected dynamically -->
      </div>
      <div id="error-message" class="mt-4 text-center text-red-600"></div>
    </section>

    <!-- ================== FEATURED SCRIPTS CAROUSEL ================== -->
    <section id="featured" class="max-w-7xl mx-auto px-4 py-16 transition-theme">
      <h2 class="text-3xl font-bold text-center mb-8">Featured Scripts</h2>
      <div class="relative">
        <div id="carousel" class="flex overflow-hidden">
          <!-- Carousel items injected dynamically -->
        </div>
        <!-- Carousel Controls -->
        <div class="absolute left-0 top-1/2 transform -translate-y-1/2">
          <button id="prev-btn" class="carousel-btn">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M15 19l-7-7 7-7"/>
            </svg>
          </button>
        </div>
        <div class="absolute right-0 top-1/2 transform -translate-y-1/2">
          <button id="next-btn" class="carousel-btn">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M9 5l7 7-7 7"/>
            </svg>
          </button>
        </div>
      </div>
    </section>

    <!-- ================== FEATURES SECTION ================== -->
    <section id="features" class="bg-gray-100 dark:bg-gray-800 py-16 px-4 transition-theme">
      <div class="max-w-7xl mx-auto">
        <h2 class="text-3xl font-bold text-center mb-8">Key Features</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
          <div class="bg-white dark:bg-gray-700 p-6 rounded shadow-lg text-center">
            <svg class="w-12 h-12 mx-auto mb-4 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M13 16h-1v-4h-1m2-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <h3 class="text-xl font-bold mb-2">Real-Time Data</h3>
            <p>Instantly view and interact with the latest scripts or upload and share your own scripts.</p>
          </div>
          <div class="bg-white dark:bg-gray-700 p-6 rounded shadow-lg text-center">
            <svg class="w-12 h-12 mx-auto mb-4 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M12 8c-3.866 0-7 3.134-7 7 0 1.657.672 3.163 1.757 4.243L12 22l5.243-2.757A6.985 6.985 0 0019 15c0-3.866-3.134-7-7-7z"/>
            </svg>
            <h3 class="text-xl font-bold mb-2">Dark/Light Mode</h3>
            <p>Switch seamlessly between dark and light themes for optimal viewing comfort any time of day.</p>
          </div>
          <div class="bg-white dark:bg-gray-700 p-6 rounded shadow-lg text-center">
            <svg class="w-12 h-12 mx-auto mb-4 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M9 17v-6a3 3 0 016 0v6m-3-10v10"/>
            </svg>
            <h3 class="text-xl font-bold mb-2">Modular & Interactive</h3>
            <p>Engage with an interface featuring modals, carousels, dynamic filtering, and user feedback.</p>
          </div>
        </div>
      </div>
    </section>

    <!-- ================== OUR PROCESS TIMELINE SECTION ================== -->
    <section id="process" class="py-16 px-4 transition-theme">
      <div class="max-w-7xl mx-auto">
        <h2 class="text-3xl font-bold text-center mb-12">Our Process</h2>
        <div class="space-y-8">
          <div class="timeline-item">
            <h3 class="text-xl font-bold">Step 1: Discovery</h3>
            <p>We research and gather the latest Roblox scripts and trends to ensure you have the best tools at your fingertips.</p>
          </div>
          <div class="timeline-item">
            <h3 class="text-xl font-bold">Step 2: Integration</h3>
            <p>Our API seamlessly integrates with your projects, providing real-time updates and interactive features.</p>
          </div>
          <div class="timeline-item">
            <h3 class="text-xl font-bold">Step 3: Optimization</h3>
            <p>We continuously optimize performance and usability for the best user experience.</p>
          </div>
          <div class="timeline-item">
            <h3 class="text-xl font-bold">Step 4: Support</h3>
            <p>I'm available if you need me to provide support and ensure smooth integration.</p>
          </div>
        </div>
      </div>
    </section>

    <!-- ================== LATEST NEWS SECTION ================== -->
    <section id="news" class="bg-gray-100 dark:bg-gray-800 py-16 px-4 transition-theme">
      <div class="max-w-7xl mx-auto">
        <h2 class="text-3xl font-bold text-center mb-12">Latest News</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
          <div class="bg-white dark:bg-gray-700 p-6 rounded shadow-lg">
            <h3 class="text-xl font-bold mb-2">New Script Released!</h3>
            <p class="mb-4 text-gray-600 dark:text-gray-300">Discover the powerful new script that automates tasks in Roblox—available now on our platform.</p>
            <a href="#" class="text-primary hover:underline">Read More &rarr;</a>
          </div>
          <div class="bg-white dark:bg-gray-700 p-6 rounded shadow-lg">
            <h3 class="text-xl font-bold mb-2">Platform Update</h3>
            <p class="mb-4 text-gray-600 dark:text-gray-300">We've updated our API for faster performance and better security. Check out the new features!</p>
            <a href="#" class="text-primary hover:underline">Read More &rarr;</a>
          </div>
          <div class="bg-white dark:bg-gray-700 p-6 rounded shadow-lg">
            <h3 class="text-xl font-bold mb-2">Developer Spotlight</h3>
            <p class="mb-4 text-gray-600 dark:text-gray-300">Meet the developers behind our most popular scripts and learn about their creative process.</p>
            <a href="#" class="text-primary hover:underline">Read More &rarr;</a>
          </div>
        </div>
      </div>
    </section>

    <!-- ================== TOP LIKED SCRIPTS SECTION ================== -->
    <section id="top-liked" class="bg-white dark:bg-gray-800 py-16 px-4 transition-theme">
      <div class="max-w-7xl mx-auto">
        <h2 class="text-3xl font-bold text-center mb-8">Top Liked Scripts</h2>
        <div id="topLikedContainer" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          <!-- Top liked scripts will be rendered here -->
        </div>
      </div>
    </section>

    <!-- ================== MODAL FOR SCRIPT DETAILS (WITH FEEDBACK & CONFETTI) ================== -->
    <div id="script-modal" class="modal">
      <div class="bg-white dark:bg-gray-800 rounded-lg max-w-3xl w-full p-6 relative shadow-lg">
        <button id="modal-close" class="absolute top-2 right-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white focus:outline-none">
          <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M6 18L18 6M6 6l12 12"/>
          </svg>
        </button>
        <div id="modal-content">
          <h3 id="modal-title" class="text-2xl font-bold mb-4"></h3>
          <p id="modal-description" class="mb-4"></p>
          <pre id="modal-script-content" class="bg-gray-100 dark:bg-gray-700 p-4 rounded overflow-auto max-h-80 text-sm font-mono"></pre>
          <!-- Feedback Section: Like/Dislike and Comments -->
          <div id="feedback-section" class="mt-4">
            <div class="flex items-center space-x-4 mb-4">
              <button id="like-button" class="bg-green-500 hover:bg-green-600 text-white px-3 py-1 rounded">Like (<span id="like-count">0</span>)</button>
              <button id="dislike-button" class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded">Dislike (<span id="dislike-count">0</span>)</button>
            </div>
            <div class="mb-4">
              <h4 class="font-bold mb-2">Comments</h4>
              <div id="comments-list" class="space-y-2">
                <!-- Comments will appear here -->
              </div>
            </div>
            <div>
              <textarea id="comment-input" placeholder="Write your comment..." class="w-full border rounded p-2"></textarea>
              <button id="comment-submit" class="mt-2 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Submit Comment</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ================== SCROLL TO TOP BUTTON ================== -->
    <button id="scrollTopBtn" title="Scroll to Top">
      <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
        <path d="M3 12l7-7 7 7H3z" />
      </svg>
    </button>

    <!-- ================== FOOTER (Including Donation Button) ================== -->
    <footer class="bg-white dark:bg-gray-800 border-t dark:border-gray-700 mt-12 transition-theme">
      <div class="max-w-7xl mx-auto px-4 py-4 text-center text-sm text-gray-500">
        Powered by Rscripts.net &copy; 2025
      </div>
      <div class="mt-4 flex justify-center">
        <script type="text/javascript"
          src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js"
          data-name="bmc-button"
          data-slug="Aura2"
          data-color="#40DCA5"
          data-emoji="🐱"
          data-font="Lato"
          data-text="Donate to the Cat"
          data-outline-color="#000000"
          data-font-color="#ffffff"
          data-coffee-color="#FFDD00">
        </script>
      </div>
    </footer>

    <!-- ================== JAVASCRIPT ================== -->
    <script>
      /***************************************
       * THEME TOGGLE LOGIC
       ***************************************/
      const themeToggleButton = document.getElementById("theme-toggle");
      const themeIcon = document.getElementById("theme-icon");

      function updateThemeIcon(isDark) {
        themeIcon.innerHTML = isDark
          ? `<path d="M17.293 13.293A8 8 0 116.707 2.707a8.001 8.001 0 0010.586 10.586z"/>`
          : `<path d="M10 2a1 1 0 011 1v2a1 1 0 01-2 0V3a1 1 0 011-1zm4.22 1.47a1 1 0 011.42 1.42l-1.42 1.42a1 1 0 01-1.42-1.42l1.42-1.42zM18 9a1 1 0 010 2h-2a1 1 0 010-2h2zM4 9a1 1 0 010 2H2a1 1 0 010-2h2zm1.64 4.78a1 1 0 011.42 1.42L5.64 17a1 1 0 01-1.42-1.42l1.42-1.4zm10.72 1.42a1 1 0 011.42-1.42l1.42 1.42a1 1 0 01-1.42 1.42l-1.42-1.42zM10 16a1 1 0 011 1v2a1 1 0 01-2 0v-2a1 1 0 011-1zm4.22-.47a1 1 0 011.42 1.42l-1.42 1.42a1 1 0 01-1.42-1.42l1.42-1.42z"/>`;
      }

      function applyTheme(theme) {
        if (theme === "dark") {
          document.documentElement.classList.add("dark");
          updateThemeIcon(true);
        } else {
          document.documentElement.classList.remove("dark");
          updateThemeIcon(false);
        }
      }

      themeToggleButton.addEventListener("click", () => {
        if (document.documentElement.classList.contains("dark")) {
          document.documentElement.classList.remove("dark");
          localStorage.setItem("theme", "light");
          updateThemeIcon(false);
        } else {
          document.documentElement.classList.add("dark");
          localStorage.setItem("theme", "dark");
          updateThemeIcon(true);
        }
      });

      document.addEventListener("DOMContentLoaded", () => {
        const storedTheme = localStorage.getItem("theme") || "light";
        applyTheme(storedTheme);
      });

      /***************************************
       * SCROLL PROGRESS INDICATOR
       ***************************************/
      const progressBar = document.getElementById("progressBar");
      window.addEventListener("scroll", () => {
        const scrollTop = document.documentElement.scrollTop;
        const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrolled = (scrollTop / scrollHeight) * 100;
        progressBar.style.width = scrolled + "%";
      });

      /***************************************
       * GUEST ID SETUP
       ***************************************/
      if (!localStorage.getItem("guestID")) {
        const guestID = Math.floor(Math.random() * 900) + 100;
        localStorage.setItem("guestID", guestID);
      }
      const guestTag = "Guest " + localStorage.getItem("guestID");

      /***************************************
       * PERSISTENT FEEDBACK STORAGE
       ***************************************/
      let state = {
        latest: [],
        trending: [],
        currentTab: "latest",
        feedback: {}
      };
      if (localStorage.getItem("feedbackData")) {
        state.feedback = JSON.parse(localStorage.getItem("feedbackData"));
      }
      function saveFeedback() {
        localStorage.setItem("feedbackData", JSON.stringify(state.feedback));
      }

      /***************************************
       * UPLOADED SCRIPTS STORAGE
       ***************************************/
      let uploadedScripts = [];
      if (localStorage.getItem("uploadedScripts")) {
        uploadedScripts = JSON.parse(localStorage.getItem("uploadedScripts"));
      }
      function saveUploadedScripts() {
        localStorage.setItem("uploadedScripts", JSON.stringify(uploadedScripts));
      }

      /***************************************
       * GLOBAL ELEMENTS
       ***************************************/
      const scriptsContainer = document.getElementById("scripts-container");
      const errorMessage = document.getElementById("error-message");
      const searchInput = document.getElementById("searchInput");
      const topLikedContainer = document.getElementById("topLikedContainer");

      // Modal & Feedback Elements (Script Details)
      const modal = document.getElementById("script-modal");
      const modalTitle = document.getElementById("modal-title");
      const modalDescription = document.getElementById("modal-description");
      const modalScriptContent = document.getElementById("modal-script-content");
      const modalClose = document.getElementById("modal-close");
      const likeButton = document.getElementById("like-button");
      const dislikeButton = document.getElementById("dislike-button");
      const likeCountSpan = document.getElementById("like-count");
      const dislikeCountSpan = document.getElementById("dislike-count");
      const commentsList = document.getElementById("comments-list");
      const commentInput = document.getElementById("comment-input");
      const commentSubmit = document.getElementById("comment-submit");

      // Upload Modal Elements
      const uploadModal = document.getElementById("upload-modal");
      const uploadBtn = document.getElementById("uploadBtn");
      const uploadModalClose = document.getElementById("upload-modal-close");
      const uploadForm = document.getElementById("uploadForm");

      // Tabs
      const latestTabButton = document.getElementById("latest-tab");
      const trendingTabButton = document.getElementById("trending-tab");

      // Carousel Elements (for Featured Scripts)
      const carousel = document.getElementById("carousel");
      const prevBtn = document.getElementById("prev-btn");
      const nextBtn = document.getElementById("next-btn");
      let carouselIndex = 0;
      let featuredScripts = [];

      // Scroll-to-top Button
      const scrollTopBtn = document.getElementById("scrollTopBtn");

      let currentScriptId = null;

      /***************************************
       * HELPER FUNCTIONS
       ***************************************/
      function createElement(tag, classNames) {
        const el = document.createElement(tag);
        if (classNames) el.className = classNames;
        return el;
      }

      function renderFeedback(scriptId) {
        // Initialize feedback object for this script if it doesn't exist.
        if (!state.feedback[scriptId]) {
          state.feedback[scriptId] = { likes: 0, dislikes: 0, comments: [], voters: {} };
        }
        likeCountSpan.textContent = state.feedback[scriptId].likes;
        dislikeCountSpan.textContent = state.feedback[scriptId].dislikes;
        commentsList.innerHTML = "";
        state.feedback[scriptId].comments.forEach(comment => {
          const commentDiv = createElement("div", "border p-2 rounded");
          commentDiv.innerHTML = `<strong>${comment.guest}</strong>: ${comment.text}`;
          commentsList.appendChild(commentDiv);
        });
      }

      function openModal(script) {
        currentScriptId = script._id;
        modalTitle.textContent = script.title;
        modalDescription.textContent = script.description || "No description provided.";
        modalScriptContent.textContent = "Loading script content...";
        modal.classList.add("active");
        renderFeedback(script._id);
        fetch(script.rawScript)
          .then((res) => {
            if (!res.ok) throw new Error("Failed to load script content.");
            return res.text();
          })
          .then((text) => {
            modalScriptContent.textContent = text;
          })
          .catch((error) => {
            modalScriptContent.textContent = "Error loading script content.";
            console.error(error);
          });
      }

      function closeModal() {
        modal.classList.remove("active");
      }

      function renderScripts(scripts) {
        errorMessage.textContent = "";
        scriptsContainer.innerHTML = "";
        if (!scripts || scripts.length === 0) {
          errorMessage.textContent = "No scripts found.";
          return;
        }
        scripts.forEach((script) => {
          const hasUser = script.user && Object.keys(script.user).length > 0;
          const profilePicture = hasUser && script.user.image ? script.user.image : "https://i.pravatar.cc/300";
          const username = hasUser ? script.user.username : script.creator || "Unknown";
          const card = createElement("div", "bg-white dark:bg-gray-800 shadow-lg rounded-lg overflow-hidden flex flex-col transform hover:scale-105 transition-transform duration-300");
          const img = createElement("img", "w-full h-48 object-cover");
          img.src = script.image || "https://via.placeholder.com/480x270?text=No+Image";
          img.alt = script.title;
          card.appendChild(img);
          const cardBody = createElement("div", "p-4 flex flex-col flex-1");
          const titleEl = createElement("h3", "text-lg font-bold mb-2");
          titleEl.textContent = script.title;
          cardBody.appendChild(titleEl);
          const descriptionEl = createElement("p", "text-gray-600 dark:text-gray-300 flex-1");
          descriptionEl.textContent = script.description && script.description.length > 100
            ? script.description.substring(0, 100) + "..."
            : script.description || "No description provided.";
          cardBody.appendChild(descriptionEl);
          const creatorDiv = createElement("div", "mt-4 flex items-center space-x-3");
          const creatorImg = createElement("img", "w-10 h-10 rounded-full object-cover");
          creatorImg.src = profilePicture;
          creatorImg.alt = username;
          creatorDiv.appendChild(creatorImg);
          const creatorName = createElement("span", "text-gray-700 dark:text-gray-200");
          creatorName.textContent = username;
          creatorDiv.appendChild(creatorName);
          cardBody.appendChild(creatorDiv);
          const actions = createElement("div", "mt-4 flex space-x-2");
          const viewButton = createElement("button", "bg-primary hover:bg-secondary dark:bg-primary dark:hover:bg-secondary text-white py-2 px-4 rounded transition-colors duration-200");
          viewButton.textContent = "View Details";
          viewButton.addEventListener("click", () => openModal(script));
          actions.appendChild(viewButton);
          cardBody.appendChild(actions);
          card.appendChild(cardBody);
          scriptsContainer.appendChild(card);
        });
      }

      function filterScripts(scripts, term) {
        if (!term) return scripts;
        term = term.toLowerCase();
        return scripts.filter(
          (script) =>
            (script.title && script.title.toLowerCase().includes(term)) ||
            (script.description && script.description.toLowerCase().includes(term))
        );
      }

      /***************************************
       * CAROUSEL FUNCTIONS (Featured Scripts)
       ***************************************/
      function renderCarouselItem(script) {
        const item = createElement("div", "min-w-full flex-shrink-0 p-4");
        const card = createElement("div", "bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden");
        const img = createElement("img", "w-full h-48 object-cover");
        img.src = script.image || "https://via.placeholder.com/480x270?text=No+Image";
        img.alt = script.title;
        card.appendChild(img);
        const cardBody = createElement("div", "p-4");
        const titleEl = createElement("h3", "text-lg font-bold mb-2");
        titleEl.textContent = script.title;
        cardBody.appendChild(titleEl);
        const btn = createElement("button", "bg-primary hover:bg-secondary dark:bg-primary dark:hover:bg-secondary text-white py-2 px-4 rounded transition-colors");
        btn.textContent = "View";
        btn.addEventListener("click", () => openModal(script));
        cardBody.appendChild(btn);
        card.appendChild(cardBody);
        item.appendChild(card);
        return item;
      }

      function renderCarousel() {
        carousel.innerHTML = "";
        if (featuredScripts.length === 0) return;
        const currentScript = featuredScripts[carouselIndex];
        carousel.appendChild(renderCarouselItem(currentScript));
      }

      function nextCarousel() {
        carouselIndex = (carouselIndex + 1) % featuredScripts.length;
        renderCarousel();
      }

      function prevCarousel() {
        carouselIndex = (carouselIndex - 1 + featuredScripts.length) % featuredScripts.length;
        renderCarousel();
      }

      setInterval(() => {
        if (featuredScripts.length > 0) nextCarousel();
      }, 5000);

      /***************************************
       * TOP LIKED SCRIPTS SECTION
       ***************************************/
      function renderTopLikedScripts() {
        topLikedContainer.innerHTML = "";
        const allScripts = [...state.latest];
        allScripts.sort((a, b) => {
          const likesA = (state.feedback[a._id] && state.feedback[a._id].likes) || 0;
          const likesB = (state.feedback[b._id] && state.feedback[b._id].likes) || 0;
          return likesB - likesA;
        });
        const topScripts = allScripts.slice(0, 3);
        if (topScripts.length === 0) {
          topLikedContainer.innerHTML = "<p class='text-center'>No top liked scripts yet.</p>";
          return;
        }
        topScripts.forEach(script => {
          const card = createElement("div", "bg-white dark:bg-gray-800 shadow-lg rounded-lg overflow-hidden p-4");
          const titleEl = createElement("h3", "text-lg font-bold mb-2");
          titleEl.textContent = script.title;
          card.appendChild(titleEl);
          const likesEl = createElement("p", "text-sm text-green-600");
          const likes = (state.feedback[script._id] && state.feedback[script._id].likes) || 0;
          likesEl.textContent = `Likes: ${likes}`;
          card.appendChild(likesEl);
          topLikedContainer.appendChild(card);
        });
      }

      /***************************************
       * FETCH FUNCTIONS
       ***************************************/
      async function fetchLatestScripts() {
        try {
          const response = await fetch("https://rscripts.net/api/v2/scripts?page=1&orderBy=date&sort=desc");
          if (!response.ok) {
            throw new Error("Failed to fetch latest scripts.");
          }
          const data = await response.json();
          state.latest = data.scripts || [];
          state.latest = [...uploadedScripts, ...state.latest];
          const filtered = filterScripts(state.latest, searchInput.value);
          renderScripts(filtered);
          featuredScripts = state.latest.slice(0, 5);
          carouselIndex = 0;
          renderCarousel();
          renderTopLikedScripts();
        } catch (error) {
          errorMessage.textContent = "Error fetching latest scripts. Please try again later.";
          console.error(error);
        }
      }

      async function fetchTrendingScripts() {
        try {
          const response = await fetch("https://rscripts.net/api/v2/trending");
          if (!response.ok) {
            throw new Error("Failed to fetch trending scripts.");
          }
          const data = await response.json();
          state.trending = data.success || [];
          state.trending = [...uploadedScripts, ...state.trending];
          const filtered = filterScripts(state.trending, searchInput.value);
          renderScripts(filtered);
        } catch (error) {
          errorMessage.textContent = "Error fetching trending scripts. Please try again later.";
          console.error(error);
        }
      }

      /***************************************
       * FEEDBACK EVENT HANDLERS WITH TOGGLE
       ***************************************/
      likeButton.addEventListener("click", () => {
        if (!currentScriptId) return;
        if (!state.feedback[currentScriptId]) {
          state.feedback[currentScriptId] = { likes: 0, dislikes: 0, comments: [], voters: {} };
        }
        const voters = state.feedback[currentScriptId].voters;
        // If guest already liked, remove like. If guest disliked, switch.
        if (voters[guestTag] === "like") {
          state.feedback[currentScriptId].likes--;
          delete voters[guestTag];
        } else {
          if (voters[guestTag] === "dislike") {
            state.feedback[currentScriptId].dislikes--;
          }
          state.feedback[currentScriptId].likes++;
          voters[guestTag] = "like";
        }
        saveFeedback();
        renderFeedback(currentScriptId);
        // Only trigger confetti when adding a like.
        if (voters[guestTag] === "like") {
          confetti({
            particleCount: 100,
            spread: 70,
            origin: { y: 0.6 }
          });
        }
        renderTopLikedScripts();
      });

      dislikeButton.addEventListener("click", () => {
        if (!currentScriptId) return;
        if (!state.feedback[currentScriptId]) {
          state.feedback[currentScriptId] = { likes: 0, dislikes: 0, comments: [], voters: {} };
        }
        const voters = state.feedback[currentScriptId].voters;
        if (voters[guestTag] === "dislike") {
          state.feedback[currentScriptId].dislikes--;
          delete voters[guestTag];
        } else {
          if (voters[guestTag] === "like") {
            state.feedback[currentScriptId].likes--;
          }
          state.feedback[currentScriptId].dislikes++;
          voters[guestTag] = "dislike";
        }
        saveFeedback();
        renderFeedback(currentScriptId);
      });

      commentSubmit.addEventListener("click", () => {
        const text = commentInput.value.trim();
        if (!text) return;
        if (currentScriptId) {
          if (!state.feedback[currentScriptId]) {
            state.feedback[currentScriptId] = { likes: 0, dislikes: 0, comments: [], voters: {} };
          }
          state.feedback[currentScriptId].comments.push({ guest: guestTag, text });
          commentInput.value = "";
          saveFeedback();
          renderFeedback(currentScriptId);
        }
      });

      /***************************************
       * UPLOAD SCRIPT HANDLING (Upload Modal)
       ***************************************/
      uploadForm.addEventListener("submit", (e) => {
        e.preventDefault();
        const title = document.getElementById("uploadTitle").value.trim();
        const gameLink = document.getElementById("uploadGameLink").value.trim();
        const discordLink = document.getElementById("uploadDiscord").value.trim();
        const description = document.getElementById("uploadDescription").value.trim();
        const code = document.getElementById("uploadCode").value.trim();
        const featuresText = document.getElementById("uploadFeatures").value.trim();
        const keywordsText = document.getElementById("uploadKeywords").value.trim();
        const mobileCompatible = document.querySelector('input[name="mobile"]:checked').value;
        const keySystem = document.querySelector('input[name="keySystem"]:checked').value;
        const paid = document.querySelector('input[name="paid"]:checked').value;
        const imageInput = document.getElementById("uploadImage");
        if (title === "" || description === "" || code === "") {
          alert("Please fill in all required fields.");
          return;
        }
        const newScript = {
          _id: "upload_" + Date.now(),
          title,
          gameLink,
          discordLink,
          description,
          rawScript: "",
          code,
          features: featuresText ? featuresText.split("\n") : [],
          keywords: keywordsText ? keywordsText.split("\n") : [],
          mobileCompatible,
          keySystem,
          paid,
          image: "",
          user: { username: guestTag, image: "" },
          creator: guestTag
        };
        function finishUpload(imgData) {
          newScript.image = imgData;
          newScript.rawScript = "data:text/plain;base64," + btoa(code);
          uploadedScripts.unshift(newScript);
          saveUploadedScripts();
          uploadForm.reset();
          alert("Script uploaded successfully!");
          uploadModal.classList.remove("active");
          fetchLatestScripts();
        }
        if (imageInput.files && imageInput.files[0]) {
          const reader = new FileReader();
          reader.onload = function(event) {
            finishUpload(event.target.result);
          };
          reader.readAsDataURL(imageInput.files[0]);
        } else {
          finishUpload("https://via.placeholder.com/480x270?text=No+Image");
        }
      });

      /***************************************
       * EVENT LISTENERS & INTERACTIONS
       ***************************************/
      document.getElementById("menu-toggle").addEventListener("click", () => {
        const navMenu = document.getElementById("nav-menu");
        navMenu.classList.toggle("hidden");
      });

      modalClose.addEventListener("click", closeModal);
      modal.addEventListener("click", (e) => {
        if (e.target === modal) closeModal();
      });

      latestTabButton.addEventListener("click", () => {
        state.currentTab = "latest";
        latestTabButton.classList.add("border-primary");
        trendingTabButton.classList.remove("border-primary");
        if (state.latest.length === 0) {
          fetchLatestScripts();
        } else {
          const filtered = filterScripts(state.latest, searchInput.value);
          renderScripts(filtered);
        }
      });

      trendingTabButton.addEventListener("click", () => {
        state.currentTab = "trending";
        trendingTabButton.classList.add("border-primary");
        latestTabButton.classList.remove("border-primary");
        if (state.trending.length === 0) {
          fetchTrendingScripts();
        } else {
          const filtered = filterScripts(state.trending, searchInput.value);
          renderScripts(filtered);
        }
      });

      searchInput.addEventListener("input", () => {
        let filtered = state.currentTab === "latest"
          ? filterScripts(state.latest, searchInput.value)
          : filterScripts(state.trending, searchInput.value);
        renderScripts(filtered);
      });

      nextBtn.addEventListener("click", nextCarousel);
      prevBtn.addEventListener("click", prevCarousel);

      window.addEventListener("scroll", () => {
        if (window.pageYOffset > 300) {
          scrollTopBtn.style.display = "block";
        } else {
          scrollTopBtn.style.display = "none";
        }
      });
      scrollTopBtn.addEventListener("click", () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
      });

      // Upload Modal Open/Close
      uploadBtn.addEventListener("click", () => {
        uploadModal.classList.add("active");
      });
      uploadModalClose.addEventListener("click", () => {
        uploadModal.classList.remove("active");
      });
      uploadModal.addEventListener("click", (e) => {
        if (e.target === uploadModal) uploadModal.classList.remove("active");
      });

      /***************************************
       * INITIALIZATION
       ***************************************/
      document.addEventListener("DOMContentLoaded", () => {
        latestTabButton.classList.add("border-primary");
        fetchLatestScripts();
      });
    </script>
  </body>
</html>
