In this javascript add a function which will reduce the 'mile-line' (defined in CSS as '#mile-line {
  width: 90%;  /* Stretches 90% of the screen width */
  height: 12px;  /* Adjust for desired line thickness */
  background-color: blue;  /* Customize the line color */
  margin-left: 5%;  /* Align to the left with a 5% margin */
  margin-right: 0;  /* Ensure no right margin */
  transition: width 0.5s ease-in-out;  /* Add a smooth transition */
  position: absolute;
  bottom: 10px;
   z-index: 1;
}' by the distanceInMiles value from each round. So after each round the line reduces in size. Where the initial length of the mile-line is equal to 1000 - var map = L.map("map").setView([39.2291886, -98.0563728], 4);

L.tileLayer(
  "https://api.mapbox.com/styles/v1/gmapsmania/clqgjez3l00fw01qy2gl91sty/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiZ21hcHNtYW5pYSIsImEiOiJOYnlnSFpvIn0.5f62d0cnrWCA1KioxzXtqg",
  {
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  }
).addTo(map);

var NewYork = L.latLng(40.7495267, -73.9480953);
var LA = L.latLng(34.0549357, -118.2418991);
var Chicago = L.latLng(41.8781136, -87.6297982);
var Houston = L.latLng(29.7526733, -95.3645294);
var Phoenix = L.latLng(33.4484851, -112.0733686);
var Philadelphia = L.latLng(39.9523064, -75.1637032);
var SanAntonio = L.latLng(29.4237873, -98.4924226);
var SanDiego = L.latLng(32.7377801, -117.1282962);
var Dallas = L.latLng(32.772347, -96.797991);
var SanJose = L.latLng(37.33809989201188, -121.89032507912425);
var SanFrancisco = L.latLng(37.7749295, -122.4194155);

const locationNames = {
  [NewYork]: "New York City",
  [LA]: "Los Angeles",
  [Chicago]: "Chicago",
  [Houston]: "Houston",
  [Phoenix]: "Phoenix",
  [Philadelphia]: "Philadelphia",
  [SanAntonio]: "San Antonio",
  [SanDiego]: "San Diego",
  [Dallas]: "Dallas",
  [SanJose]: "San Jose",
  [SanFrancisco]: "San Francisco",
};

// Start the game with all reference points

function toPlay() {
  playbutton.remove();
  const entries = [
    NewYork,
    LA,
    Chicago,
    Houston,
    Phoenix,
    Philadelphia,
    SanAntonio,
    SanDiego,
    Dallas,
    SanJose,
    SanFrancisco,
  ];

  // Use entries directly, no need to shuffle or slice
  generateAndPlay(entries);
  myDiv.innerHTML = "";
}

const station = document.getElementById("station");
const myDiv = document.getElementById("my-div");

const userMarkers = []; // Array to store user-added markers

const nextButton = document.createElement("button");
nextButton.innerText = "Next City";
nextButton.id = "buttonsdiv";
nextButton.disabled = true;
nextButton.className = "my-button";

const submitButton = document.createElement("subbutton");
submitButton.innerText = "Submit";
submitButton.id = "buttonsdiv";
submitButton.disabled = true;
submitButton.className = "my-button";

let totalDistance = 0; // Keep track of accumulated distance
let roundDistances = []; // Array to store distance for each round
let total = 1000; // Create the total variable with initial value of 1000

// Custom station marker icon
const LeafIcon = L.Icon.extend({
  options: {
    iconSize: [25, 41],
    iconAnchor: [12, 40],
  },
});

const greenIcon = new LeafIcon({
  iconUrl:
    "https://cdn.glitch.global/f4cb3da3-e38f-4c57-8538-cd16160b85b3/marker-icon-green.png?v=1704485394304",
});

