<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;
      }

      .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-gallery img {
          max-width: 80px;
          max-height: 80px;
        }
      
  </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>

  <!-- Admin Area -->
  <div class="admin-area">
   <h2>
    Admin Area
   </h2>
   <button class="admin-button" id="create-bid">
    Create New Bid
   </button>
   <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>
<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
    } 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 currentUser = null;
let isAdmin = false;

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

// Authentication
onAuthStateChanged(auth, async (user) => {
    const userNameElement = document.getElementById("user-name");
    const googleSignInElement = document.getElementById("google-sign-in");

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

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

        await fetchBids();
    } else {
        currentUser = null;
        userNameElement.textContent = "You need to be signed in to Participate/view Bids";
        googleSignInElement.textContent = "Sign In with Google";
        googleSignInElement.onclick = () => signInWithPopup(auth, provider);

        // 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-header" onclick="toggleBidDetails(this)">
                    <div>
                        <h2>${bidData.title}</h2>
                        <p>${bidData.description}</p>
                        <div id="timer-${bidId}" class="timer"></div>
                    </div>
                </div>
                <div class="bid-details" style="display: none;">
                    <p>Starting Bid: ${formatCurrency(bidData.startingPrice)}</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) {
        const details = header.nextElementSibling;
        details.style.display = details.style.display === 'none' || details.style.display === '' ? 'block' : 'none';
    };

    // 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!");
        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!");
            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.");
        }
    }
  
     // Fetch all bids on page load
    fetchBids();
 
  
</script> 
</body>
</html>