
<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 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 {
  background-color: transparent;
  color: #dc3545;
  border: 2px solid #dc3545; /* Red outline */
  padding: 10px 15px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.delete-button:hover {
  background-color: #f8d7da;
}

.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 */
      @media (max-width: 768px) {
        .bid-gallery {
          flex: 100%;
          gap: 5px;
        }

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

        /* Ensure inputs and buttons are properly aligned on small screens */
        .form-group {
          flex-direction: column;
        }

        .admin-input,
        .admin-button {
          width: 100%;
        }
      }

      @media (max-width: 480px) {
        .bid-item {
          padding: 15px;
        }

        .admin-area,
        .bid-container {
          margin: 10px;
          padding: 15px;
        }

        .admin-area {
    display: none; /* Hide by default */
}

        

        
        .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>
        <!-- Archived Bids Section (Initially Hidden) -->
  <div id="archived-bids" style="display:none;">
    <h2>Archived Bids</h2>
    <p>No archived bids to display yet.</p>
  </div>
      
    </div>

    <!-- Admin Area -->
    <div class="admin-area" style="display: none;">
      <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>
          
          <button id="close-bid-form" class="admin-button close-button">Close</button>
          
        </form>
      </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;
                        const adminEmail = "noahkalirani@gmail.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;
                                if (userNameElement) userNameElement.textContent = `Signed in as ${user.displayName}`;
                                if (googleSignInElement) {
                                    googleSignInElement.textContent = "Sign Out";
                                    googleSignInElement.onclick = () => signOut(auth);
                                }

                                const userIsAdmin = user.email === adminEmail;
                                isAdmin = userIsAdmin;
                                const adminAreaElement = document.querySelector(".admin-area");
                                if (adminAreaElement) adminAreaElement.style.display = userIsAdmin ? "block" : "none";

                                await fetchBids();
                            } else {
                                currentUser = null;
                                if (userNameElement) userNameElement.textContent = "You need to be signed in to Participate/view Bids";
                                if (googleSignInElement) {
                                    googleSignInElement.textContent = "Sign In with Google";
                                    googleSignInElement.onclick = () => signInWithPopup(auth, provider);
                                }
                                const adminAreaElement = document.querySelector(".admin-area");
                                if (adminAreaElement) adminAreaElement.style.display = "none";
                                const bidItemsElement = document.getElementById("bid-items");
                                if (bidItemsElement) bidItemsElement.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>
                                        <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>
` : ""}
</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;
                            const isHidden = details.style.display === 'none' || details.style.display === '';
                            details.style.display = isHidden ? '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) {
                                    if (timerElement) 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);

                  let timeText = `${days}d ${hours}h ${minutes}m ${seconds}s`;

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

                                    if (timerElement) timerElement.textContent = timeText;
                                }
                            }, 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;
                      }

                      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; // Use null if missing
                          const currentHighestBid = bidData?.highestBid ?? null;

                          // Safeguard: Ensure currentBid and currentHighestBid are valid numbers
                          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;
                          }

                          // Validate bid against starting price
                          if (newBidAmount <= currentBid) {
                              alert("Your bid must be higher than the Starting Price");
                              return;
                          }

                          // Validate bid against current highest bid if it exists
                          if (currentHighestBid !== null && newBidAmount <= currentHighestBid) {
                              alert("Your bid must be higher than the Current Highest Bid");
                              return;
                          }

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

                          // Update Firestore with new bid
                          await updateDoc(bidRef, {
                              highestBid: newBidAmount,
                              highestBidder: currentBidder,
                              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
// Open the Create New Bid Form
document.getElementById("create-bid")?.addEventListener("click", () => {
    const formModal = document.getElementById("new-bid-form");
    if (formModal) formModal.style.display = "block";
});

// Close Create New Bid Form
document.getElementById("close-bid-form")?.addEventListener("click", () => {
    const formModal = document.getElementById("new-bid-form");
    if (formModal) {
        formModal.style.display = "none";

        // Reset the form fields for a clean state
        document.getElementById("bid-form").reset();
    }
});

                        // 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");

        // Reset and hide progress bar initially
        if (progressBar) {
          progressBar.style.width = "0%";
        }

        if (progressText) {
          progressText.innerHTML = "";
        }

        // Only show progress bar and text if files are selected
        if (files.length > 0) {
          const progressContainer = document.getElementById("upload-progress");
          if (progressContainer) {
            progressContainer.style.display = "block";  // Show progress bar
          }
          if (progressText) {
            progressText.style.display = "block"; // Show progress text
            progressText.innerHTML = "Starting upload...";
          }
        } else {
          const progressContainer = document.getElementById("upload-progress");
          if (progressContainer) {
            progressContainer.style.display = "none";  // Hide progress bar
          }
          if (progressText) {
            progressText.style.display = "none";  // Hide progress text
          }
        }

        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,
            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();
                        };

// Archive Bids
async function archiveEndedBids() {
    try {
        const bidsSnapshot = await getDocs(collection(db, "bids"));
        const archiveCollection = collection(db, "archived_bids");
        const currentTime = new Date();

        let archivedCount = 0; // Count to track archived bids
        const archivePromises = [];

        bidsSnapshot.forEach((doc) => {
            const bidData = doc.data();
            const endTime = bidData.endTime?.toDate ? bidData.endTime.toDate() : new Date(bidData.endTime);

            if (currentTime > endTime) {
                // Archive and delete bid
                archivePromises.push(
                    (async () => {
                        await addDoc(archiveCollection, {
                            ...bidData,
                            archivedAt: currentTime,
                        });
                        await deleteDoc(doc.ref);
                        archivedCount++;
                    })()
                );
            }
        });

        await Promise.all(archivePromises);

        // Notify admin
        if (archivedCount > 0) {
            alert(`${archivedCount} bid(s) archived successfully.`);
        } else {
            alert("No bids to archive.");
        }

        // Refresh UI
        fetchBids();
        fetchArchivedBids();
    } catch (error) {
        console.error("Error archiving bids:", error);
        alert("An error occurred while archiving bids. Please try again.");
    }
}

// Fetch Archived Bids
async function fetchArchivedBids() {
    try {
        const archiveContainer = document.getElementById("archived-bids");
        if (!archiveContainer) return;

        archiveContainer.innerHTML = "<p>Loading archived bids...</p>";

        const archivedSnapshot = await getDocs(collection(db, "archived_bids"));

        if (archivedSnapshot.empty) {
            archiveContainer.innerHTML = "<p>No archived bids available.</p>";
            return;
        }

        archiveContainer.innerHTML = "<h2>Archived Bids</h2>";

        archivedSnapshot.forEach((doc) => {
            const archivedBid = doc.data();
            const archivedElement = document.createElement("div");
            archivedElement.classList.add("archived-item");
            archivedElement.innerHTML = `
                <h3>${archivedBid.title}</h3>
                <p>${archivedBid.description}</p>
                <p>Highest Bid: ${formatCurrency(archivedBid.highestBid || 0)}</p>
                <p>Winner: ${archivedBid.highestBidder || "No Bids"}</p>
                <h4>Bid History:</h4>
                <ul>
                    ${archivedBid.historyList
                        ? archivedBid.historyList
                              .map(
                                  (bid) => `<li>${bid.bidder}: ${formatCurrency(bid.amount)} at ${new Date(bid.timestamp).toLocaleString()}</li>`
                              )
                              .join("")
                        : "<li>No History</li>"}
                </ul>
            `;
            archiveContainer.appendChild(archivedElement);
        });
    } catch (error) {
        console.error("Error fetching archived bids:", error);
        const archiveContainer = document.getElementById("archived-bids");
        if (archiveContainer) {
            archiveContainer.innerHTML = "<p>Failed to load archived bids. Please try again later.</p>";
        }
    }
}

// Add Button for Admin to Archive Ended Bids
function setupAdminButtons() {
    const adminArea = document.querySelector(".admin-area");

    if (!adminArea) return;

    // Archive Button
    const archiveButton = document.createElement("button");
    archiveButton.textContent = "Archive Ended Bids";
    archiveButton.classList.add("admin-button");
    archiveButton.onclick = archiveEndedBids;
    adminArea.appendChild(archiveButton);

    // Toggle Archived Bids Button
    const toggleArchiveButton = document.createElement("button");
    toggleArchiveButton.textContent = "Show Archived Bids";
    toggleArchiveButton.classList.add("admin-button");
    toggleArchiveButton.onclick = () => {
        const archiveContainer = document.getElementById("archived-bids");
        if (archiveContainer) {
            const isHidden = archiveContainer.style.display === "none";
            archiveContainer.style.display = isHidden ? "block" : "none";
            toggleArchiveButton.textContent = isHidden ? "Hide Archived Bids" : "Show Archived Bids";
        }
    };
    adminArea.appendChild(toggleArchiveButton);
}

// Initialize Archived Bids Section
function setupArchivedBidsContainer() {
    const archiveContainer = document.createElement("div");
    archiveContainer.id = "archived-bids";
    archiveContainer.style.display = "none"; // Initially hidden
    document.body.appendChild(archiveContainer);
}

// Fetch and Display Archived Bids for Users
function setupUserToggle() {
    const userInfo = document.querySelector(".user-info");

    if (!userInfo) return;

    const toggleArchiveForUsers = document.createElement("button");
    toggleArchiveForUsers.textContent = "Show Archived Bids";
    toggleArchiveForUsers.classList.add("user-button");
    toggleArchiveForUsers.onclick = () => {
        const archiveContainer = document.getElementById("archived-bids");
        if (archiveContainer) {
            const isHidden = archiveContainer.style.display === "none";
            archiveContainer.style.display = isHidden ? "block" : "none";
            toggleArchiveForUsers.textContent = isHidden ? "Hide Archived Bids" : "Show Archived Bids";
        }
    };

    userInfo.appendChild(toggleArchiveForUsers);
}

// Initialize
function init() {
    setupArchivedBidsContainer();
    setupAdminButtons();
    setupUserToggle();
    fetchArchivedBids(); // Initial fetch for archived bids
}

init();

      
                        // Fetch all bids on page load
                        fetchBids();
    </script>
  </body>
</html>
