<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Thugil Creation - Premium Silk Saree Designs for Every Occasion</title>
  <!-- Bootstrap CSS (via CDN) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat+Alternates&family=Montserrat:ital,wght@0,100..900;1,100..900&family=PT+Sans:ital,wght@0,400;0,700;1,400;1,700&family=Righteous&display=swap" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Atomic+Age&family=Silkscreen:wght@400;700&display=swap" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <meta name="theme-color" content="#561C24">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Andika:ital,wght@0,400;0,700;1,400;1,700&family=Atomic+Age&family=Encode+Sans+SC:wght@100..900&family=Outfit:wght@100..900&family=Silkscreen:wght@400;700&display=swap" rel="stylesheet">
  <meta name="description" content="Thugil Creation offers a stunning collection of premium silk sarees. From luxurious wedding sarees to festive designs, explore handcrafted silk sarees that combine tradition with modern elegance.">
  <meta name="keywords" content="silk sarees, wedding sarees, festival sarees, bridal sarees, luxury silk sarees, handcrafted sarees, Indian sarees, designer sarees, Thugil Creation, sarees online, traditional silk sarees, premium sarees">
  <meta property="og:title" content="Thugil Creation - Premium Silk Sarees">
  <meta property="og:description" content="Explore Thugil Creation's exquisite collection of premium silk sarees. Perfect for weddings, festivals, and special occasions. Handcrafted to bring elegance to every moment.">
  <meta property="og:image" content="https://thugil-creation-video.b-cdn.net/logo.png"> <!-- Add the URL of an image representing the brand or product -->
  <meta property="og:url" content="https://www.thugilcreation.com">
  <meta property="og:type" content="website">
   <!-- JSON-LD structured data for Organization -->
   <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "Organization",
      "name": "Thugil Creation",
      "url": "https://www.thugilcreation.com",
      "logo": "https://thugil-creation-video.b-cdn.net/logo.png",  <!-- Replace with your actual logo URL -->
      "contactPoint": {
        "@type": "ContactPoint",
        "telephone": "+91 8838008499",  <!-- Replace with your actual contact number -->
        "contactType": "Customer Service"
      },
      "sameAs": [
        "https://www.facebook.com/thugilcreation29", 
        "https://www.instagram.com/thugil_creation29/?next=%2F"
      ]
    }
    </script>
  <link rel="stylesheet" href="style.css">
   <!-- Favicon -->
   <link rel="icon" href="icons/logo.png" type="image/x-icon">
 </head>
 <body>
  <div class="upper-nav">
   <div class="text-slider">
    <div class="text-item" id="text1">Where Silk Meets Style</div>
    <div class="text-item" id="text2">Crafting Silk, Creating Beauty</div>
    <div class="text-item" id="text3">Luxury in Every Thread</div>
   </div>
   <!-- Left and right navigation buttons using Font Awesome icons -->
   <button class="nav-button prev" onclick="moveSlide('prev')">
    <i class="fa fa-chevron-left"></i>
   </button>
   <button class="nav-button next" onclick="moveSlide('next')">
    <i class="fa fa-chevron-right"></i>
   </button>
  </div>
  <nav class="navbar navbar-expand-lg bg-body-tertiary sticky-top">
   <div class="container-fluid">
    <!-- Wrapper for Logo and Toggle Button -->
    <div class="navbar-header">
     <!-- Navbar Toggler for mobile responsiveness -->
     <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation" id="navbar-toggler">
      <i class="fa-solid fa-bars" style="color: #E8D8C4;"></i>
     </button>
     <!-- Company Logo and Name on the left -->
     <a class="navbar-brand" href="index.html">
      <img src="icons/logo.png" alt="Thugil Creation Logo" style="width: 40px; height: auto; margin-right: 10px;"> Thugil Creation </a>
    </div>
    <!-- Navbar Links and Dropdowns -->
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
     <ul class="navbar-nav">
      <li class="nav-item">
       <a class="nav-link active" aria-current="page" href="index.html">Home</a>
      </li>
      <li class="nav-item">
       <a class="nav-link" href="thugil-creation-membership.html">Membership</a>
      </li>
      <li class="nav-item">
       <a class="nav-link" href="thugil-creation.html">Purchase</a>
      </li>
      <li class="nav-item">
       <a class="nav-link" href="contact.html">Contact</a>
      </li>
     </ul>
    </div>
    <!-- Right Side: User and Cart Icons (This part will be hidden on toggle) -->
    <div class="d-flex navbar-icons" id="navbar-icons">
      <!-- Search Input -->
      <input type="text" id="searchInput" class="form-control me-2" style="display: none; width: 100px; transition: width 0.5s ease;" placeholder="Search by Hooks">
      <button id="searchButton" class="btn me-2">
        <i class="fa-solid fa-magnifying-glass fa-fade fa-lg" style="font-size: 20px; color: #E8D8C4;"></i>
      </button>
      <!-- Cart Icon -->
      <a href="#" class="nav-link" id="cart-icon">
        <i class="fa-solid fa-bag-shopping" style="font-size: 24px; color: #E8D8C4;"></i>
      </a>
    </div>
    <!-- Sidebar for Cart (Initially hidden) -->
    <div id="cart-sidebar" class="cart-sidebar">
     <div class="sidebar-header">
      <h5>Cart</h5>
      <button id="close-cart" class="btn-close">X</button>
     </div>
     <div class="sidebar-body">
      <!-- Cart items will be displayed here -->
      <ul id="cart-items"></ul>
     </div>
     <!-- Total Section (Added at the bottom) -->
     <div id="cart-totals" class="cart-totals">
      <div class="total-row">
       <span>Total Products:</span>
       <span id="total-products">0</span>
       <!-- Dynamically updated -->
      </div>
      <div class="total-row">
       <span>Total (Including Tax):</span>
       <span id="total-price">₹0.00</span>
       <!-- Dynamically updated -->
      </div>
      <!-- Checkout Button -->
      <div class="checkout-btn-container">
       <button id="checkout-btn" class="btn btn-primary">Proceed to Checkout</button>
      </div>
     </div>
    </div>
   </div>
  </nav>
  <div class="banner">
   <div class="banner-content">
    <h1>Heritage</h1>
    <p>Explore handloomed sarees that fuse modern style with timeless craftsmanship, offering luxury and sophistication for the heritage-loving woman. Discover the perfect blend of classic beauty and contemporary design in our premium silk collection.</p>
   </div>
  </div>
  <div class="container text-center mt-5 mb-5">
   <!-- Title -->
   <h2 class="mb-4">Saree Motif Styles</h2>
   <!-- Row with gap -->
   <div class="row g-3 align-items-center" style="overflow-x: auto; white-space: nowrap; padding-bottom: 20px; display: flex;">
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
      <a href="#" style="text-decoration: none;" data-name="butta" onclick="storeInLocalStorage(this); redirectWithRandomID(this)">
          <div class="card" style="position: relative; overflow: hidden;">
              <img src="img/Butta.png" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
              <div class="card-text-bottom">
                  <p>Butta</p>
              </div>
          </div>
      </a>
  </div>
  
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="pattern" onclick="storeInLocalStorage(this); redirectWithRandomID('pattern')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="img/Pattern.jpg" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Patterns</p>
                </div>
            </div>
        </a>
    </div>
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="full-set" onclick="storeInLocalStorage(this); redirectWithRandomID('full-set')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="img/Full Set.png" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Full Set</p>
                </div>
            </div>
        </a>
    </div>
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="brocade" onclick="storeInLocalStorage(this); redirectWithRandomID('brocade')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="img/Mixed.png" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Brocade</p>
                </div>
            </div>
        </a>
    </div>
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="pallu" onclick="storeInLocalStorage(this); redirectWithRandomID('pallu')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="img/Free Image.png" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Pallu</p>
                </div>
            </div>
        </a>
    </div>
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="border" onclick="storeInLocalStorage(this); redirectWithRandomID('border')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="https://cdn.vectorstock.com/i/500p/86/69/indian-ethnic-sari-design-which-is-originated-vector-53698669.jpg" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Border</p>
                </div>
            </div>
        </a>
    </div>
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="embose" onclick="storeInLocalStorage(this); redirectWithRandomID('embose')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="https://img.freepik.com/premium-vector/pattern-paisley-dark-purple-background_1055519-1932.jpg" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Embose</p>
                </div>
            </div>
        </a>
    </div>
    <div class="col-6 col-md-3" style="flex-shrink: 0;">
        <a href="#" style="text-decoration: none;" data-name="free-images" onclick="storeInLocalStorage(this); redirectWithRandomID('free-images')">
            <div class="card" style="position: relative; overflow: hidden;">
                <img src="https://static.vecteezy.com/system/resources/thumbnails/053/120/178/small/golden-big-floral-border-for-saree-vector.jpg" class="card-img-top" alt="Card image" style="height: 150px; width: 100%; object-fit: cover;">
                <div class="card-text-bottom">
                    <p>Free Image</p>
                </div>
            </div>
        </a>
    </div>
