<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Thugil Creation Search</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">
    <meta name="theme-color" content="#561C24">
        <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="stylesheet" href="style.css">
        <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=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">
        <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">
					<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="font-size: 24px; color: #E8D8C4;"></i>
					</button>
					<a class='navbar-brand' href='/'>
						<img src="icons/logo.png" alt="Thugil Creation Logo" style="width: 40px; height: auto; margin-right: 10px;">
						<span id="companyName">Thugil Creation</span>
					</a>
				</div>
				<div class="collapse navbar-collapse" id="navbarNavDropdown">
					<ul class="navbar-nav">
						<li class="nav-item">
							<a aria-current='page' class='nav-link active' href='/'>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 -->
				<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">
						<ul id="cart-items"></ul>
					</div>
					<div id="cart-totals" class="cart-totals">
						<div class="total-row">
							<span>Total Products:</span>
							<span id="total-products">0</span>
						</div>
						<div class="total-row">
							<span>Total (Including Tax):</span>
							<span id="total-price">₹0.00</span>
						</div>
						<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="row">
            <div class="col-md-12">
                <!-- Description Box -->
                <div class="description-box">
                    <h4>Harness Description</h4>
                    <div class="description-row">
                        <!-- Single Description -->
                        <div class="description-item">
                            <h5>Single</h5>
                            <p><strong>1 Hook</strong> = 1 Harness / 1 Bedha / 1 Vadi</p>
                        </div>
                        <!-- Double Description -->
                        <div class="description-item">
                            <h5>Double</h5>
                            <p><strong>1 Hook</strong> = 2 Harness / 2 Bedha / 2 Vadi</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
		
		<div class="product-wrapper">
			<div id="productContainer" class="row">
				<!-- Skeleton loading cards will be inserted here initially -->
				<div class="col mb-2 skeleton-card"></div>
				<div class="col mb-2 skeleton-card"></div>
				<div class="col mb-2 skeleton-card"></div>
				<div class="col mb-2 skeleton-card"></div>
				<div class="col mb-2 skeleton-card"></div>
				<div class="col mb-2 skeleton-card"></div>
			</div>
			<div id="paginationContainer" class="pagination"></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-Tamil Nadu</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>
			<div class="footer-bottom">
				<p>&copy; 2024 Thugil Creation. All Rights Reserved.</p>
			</div>
		</footer>
		<!-- 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
				});
			});
			// 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 type="module">
   
   import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js';
    import { getAuth } from 'https://www.gstatic.com/firebasejs/9.10.0/firebase-auth.js';
    import { getDatabase, ref, get, set, remove, onChildAdded, onChildChanged, onChildRemoved, push, onValue, update} 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);
    let productsDb;

// Open or create the productsDB
const productsRequest = indexedDB.open('productsDB', 1);

productsRequest.onupgradeneeded = function(event) {
  productsDb = event.target.result;
  if (!productsDb.objectStoreNames.contains('products')) {
    const store = productsDb.createObjectStore('products', { keyPath: 'productId' });
    store.createIndex('sareeStyle', 'sareeStyle', { unique: false });
  }
};

productsRequest.onerror = function(event) {
  console.error("Error opening productsDB:", event.target.error);
};

productsRequest.onsuccess = function(event) {
  productsDb = event.target.result;
  console.log("productsDB opened successfully.");
  // Once the DB is opened, you can call your function to retrieve data
  loadSearchResults(); // Call loadSearchResults only when the DB is ready
};

// Function to retrieve products from IndexedDB
function getProductsFromIndexedDB(callback) {
  if (!productsDb) {
    console.error("productsDb is not initialized.");
    return;
  }

  const transaction = productsDb.transaction(['products'], 'readonly');
  const store = transaction.objectStore('products');
  const request = store.getAll(); // Get all products

  request.onsuccess = function(event) {
    const products = event.target.result;
    console.log("Products retrieved from IndexedDB:", products);
    callback(products); // Return the products to the callback function
  };

  request.onerror = function(event) {
    console.error("Error retrieving products from IndexedDB:", event.target.error);
  };
}

