<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Bidding Platform</title>
    <link href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" rel="stylesheet">
    <script async="async" src="https://cdn.jsdelivr.net/npm/glightbox/dist/js/glightbox.min.js"></script>
    <style>
         /* Universal Box-Sizing */
            *,
            *::before,
            *::after {
              box-sizing: border-box;
            }

            /* Base body styling */
            body {
              font-family: Arial, sans-serif, "Helvetica Neue", Helvetica;
              margin: 0;
              padding: 0;
            }

            /* Global styles for text, buttons, and inputs */
            label {
              font-weight: bold;
              margin-bottom: 5px;
            }

            input, button, select, textarea {
              font-family: inherit;
              font-size: inherit;
              border: none;
              outline: none;
            }

            /* Bid item container */
            .bid-item {
              border: 2px solid #ddd;
              padding: 20px;
              margin-bottom: 20px;
              border-radius: 8px;
              box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }

            /* Timer styling */
            .timer {
              font-size: 18px;
              font-weight: bold;
              color: #1c1b1b;
            }

            /* Admin area styling */
            .admin-area {
              margin: 20px 0;
              border: 2px solid #007bff;
              padding: 15px;
              border-radius: 8px;
              display: none;
            }

            .admin-button {
              background-color: #007bff;
              color: white;
              padding: 10px 15px;
              border-radius: 5px;
              cursor: pointer;
              transition: background-color 0.3s ease;
            }

            .admin-button:hover {
              background-color: #0056b3;
            }

            /* Bid controls */
            .bid-controls {
              margin-top: 15px;
            }

            button {
              margin-right: 10px;
            }

      /* Delete Button - Red */
      .delete-button {
        background-color: #dc3545;
        color: white;
      }
      .delete-button:hover {
        background-color: #c82333;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
      }

      .edit-button {
        background-color: transparent;
        color: #28a745;
        border: 2px solid #007bff; /* Blue outline */
        padding: 10px 15px;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;
      }

      .edit-button:hover {
        background-color: #e2f4ff;
      }

            /* Form input styles */
            .bid-input {
              padding: 8px;
              width: 100%;
              margin-top: 10px;
              margin-bottom: 15px;
              box-sizing: border-box;
            }

            /* New bid form container */
            #new-bid-form {
              display: none;
              margin-top: 20px;
              padding: 20px;
              border: 1px solid #007bff;
              border-radius: 8px;
              background-color: #f9f9f9;
              box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }

            .form-group {
              display: flex;
              flex-direction: column;
              margin-bottom: 15px;
            }

            /* Admin input styles */
            .admin-input {
              padding: 12px;
              border: 1px solid #ccc;
              border-radius: 5px;
              width: 100%;
              box-sizing: border-box;
              transition: border-color 0.3s;
            }

            .admin-input:focus {
              border-color: #007bff;
            }

            /* Responsive bid container */
            .bid-container {
              border: 1px solid #ccc;
              border-radius: 8px;
              margin: 10px 0;
              padding: 10px;
              box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }

            .bid-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              cursor: pointer;
            }

            .bid-details {
              display: none;
              padding-top: 10px;
            }

            /* Flexbox for bid gallery */
            .bid-gallery {
              flex: 1;
              display: flex;
              flex-wrap: wrap;
              gap: 10px;
              justify-content: center;
            }

            .bid-gallery img {
              max-width: 100px;
              max-height: 100px;
              object-fit: cover;
              border: 1px solid #ccc;
              border-radius: 5px;
            }

            /* Bid history styles */
            .bid-history {
              max-height: 150px;
              overflow-y: auto;
              padding: 5px;
              border: 1px solid #ccc;
              border-radius: 5px;
            }

            /* History list styling */
            ul[id^="history-list-"] {
              max-height: 50px;
              overflow-y: auto;
              list-style-type: none;
              padding: 0;
              margin: 0;
            }

            ul[id^="history-list-"] li {
              word-wrap: break-word;
              padding: 5px 0;
              border-bottom: 1px solid #ddd;
            }

            ul[id^="history-list-"] li:last-child {
              border-bottom: none;
            }

            /* Red color class */
            .red {
              color: red;
            }

            /* Responsive Media Queries */
          #archived-bids {
            margin-top: 15px;
            border: 1px solid #ccc;
            padding: 15px;
            border-radius: 8px;
            background-color: #f9f9f9;
          }
          /* Responsive Styling */
          @media (max-width: 768px) {
            #archived-bids {
              margin: 10px 0;
              width: 100%;
            }
          }
          @media (max-width: 480px) {
            #archived-bids {
              padding: 10px;
              margin-top: 10px;
            }
          }
      .user-info {
          display: flex;
          align-items: center;
          gap: 10px; /* Adds space between elements */
      }



      /* Google Sign In - Blue */
      .auth-button {
        background-color: #007bff;
        color: white;
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: bold;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      }

      .auth-button:hover {
        background-color: #0056b3;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
      }

      .bid-header {
          display: flex;
          align-items: center;
          transition: all 0.3s ease;
      }

      .bid-header .header-image.enlarged {
          width: 200px; /* Enlarged size */
          height: 200px;
          margin-right: 15px;
          border-radius: 5px;
          object-fit: cover;
          transition: all 0.3s ease;
      }

      .bid-details {
          display: none; /* Initially hidden */
      }

      /* Hide the image when bid-details are displayed */
      .bid-header.toggle-active .header-image {
          display: none;
      }

              .bid-gallery img {
                max-width: 80px;
                max-height: 80px;
              }

       .review-section {
          margin: 20px auto;
          padding: 15px;
          border: 1px solid #ddd;
          border-radius: 8px;
          background-color: #f9f9f9;
          max-width: 600px;
          text-align: center;
      }

      .review-button {
          background-color: #f39c12;
          color: white;
          padding: 10px 20px;
          border-radius: 5px;
          border: none;
          cursor: pointer;
          margin-top: 10px;
          font-size: 16px;
      }

      .review-button:hover {
          background-color: #e67e22;
      }

      .star-rating {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 10px;
      }

      .star-rating span {
          font-size: 30px;
          cursor: pointer;
          color: #ddd;
          transition: color 0.3s ease;
      }

      .star-rating span.active {
          color: #f39c12;
      }

      .star-rating span:hover,
      .star-rating span:hover ~ span {
          color: #f39c12;
      }

      .reviews-panel {
          border: 1px solid #ddd;
          border-radius: 8px;
          margin: 10px 0;
          overflow: hidden;
      }

      .reviews-header {
          background: #f8f9fa;
          padding: 15px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
      }

      .reviews-content {
          max-height: 0;
          overflow: hidden;
          transition: max-height 0.3s ease-out;
          padding: 0 15px;
      }

      .reviews-content.expanded {
          max-height: 1000px;
          transition: max-height 0.5s ease-in;
      }

      .toggle-icon::after {
          content: '\25BC';
          display: inline-block;
          margin-left: 10px;
          transition: transform 0.3s;
      }

      .toggle-icon.expanded::after {
          transform: rotate(180deg);
      }



              /* Style for modal */
              .modal {
                  display: none;
                  position: fixed;
                  z-index: 1;
                  left: 0;
                  top: 0;
                  width: 100%;
                  height: 100%;
                  background-color: rgba(0,0,0,0.5);
              }
              .modal-content {
                  background-color: white;
                  margin: 15% auto;
                  padding: 20px;
                  width: 300px;
                  text-align: center;
                  border-radius: 8px;
              }
              .close {
                  float: right;
                  cursor: pointer;
              }
    </style>
  </head>
  <body>
    <h1>Bidding Platform</h1>
    <!-- User Authentication -->
    <div class="user-info">
      <button class="auth-button" id="google-sign-in">
        Sign In with Google
      </button>
      <p id="user-name"></p>
    </div>

    <!-- Archived Bids Section -->
    <div id="archived-bids" style="display: none;">
      <h4>Archived Bids</h4>
      <p>No archived bids to display yet.</p>
    </div>

    <!-- Register Button -->

    <!-- Modal -->
    <div class="modal" id="registerModal">
      <div class="modal-content">
        <span class="close" onclick="closeModal()">×</span>
        <h2>Registration</h2>
        <input id="emailInput" placeholder="Enter bidder's email" required="" type="email" />
        <br /><br />
        <button onclick="registerEmail()">Submit</button>
      </div>
    </div>

    <!-- Admin Area -->
    <div class="admin-area">
      <h2>Admin Area</h2>
      <div class="button-container">
        <button class="admin-button" id="create-bid">Create New Bid</button>
        <button class="admin-button" onclick="openModal()">Register Bidder</button>
      </div>
      <div id="new-bid-form" style="display: none;">
        <h3>Create New Bid Item</h3>
        <form id="bid-form">
          <div class="form-group">
            <label for="new-bid-title"> Title </label>
            <input class="admin-input" id="new-bid-title" type="text" />
          </div>
          <div class="form-group">
            <label for="new-bid-description"> Description </label>
            <textarea class="admin-input" id="new-bid-description"></textarea>
          </div>
          <div class="form-group">
            <label for="new-bid-starting-price"> Opening Bid </label>
            <input class="admin-input" id="new-bid-starting-price" type="number" />
          </div>
          <div class="form-group">
            <label for="new-bid-timer"> Duration (in hours) </label>
            <input class="admin-input" id="new-bid-timer" type="number" />
          </div>
          <div class="form-group">
            <label for="new-bid-images"> Upload Images </label>
            <input class="admin-input" id="new-bid-images" multiple="" type="file" />
          </div>
          <button class="admin-button" id="submit-new-bid">
            Submit New Bid
          </button>
        </form>
        <button class="admin-button" id="close-new-bid" style="background-color: red; margin-top: 10px;">
          Close
        </button>
      </div>
    </div>
    <!-- Upload Progress Bar -->
    <div id="upload-progress" style="background-color: #f3f3f3; display: none; margin-top: 10px; width: 100%;">
      <div id="upload-progress-bar" style="background: linear-gradient(90deg, #4caf50, #00bcd4, #ff9800, #e91e63); border-radius: 5px; color: white; height: 20px; text-align: center; width: 0%;"></div>
    </div>
    <!-- Progress Text for File Upload -->
    <p id="upload-progress-text" style="display: none;"></p>
    <!-- Bid Items for Regular Users -->
    <div id="bid-items"></div>
    <div id="bid-container"></div>
    <div class="review-section" id="global-review-section">
      <h2>Customer Reviews</h2>
      <div id="global-reviews">
        <p>No reviews yet. Be the first to review!</p>
      </div>
      <button class="review-button" onclick="promptGlobalReview()">
        Write a Review
      </button>
    </div>

    <script type="module">
          // Firebase script
          import { initializeApp } from "https://www.gstatic.com/firebasejs/11.0.2/firebase-app.js";
          import {
              getFirestore,
              collection,
              getDocs,
              doc,
              getDoc,
              updateDoc,
              addDoc,
              deleteDoc,
            query, where, onSnapshot,
          } from "https://www.gstatic.com/firebasejs/11.0.2/firebase-firestore.js";
          import {
              getAuth,
              GoogleAuthProvider,
              signInWithPopup,
              signOut,
              onAuthStateChanged,
          } from "https://www.gstatic.com/firebasejs/11.0.2/firebase-auth.js";
          import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "https://www.gstatic.com/firebasejs/11.0.2/firebase-storage.js";

          // Firebase configuration
          const firebaseConfig = {
              apiKey: "AIzaSyBJ2BpYbr0_79aL5ZqFN-bjcG5VvxG_ees",
              authDomain: "bidding-8cc5c.firebaseapp.com",
              projectId: "bidding-8cc5c",
              storageBucket: "bidding-8cc5c.firebasestorage.app",
              messagingSenderId: "575864398723",
              appId: "1:575864398723:web:edebce67abc6abcbd74cb6",
              measurementId: "G-E1TV00RS1P"
          };

          const app = initializeApp(firebaseConfig);
          const db = getFirestore(app);
          const auth = getAuth(app);
          const provider = new GoogleAuthProvider();
          const storage = getStorage(app, "gs://bidding-8cc5c.firebasestorage.app");

        let globalReviews = []; // Array to store global reviews

          let currentUser = null;
      let isAdmin = false;

      // List of admin emails
      const adminEmails = ["noahkalirani@gmail.com", "anotheradmin@example.com", "admin2@example.com"];
      const timerIntervals = {};

      // Function to check if user exists in Firestore "users" collection
      const listenToUserInFirestore = (email) => {
          const usersRef = collection(db, "users");
          const q = query(usersRef, where("email", "==", email));

          // Real-time listener for Firestore
          return onSnapshot(q, (querySnapshot) => {
              if (querySnapshot.empty) {
                  // console.log("Email not found in Firestore."); -->
                  alert("Please register first. To access Bid & Win ");
                  signOut(auth);
              } else {
                  querySnapshot.forEach((doc) => {
                      const userData = doc.data();
                      // console.log("User exists in Firestore:", userData); -->
                    fetchBids()
                  });
              }
          }, (error) => {
             // console.error("Error with snapshot listener:", error); -->
          });
      };

      // Authentication state change listener
      onAuthStateChanged(auth, async (user) => {
          const userNameElement = document.getElementById("user-name");
          const googleSignInElement = document.getElementById("google-sign-in");
          const adminArea = document.querySelector(".admin-area");

          if (user) {
            currentUser = user;
              userNameElement.textContent = `Signed in as ${user.displayName}`;
              googleSignInElement.textContent = "Sign Out";
              googleSignInElement.onclick = () => {
                signOut(auth);
                clearBidsFromUI();
              };

              // Check if the user is an admin
               isAdmin = adminEmails.includes(user.email);
              adminArea.style.display = isAdmin ? "block" : "none";

              // Now, check if the user exists in Firestore "users" collection
              listenToUserInFirestore(user.email);
          } else {
            currentUser = null;
            isAdmin = false;
            adminArea.style.display = "none";

              userNameElement.textContent = "Click me, Register to Participate";
              userNameElement.style.cursor = "pointer"; // Make it look clickable
              userNameElement.style.color = "blue"; // Optional: Change color to indicate action

              // Add click event to show an alert when clicked
              userNameElement.onclick = () => {
                  alert("Pay K1,000 on the 1st day of every month. The subscription resets on the 28th day of each month. Send the payment to 0992116674 via Airtel Money and forward the transaction reference on WhatsApp to the same number.");
              };

              googleSignInElement.textContent = "Sign In with Google";
              googleSignInElement.onclick = () => signInWithPopup(auth, provider);
            clearBidsFromUI();
          }
      });

        function clearBidsFromUI() {
          const bidContainer = document.getElementById("bid-items"); // Ensure correct ID
          if (bidContainer) {
              bidContainer.innerHTML = ""; // Clears all bids
          }
      }

        // Hide admin area and clear bids for signed-out users
              document.querySelector(".admin-area").style.display = "none";
              document.getElementById("bid-items").innerHTML = "";


          // Format number with commas and MK symbol
          function formatCurrency(amount) {
              return `MK ${new Intl.NumberFormat('en-MW').format(amount)}`;
          }

          // Fetch Bids
          async function fetchBids() {
              const bidsSnapshot = await getDocs(collection(db, "bids"));
              const bidItemsContainer = document.getElementById("bid-items");
              if (!bidItemsContainer) return;
              bidItemsContainer.innerHTML = "";

              bidsSnapshot.forEach((doc) => {
                  const bidData = doc.data();
                  const bidElement = document.createElement("div");
                  bidElement.classList.add("bid-item");

                  const endTime = bidData.endTime?.toDate ? bidData.endTime.toDate() : new Date(bidData.endTime);
                  const bidId = doc.id;

                  bidElement.innerHTML = `
      <div class="bid-container">
          <div class="bid-header" onclick="toggleBidDetails(this)">
              <div>
                  ${Array.isArray(bidData.imageUrls) && bidData.imageUrls.length > 0
                    ? `<img src="${bidData.imageUrls[0]}" alt="${bidData.title}" class="header-image enlarged" />`
                    : '<img src="placeholder.jpg" alt="No Image Available" class="header-image enlarged" />'}
                  <h2>${bidData.title}</h2>
                  <h2>Starting Bid: ${formatCurrency(bidData.startingPrice)}</h2>
                  <div id="timer-${bidId}" class="timer"></div>
              </div>
          </div>
          <div class="bid-details" style="display: none;">
          	<p>${bidData.description}</p>

              <p class="current-bid">Highest Bid: ${bidData.highestBid ? formatCurrency(bidData.highestBid) : "None Yet"}</p>
              ${isAdmin
                ? `<p>Highest Bidder: ${bidData.highestBidder || "None Yet"} (${bidData.highestBidderEmail})</p>`
                : `<p>Highest Bidder: ${bidData.highestBidder || "None Yet"}</p>`}
              <div class="bid-gallery">
                  ${Array.isArray(bidData.imageUrls) && bidData.imageUrls.length > 0
                    ? bidData.imageUrls.map((url) => `
                      <a href="${url}" class="glightbox" data-gallery="bid-${bidId}" data-title="${bidData.title}">
                          <img src="${url}" alt="Bid Image" />
                      </a>`).join("")
                    : '<p>No images available</p>'}
              </div>


      <h3>Bid History</h3>
      <ul id="history-list-${bidId}">
      ${Array.isArray(bidData.historyList) && bidData.historyList.length > 0
          ? bidData.historyList.map(bid => `<li>${bid.bidder}: ${formatCurrency(bid.amount)} (Placed on ${new Date(bid.timestamp).toLocaleString()})</li>`).join('')
          : '<li>No bids yet</li>'}
      </ul>
      ${endTime - new Date() > 0
          ? isAdmin
              ? `<input type="number" id="bid-input-${bidId}" disabled placeholder="Admin Cannot Place Bid" />
                 <button disabled>Place Bid</button>`
              : `<input type="number" id="bid-input-${bidId}" placeholder="Place your bid" />
                 <button onclick="placeBid('${bidId}')">Place Bid</button>`
          : `<input type="number" id="bid-input-${bidId}" disabled placeholder="Auction Ended" />
             <button disabled>Place Bid</button>`}
      ${isAdmin ? `
      <button onclick="editBid('${bidId}', '${bidData.title}', '${bidData.description}', ${bidData.startingPrice})">Edit</button>
      <button onclick="deleteBid('${bidId}')">Delete</button>
      <button onclick="archiveBid('${bidId}')" ${endTime - new Date() > 0 ? 'disabled' : ''}>Archive</button>
      ` : ""}
                      <style>
                        button[onclick^="placeBid"] {
                        background-color: #4CAF50;
                        color: white;
                        padding: 10px 20px;
                        border-radius: 5px;
                        cursor: pointer;
                        transition: all 0.3s ease;
                        }
                        button[onclick^="placeBid"]:hover {
                        background-color: #45a049;
                        transform: translateY(-2px);
                        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                        }
                        button[disabled] {
                        background-color: #cccccc;
                        cursor: not-allowed;
                        }
                        button[onclick^="editBid"] {
                        background-color: #2196F3;
                        color: white;
                        padding: 8px 16px;
                        margin: 5px;
                        border-radius: 4px;
                        transition: all 0.3s ease;
                        }
                        button[onclick^="editBid"]:hover {
                        background-color: #1976D2;
                        transform: translateY(-2px);
                        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                        }
                        button[onclick^="deleteBid"] {
                        background-color: #f44336;
                        color: white;
                        padding: 8px 16px;
                        margin: 5px;
                        border-radius: 4px;
                        transition: all 0.3s ease;
                        }
                        button[onclick^="deleteBid"]:hover {
                        background-color: #d32f2f;
                        transform: translateY(-2px);
                        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                        }
                        button[onclick^="archiveBid"] {
                        background-color: #9e9e9e;
                        color: white;
                        padding: 8px 16px;
                        margin: 5px;
                        border-radius: 4px;
                        transition: all 0.3s ease;
                        }
                        button[onclick^="archiveBid"]:hover:not([disabled]) {
                        background-color: #757575;
                        transform: translateY(-2px);
                        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                        }
                        button[onclick^="archiveBid"][disabled] {
                        background-color: #cccccc;
                        cursor: not-allowed;
                        }
                      </style>
                      </div>
                  `;

                  bidItemsContainer.appendChild(bidElement);
                  updateTimer(bidId, endTime);
              });
              initializeGallery();
          }

          // Initialize Image Gallery
          function initializeGallery() {
              GLightbox({ selector: '.glightbox' });
          }

          // Toggle Bid Details
      window.toggleBidDetails = function (header) {
          // Get parent container
          const container = header.closest(".bid-container");

          // Find the header image
          const headerImage = container.querySelector(".header-image");

          // Find the bid details
          const details = container.querySelector(".bid-details");

          if (!details || !headerImage) return;

          // Toggle visibility
          if (details.style.display === "none" || details.style.display === "") {
              details.style.display = "block"; // Show details
              headerImage.style.display = "none"; // Hide image
          } else {
              details.style.display = "none"; // Hide details
              headerImage.style.display = "block"; // Show image
          }
      };

          // Update Timer
          function updateTimer(bidId, endTime) {
              if (timerIntervals[bidId]) clearInterval(timerIntervals[bidId]);
              const timerElement = document.getElementById(`timer-${bidId}`);

              timerIntervals[bidId] = setInterval(() => {
                  const now = new Date();
                  const diff = endTime - now;

                  if (diff <= 0) {
                      timerElement.textContent = "Auction Ended";
                      clearInterval(timerIntervals[bidId]);
                  } else {
                      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                      const seconds = Math.floor((diff % (1000 * 60)) / 1000);

                      timerElement.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;

                      if (diff <= 60000) {
                          timerElement.classList.add("red");
                      }
                  }
              }, 1000);
          }

          // Place Bid
          window.placeBid = async function (bidId) {
          const bidInput = document.getElementById(`bid-input-${bidId}`);
          if (!bidInput) return;

          const newBidAmount = parseFloat(bidInput.value);
          if (isNaN(newBidAmount) || newBidAmount <= 0) {
              alert("Please enter a valid bid amount.");
              return;
          }

          // Ensure bid amount is in multiples of 500
          if (newBidAmount % 500 !== 0) {
              alert("Your bid must be in multiples of MK500 (e.g., MK6,500, MK7,000).");
              return;
          }

          try {
              const bidRef = doc(db, "bids", bidId);
              const bidDoc = await getDoc(bidRef);

              if (!bidDoc.exists()) {
                  alert("Bid item not found. Please try again.");
                  return;
              }

              const bidData = bidDoc.data();
              const currentBid = bidData?.startingPrice ?? null;
              const currentHighestBid = bidData?.highestBid ?? null;

              if (currentBid === null || isNaN(currentBid)) {
                  alert("Starting Price is missing or invalid. Please contact support.");
                  return;
              }

              if (currentHighestBid !== null && isNaN(currentHighestBid)) {
                  alert("Current Highest Bid is invalid. Please contact support.");
                  return;
              }

              if (newBidAmount <= currentBid) {
                  alert("Your bid must be higher than the Starting Price.");
                  return;
              }

              if (currentHighestBid !== null && newBidAmount <= currentHighestBid) {
                  alert("Your bid must be higher than the Current Highest Bid.");
                  return;
              }

              const currentBidder = currentUser.displayName;
              const currentBidderEmail = currentUser.email;
              const historyList = bidData?.historyList || [];
              historyList.push({
                  bidder: currentBidder,
                  amount: newBidAmount,
                  email: currentBidderEmail,
                  timestamp: new Date().toISOString()
              });

              await updateDoc(bidRef, {
                  highestBid: newBidAmount,
                  highestBidder: currentBidder,
                  highestBidderEmail: currentBidderEmail,
                  historyList: historyList,
              });

              alert("Your bid has been placed!");
            maybePromptGlobalReview();
              fetchBids();
          } catch (error) {
             // console.error("Error placing bid:", error); -->
              alert("An error occurred while placing your bid. Please try again.");
          }
      };

          // Admin Add New Bid
          document.getElementById("create-bid")?.addEventListener("click", () => {
              document.getElementById("new-bid-form").style.display = "block";
          });

          // Handle bid creation
          document.getElementById("submit-new-bid")?.addEventListener("click", async (e) => {
              e.preventDefault();

              const title = document.getElementById("new-bid-title").value;
              const description = document.getElementById("new-bid-description").value;
              const startingPrice = parseFloat(document.getElementById("new-bid-starting-price").value);
              const duration = parseInt(document.getElementById("new-bid-timer").value, 10);
              const files = document.getElementById("new-bid-images").files;

              const progressBar = document.getElementById("upload-progress-bar");
              const progressText = document.getElementById("upload-progress-text");

              if (progressBar) progressBar.style.width = "0%";
              if (progressText) progressText.innerHTML = "";

              if (files.length > 0) {
                  document.getElementById("upload-progress").style.display = "block";
                  progressText.style.display = "block";
                  progressText.innerHTML = "Starting upload...";
              } else {
                  document.getElementById("upload-progress").style.display = "none";
                  progressText.style.display = "none";
              }

              if (!title || !description || isNaN(startingPrice) || isNaN(duration)) {
                  alert("Please fill in all fields!");
                  return;
              }

              const endTime = new Date();
              endTime.setHours(endTime.getHours() + duration);
              const imageUrls = [];

              try {
                  if (files.length > 0) {
                      const uploadPromises = Array.from(files).map((file) => {
                          const storageRef = ref(storage, `bids/${Date.now()}_${file.name}`);
                          const uploadTask = uploadBytesResumable(storageRef, file);

                          return new Promise((resolve, reject) => {
                              uploadTask.on(
                                  "state_changed",
                                  (snapshot) => {
                                      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                                      if (progressBar) progressBar.style.width = `${progress}%`;
                                      if (progressText) progressText.innerHTML = `Uploading ${file.name}: ${Math.round(progress)}%`;
                                  },
                                  (error) => {
                                     // console.error("Upload failed:", error); -->
                                      reject(error);
                                  },
                                  () => {
                                      getDownloadURL(uploadTask.snapshot.ref).then((url) => resolve(url));
                                  }
                              );
                          });
                      });

                      const urls = await Promise.all(uploadPromises);
                      imageUrls.push(...urls);
                  }

                  const newBid = {
                      title,
                      description,
                      startingPrice,
                      endTime,
                      imageUrls,
                      highestBid: null,
                      highestBidder: null,
                      highestBidderEmail: null,
                      historyList: []
                  };

                  await addDoc(collection(db, "bids"), newBid);

                  alert("Bid created successfully!");
                        // Reset the form fields
              document.getElementById("bid-form").reset();

              // Hide the form
              document.getElementById("new-bid-form").style.display = "none";
              document.getElementById("upload-progress").style.display = "none";
                  fetchBids();
              } catch (error) {
                 // console.error("Error uploading files:", error); -->
                  alert("Failed to upload files. Please try again.");
              }
          });

          // Delete Bid
          window.deleteBid = async function (bidId) {
              const bidRef = doc(db, "bids", bidId);
              await deleteDoc(bidRef);
              fetchBids();
          };

          // Edit Bid
          window.editBid = async function (bidId, title, description, startingPrice) {
              const newTitle = prompt("Enter new title", title);
              const newDescription = prompt("Enter new description", description);
              const newStartingPrice = parseFloat(prompt("Enter new starting price", startingPrice));

              if (!newTitle || !newDescription || isNaN(newStartingPrice)) {
                  alert("Invalid input");
                  return;
              }

              const bidRef = doc(db, "bids", bidId);
              await updateDoc(bidRef, {
                  title: newTitle,
                  description: newDescription,
                  startingPrice: newStartingPrice
              });

              fetchBids();
          };

          // Toggle Archived Bids for All Users
          const toggleArchiveForUsers = document.createElement("button");
          toggleArchiveForUsers.textContent = "Show Archived Bids";
          toggleArchiveForUsers.classList.add("user-info");

      toggleArchiveForUsers.onclick = async () => {
          const archiveContainer = document.getElementById("archived-bids");
          const isHidden = archiveContainer.style.display === "none";

          if (isHidden) {
              await fetchArchivedBids(); // Now `await` works because the function is async.
          }

          archiveContainer.style.display = isHidden ? "block" : "none";
          toggleArchiveForUsers.textContent = isHidden ? "Hide Archived Bids" : "Show Archived Bids";
      };

          document.querySelector(".user-info").appendChild(toggleArchiveForUsers);


          // Close the new bid form
          document.getElementById("close-new-bid")?.addEventListener("click", () => {
              document.getElementById("new-bid-form").style.display = "none";
          });

          // Archive Bid
          window.archiveBid = async function(bidId) {
              try {
                  const bidRef = doc(db, "bids", bidId);
                  const bidDoc = await getDoc(bidRef);

                  if (!bidDoc.exists()) {
                      alert("Bid item not found.");
                      return;
                  }

                  const bidData = bidDoc.data();
                  await deleteDoc(bidRef);

                  await addDoc(collection(db, "archived_bids"), bidData);

                  alert("Bid archived successfully!");
                  fetchBids();
              } catch (error) {
                 // console.error("Error archiving bid:", error); -->
                  alert("Failed to archive bid. Please try again.");
              }
          };

          // Fetch Archived Bids
          async function fetchArchivedBids() {
              try {
                  const archivedBidsSnapshot = await getDocs(collection(db, "archived_bids"));
                  const archivedBidsContainer = document.getElementById("archived-bids");

                  if (!archivedBidsContainer) {
                      // console.error("Archived bids container not found in the DOM."); -->
                      return;
                  }

                  archivedBidsContainer.innerHTML = '<h4>Archived Bids</h4>';

                  if (archivedBidsSnapshot.empty) {
                      archivedBidsContainer.innerHTML += '<p>No archived bids to display yet.</p>';
                      // console.log("No archived bids found."); -->
                      return;
                  }

                  archivedBidsSnapshot.forEach((doc) => {
                      const bidData = doc.data();
                      const bidElement = document.createElement("div");
                      bidElement.classList.add("bid-item");
                      bidElement.innerHTML = `
                          <h3>${bidData.title}</h3>

                          <p>Winning bid: ${formatCurrency(bidData.highestBid || 0)}</p>
                          <p>Winner: ${bidData.highestBidder}</p>

                          <p>Bid history:</p>
      <ul>
        ${bidData.historyList.map(item => `<li>${item.bidder}: ${formatCurrency(item.amount || 0)} (Placed on ${new Date(item.timestamp).toLocaleString()})</li>`).join('')}
      </ul>
                      `;
                      archivedBidsContainer.appendChild(bidElement);
                  });
              } catch (error) {
                 // console.error("Error fetching archived bids:", error); -->
                  alert("Failed to load archived bids. Please try again.");
              }
          }

      async function displayGlobalReviews() {
          const reviewContainer = document.getElementById("global-reviews");
          if (!reviewContainer) return;

          try {
              const reviewsSnapshot = await getDocs(collection(db, "global_reviews"));
              const reviews = [];
              reviewsSnapshot.forEach(doc => reviews.push(doc.data()));

              if (reviews.length === 0) {
                  reviewContainer.innerHTML = '<p>No reviews yet. Be the first to review!</p>';
                  return;
              }

              const averageRating = (reviews.reduce((acc, r) => acc + r.rating, 0) / reviews.length).toFixed(1);
              const isExpanded = localStorage.getItem('reviewsPanelExpanded') === 'true';

              reviewContainer.innerHTML = `
                  <div class="reviews-panel">
                      <div class="reviews-header" onclick="toggleReviews()">
                          <div>
                              <strong>Dziwani Bid & Win Reviews:</strong> ${averageRating}/5 (${reviews.length} reviews)
                          </div>
                          <span class="toggle-icon ${isExpanded ? 'expanded' : ''}"></span>
                      </div>
                      <div class="reviews-content ${isExpanded ? 'expanded' : ''}">
                          <ul>
                              ${reviews.map(r => `
                                  <li>
                                      <strong>${r.user}</strong>: ${r.rating} ⭐
                                      <p>${r.comment}</p>
                                      <small>${new Date(r.timestamp).toLocaleString()}</small>
                                  </li>
                              `).join('')}
                          </ul>
                      </div>
                  </div>
              `;
          } catch (error) {
              // console.error("Error loading reviews:", error); -->
              reviewContainer.innerHTML = '<p>Error loading reviews. Please try again.</p>';
          }
      }

      function toggleReviews() {
          const content = document.querySelector('.reviews-content');
          const icon = document.querySelector('.toggle-icon');
          const isExpanded = content.classList.toggle('expanded');
          icon.classList.toggle('expanded');
          localStorage.setItem('reviewsPanelExpanded', isExpanded);
      }

      // Make toggle function globally available
      window.toggleReviews = toggleReviews;
      // Call this function when page loads and after new review is submitted
      displayGlobalReviews();
      // Make function globally accessible
      window.promptGlobalReview = async function() {
          try {
              const userName = currentUser ? currentUser.displayName : "Anonymous";
              const rating = prompt("Rate the bidding platform (1-5 stars):");
              const comment = prompt("Write a short review:");

              if (!rating || isNaN(rating) || rating < 1 || rating > 5) {
                  alert("Invalid rating. Please enter a number between 1-5.");
                  return;
              }

              const review = {
                  user: userName,
                  rating: parseInt(rating, 10),
                  comment: comment || "No comment.",
                  timestamp: new Date().toISOString()
              };

              globalReviews.push(review);
              await saveGlobalReview(review);
              alert("Thank you for your review!");
              displayGlobalReviews();
          } catch (error) {
              //console.error("Error in promptGlobalReview:", error);
          }
      };

      // Make helper functions globally accessible
      window.displayGlobalReviews = function() {
          // Implementation here
      };

      window.saveGlobalReview = async function(review) {
          try {
              await addDoc(collection(db, "global_reviews"), review);
             // console.log("Review saved successfully!"); 
          } catch (error) {
              console.error("Error saving review:", error);
          }
      };

      function maybePromptGlobalReview() {
          // 30% chance of prompting the user
          if (Math.random() < 0.3) {
              setTimeout(promptGlobalReview, 2000); // Delay for better user experience
          }
      }

        // Function to open the modal
              window.openModal = function () {
                  document.getElementById("registerModal").style.display = "block";
              };

              // Function to close the modal
              window.closeModal = function () {
                  document.getElementById("registerModal").style.display = "none";
              };

              // Function to register email
              window.registerEmail = async function () {
                  const emailInput = document.getElementById("emailInput").value.trim();

                  if (emailInput === "") {
                      alert("Please enter an email.");
                      return;
                  }

                  const usersRef = collection(db, "users");

                  // Check if email already exists
                  const q = query(usersRef, where("email", "==", emailInput));
                  const querySnapshot = await getDocs(q);

                  if (!querySnapshot.empty) {
                      alert("Email is already registered.");
                      return;
                  }

                  // Save new email to Firestore
                  try {
                      await addDoc(usersRef, { email: emailInput });
                      alert("Registration successful!");
                      document.getElementById("emailInput").value = ""; // Clear input
                      closeModal();
                  } catch (error) {
                     // console.error("Error adding email: ", error); 
                      alert("Error registering. Try again.");
                  }
              };


           // Fetch all bids on page load
          fetchBids();
    </script>
    <center>
      <li>
        <a href="https://forms.gle/beHk8UDpVVVCR7mK9">Click here to list your item for auction for ONLY K2,000.</a>
      </li>

      <li>
        <a href="https://dziwaniphone.blogspot.com/p/blog-page.html">Back to Bid and Win Homepage, Terms and conditions, Public Privacy
          Policy, Contact for support and/or partnerships</a>
      </li>
    </center>
  </body>
</html>