</div>
<script>
 // Generate a random code
function generateRandomCode() {
    return Math.floor(Math.random() * 1000000000000); // generates a random 12-digit number
}

// Store the selected motif in localStorage
function storeInLocalStorage(element) {
    const motif = element.getAttribute('data-name'); // Get the selected motif from the data-name attribute
    localStorage.setItem('selectedMotif', motif); // Save the motif in localStorage
}

// Redirect to the new URL with random code and selected motif in query parameters
function redirectWithRandomID(element) {
    var uniqueCode = generateRandomCode(); // Generate a unique code
    var selectedMotif = localStorage.getItem('selectedMotif'); // Fetch the selected motif from localStorage

    if (selectedMotif) {
        // Construct the URL with query parameters
        var newURL = '/thugil-creation-design-page.html?code=' + uniqueCode + '&motif=' + selectedMotif;
        
        // Redirect to the new URL
        window.location.href = newURL;
    } else {
        console.log('Selected motif is not stored in localStorage.');
    }
}

</script>

  
  </div>
  <div class="container text-center mt-5 mb-5">
    <div class="tutor mb-5" style="position: relative;">
        <video id="introVideo" width="100%" height="auto" loop muted>
            <!-- Local video source -->
            <source src="videos/intro.mp4" type="video/mp4">
            Your browser does not support the video tag.
        </video>
        
        <!-- Explore Button -->
        <a href="class/index.html" target="_blank" 
           style="position: absolute; bottom: 20px; right: 20px; padding: 10px 20px; background-color: #561C24; color: #fff; text-decoration: none; border-radius: 5px;">
            Explore Courses
        </a>
    </div>