// Function to fetch and display search results
function loadSearchResults() {
  // Get the query parameter from the URL
  const urlParams = new URLSearchParams(window.location.search);
  const searchQuery = urlParams.get('query');

  if (searchQuery) {
    // Get products from IndexedDB and filter them based on the search query
    getProductsFromIndexedDB((products) => {
      const filteredProducts = products.filter(product => {
        return (
          product.hooks.toString().toLowerCase().includes(searchQuery) ||
          product.cards.toString().toLowerCase().includes(searchQuery) ||
          product.sareeStyle.toLowerCase().includes(searchQuery) ||
          product.imageType.toLowerCase().includes(searchQuery)
        );
      });

      // Display the filtered products on the page
      displayProducts(filteredProducts);
    });
  } else {
    // No search query, show all products or a message
    getProductsFromIndexedDB((products) => {
      displayProducts(products); // Display all products if no query
    });
  }
}

let currentSort = 'price-low-high'; // Default sorting order

// Add event listeners for sorting
document.querySelectorAll('.dropdown-item').forEach(item => {
  item.addEventListener('click', function() {
    currentSort = this.getAttribute('data-sort'); // Get the sorting criteria
    displayProducts(products); // Re-render products based on new sort
  });
});

async function displayProducts(products) {
  const productContainer = document.getElementById('productContainer');
  const paginationContainer = document.getElementById('paginationContainer');
  productContainer.innerHTML = ''; // Clear the container before appending new products
  paginationContainer.innerHTML = ''; // Clear previous pagination controls

  // Get the selected motif from localStorage, default to 'Butta' if not found
  const selectedMotif = localStorage.getItem('selectedMotif') || 'Butta';

  // Filter products based on the selected motif
  const filteredProducts = products.filter(product => product.sareeStyle === selectedMotif);

  // If no matching products, show a message and return
  if (filteredProducts.length === 0) {
    console.log(`No products found for motif: ${selectedMotif}`);
    productContainer.innerHTML = "<p>No products found for this motif.</p>";
    return;
  }

  // Sort the filtered products based on the selected sorting option
  switch (currentSort) {
    case 'price-low-high':
      filteredProducts.sort((a, b) => a.finalPrice - b.finalPrice);
      break;
    case 'price-high-low':
      filteredProducts.sort((a, b) => b.finalPrice - a.finalPrice);
      break;
    case 'newest-first':
      filteredProducts.sort((a, b) => new Date(b.releaseDate) - new Date(a.releaseDate));
      break;
    case 'oldest-first':
      filteredProducts.sort((a, b) => new Date(a.releaseDate) - new Date(b.releaseDate));
      break;
    case 'popularity':
      filteredProducts.sort((a, b) => b.popularity - a.popularity); // Assuming `popularity` is a number
      break;
    default:
      break;
  }
  let currentPage = 1;  // Tracks the current page
  const itemsPerPage = 12;  // Number of products to display per page
  // Calculate total pages for pagination
  const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);

  // Get products for the current page
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedProducts = filteredProducts.slice(startIndex, endIndex);

  for (const product of paginatedProducts) {
    const productCard = document.createElement('div');
    productCard.className = 'col mb-2';

    const cardElement = document.createElement('div');
    cardElement.className = 'card product-card';

    const cardImgContainer = document.createElement('div');
    cardImgContainer.className = 'card-img-container';

    const blurredImage = document.createElement('div');
    blurredImage.className = 'blurred-image';

    const productImage = document.createElement('img');
    productImage.src = product.imageUrl;
    productImage.className = 'card-img-top product-image';
    productImage.alt = product.name;

    const clearImage = document.createElement('div');
    clearImage.className = 'clear-image';

    blurredImage.appendChild(productImage);
    blurredImage.appendChild(clearImage);

    const productLabel = document.createElement('span');
    productLabel.className = 'product-label';
    productLabel.textContent = product.label;

    const hoverDetails = document.createElement('div');
    hoverDetails.className = 'hover-details';
    hoverDetails.innerHTML = ` 
        <p><strong>Hooks:</strong> ${product.hooks}</p>
        <p><strong>Cards:</strong> ${product.cards}</p>
        <p><strong>EPI:</strong> ${product.epi}</p>
        <p><strong>PPI:</strong> ${product.ppi}</p>
        <p><strong>Harnessbuild:</strong> ${product.harnessbuild}</p>
        <p><strong>Image Type:</strong> ${product.imageType}</p>
    `;

    cardImgContainer.appendChild(blurredImage);
    cardImgContainer.appendChild(productLabel);
    cardImgContainer.appendChild(hoverDetails);

    const cardBody = document.createElement('div');
    cardBody.className = 'card-body';

    const cardTitle = document.createElement('h5');
    cardTitle.className = 'card-title';
    cardTitle.textContent = product.name;
    // Create the button and the separator
const viewBtn = document.createElement('button');
viewBtn.className = 'view-btn';

// Create the separator element
const separator = document.createElement('span');
separator.textContent = ' |';
separator.style.marginRight = '10px'; // Optional: space between separator and button text

// Create the text element for the button content
const buttonText = document.createElement('span');
buttonText.textContent = 'View';

// Style the button text (this will have the background)
buttonText.style.backgroundColor = '#561C24';
buttonText.style.color = 'white'; // Text color
buttonText.style.padding = '0px 5px'; // Padding for the button
buttonText.style.borderRadius = '0px'; // Optional: rounded corners
buttonText.style.fontSize = '12px'; // Smaller font size (adjust as needed)

// Append the separator and the button text to the button
viewBtn.appendChild(separator);
viewBtn.appendChild(buttonText);

viewBtn.addEventListener('click', () => {
  showImagePopup(product.imageUrl);
});


    cardTitle.appendChild(viewBtn);

    const cardPrice = document.createElement('p');
    cardPrice.className = 'card-price';
    cardPrice.textContent = `Price ₹${product.listingRate}`;

    const actionBtn = document.createElement('button');
    actionBtn.className = 'add-to-cart-btn';

    if (product.sareeStyle === 'free-images') {
      actionBtn.innerHTML = `<i class="fa-solid fa-download" style="margin-right: 8px;"></i> Download`;
      actionBtn.onclick = () => downloadProduct(product);
    } else {
      actionBtn.innerHTML = `<i class="fa-solid fa-bag-shopping" style="margin-right: 8px;"></i> Add to Cart`;
      actionBtn.onclick = () => addToCart(product, actionBtn);

      const userUID = localStorage.getItem('userUID');
      const cartRef = ref(database, 'users/' + userUID + '/cart');
      
      get(cartRef)
        .then((snapshot) => {
          let cartItems = snapshot.exists() ? snapshot.val() : {};
          if (cartItems[product.productId]) {
            actionBtn.innerHTML = `<i class="fa-solid fa-check" style="margin-right: 8px;"></i> In Cart`;
            actionBtn.onclick = () => removeFromCart(product, actionBtn);
          }
        })
        .catch((error) => {
          console.error('Error checking cart:', error);
        });

      onValue(cartRef, (snapshot) => {
        let cartItems = snapshot.exists() ? snapshot.val() : {};
        if (cartItems[product.productId]) {
          actionBtn.innerHTML = `<i class="fa-solid fa-check" style="margin-right: 8px;"></i> In Cart`;
          actionBtn.onclick = () => removeFromCart(product, actionBtn);
        } else {
          actionBtn.innerHTML = `<i class="fa-solid fa-bag-shopping" style="margin-right: 8px;"></i> Add to Cart`;
          actionBtn.onclick = () => addToCart(product, actionBtn);
        }
      });
    }

    cardBody.appendChild(cardTitle);
    cardBody.appendChild(cardPrice);
    cardBody.appendChild(actionBtn);

    cardElement.appendChild(cardImgContainer);
    cardElement.appendChild(cardBody);

    productCard.appendChild(cardElement);
    productContainer.appendChild(productCard);
  }

  for (let i = 1; i <= totalPages; i++) {
    const pageButton = document.createElement('button');
    pageButton.className = `page-btn ${i === currentPage ? 'active' : ''}`;
    pageButton.textContent = i;
    pageButton.onclick = () => {
      currentPage = i;
      displayProducts(products);
    };
    paginationContainer.appendChild(pageButton);
  }
}
// Function to add product to cart
    function addToCart(product, button) {
      const userUID = localStorage.getItem('userUID');
      
      if (!userUID) {
          // User is not logged in, redirect to signup page
          localStorage.setItem('redirectTo', window.location.href); // Save current page URL
          window.location.href = 'signup.html'; // Redirect to sign-up page
          return;
      }
    
      // User is logged in, proceed to add item to cart
      const cartRef = ref(database, 'users/' + userUID + '/cart');
      
      // Get the current cart data from Firebase
      get(cartRef)
          .then((snapshot) => {
              let cartItems = snapshot.exists() ? snapshot.val() : {}; // Existing cart or empty object
    
              // Check if the product is already in the cart by productId
              if (!cartItems[product.productId]) {
                  // If product is not in cart, add it using its productId as the key
                  cartItems[product.productId] = product;
                  set(cartRef, cartItems)
                      .then(() => {
                          button.innerHTML = `<i class="fa-solid fa-check" style="margin-right: 8px;"></i> In Cart`;
                          button.onclick = () => removeFromCart(product, button); // Change button action to remove
                          
                          // Refresh the cart immediately
                          fetchCartItems();
                      })
                      .catch((error) => {
                          console.error('Error adding product to cart:', error);
                      });
              }
          })
          .catch((error) => {
              console.error('Error checking cart:', error);
          });
    }
    
    // Function to remove product from cart
    function removeFromCart(product, button) {
      const userUID = localStorage.getItem('userUID');
      
      if (!userUID) {
        // User is not logged in, redirect to signup page
        localStorage.setItem('redirectTo', window.location.href); // Save current page URL
        window.location.href = 'signup.html'; // Redirect to sign-up page
        return;
      }
    
      // User is logged in, proceed to remove item from cart
      const cartRef = ref(database, 'users/' + userUID + '/cart');
      
      // Get the current cart data from Firebase
      get(cartRef)
        .then((snapshot) => {
          let cartItems = snapshot.exists() ? snapshot.val() : {}; // Existing cart or empty object
    
          // Remove product from cart by its productId
          if (cartItems[product.productId]) {
            delete cartItems[product.productId]; // Delete product from cartItems object
            
            // Save updated cart in Firebase
            set(cartRef, cartItems)
              .then(() => {
                button.innerHTML = `<i class="fa-solid fa-bag-shopping" style="margin-right: 8px;"></i> Add to Cart`;
                button.onclick = () => addToCart(product, button); // Allow adding item back
    
                // Refresh the cart immediately
                fetchCartItems();
              })
              .catch((error) => {
                console.error('Error removing from cart:', error);
              });
          }
        })
        .catch((error) => {
          console.error('Error fetching cart data:', error);
        });
    }
    
    // Function to fetch and display cart items
    function fetchCartItems() {
        const userId = localStorage.getItem('userUID');
    
        if (!userId) {
            console.error('User ID not found in local storage');
            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);
            }
        });
    }
   
