<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="logo.webp" type="image/x-icon">
    <title>Hosteller</title>

    <!-- Add Bootstrap CSS -->
    
        <!-- ... existing head content ... -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
     
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- box icons  -->
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
    <!-- styles  -->
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <!-- Updated Header/Navbar -->
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm ">
            <div class="container">
                <!-- Logo -->
                <a class="navbar-brand d-flex align-items-center" href="#">
                    <span class="logo-icon bg-primary text-white rounded p-2 me-2">H</span>
                    <span class="logo-text fw-bold">osteller</span>
                </a>

                <!-- Update the Mobile Toggle Button -->
                <button class="navbar-toggler border-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">
                    <i class='bx bx-menu fs-3'></i>
                </button>

                <!-- Navbar Content -->
                <div class="collapse navbar-collapse" id="navbarContent">
                    <!-- Navigation Links -->
                    <ul class="navbar-nav mx-auto mb-2 mb-lg-0">
                        <li class="nav-item">
                            <a class="nav-link active" href="#home">
                                <i class='bx bx-home-alt'></i> Home
                            </a>
                        </li>
                        
                        <li class="nav-item">
                            <a class="nav-link" href="profile.html">
                                <i class='bx bx-user-circle'></i> Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="order.html">
                                <i class='bx bx-time'></i> Order
                            </a>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link border-0 bg-transparent" id="darkModeToggle">
                                <i class='bx bx-moon fs-4'>Mode</i>
                            </button>
                        </li>
                    </ul>

                    <!-- Auth Section (Login/Signup) -->
                    <li class="nav-item" id="authSection">
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-primary btn-sm" onclick="showAuthModal('login')">Login</button>
                            <button class="btn btn-primary btn-sm" onclick="showAuthModal('signup')">Sign Up</button>
                        </div>
                    </li>
                    
                    <!-- Profile Section (Shows after login) -->
                    <li class="nav-item dropdown">
                        <a class="nav-link d-flex align-items-center gap-2" href="#" id="navbarProfile" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <!-- Profile content will be inserted here -->
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                            <!-- Dropdown content will be inserted here -->
                        </ul>
                    </li>

                    <!-- Search and Cart -->
                    <ul class="navbar-nav ms-2">
                        <li class="nav-item">
                            <a class="nav-link position-relative" href="#" id="cartIcon">
                                <i class='bx bx-shopping-bag fs-4'>Cart</i>
                                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger cart-count">
                                    0
                                </span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <!-- Cart -->
        <div class="cart">
            <h2 class="cart-title">Your Cart</h2>
            <!-- Content -->
            <div class="cart-content">
                <!-- Cart items will be added here dynamically -->
            </div>
            <!-- Total -->
            <div class="total">
                <div class="total-title">Total</div>
                <div class="total-price">₹0</div>
            </div>
            <!-- Buy Button -->
            <a href="buynow.html" class="buy-now-button">Buy Now</a>
            <!-- Cart Close -->
            <i class='bx bx-x' id="cart-close"></i>
        </div>
    </header>

    <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <div id="cartToast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    <i class='bx bx-check-circle me-2'></i>
                    Item added to cart successfully!
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
        
        <div id="loginRequiredToast" class="toast align-items-center text-white bg-warning border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    <i class='bx bx-lock-alt me-2'></i>
                    Please login to complete your purchase
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
        
        <div id="emptyCartToast" class="toast align-items-center text-white bg-warning border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    <i class='bx bx-cart me-2'></i>
                    Please add items to your cart before proceeding
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    </div>

        <div class="img-slider">
            <div id="heroCarousel" class="carousel slide" data-bs-ride="carousel">
                <!-- Indicators/dots -->
                <div class="carousel-indicators">
                    <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="0" class="active"></button>
                    <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="1"></button>
                    <button type="button" data-bs-target="#heroCarousel" data-bs-slide-to="2"></button>
                </div>

                <!-- The slideshow/carousel -->
                <div class="carousel-inner">
                    <div class="carousel-item active">
                        <img src="slider1.jpg" class="d-block w-100" alt="Shopping Slide 1">
                        <div class="carousel-caption">
                            <h1 class="display-4 fw-bold animate__animated animate__fadeInDown">Welcome to Hosteller</h1>
                            <p class="animate__animated animate__fadeInUp"></p>
                            <a href="#product"><button class="btn btn-primary btn-lg animate__animated animate__fadeInUp">Shop Now</button></a>
                        </div>
                    </div>
                    <div class="carousel-item">
                        <img src="slider2.jpg" class="d-block w-100" alt="Shopping Slide 2">
                        <div class="carousel-caption">
                            <h1 class="display-4 fw-bold animate__animated animate__fadeInDown">New Arrivals</h1>
                            <p class="animate__animated animate__fadeInUp">Check out our latest collection</p>
                            <a href="#product"><button class="btn btn-primary btn-lg animate__animated animate__fadeInUp">View Collection</button></a>
                        </div>
                    </div>
                    <div class="carousel-item">
                        <img src="slider3.jpg" class="d-block w-100" alt="Shopping Slide 3">
                        <div class="carousel-caption">
                            <h1 class="display-4 fw-bold animate__animated animate__fadeInDown">Special Offers</h1>
                            <p class="animate__animated animate__fadeInUp">Limited time deals on selected items</p>
                            <a href="#product"><button class="btn btn-primary btn-lg animate__animated animate__fadeInUp">Shop Deals</button></a>
                        </div>
                    </div>
                </div>

                <!-- Left and right controls/icons -->
                <button class="carousel-control-prev" type="button" data-bs-target="#heroCarousel" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon"></span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#heroCarousel" data-bs-slide="next">
                    <span class="carousel-control-next-icon"></span>
                </button>
            </div>
        </div>
    <!-- SHOP SECTION  -->
    <section class="shop container py-5">
        <h2 class="section-title text-center mb-5 position-relative">
            <span class="position-relative pb-2">Shop Products</span>
        </h2>

        <!-- CONTENT  -->
        <div class="row g-4" id="product">
            <!-- BOX 1 -->
            <div class="col-sm-6 col-lg-3">
                <div class="product-box card h-100 border-0 shadow-sm product-card">
                    <div class="card-img-top position-relative overflow-hidden">
                        <img src="egg.jpg" alt="Egg" class="product-img w-100">
                        <div class="product-actions">
                            <button class="btn btn-primary add-cart-btn btn-sm" 
                                    data-product-id="1" 
                                    data-product-title="Egg" 
                                    data-product-price="10" 
                                    data-product-image="egg.jpg">
                                <i class='bx bx-shopping-bag me-1'></i>Add to Cart
                            </button>
                        </div>
                    </div>

                    <div class="card-body">
                        <h5 class="product-title card-title mb-2">Egg</h5>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="product-price fw-bold text-primary">₹10</span>
                            <div class="product-rating text-warning">
                                <i class='bx bxs-star'></i>
                                <i class='bx bxs-star'></i>
                                <i class='bx bxs-star'></i>
                                <i class='bx bxs-star'></i>
                                <i class='bx bxs-star-half'></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            
            <!-- BOX 2 -->
            

                        <!-- BOX 3 -->
                        <div class="col-sm-6 col-lg-3">
                            <div class="product-box card h-100 border-0 shadow-sm product-card">
                                <div class="card-img-top position-relative overflow-hidden">
                                    <img src="maggie.webp" alt="Maggie" class="product-img w-100">
                                    <div class="product-actions">
                                        <button class="btn btn-primary add-cart-btn btn-sm" 
                                                data-product-id="3" 
                                                data-product-title="Maggie" 
                                                data-product-price="18" 
                                                data-product-image="maggie.webp">
                                            <i class='bx bx-shopping-bag me-1'></i>Add to Cart
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <h5 class="product-title card-title mb-2">Maggie</h5>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="product-price fw-bold text-primary">₹18</span>
                                        <div class="product-rating text-warning">
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star-half'></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
            
                        <!-- BOX 4 -->
                        <div class="col-sm-6 col-lg-3">
                            <div class="product-box card h-100 border-0 shadow-sm product-card">
                                <div class="card-img-top position-relative overflow-hidden">
                                    <img src="boiled egg.jpg" alt="Boil Egg" class="product-img w-100">
                                    <div class="product-actions">
                                        <button class="btn btn-primary add-cart-btn btn-sm" 
                                                data-product-id="4" 
                                                data-product-title="Boil Egg" 
                                                data-product-price="13" 
                                                data-product-image="boiled egg.jpg">
                                            <i class='bx bx-shopping-bag me-1'></i>Add to Cart
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <h5 class="product-title card-title mb-2">Boil Egg</h5>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="product-price fw-bold text-primary">₹13</span>
                                        <div class="product-rating text-warning">
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                            <i class='bx bxs-star'></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
            
                        

           

            <!-- Repeat similar structure for other products -->
            <!-- ... -->
        </div>
    </section>
    <!-- Add this before closing body tag -->