</div>

  <div class="text" style="position: relative; padding: 20px; background-color: #6D2932; border-radius: 0px">
   <!-- Title at the top left -->
   <h2 style="position: absolute; top: 10px; left: 20px; margin: 0; font-size: 2rem; color: #DAD4B5 !important; font-weight: 600;">Saree Design</h2>
   <!-- Description about the silk saree making process -->
   <p style="text-align: justify; font-size: 1rem; line-height: 1.8; color: #C7B7A3; margin-top: 40px; letter-spacing: 0.5px;"> Silk saree design is a meticulous and intricate process that requires skilled craftsmanship. The design begins with choosing high-quality silk fabric, followed by hand weaving or machine weaving. Artisans carefully create intricate patterns, often using zari threads to add a metallic finish. The sarees are dyed using natural or chemical dyes to achieve vibrant and rich colors. Finally, the saree is hand-embroidered or machine-stitched to enhance the overall design. </p>
   <p style="text-align: justify; font-size: 1rem; line-height: 1.8; color: #C7B7A3; letter-spacing: 0.5px;"> The entire process can take days or even weeks depending on the complexity of the design. Traditional silk sarees are often crafted using age-old techniques passed down through generations. The weaving process involves skilled hands working meticulously to ensure the patterns align perfectly. After the weaving, the saree is checked for any imperfections, ensuring that only the best quality fabric is used. Once complete, the saree is ready to be worn on special occasions, reflecting the rich heritage of Indian craftsmanship. </p>
  </div>
  <div class="payment mt-0 mb-0">
   <div class="payment-marquee">
    <img src="icons/google-pay-icon.png" alt="Google Pay" class="payment-logo">
    <img src="icons/paytm-icon.png" alt="Paytm" class="payment-logo">
    <img src="icons/phonepe-icon.png" alt="PhonePe" class="payment-logo">
    <img src="icons/razorpay-icon.png" alt="Google Pay" class="payment-logo">
   </div>
  </div>
  <footer class="footer">
    <div class="footer-content">
     <div class="footer-column">
      <h3>About Us</h3>
      <p>At Thugil Creations, we specialize in creating exquisite, handwoven silk sarees that blend timeless tradition with modern elegance.</p>
     </div>
     <div class="footer-column">
      <h3>Quick Links</h3>
      <ul>
        <li><a href="#" class="nav-link">Home</a></li>
        <li><a href="thugil-creation.html" class="nav-link">Purchases</a></li>
        <li><a href="contact.html" class="nav-link">Contact</a></li>
        <li><a href="privacy-policy.html" class="nav-link">Privacy Policy</a></li> <!-- Added link -->
        <li><a href="thugilcreation-Policy.html" class="nav-link">Terms & Conditions</a></li> <!-- Added link -->
      </ul>
     </div>
     <div class="footer-column mb-2">
       <h3>Contact Information</h3>
       <p>Email: thugilcreation@gmail.com</p>
       <p>Phone: +91 8838008499 <span style="margin-left: 1%;"></span> +91 9994266271 </p>
       <p>Address: Kondalampatty, Salem-TamilNadu</p>
       <div class="social-links">
         <a href="https://www.facebook.com/thugilcreation29" target="_blank">
           <i class="fab fa-facebook-f" style="color: #6D2932;"></i>
         </a>
         <a href="https://www.youtube.com/@THUGILCREATION" target="_blank">
           <i class="fa-brands fa-youtube" style="color: #6D2932;"></i>
         </a>
         <a href="https://www.instagram.com/thugil_creation29/?next=%2F" target="_blank">
           <i class="fab fa-instagram" style="color: #6D2932;"></i>
         </a>
       </div>
     </div>
     <div class="footer-column newsletter-column">
      <h3>Newsletter</h3>
      <p>Stay updated with our latest news and offers. Subscribe to our newsletter.</p>
      <form id="newsletter-form" action="#" method="POST">
       <input type="email" id="email" placeholder="Enter your email" required>
       <button type="submit">Subscribe</button>
      </form>
     </div>
    </div>
    <div class="footer-bottom">
     <p>&copy; 2024 Thugil Creation. All Rights Reserved.</p>
    </div>
 </footer>
 
  <!-- Firebase Script -->
  <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
  <script type="module">
   import {
    initializeApp
   } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js';
   import {
    getAuth,
    onAuthStateChanged
   } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-auth.js';
   import {
    getDatabase,
    ref,
    push,
    get,
    child,
    remove,
    set,
    onValue
   } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-database.js';
   // Firebase Configuration
   const firebaseConfig = {
    apiKey: "AIzaSyBa2JROkkVR6GWboFZJT2G5NMycYa9zRJ8",
    authDomain: "thugilcreations.firebaseapp.com",
    projectId: "thugilcreations",
    storageBucket: "thugilcreations.firebasestorage.app",
    messagingSenderId: "621636941555",
    appId: "1:621636941555:web:9648e3188471af8a2fe986"
   };
   // Initialize Firebase
   const app = initializeApp(firebaseConfig);
   const auth = getAuth(app);
   const database = getDatabase(app);
   // Popup Setup (keep as per your existing format)
   const popupContainer = document.createElement('div');
   popupContainer.id = 'popup-newsletter';
   popupContainer.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    opacity: 0;
    transition: opacity 0.3s ease;
  `;
   document.body.appendChild(popupContainer);
   // Popup HTML Content (keep as per your existing format)
   popupContainer.innerHTML = `
    
			<style>
      #newsletter-content {
        background-color: #fff;
        max-width: 800px;
        width: 90%;
        max-height: 400px;
        height: 70%;
        display: flex;
        flex-direction: row;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        position: relative;
        overflow: hidden;
      }

      @media (max-width: 768px) {
        #newsletter-content {
          flex-direction: column;
          width: 95%;
          max-height: 45vh;
          height: auto;
        }
      }

      #newsletter-image {
        flex: 1;
        width: 100%;
        height: 100%;
        object-fit: cover;
        object-position: center;
      }

      @media (max-width: 768px) {
        #newsletter-image {
          height: 50px !important;
        }
      }

      #newsletter-form-container {
        flex: 1;
        padding: 20px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      #close-popup {
        position: absolute;
        top: 10px;
        right: 10px;
        background: transparent;
        border: none;
        font-size: 24px;
        color: #aaa;
        cursor: pointer;
        transition: color 0.3s ease;
      }

      #close-popup:hover {
        color: #333;
      }
    </style>
      <div id="newsletter-content" class="newsletter-column">
        <img id="newsletter-image" src="https://images.meesho.com/images/products/62188977/cddr5_512.jpg" alt="Newsletter Promo">
          <div id="newsletter-form-container">
            <h2>Subscribe to our Newsletter</h2>
            <p>Get the latest updates and offers from Thugil Creations!</p>
            <form id="popup-newsletter-form">
              <input type="email" id="popup-email" placeholder="Enter your email" required>
                <button type="submit">Subscribe</button>
              </form>
            </div>
            <button id="close-popup">&times;</button>
          </div>
  `;
   // Handle closing the popup
   const closeButton = document.getElementById('close-popup');
   closeButton.addEventListener('click', function() {
    popupContainer.style.opacity = '0';
    setTimeout(() => {
     popupContainer.style.display = 'none';
    }, 300);
   })
   function subscribeNewsletter(email) {
    let userUID = null;
    
    // Check if userUID is in localStorage
    const storedUserUID = localStorage.getItem('userUID');
    
    if (storedUserUID) {
        userUID = storedUserUID;
    } else {
        const user = auth.currentUser;
        if (user) {
            userUID = user.uid;
        } else {
            // Save current page URL
            localStorage.setItem('redirectTo', window.location.href);
            
            // Redirect to signup page
            window.location.href = 'signup.html';
            return;
        }
    }
    
    // Display a loading message or indicator
    const loadingIndicator = document.getElementById('loadingIndicator'); // Assuming you have a div with this ID
    if (loadingIndicator) {
        loadingIndicator.style.display = 'block';  // Show loading indicator
    }

    // Reference to Firebase location
    const newsletterRef = ref(database, 'newsletters');
    push(newsletterRef, {
        email: email,
        userId: userUID,
        subscribedAt: new Date().toISOString()
    }).then(() => {
        // Hide the loading indicator
        if (loadingIndicator) {
            loadingIndicator.style.display = 'none';  // Hide loading indicator
        }

        // Close the popup or perform any other necessary actions
        closePopup();
    }).catch((error) => {
        // Hide the loading indicator in case of error
        if (loadingIndicator) {
            loadingIndicator.style.display = 'none';  // Hide loading indicator
        }

    });
}

   // Function to open the popup
   function showPopup() {
    popupContainer.style.display = 'flex';
    setTimeout(() => {
     popupContainer.style.opacity = '1';
    }, 2000);
   }
   // Close Popup function
   function closePopup() {
    popupContainer.style.opacity = '0';
    setTimeout(() => {
     popupContainer.style.display = 'none';
    }, 300);
   }
   // Setup the popup form submission
   const popupNewsletterForm = document.getElementById('popup-newsletter-form');
   popupNewsletterForm.addEventListener('submit', function(event) {
    event.preventDefault();
    const emailInput = document.getElementById('popup-email');
    const email = emailInput.value.trim();
    if (!email) {
     alert('Please enter a valid email address.');
     return;
    }
    // Save email in Firebase
    subscribeNewsletter(email);
   });
   // Footer form handling
   const footerNewsletterForm = document.getElementById('newsletter-form');
   footerNewsletterForm.addEventListener('submit', function(event) {
    event.preventDefault();
    const emailInput = document.getElementById('email');
    const email = emailInput.value.trim();
    if (!email) {
     alert('Please enter a valid email address.');
     return;
    }
    // Save email in Firebase
    subscribeNewsletter(email);
   });
   // Check authentication and show popup if necessary
   onAuthStateChanged(auth, (user) => {
    if (user) {
     // Check if the user is already subscribed to the newsletter in Firebase
     const userUID = user.uid;
     const userRef = ref(database, 'newsletters');
     // Query Firebase to check if the user has already subscribed
     get(userRef).then((snapshot) => {
      let isSubscribed = false;
      snapshot.forEach((childSnapshot) => {
       if (childSnapshot.val().userId === userUID) {
        isSubscribed = true;
       }
      });
      if (!isSubscribed) {
       // If the user is not subscribed, show the popup
       showPopup();
      }
     }).catch((error) => {
      console.error('Error checking user subscription:', error);
     });
    } else {
     showPopup(); // Show popup if user is not authenticated
    }
   });
   document.addEventListener('DOMContentLoaded', function () {
        const searchInput = document.getElementById('searchInput');
        const searchButton = document.getElementById('searchButton');
        const companyName = document.getElementById('companyName');
        const logo = document.querySelector('.navbar-brand img'); // Select the logo image
    
        // Show search input and hide company name and logo on click
        searchButton.addEventListener('click', function () {
            if (searchInput.style.display === 'none' || searchInput.style.display === '') {
                // Check if the screen width is less than 768px (mobile view)
                if (window.innerWidth < 768) {
                    logo.style.opacity = '0'; // Fade out logo
                    
                    logo.style.transition = 'opacity 0.5s ease'; // Smooth transition
                }
                searchInput.style.display = 'block'; // Show search input
                searchInput.style.width = '250px'; // Expand to desired width
                searchInput.focus();
            } else {
                // Check if the screen width is less than 768px (mobile view)
                if (window.innerWidth < 768) {
                    
                    logo.style.opacity = '1'; // Fade in logo
                }
                searchInput.style.width = '0'; // Collapse the input
                setTimeout(() => {
                    searchInput.style.display = 'none'; // Hide input after transition
                }, 500); // Wait for the transition to finish
            }
        });
    
        // Optional: Add an event listener to handle window resize
        window.addEventListener('resize', function () {
            if (window.innerWidth >= 768) {
                companyName.style.opacity = '1'; // Ensure company name is visible on larger screens
                logo.style.opacity = '1'; // Ensure logo is visible on larger screens
                searchInput.style.display = 'none'; // Hide search input if it's not needed
                searchInput.style.width = '0'; // Reset width
            }
        });
    });
    function searchProducts() {
  const searchQuery = document.getElementById('searchInput').value.trim().toLowerCase();

  if (searchQuery) {
    // Clear the search input field immediately (before the page redirect)
    document.getElementById('searchInput').value = '';

    // Redirect to the search.html page with the search query as a URL parameter
    // Using encodeURIComponent to make sure the search query is safely passed in the URL
    window.location.href = `search.html?query=${encodeURIComponent(searchQuery)}`;
  }
}

// Event listener for the Search button
document.getElementById('searchButton').addEventListener('click', function() {
  searchProducts();
});

// Optional: Add an event listener for the Enter key to trigger search
document.getElementById('searchInput').addEventListener('keypress', function (e) {
  if (e.key === 'Enter') {
    searchProducts();
  }
});


   // Function to fetch and display cart items
   function fetchCartItems() {
        const userId = localStorage.getItem('userUID');
    
        if (!userId) {
            return;
        }
    
        // Declare cartRef once
        const cartRef = ref(database, `users/${userId}/cart`);
    
        // Initial fetch - this fetches cart items once
        get(cartRef)
            .then((snapshot) => {
                const cartItems = snapshot.val();
                let totalProducts = 0;
                let totalPrice = 0;
    
                const cartItemsList = document.getElementById('cart-items');
                cartItemsList.innerHTML = ''; // Clear existing items
    
                if (cartItems) {
                    Object.values(cartItems).forEach(item => {
                        totalProducts++;
                        const itemPriceWithTax = item.finalPrice * (1 + (item.taxRate || 0) / 100);
                        totalPrice += itemPriceWithTax;
    
                        const cartItemRow = document.createElement('div');
                        cartItemRow.className = 'cart-item-row';
                        cartItemRow.id = item.productId; // Set productId as ID for removal
    
                        // Top Row Content
                        const topRowContent = document.createElement('div');
                        topRowContent.className = 'cart-item-top-row';
    
                        // Image
                        const imageContainer = document.createElement('div');
                        imageContainer.className = 'cart-item-image';
                        const productImage = document.createElement('img');
                        productImage.src = item.imageUrl;
                        productImage.className = 'cart-item-img';
                        productImage.alt = item.name;
                        imageContainer.appendChild(productImage);
    
                        // Details
                        const productDetails = document.createElement('div');
                        productDetails.className = 'cart-item-details';
    
                        const productName = document.createElement('h5');
                        productName.className = 'cart-item-name';
                        productName.innerText = item.name;
    
                        const productPrice = document.createElement('p');
                        productPrice.className = 'cart-item-price';
                        productPrice.innerText = `₹${item.finalPrice}`;
    
                        // Actions
                        const actionContainer = document.createElement('div');
                        actionContainer.className = 'cart-item-actions';
    
                        // Replace button with text label to toggle the dropdown
                        const toggleText = document.createElement('span');
                        toggleText.className = 'dropdown-toggle-text';
                        toggleText.innerText = 'Show'; // Initial text is 'Show'
                        toggleText.style.fontSize = '12px'; // Make text small
    
                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'btn btn-danger';
                        deleteBtn.innerText = 'Delete';
                        deleteBtn.onclick = () => deleteCartItem(item.productId, cartItemRow); // Pass row to remove
    
                        // Append to top row
                        productDetails.appendChild(productName);
                        productDetails.appendChild(productPrice);
                        
                        actionContainer.appendChild(toggleText);
                        actionContainer.appendChild(deleteBtn);
    
                        topRowContent.appendChild(imageContainer);
                        topRowContent.appendChild(productDetails);
                        topRowContent.appendChild(actionContainer);
    
                        // Dropdown Details
                        const detailsDropdown = document.createElement('div');
                        detailsDropdown.className = 'cart-item-dropdown';
                        detailsDropdown.style.display = 'none'; // Initially hidden
    
                        const detailsList = document.createElement('ul');
                        detailsList.className = 'list-group';
    
                        const details = [
                            `Hooks: ${item.hooks}`,
                            `Cards: ${item.cards || 'N/A'}`,
                            `Epi: ${item.epi}`,
                            `PPI: ${item.ppi || 'N/A'}`,
                            `Image Type: ${item.imageType}`,
                        ];
    
                        details.forEach(detail => {
                            const li = document.createElement('li');
                            li.className = 'list-group-item';
                            li.innerText = detail;
                            detailsList.appendChild(li);
                        });
    
                        detailsDropdown.appendChild(detailsList);
    
                        // Append to cart item row
                        cartItemRow.appendChild(topRowContent);
                        cartItemRow.appendChild(detailsDropdown);
    
                        cartItemsList.appendChild(cartItemRow);
    
                        // Toggle the dropdown and change the text
                        toggleText.addEventListener('click', () => {
                            const isOpen = detailsDropdown.style.display === 'block';
    
                            // Toggle the display of the dropdown
                            detailsDropdown.style.display = isOpen ? 'none' : 'block';
                            
                            // Change the text between "Show" and "Hide"
                            toggleText.innerText = isOpen ? 'Show' : 'Hide';
                        });
                    });
    
                    // Update totals
                    document.getElementById('total-products').textContent = totalProducts;
                    document.getElementById('total-price').textContent = `₹${totalPrice.toFixed(2)}`;
                } else {
                     // Check if the 'No items in your cart' message already exists
        const existingMessage = document.getElementById('empty-message');
        if (!existingMessage) {
            // Create the empty message if it doesn't exist
            const emptyMessage = document.createElement('div');
            emptyMessage.id = 'empty-message'; // Give it an ID to easily check later
            emptyMessage.innerHTML = `
        <div class="empty-message-container">
            <img src="icons/undraw_shopping_re_hdd9.svg" alt="Empty Cart" class="empty-message-image">
            <p>No items in your cart.</p>
        </div>
    `;
    
            document.getElementById('cart-items').appendChild(emptyMessage);
        }
    
        // Reset the total products and price
        document.getElementById('total-products').textContent = '0';
        document.getElementById('total-price').textContent = '₹0.00';
                }
            })
            .catch((error) => {
                console.error('Error fetching cart items:', error);
            });
    
        // Listen for real-time changes in the cart (item added or deleted)
        onValue(cartRef, (snapshot) => {
            const cartItems = snapshot.val();
            const cartItemsList = document.getElementById('cart-items');
            
            // Clear the current items
            cartItemsList.innerHTML = '';
    
            if (cartItems) {
                let totalProducts = 0;
                let totalPrice = 0;
    
                Object.values(cartItems).forEach(item => {
                    totalProducts++;
                    const itemPriceWithTax = item.finalPrice * (1 + (item.taxRate || 0) / 100);
                    totalPrice += itemPriceWithTax;
    
                    const cartItemRow = document.createElement('div');
                    cartItemRow.className = 'cart-item-row';
                    cartItemRow.id = item.productId; // Set productId as ID for removal
    
                    // Top Row Content
                    const topRowContent = document.createElement('div');
                    topRowContent.className = 'cart-item-top-row';
    
                    // Image
                    const imageContainer = document.createElement('div');
                    imageContainer.className = 'cart-item-image';
                    const productImage = document.createElement('img');
                    productImage.src = item.imageUrl;
                    productImage.className = 'cart-item-img';
                    productImage.alt = item.name;
                    imageContainer.appendChild(productImage);
    
                    // Details
                    const productDetails = document.createElement('div');
                    productDetails.className = 'cart-item-details';
    
                    const productName = document.createElement('h5');
                    productName.className = 'cart-item-name';
                    productName.innerText = item.name;
    
                    const productPrice = document.createElement('p');
                    productPrice.className = 'cart-item-price';
                    productPrice.innerText = `₹${item.finalPrice}`;
    
                    // Actions
                    const actionContainer = document.createElement('div');
                    actionContainer.className = 'cart-item-actions';
    
                    // Replace button with text label to toggle the dropdown
                    const toggleText = document.createElement('span');
                    toggleText.className = 'dropdown-toggle-text';
                    toggleText.innerText = 'Show'; // Initial text is 'Show'
                    toggleText.style.fontSize = '12px'; // Make text small
    
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'btn btn-danger';
                    deleteBtn.innerText = 'Delete';
                    deleteBtn.onclick = () => deleteCartItem(item.productId, cartItemRow); // Pass row to remove
    
                    // Append to top row
                    productDetails.appendChild(productName);
                    productDetails.appendChild(productPrice);
                    
                    actionContainer.appendChild(toggleText);
                    actionContainer.appendChild(deleteBtn);
    
                    topRowContent.appendChild(imageContainer);
                    topRowContent.appendChild(productDetails);
                    topRowContent.appendChild(actionContainer);
    
                    // Dropdown Details
                    const detailsDropdown = document.createElement('div');
                    detailsDropdown.className = 'cart-item-dropdown';
                    detailsDropdown.style.display = 'none'; // Initially hidden
    
                    const detailsList = document.createElement('ul');
                    detailsList.className = 'list-group';
    
                    const details = [
                        `Hooks: ${item.hooks}`,
                        `Cards: ${item.cards || 'N/A'}`,
                        `Epi: ${item.epi}`,
                        `PPI: ${item.ppi || 'N/A'}`,
                        `Image Type: ${item.imageType}`,
                    ];
    
                    details.forEach(detail => {
                        const li = document.createElement('li');
                        li.className = 'list-group-item';
                        li.innerText = detail;
                        detailsList.appendChild(li);
                    });
    
                    detailsDropdown.appendChild(detailsList);
    
                    // Append to cart item row
                    cartItemRow.appendChild(topRowContent);
                    cartItemRow.appendChild(detailsDropdown);
    
                    cartItemsList.appendChild(cartItemRow);
    
                    // Toggle the dropdown and change the text
                    toggleText.addEventListener('click', () => {
                        const isOpen = detailsDropdown.style.display === 'block';
    
                        // Toggle the display of the dropdown
                        detailsDropdown.style.display = isOpen ? 'none' : 'block';
                        
                        // Change the text between "Show" and "Hide"
                        toggleText.innerText = isOpen ? 'Show' : 'Hide';
                    });
                });
    
                // Update totals
                document.getElementById('total-products').textContent = totalProducts;
                document.getElementById('total-price').textContent = `₹${totalPrice.toFixed(2)}`;
            } else {
                // No items in the cart, show empty message
                const emptyMessage = document.createElement('div');
                emptyMessage.id = 'empty-message'; // Give it an ID to easily check later
                emptyMessage.innerHTML = `
                <div class="empty-message-container">
                    <img src="icons/undraw_shopping_re_hdd9.svg" alt="Empty Cart" class="empty-message-image">
                    <p>No items in your cart.</p>
                </div>
            `;
    
                document.getElementById('cart-items').appendChild(emptyMessage);
            }
        });
    }
   // Popup Setup for User Details (appears on checkout)
   const userDetailsPopupContainer = document.createElement('div');
   userDetailsPopupContainer.id = 'popup-user-details';
   userDetailsPopupContainer.style.cssText = `
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  opacity: 0;
  transition: opacity 0.3s ease;