// Function to run the game with remaining reference points
function generateAndPlay(remainingPoints) {
  if (remainingPoints.length === 0) {
    // Fit the map to the user-added markers
    const bounds = new L.LatLngBounds();
    //fitmapbounds ro userMarker
    userMarkers.forEach(function (markerLatLng) {
      bounds.extend(markerLatLng);
    });
    map.fitBounds(bounds);
    //remove round 5 picture
    ghostinfo.innerHTML = "";

    // Add the "Play Again" button
    const playAgainButton = document.createElement("button");
    playAgainButton.id = "playAgain";
    playAgainButton.innerText = "Play Again";
    playAgainButton.className = "my-button";

    // Add click event listener to the button
    playAgainButton.addEventListener("click", function () {
      //cheating by reloading the browser. Instead this function should reset all variables and remove markers from map
      location.reload();
    });

    document.getElementById("ghostinfo").appendChild(playAgainButton);

    //display game score
    station.innerHTML = `Well done!<br><br> You've found all the cities! <br><br>
${roundDistances
  .map((distance, index) => `Round ${index + 1}: ${distance.toFixed(2)} miles`)
  .join("<br>")}<br>
<br>Total distance: ${totalDistance.toFixed(2)} miles.`;

    // Retrieve the previously saved personal best, or set it to 0 if not found
    const savedPersonalBest = localStorage.getItem("personalBest") || 0;

    // Check if the current totalDistance is a new personal best
    if (totalDistance < savedPersonalBest) {
      // Update the personal best in local storage
      localStorage.setItem("personalBest", totalDistance);

      // Add the personal best statement to the innerHTML
      station.innerHTML += `<br><br>Personal Best: ${totalDistance.toFixed(
        2
      )} miles`;
    } else {
      // If not a new personal best, display the saved personal best
      station.innerHTML += `<br><br>Personal Best: ${savedPersonalBest.toFixed(
        2
      )} miles`;
    }

    document.getElementById("buttondiv").removeChild(submitButton);
    document
      .getElementById("station")
      .animate(
        [
          { transform: "rotate(-10deg)" },
          { transform: "rotate(10deg)" },
          { transform: "rotate(-10deg)" },
          { transform: "rotate(10deg)" },
          { transform: "rotate(-10deg)" },
          { transform: "rotate(10deg)" },
        ],
        {
          duration: 1000,
          iterations: 1,
        }
      );

    return;
  }

  const randomIndex = Math.floor(Math.random() * remainingPoints.length);
  const referencePoint = remainingPoints[randomIndex];

  const roundNumber = Math.ceil(11 - remainingPoints.length + 1); // Calculate round number

  station.innerHTML = `Round ${roundNumber}: Drop a marker on the location of ${locationNames[referencePoint]}.<br>`;
  ghostinfo.innerHTML = `${locationNames[referencePoint]}<br>`;

  map.off("click"); // Remove previous click event listener

  // Function to create the midpoint variable
  function createMidpoint(markerLatLng, referencePointLatLng) {
    const markerLat = markerLatLng.lat;
    const markerLng = markerLatLng.lng;
    const referencePointLat = referencePointLatLng.lat;
    const referencePointLng = referencePointLatLng.lng;

    // Calculate the midpoint's latitude and longitude
    const midpointLat = (markerLat + referencePointLat) / 2;
    const midpointLng = (markerLng + referencePointLng) / 2;

    // Create the midpoint L.latLng object
    const midpoint = L.latLng(midpointLat, midpointLng);

    return midpoint;
  }

  map.on("click", function (e) {
    // Add user marker to the array
    var userMarker = L.marker(e.latlng).addTo(map);
    userMarkers.push(userMarker.getLatLng());

    //add submitbutton
    document.getElementById("buttonsdiv").appendChild(submitButton);

    submitButton.onclick = function () {
      const marker = L.marker(e.latlng).addTo(map);
      const distance = L.latLng(e.latlng).distanceTo(referencePoint);
      // Calculate distanceInMiles before using it
      map.off("click");

      // Create a bounds object encompassing both markers
      const bounds = L.latLngBounds([e.latlng, referencePoint]);

      // Zoom the map to fit those bounds
      map.fitBounds(bounds);

      //remove submit button and add next painting button
      document.getElementById("buttonsdiv").appendChild(nextButton);
      document.getElementById("buttonsdiv").removeChild(submitButton);

      const distanceInMiles = distance * 0.000621371;

   

      // Update myDiv with the total value
      myDiv.innerHTML = `You clicked ${distanceInMiles.toFixed(2)} miles from ${
        locationNames[referencePoint]
      }. You have ${total.toFixed(2)} miles left.`;

      // Create the midpoint variable and display message
      const midpoint = createMidpoint(e.latlng, referencePoint);
      const popup = L.popup()
        .setLatLng(midpoint)
        .setContent(
          distanceInMiles < 18
            ? "Perfect"
            : distanceInMiles < 50
            ? "Fairly Good"
            : distanceInMiles < 100
            ? "Could be closer!"
            : "Oh well, better luck next time!" // Default message for distances 10 miles or more
        )
        .openOn(map);

      // Update total distance with clicked marker's distance
      totalDistance += distanceInMiles;
      roundDistances.push(distanceInMiles); // Add distance to the roundDistances array
      // connect user marker to correct location
      const polyline = L.polyline([e.latlng, referencePoint], {
        color: "black",
      }).addTo(map);

      // Put marker on correct location
      const stationMarker = L.marker(referencePoint, { icon: greenIcon }).addTo(
        map
      );

      // Remove the used reference point from the remaining pool
      remainingPoints.splice(randomIndex, 1);
    };
  });

  // Enable next button when a new game round starts
  nextButton.disabled = false;

  // Handle next button click
  nextButton.onclick = function () {
    //remove popup message
    map.closePopup();
    // Change button text to "Results" on the fifth question
    if (roundNumber === 4) {
      nextButton.innerText = "Results";
    }

    //remove next button and add submit painting button
    document.getElementById("buttonsdiv").removeChild(nextButton);
    map.setView([39.2291886, -98.0563728], 4);
    document
      .getElementById("station")
      .animate(
        [
          { transform: "translateX(-3px)" },
          { transform: "translateX(3px)" },
          { transform: "translateX(-3px)" },
          { transform: "translateX(3px)" },
          { transform: "translateX(-3px)" },
          { transform: "translateX(3px)" },
        ],
        {
          duration: 1000,
          iterations: 1,
        }
      );

    generateAndPlay(remainingPoints);
    myDiv.innerHTML = "";
  };
}