function showImagePopup(imageUrl) {
  // Create overlay for better centering and background effect
  const overlay = document.createElement('div');
  overlay.className = 'popup-overlay';
  overlay.style.position = 'fixed';
  overlay.style.top = '0';
  overlay.style.left = '0';
  overlay.style.width = '100%';
  overlay.style.height = '100%';
  overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
  overlay.style.display = 'flex';
  overlay.style.justifyContent = 'center';
  overlay.style.alignItems = 'center';
  overlay.style.zIndex = '9999';

  // Create the popup container
  const popup = document.createElement('div');
  popup.className = 'image-popup';
  popup.style.position = 'relative';
  popup.style.display = 'flex';
  popup.style.justifyContent = 'center';
  popup.style.alignItems = 'center';
  popup.style.padding = '10px';
  popup.style.borderRadius = '10px';
  popup.style.backgroundColor = 'transparent';

  // Create the image element
  const imageElement = document.createElement('img');
  imageElement.src = imageUrl;
  imageElement.className = 'popup-image';
  imageElement.style.maxWidth = '90vw';
  imageElement.style.maxHeight = '90vh';
  imageElement.style.objectFit = 'contain';
  imageElement.style.borderRadius = '8px';
  imageElement.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';

  // Create the close button (X icon)
  const closeButton = document.createElement('div');
  closeButton.className = 'close-button';
  closeButton.style.position = 'absolute';
  closeButton.style.top = '10px';
  closeButton.style.right = '10px';
  closeButton.style.fontSize = '30px';
  closeButton.style.color = '#fff';
  closeButton.style.cursor = 'pointer';
  closeButton.textContent = '×'; // The "X" character for closing

  // Add click event to close the popup
  closeButton.addEventListener('click', () => {
    Array.from(document.body.children).forEach(child => {
      if (child !== overlay) {
        child.style.filter = '';
      }
    });
    document.body.style.overflow = '';
    document.body.removeChild(overlay);
  });

  // Ensure image is loaded before displaying
  imageElement.onload = () => {
    popup.appendChild(imageElement);
    popup.appendChild(closeButton);  // Append the close button
    overlay.appendChild(popup);
    document.body.appendChild(overlay);
    
    // Apply blur to background content
    document.body.style.overflow = 'hidden';
    Array.from(document.body.children).forEach(child => {
      if (child !== overlay) {
        child.style.filter = 'blur(2px)';
      }
    });
  };

  // Close popup on click anywhere on overlay (optional)
  overlay.addEventListener('click', () => {
    Array.from(document.body.children).forEach(child => {
      if (child !== overlay) {
        child.style.filter = '';
      }
    });
    document.body.style.overflow = '';
    document.body.removeChild(overlay);
  });

  // Auto-close after 5 seconds (optional)
  setTimeout(() => {
    if (document.body.contains(overlay)) {
      Array.from(document.body.children).forEach(child => {
        if (child !== overlay) {
          child.style.filter = '';
        }
      });
      document.body.style.overflow = '';
      document.body.removeChild(overlay);
    }
  }, 5000);
}

    // Function to delete the cart item (this will remove the item from the Firebase database)
    function deleteCartItem(productId, cartItemRow) {
        const userId = localStorage.getItem('userUID');
        if (!userId) {
            console.error('User ID not found in local storage');
            return;
        }
    
        const cartRef = ref(database, `users/${userId}/cart/${productId}`);
    
        remove(cartRef)
            .then(() => {
                // Remove the item from the DOM immediately
                cartItemRow.remove();
            })
            .catch((error) => {
                console.error('Error deleting cart item:', error);
            });
    }
    
    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) {
    console.error('User UID not found in localStorage');
    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 {
        console.error('User data not found');
        return null;
      }
    })
    .catch((error) => {
      console.error('Error fetching user details:', error);
      return null;
    });
}

  // Function to initiate Razorpay payment
  function initiateRazorpayPayment(totalAmount) {
    if (totalAmount <= 0) {
      return;
    }

    // Fetch user details
    getUserDetails().then((userDetails) => {
      if (!userDetails) {
        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(cartRef)
        .then(() => {
          console.log('Cart items removed successfully.');
          window.location.href = "confirm-payment-page.html"; // Redirect to order confirmation page
        })
        .catch((error) => {
          console.error('Error removing cart items:', error);
        });
    }
    
    
    
    // Add event listener for the checkout button
    document.getElementById('checkout-btn').addEventListener('click', function() {
      const userId = localStorage.getItem('userUID');
      if (!userId) {
        console.error('User ID not found in local storage');
        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
    
    // 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 {
      }
    });
    
    // Close the popup
    function closeUserDetailsPopup() {
      userDetailsPopupContainer.style.opacity = '0';
      setTimeout(() => {
        userDetailsPopupContainer.style.display = 'none';
      }, 300);
    }
    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();
  }
});


    </script>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></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>
    
 </script>
</body>
</html>