`;
   document.body.appendChild(userDetailsPopupContainer);
   // Popup HTML Content for User Details
   userDetailsPopupContainer.innerHTML = `
  
																																<style>
  /* Popup container */
  #user-details-content {
    background-color: #fff;
    max-width: 500px;
    width: 90%;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    max-height: 500px;
    overflow: hidden;
    border-radius: 8px; /* Rounded corners */
    transition: all 0.3s ease;
  }

  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
  }

  /* Form styling */
  #user-details-form {
    width: 100%;
  }

  #user-details-form input {
    width: 100%;
    padding: 12px;
    margin: 10px 0;
    border: 1px solid #ccc;
    font-size: 16px;
    border-radius: 4px; /* Rounded input fields */
    transition: border-color 0.3s ease;
  }

  #user-details-form input:focus {
    border-color: #FF4545; /* Focus color for inputs */
    outline: none;
  }

  /* Submit button */
  #user-details-form button {
    width: 100%;
    padding: 12px;
    margin-top: 20px;
    border: none;
    background-color: #FF9C73; /* Background color for the button */
    color: white;
    font-size: 18px;
    cursor: pointer;
    border-radius: 4px; /* Rounded button corners */
    transition: background-color 0.3s ease;
  }

  #user-details-form button:hover {
    background-color: #FF4545; /* Hover effect */
  }

  /* Close button */
  #close-user-details {
    position: absolute;
    top: 15px;
    right: 15px;
    background: transparent;
    border: none;
    font-size: 28px;
    color: #aaa;
    cursor: pointer;
    transition: color 0.3s ease;
  }

  #close-user-details:hover {
    color: #333;
  }

  /* Description text under the form */
  .form-description {
    font-size: 16px;
    color: #666;
    margin-bottom: 20px;
    text-align: center;
  }