<footer class="footer">
    
       
       
    <div class="footer-bottom">
        <p ">&copy; 2024 Hosteller. All rights reserved. <br> <span style="color: rgb(0, 0, 0);background-color: red;"> Developed by <a href="https://www.linkedin.com/in/rahul-sharma-5a19a8293/" style="color: black;">Rahul Sharma</a></span></p>
    </div>
</footer>
    <!-- Add Bootstrap JS and Popper.js before closing body tag -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="main.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', () => {
      // Get all dropdowns on the page
      const dropdowns = document.querySelectorAll('.dropdown');

      // Add click event to all dropdown triggers
      dropdowns.forEach(dropdown => {
        dropdown.addEventListener('click', (event) => {
          event.stopPropagation();
          dropdown.classList.toggle('is-active');
        });
      });

      // Close dropdowns when clicking outside
      document.addEventListener('click', (event) => {
        dropdowns.forEach(dropdown => {
          dropdown.classList.remove('is-active');
        });
      });
    });
    </script>
    <!-- Add this after your existing profile icon dropdown -->
    <div class="modal fade" id="authModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body p-4">
                    <!-- Tab Navigation -->
                    <ul class="nav nav-pills nav-justified mb-4" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" data-bs-toggle="pill" href="#login">Login</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" data-bs-toggle="pill" href="#signup">Sign Up</a>
                        </li>
                    </ul>

                    <!-- Tab Content -->
                    <div class="tab-content">
                        <!-- Login Tab -->
                        <div class="tab-pane fade show active" id="login">
                            <form id="loginForm">
                                <div class="mb-3">
                                    <input type="email" class="form-control" id="loginEmail" 
                                        placeholder="Email" required>
                                </div>
                                <div class="mb-3">
                                    <input type="password" class="form-control" id="loginPassword" 
                                        placeholder="Password" required>
                                </div>
                                <button type="submit" class="btn btn-primary w-100">Login</button>
                            </form>
                        </div>

                        <!-- Sign Up Tab -->
                        <div class="tab-pane fade" id="signup">
                            <form id="signupForm">
                                <div class="mb-3">
                                    <input type="text" class="form-control" id="signupName" 
                                        placeholder="Full Name" required>
                                </div>
                                <div class="mb-3">
                                    <input type="tel" class="form-control" id="signupPhone" 
                                        placeholder="Phone Number" required 
                                        pattern="[0-9]{10}" 
                                        title="Please enter a valid 10-digit phone number">
                                </div>
                                <div class="mb-3">
                                    <input type="email" class="form-control" id="signupEmail" 
                                        placeholder="Email" required>
                                </div>
                                <div class="mb-3">
                                    <input type="password" class="form-control" id="signupPassword" 
                                        placeholder="Password" required minlength="6">
                                </div>
                                <button type="submit" class="btn btn-primary w-100">Sign Up</button>
                            </form>
                        </div>
                    </div>

                    <!-- Social Login -->
                    <div class="text-center mt-4">
                        <p class="text-muted">Or continue with</p>
                        <button id="googleSignIn" class="btn btn-outline-secondary">
                            <i class='bx bxl-google'></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const auth = firebase.auth();
        
        // Get elements
        const navbarProfile = document.getElementById('navbarProfile');
        const dropdownMenu = document.querySelector('.dropdown-menu');
        const authSection = document.getElementById('authSection');
        
        // Auth state observer
        auth.onAuthStateChanged((user) => {
            console.log('Auth state changed:', user);
            
            if (user) {
                // User is logged in
                if (navbarProfile && dropdownMenu) {
                    // Show profile section
                    navbarProfile.style.display = 'flex';
                    // Hide auth section
                    if (authSection) authSection.style.display = 'none';
                    
                    // Update profile content
                    navbarProfile.innerHTML = `
                        <div class="d-flex align-items-center">
                            <div class="profile-image-container me-2">
                                ${user.photoURL ? 
                                    `<img src="${user.photoURL}" alt="Profile" class="profile-image rounded-circle">` :
                                    `<div class="profile-initial rounded-circle">${(user.displayName || user.email || '?')[0].toUpperCase()}</div>`
                                }
                            </div>
                            <span class="profile-name d-none d-md-block">${user.displayName || 'User'}</span>
                        </div>
                    `;
                    
                    // Enable dropdown
                    navbarProfile.setAttribute('data-bs-toggle', 'dropdown');
                    
                    // Update dropdown content
                    dropdownMenu.innerHTML = `
                        <div class="px-4 py-3">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    ${user.photoURL ? 
                                        `<img src="${user.photoURL}" class="rounded-circle" width="45" height="45" alt="Profile">` :
                                        `<div class="profile-initial-large rounded-circle">${(user.displayName || user.email || '?')[0].toUpperCase()}</div>`
                                    }
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h6 class="mb-0 fw-semibold">${user.displayName || 'User'}</h6>
                                    <small class="text-muted">${user.email}</small>
                                </div>
                            </div>
                        </div>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="profile.html">
                            <i class='bx bx-user-circle me-2'></i>View Profile
                        </a>
                        <a class="dropdown-item" href="#">
                            <i class='bx bx-cog me-2'></i>Settings
                        </a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item text-danger" href="#" onclick="handleSignOut(event)">
                            <i class='bx bx-log-out me-2'></i>Logout
                        </a>
                    `;
                }
            } else {
                // User is logged out
                if (navbarProfile) {
                    navbarProfile.style.display = 'none';
                }
                // Show auth section
                if (authSection) {
                    authSection.style.display = 'flex';
                }
            }
        });
    });
    </script>
    <!-- Make sure you have these scripts in the correct order -->
    <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.1.3/dist/js/bootstrap.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-auth-compat.js"></script>
    <!-- Initialize Firebase -->
    <script>
        const firebaseConfig = {
            // Your firebase config here
            apiKey: "AIzaSyB4BNpLQK0RHUmklOMh2HiNMzwFP5uDE5s",
  authDomain: "hosteller-efdb5.firebaseapp.com",
  databaseURL: "https://hosteller-efdb5-default-rtdb.firebaseio.com",
  projectId: "hosteller-efdb5",
  storageBucket: "hosteller-efdb5.firebasestorage.app",
  messagingSenderId: "250843951769",
  appId: "1:250843951769:web:01f0d52d2b1724816cbe08"
        };
        
        // Initialize Firebase
        if (!firebase.apps.length) {
            firebase.initializeApp(firebaseConfig);
        }
    </script>
    <!-- Initialize Firebase Auth -->
    <script>
        const auth = firebase.auth();

        // Login Form Submit Handler
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Get form values
            const email = document.getElementById('loginEmail').value;
            const password = document.getElementById('loginPassword').value;
            
            // Show loading state
            const loginButton = this.querySelector('button[type="submit"]');
            loginButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Loading...';
            loginButton.disabled = true;

            // Sign in with Firebase
            auth.signInWithEmailAndPassword(email, password)
                .then((userCredential) => {
                    const user = userCredential.user;
                    console.log('Login successful:', user);
                    
                    // Close modal
                    const authModal = bootstrap.Modal.getInstance(document.getElementById('authModal'));
                    authModal.hide();
                    
                    // Show success message
                    alert('Login successful!');
                })
                .catch((error) => {
                    console.error('Login error:', error);
                    alert(error.message);
                })
                .finally(() => {
                    // Reset button state
                    loginButton.innerHTML = 'Login';
                    loginButton.disabled = false;
                });
        });

        // Signup Form Submit Handler
        document.getElementById('signupForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Get form values
            const name = document.getElementById('signupName').value;
            const email = document.getElementById('signupEmail').value;
            const password = document.getElementById('signupPassword').value;
            
            // Show loading state
            const signupButton = this.querySelector('button[type="submit"]');
            signupButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Loading...';
            signupButton.disabled = true;

            // Create user with Firebase
            auth.createUserWithEmailAndPassword(email, password)
                .then((userCredential) => {
                    const user = userCredential.user;
                    
                    // Update profile with name
                    return user.updateProfile({
                        displayName: name
                    });
                })
                .then(() => {
                    console.log('Signup successful');
                    
                    // Close modal
                    const authModal = bootstrap.Modal.getInstance(document.getElementById('authModal'));
                    authModal.hide();
                    
                    // Show success message
                    alert('Account created successfully!');
                })
                .catch((error) => {
                    console.error('Signup error:', error);
                    alert(error.message);
                })
                .finally(() => {
                    // Reset button state
                    signupButton.innerHTML = 'Sign Up';
                    signupButton.disabled = false;
                });
        });

        // Google Sign In
        document.getElementById('googleSignIn').addEventListener('click', function() {
            const provider = new firebase.auth.GoogleAuthProvider();
            
            auth.signInWithPopup(provider)
                .then((result) => {
                    console.log('Google sign in successful');
                    
                    // Close modal
                    const authModal = bootstrap.Modal.getInstance(document.getElementById('authModal'));
                    authModal.hide();
                })
                .catch((error) => {
                    console.error('Google sign in error:', error);
                    alert(error.message);
                });
        });

        // Auth state observer
        auth.onAuthStateChanged((user) => {
            if (user) {
                // User is signed in
                console.log('User is signed in:', user);
                updateUIForUser(user);
            } else {
                // User is signed out
                console.log('User is signed out');
                updateUIForSignedOut();
            }
        });

        // Update your auth modal HTML to include these IDs:
    </script>
    <!-- Show auth modal -->
    <script>
    function showAuthModal(tab = 'login') {
        const authModal = new bootstrap.Modal(document.getElementById('authModal'));
        authModal.show();
        
        if (tab === 'signup') {
            // Switch to signup tab if requested
            const signupTab = document.querySelector('[href="#signup"]');
            if (signupTab) {
                signupTab.click();
            }
        }
    }

    // Handle sign out
    function handleSignOut(event) {
        event.preventDefault();
        
        firebase.auth().signOut().then(() => {
            console.log('Signed out successfully');
            
            // Hide dropdown if open
            const navbarProfile = document.getElementById('navbarProfile');
            const bsDropdown = bootstrap.Dropdown.getInstance(navbarProfile);
            if (bsDropdown) {
                bsDropdown.hide();
            }
            
            // Show auth modal
            showAuthModal('login');
        }).catch((error) => {
            console.error('Sign out error:', error);
            alert('Error signing out: ' + error.message);
        });
    }
    </script>
    <!-- Add this to your existing JavaScript -->
    <script>
    function showProfileDetails() {
        const user = firebase.auth().currentUser;
        if (!user) return;

        // Get profile details from Firestore if you're using it
        // For now, we'll just use the auth user data
        document.getElementById('profileName').value = user.displayName || '';
        document.getElementById('profileEmail').value = user.email || '';
        
        // Update profile image preview
        const profileImagePreview = document.getElementById('profileImagePreview');
        if (user.photoURL) {
            profileImagePreview.innerHTML = `<img src="${user.photoURL}" class="rounded-circle" width="100" height="100" alt="Profile">`;
        } else {
            profileImagePreview.innerHTML = `
                <div class="profile-initial-xl rounded-circle">
                    ${(user.displayName || user.email || '?')[0].toUpperCase()}
                </div>
            `;
        }

        // Show modal
        const profileModal = new bootstrap.Modal(document.getElementById('profileDetailsModal'));
        profileModal.show();
    }

    // Handle profile image upload
    document.getElementById('profileImageInput').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const profileImagePreview = document.getElementById('profileImagePreview');
                profileImagePreview.innerHTML = `<img src="${e.target.result}" class="rounded-circle" width="100" height="100" alt="Profile">`;
            }
            reader.readAsDataURL(file);
        }
    });

    // Handle profile update form submission
    document.getElementById('profileUpdateForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const user = firebase.auth().currentUser;
        if (!user) return;

        const name = document.getElementById('profileName').value;
        const phone = document.getElementById('profilePhone').value;
        const bio = document.getElementById('profileBio').value;

        try {
            // Update display name
            await user.updateProfile({
                displayName: name
            });

            // If you're using Firestore, you can save additional details there
            // For example:
            // await firebase.firestore().collection('users').doc(user.uid).set({
            //     name: name,
            //     phone: phone,
            //     bio: bio
            // }, { merge: true });

            // Close modal
            const profileModal = bootstrap.Modal.getInstance(document.getElementById('profileDetailsModal'));
            profileModal.hide();

            // Show success message
            alert('Profile updated successfully!');
            
            // Refresh UI
            updateUIForUser(user);
        } catch (error) {
            console.error('Error updating profile:', error);
            alert('Error updating profile: ' + error.message);
        }
    });

    // Update the dropdown menu to include the profile details link
    function updateUIForUser(user) {
        const dropdownMenu = document.querySelector('.dropdown-menu');
        if (dropdownMenu) {
            dropdownMenu.innerHTML = `
                <div class="px-4 py-3">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            ${user.photoURL ? 
                                `<img src="${user.photoURL}" class="rounded-circle" width="45" height="45" alt="Profile">` :
                                `<div class="profile-initial-large rounded-circle">${(user.displayName || user.email || '?')[0].toUpperCase()}</div>`
                            }
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-0 fw-semibold">${user.displayName || 'User'}</h6>
                            <small class="text-muted">${user.email}</small>
                        </div>
                    </div>
                </div>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="profile.html">
                    <i class='bx bx-user-circle me-2'></i>View Profile
                </a>
                <a class="dropdown-item" href="#">
                    <i class='bx bx-cog me-2'></i>Settings
                </a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item text-danger" href="#" onclick="handleSignOut(event)">
                    <i class='bx bx-log-out me-2'></i>Logout
                </a>
            `;
        }
    }
    </script>
    <!-- Profile Details Modal -->
    <div class="modal fade" id="profileDetailsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Profile Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="profileUpdateForm">
                        <div class="text-center mb-4">
                            <div class="position-relative d-inline-block">
                                <div id="profileImagePreview" class="profile-image-large rounded-circle">
                                    <!-- Profile image will be inserted here -->
                                </div>
                                <label for="profileImageInput" class="position-absolute bottom-0 end-0 bg-primary text-white rounded-circle p-2 cursor-pointer">
                                    <i class='bx bx-camera'></i>
                                    <input type="file" id="profileImageInput" class="d-none" accept="image/*">
                                </label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="profileName" placeholder="Enter your name">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" id="profileEmail" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone Number</label>
                            <input type="tel" class="form-control" id="profilePhone" placeholder="Enter your phone number">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Bio</label>
                            <textarea class="form-control" id="profileBio" rows="3" placeholder="Tell us about yourself"></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">Save Changes</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Cart functionality
        const cartIcon = document.querySelector("#cartIcon");
        const cart = document.querySelector(".cart");
        const closeCart = document.querySelector("#cart-close");
        const cartContent = document.querySelector(".cart-content");
        const totalPrice = document.querySelector(".total-price");
        const cartCount = document.querySelector(".cart-count");

        // Open Cart
        cartIcon.addEventListener("click", () => {
            cart.classList.add("active");
        });

        // Close Cart
        closeCart.addEventListener("click", () => {
            cart.classList.remove("active");
        });

        // Add to Cart
        document.querySelectorAll('.add-cart-btn').forEach(button => {
            button.addEventListener('click', function() {
                const productId = this.dataset.productId;
                const productTitle = this.dataset.productTitle;
                const productPrice = this.dataset.productPrice;
                const productImage = this.dataset.productImage;

                addProductToCart(productId, productTitle, productPrice, productImage);
                updateCartCount();
                
                // Show success toast
                const cartToast = new bootstrap.Toast(document.getElementById('cartToast'));
                cartToast.show();
            });
        });

        function addProductToCart(id, title, price, image) {
            // Check if product already exists in cart
            const cartItems = cartContent.getElementsByClassName('cart-box');
            for(let item of cartItems) {
                if(item.dataset.productId === id) {
                    alert('This item is already in cart!');
                    return;
                }
            }

            // Create cart item
            const cartBoxContent = `
                <div class="cart-box" data-product-id="${id}">
                    <img src="${image}" alt="${title}" class="cart-img">
                    <div class="detail-box">
                        <div class="cart-product-title">${title}</div>
                        <div class="cart-price">${price}</div>
                        <input type="number" value="1" class="cart-quantity" min="1">
                    </div>
                    <i class='bx bxs-trash-alt cart-remove'></i>
                </div>
            `;

            cartContent.insertAdjacentHTML('beforeend', cartBoxContent);

            // Add event listeners to new cart item
            const newItem = cartContent.lastElementChild;
            newItem.querySelector('.cart-remove').addEventListener('click', removeCartItem);
            newItem.querySelector('.cart-quantity').addEventListener('change', quantityChanged);

            updateTotal();
            updateCartCount();
        }

        // Remove Cart Item
        function removeCartItem(event) {
            const buttonClicked = event.target;
            buttonClicked.closest('.cart-box').remove();
            updateTotal();
            updateCartCount();
        }

        // Quantity Changes
        function quantityChanged(event) {
            const input = event.target;
            if (isNaN(input.value) || input.value <= 0) {
                input.value = 1;
            }
            updateTotal();
        }

        // Update Total
        function updateTotal() {
            let total = 0;
            const cartBoxes = document.getElementsByClassName('cart-box');
            
            for(let cartBox of cartBoxes) {
                const priceElement = cartBox.querySelector('.cart-price');
                const quantityElement = cartBox.querySelector('.cart-quantity');
                const price = parseFloat(priceElement.innerText.replace('₹', ''));
                const quantity = quantityElement.value;
                total += price * quantity;
            }

            // Round to 2 decimal places
            total = Math.round(total * 100) / 100;
            totalPrice.innerText = '₹' + total;
        }

        // Update Cart Count
        function updateCartCount() {
            const itemCount = cartContent.getElementsByClassName('cart-box').length;
            cartCount.textContent = itemCount;
        }

        // Buy Now button
        const buyButton = document.querySelector('.btn-buy');
        if(buyButton) {
            buyButton.addEventListener('click', () => {
                if(cartContent.getElementsByClassName('cart-box').length > 0) {
                    alert('Your order has been placed!');
                    // Clear cart
                    while(cartContent.firstChild) {
                        cartContent.removeChild(cartContent.firstChild);
                    }
                    updateTotal();
                    updateCartCount();
                    cart.classList.remove("active");
                } else {
                    alert('Please add items to cart first!');
                }
            });
        }

        // Close cart when clicking outside
        document.addEventListener('click', (e) => {
            if (!cart.contains(e.target) && !cartIcon.contains(e.target)) {
                cart.classList.remove("active");
            }
        });
    });
    </script>
    <!-- Add this to your cart-related JavaScript -->
    <script>
    function saveCartItems() {
        const cartItems = Array.from(document.getElementsByClassName('cart-box')).map(box => {
            return {
                id: box.dataset.productId,
                title: box.querySelector('.cart-product-title').textContent,
                price: parseFloat(box.querySelector('.cart-price').textContent.replace('₹', '')),
                quantity: parseInt(box.querySelector('.cart-quantity').value),
                image: box.querySelector('.cart-img').src
            };
        });
        
        localStorage.setItem('cartItems', JSON.stringify(cartItems));
    }

    // Modify your existing buy now button click handler
    document.querySelector('.buy-now-button').addEventListener('click', function(e) {
        // Get the total price
        const totalPrice = parseFloat(document.querySelector('.total-price').textContent.replace('₹', ''));
        
        // Check if cart is empty (total is 0)
        if (totalPrice === 0) {
            e.preventDefault(); // Prevent navigation
            
            // Show empty cart toast
            const emptyCartToast = new bootstrap.Toast(document.getElementById('emptyCartToast'));
            emptyCartToast.show();
            return;
        }

        // Check if user is logged in
        const user = firebase.auth().currentUser;
        
        if (!user) {
            e.preventDefault();
            const loginToast = new bootstrap.Toast(document.getElementById('loginRequiredToast'));
            loginToast.show();
            
            setTimeout(() => {
                showAuthModal('login');
            }, 1000);
            return;
        }
        
        // If cart is not empty and user is logged in, proceed with purchase
        saveCartItems();
        window.location.href = 'buynow.html';
    });
    </script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Get navbar elements
        const navbarToggler = document.querySelector('.navbar-toggler');
        const navbarCollapse = document.querySelector('#navbarContent');
        
        // Initialize Bootstrap collapse
        const bsCollapse = new bootstrap.Collapse(navbarCollapse, {
            toggle: false
        });

        // Toggle icon on navbar state change
        navbarCollapse.addEventListener('show.bs.collapse', function () {
            navbarToggler.innerHTML = '<i class="bx bx-x fs-3"></i>';
        });

        navbarCollapse.addEventListener('hide.bs.collapse', function () {
            navbarToggler.innerHTML = '<i class="bx bx-menu fs-3"></i>';
        });

        // Close navbar when clicking outside
        document.addEventListener('click', function(event) {
            const isClickInside = navbarCollapse.contains(event.target) || 
                                navbarToggler.contains(event.target);
            
            if (!isClickInside && navbarCollapse.classList.contains('show')) {
                bsCollapse.hide();
            }
        });

        // Close navbar when clicking on nav links
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', () => {
                if (navbarCollapse.classList.contains('show')) {
                    bsCollapse.hide();
                }
            });
        });
    });
    </script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const darkModeToggle = document.getElementById('darkModeToggle');
        const icon = darkModeToggle.querySelector('i');
        
        // Check for saved theme preference or system preference
        const savedTheme = localStorage.getItem('theme');
        const systemDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
        
        // Set initial theme
        if (savedTheme) {
            document.documentElement.setAttribute('data-theme', savedTheme);
            updateIcon(savedTheme === 'dark');
        } else if (systemDarkMode) {
            document.documentElement.setAttribute('data-theme', 'dark');
            updateIcon(true);
        }
        
        // Toggle theme on button click
        darkModeToggle.addEventListener('click', () => {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateIcon(newTheme === 'dark');
        });
        
        // Update icon based on theme
        function updateIcon(isDark) {
            icon.className = isDark ? 'bx bx-sun fs-4' : 'bx bx-moon fs-4';
        }
        
        // Listen for system theme changes
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
            if (!localStorage.getItem('theme')) {
                const newTheme = e.matches ? 'dark' : 'light';
                document.documentElement.setAttribute('data-theme', newTheme);
                updateIcon(e.matches);
            }
        });
    });
    </script>
</body>

</html>