</style>
																																<div id="user-details-content">
																																	<h2>Enter Your Details</h2>
																																	<p class="form-description">We need a few details to proceed with your payment. Your data is secure with us!</p>
																																	<form id="user-details-form">
																																		<input type="text" id="user-name" placeholder="Enter your Name" required>
																																			<input type="text" id="user-mobile" placeholder="Enter your Mobile Number" required>
																																				<input type="text" id="user-city" placeholder="Enter your City" required>
																																					<button type="submit">Proceed to Payment</button>
																																				</form>
																																				<button id="close-user-details">&times;</button>
																																			</div>
`;
   const closeUserDetailsButton = document.getElementById('close-user-details');
   closeUserDetailsButton.addEventListener('click', function() {
    userDetailsPopupContainer.style.opacity = '0';
    setTimeout(() => {
     userDetailsPopupContainer.style.display = 'none';
    }, 300);
   });
   // Function to open the User Details Popup
   function showUserDetailsPopup() {
    userDetailsPopupContainer.style.display = 'flex';
    setTimeout(() => {
     userDetailsPopupContainer.style.opacity = '1';
    }, 10);
   }
   // Handle form submission for user details
   const userDetailsForm = document.getElementById('user-details-form');
   userDetailsForm.addEventListener('submit', function(event) {
    event.preventDefault();
    const name = document.getElementById('user-name').value.trim();
    const mobile = document.getElementById('user-mobile').value.trim();
    const city = document.getElementById('user-city').value.trim();
    if (!name || !mobile || !city) {
     alert('Please fill in all fields.');
     return;
    }
    // Save user details to Firebase
    const userId = localStorage.getItem('userUID');
    if (userId) {
     const userRef = ref(database, `users/${userId}/details`);
     set(userRef, {
      name: name,
      mobile: mobile,
      city: city
     }).then(() => {
      closeUserDetailsPopup();
     }).catch((error) => {
      console.error('Error saving user details:', error);
      alert('Failed to save details. Please try again.');
     });
    } else {
     alert('User not authenticated.');
    }
   });
   // Close the popup
   function closeUserDetailsPopup() {
    userDetailsPopupContainer.style.opacity = '0';
    setTimeout(() => {
     userDetailsPopupContainer.style.display = 'none';
    }, 300);
   }
   fetchCartItems();
   // Function to calculate the total cart amount
function calculateCartTotal() {
  let total = 0;

  const userId = localStorage.getItem('userUID');
  if (!userId) {
    console.error('User ID not found in local storage');
    return 0;
  }

  const cartRef = ref(database, `users/${userId}/cart`); // Correct reference for the cart
  get(cartRef)
    .then((snapshot) => {
      const cartItems = snapshot.val();
      if (cartItems) {
        Object.values(cartItems).forEach(item => {
          const itemPriceWithTax = item.listingRate * (1 + (item.taxRate || 0) / 100);
          total += itemPriceWithTax;
        });
      }

      // Now we have the total amount, let's use it for the Razorpay payment.
      initiateRazorpayPayment(total); // Pass total directly to Razorpay function
    })
    .catch((error) => {
      console.error('Error calculating cart total:', error);
    });

  return total; // Return the total amount in INR
}


 // Function to fetch user details using userUID from localStorage
function getUserDetails() {
  const userUID = localStorage.getItem('userUID'); // Get userUID from localStorage

  if (!userUID) {
    return null;
  }

  // Reference to the user's details in the database
  const userRef = ref(database, `users/${userUID}/details`);

  return get(userRef)
    .then((snapshot) => {
      const userData = snapshot.val();
      if (userData) {
        return {
          name: userData.name || 'Default Name',
          mobile: userData.mobile || 'Default Mobile',
          city: userData.city || 'Default City',
        };
      } else {
        return null;
      }
    })
    .catch((error) => {
              return null;
    });
}

  // Function to initiate Razorpay payment
  function initiateRazorpayPayment(totalAmount) {
    if (totalAmount <= 0) {
      alert('Cart is empty or total amount is invalid.');
      return;
    }

    // Fetch user details
    getUserDetails().then((userDetails) => {
      if (!userDetails) {
        alert('Failed to retrieve user details.');
        return;
      }

      // Razorpay payment options
      const options = {
        key: "rzp_live_yd0X4n9mljd7B5", // Replace with your Razorpay Key ID
        amount: totalAmount * 100, // Razorpay expects the amount in paise (1 INR = 100 paise)
        currency: "INR",
        name: "Thugil Creation",
        description: "Checkout Description",
        image: "icons/logo.png", // Optional: Add a logo
        handler: function (response) {
          // Payment successful, create order and remove cart items
          createPurchaseOrder(response, totalAmount);
        },
        prefill: {
          name: userDetails.name || "Customer Name",  // Prefill customer name
          contact: userDetails.mobile || "+919876543210"  // Prefill customer contact
        },
        notes: {
          address: userDetails.city || "Customer Address"  // Optional: Add address to notes
        },
        theme: {
          color: "#561C24"  // Optional: Change the button color
        }
      };

      // Initialize Razorpay
      const razorpay = new Razorpay(options);
      razorpay.open();
    });
  }


   // Function to create a purchase order in the database and remove cart items
   function createPurchaseOrder(paymentResponse, totalAmount) {
    const userId = localStorage.getItem('userUID');
    const cartRef = ref(database, `users/${userId}/cart`);
    const ordersRef = ref(database, `users/${userId}/orders`);
    // Get the current date and time
    const currentDate = new Date();
    const purchaseDate = currentDate.toISOString(); // ISO format (e.g., "2024-11-30T10:15:30.000Z")
    // Create an order object
    const orderDetails = {
     paymentId: paymentResponse.razorpay_payment_id,
     orderId: paymentResponse.razorpay_order_id,
     amount: totalAmount,
     status: 'Completed',
     items: [], // List of cart items (could be stored separately or in this object)
     purchaseDate: purchaseDate // Add the purchase date and time
    };
    // Fetch the cart items
    get(cartRef).then((snapshot) => {
     const cartItems = snapshot.val();
     if (cartItems) {
      orderDetails.items = Object.values(cartItems); // Add cart items to order
      // Create the order in the database
      const orderId = push(ordersRef).key; // Generate a unique order ID
      orderDetails.orderId = orderId; // Add the order ID to the order details
      set(ref(database, `users/${userId}/orders/${orderId}`), orderDetails).then(() => {
       // After order is created, remove all cart items
       removeCartItems(userId, cartRef);
      }).catch((error) => {
       console.error('Error saving order to database:', error);
      });
     }
    }).catch((error) => {
     console.error('Error fetching cart items:', error);
    });
   }
   // Function to remove cart items after placing the order
   function removeCartItems(userId, cartRef) {
    // Remove the cart from Firebase
    remove(cartRef).then(() => {
     // Also remove cart items from localStorage
     localStorage.removeItem('localCart');
     // Optionally, if you want to give the user feedback here, you can do so.
     // Redirect to the order confirmation page
     window.location.href = "confirm-payment-page.html";
    }).catch((error) => {
     console.error('Error removing cart items from Firebase:', error);
     // You can add some feedback to the user here in case of error
     alert('There was an error processing your order. Please try again later.');
    });
   }
   // Function to delete a cart item from Firebase and localStorage
   function deleteCartItem(itemId, cartItemRow) {
    const userId = localStorage.getItem('userUID');
    if (!userId) {
     return;
    }
    // Remove item from Firebase database
    const cartRef = ref(database, `users/${userId}/cart/${itemId}`);
    // Remove item from Firebase
    remove(cartRef).then(() => {
     // Remove the item from the UI immediately
     cartItemRow.remove();
     // Also remove the item from localStorage
     let cartItems = JSON.parse(localStorage.getItem('localCart')) || {}; // Get the cart from localStorage
     if (cartItems[itemId]) {
      delete cartItems[itemId]; // Remove item from localStorage cart
      localStorage.setItem('localCart', JSON.stringify(cartItems)); // Update localStorage
     }
     // Refresh the cart to reflect any changes in UI
     fetchCartItems();
    }).catch((error) => {
     console.error('Error removing item from cart:', error);
    });
   }
   // Add event listener for the checkout button
   document.getElementById('checkout-btn').addEventListener('click', function() {
    const userId = localStorage.getItem('userUID');
    if (!userId) {
     return;
    }
    // Check if the user has already provided details
    const userRef = ref(database, `users/${userId}/details`);
    get(userRef).then((snapshot) => {
     const userDetails = snapshot.val();
     if (userDetails) {
      // If user details already exist, skip the popup and proceed with payment
      calculateCartTotal(); // Trigger the total amount calculation
     } else {
      // Show the user details form if not already provided
      showUserDetailsPopup();
     }
    }).catch((error) => {
     console.error('Error fetching user details:', error);
    });
   });
   // Fetch cart items initially
   fetchCartItems(); // Initial fetch
  </script>
  <!-- Bootstrap JS and Popper.js (via CDN) -->
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script>
   // Get the toggle button and the icons container
   const toggleButton = document.getElementById('navbar-toggler');
   const navbarIcons = document.getElementById('navbar-icons');
   // Add event listener to the toggle button to hide/show the icons
   toggleButton.addEventListener('click', function() {
    navbarIcons.classList.toggle('d-none'); // Toggle the d-none class to hide/show
   });
   let currentSlide = 0;
   const slides = document.querySelectorAll('.text-item');
   const totalSlides = slides.length;

   function showSlide(index) {
    const slider = document.querySelector('.text-slider');
    slider.style.transform = `translateX(-${index * 100}%)`;
   }

   function moveSlide(direction) {
    if (direction === 'next') {
     currentSlide = (currentSlide + 1) % totalSlides; // Loop to first slide after last
    } else if (direction === 'prev') {
     currentSlide = (currentSlide - 1 + totalSlides) % totalSlides; // Loop to last slide before first
    }
    showSlide(currentSlide);
   }

   function autoSlide() {
    currentSlide = (currentSlide + 1) % totalSlides;
    showSlide(currentSlide);
   }
   // Auto slide every 3 seconds
   setInterval(autoSlide, 3000);
   // Initial display of first slide
   showSlide(currentSlide);
   window.addEventListener('load', function() {
    var video = document.getElementById('introVideo');
    var tutorContainer = document.querySelector('.tutor');
    // Play the video once it comes into view and user has unmuted
    var observer = new IntersectionObserver(function(entries) {
     entries.forEach(entry => {
      if (entry.isIntersecting) {
       // The video is in the viewport, start playing
       video.play();
       // Only play audio if unmuted
       if (!video.muted) {
        video.play(); // Resume audio play if unmuted
       }
       // Add ambient light effect when video plays
       tutorContainer.classList.add('playing');
      } else {
       // Pause the video if it's out of the viewport
       video.pause();
       // Remove ambient light effect when video pauses
       tutorContainer.classList.remove('playing');
      }
     });
    }, {
     threshold: 0.5 // Trigger when 50% of the video is in view
    });
    // Observe the video element
    observer.observe(video);
    // Toggle mute/unmute when the video is clicked
    video.addEventListener('click', function() {
     video.muted = !video.muted; // Toggle the muted state
     if (!video.muted) {
      video.play(); // Ensure the audio is played when unmuted
     }
    });
   });

   function storeInLocalStorage(element) {
    const motifName = element.getAttribute('data-name'); // Get the value of the data-name attribute
    localStorage.setItem('selectedMotif', motifName); // Store it in localStorage
   }
   // Get the elements
   const cartIcon = document.getElementById('cart-icon');
   const cartSidebar = document.getElementById('cart-sidebar');
   const closeCartBtn = document.getElementById('close-cart');
   // Open the cart sidebar when the cart icon is clicked
   cartIcon.addEventListener('click', function(event) {
    event.preventDefault(); // Prevent navigation
    cartSidebar.classList.add('open'); // Show the sidebar
    document.body.classList.add('cart-sidebar-open'); // Disable body scroll
   });
   // Close the cart sidebar when the close button is clicked
   closeCartBtn.addEventListener('click', function() {
    cartSidebar.classList.remove('open'); // Hide the sidebar
    document.body.classList.remove('cart-sidebar-open'); // Enable body scroll
   });
   // Disable zooming with JavaScript
   document.addEventListener('wheel', function(e) {
    if (e.ctrlKey || e.metaKey) {
     e.preventDefault();
    }
   }, {
    passive: false
   });
   // Disable pinch to zoom on touch devices
   document.addEventListener('touchstart', function(e) {
    if (e.touches.length > 1) {
     e.preventDefault();
    }
   }, {
    passive: false
   });
  </script>
  <script>
   // Function to apply blur to the entire page
   function applyBlur() {
    document.body.classList.add('blurred');
   }
   // Function to remove the blur from the page
   function removeBlur() {
    document.body.classList.remove('blurred');
   }
   // Listen for the PrintScreen key press and apply blur
   document.addEventListener('keydown', function(event) {
    // Block PrintScreen key
    if (event.key === 'PrintScreen') {
     event.preventDefault(); // Prevent the screenshot action
     applyBlur(); // Apply blur effect to the page
     // Optional: Remove the blur after a short period
     setTimeout(removeBlur, 2000); // Removes blur after 2 seconds
    }
   });
   // Disable right-click (context menu)
   document.addEventListener('contextmenu', function(event) {
    event.preventDefault();
   });
   // Disable Ctrl+S (Save) key
   document.addEventListener('keydown', function(event) {
    if (event.ctrlKey && event.key === 's') {
     event.preventDefault(); // Prevent Save
    }
   });
   // Developer Tools Detection (basic check for changes in window size)
   let isDevToolsOpen = false;
   const threshold = 160;
   setInterval(() => {
    const widthThreshold = window.outerWidth - window.innerWidth > threshold;
    const heightThreshold = window.outerHeight - window.innerHeight > threshold;
    if (widthThreshold || heightThreshold) {
     if (!isDevToolsOpen) {
      isDevToolsOpen = true;
      applyBlur(); // Blur the page when dev tools are detected
     }
    } else {
     if (isDevToolsOpen) {
      isDevToolsOpen = false;
      removeBlur(); // Remove the blur effect when dev tools are closed
     }
    }
   }, 1000);
  </script>
 </body>
</html>