<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Type Ahead</title>

  <link rel="stylesheet" href="./styles.css"/>
</head>
<body>
  <div class="search">
    <form class="search-form">
      <input type="text"
             class="search-input"
             placeholder="City or State"
             autofocus>
    </form>

    <ul class="search-result"></ul>
  </div>

  <script src="./scripts.js"></script>
</body>
</html>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  align-items: center;
  flex-direction: column;
  background: #5D8CD3;
}

.search {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 80vw;
}

.search-form .search-input {
  width: 400px;
  height: 100px;
  border-radius: 10px;
  border: 8px solid #86A137;
  margin-top: 50px;
  padding: 20px;
  font-size: 30px;
  outline: none;
  text-align: center;
}

ul.search-result {
  width: 400px;
  margin-top: 9px;
}

ul.search-result li {
  display: flex;
  justify-content: space-between;
  list-style-type: none;
  background: #fafafa;
  padding: 20px;
  margin: 10px;
  border: 1px solid #e5e5e5;
  text-transsearch-form: capitalize;
}

ul.search-result li:nth-child(odd) {
  background: #f0f3f0;
  margin-top: -9px;
  transform: perspective(20px) rotateX(-1deg);
}

ul.search-result li:nth-child(even) {
  margin-top: -12px;
  transform: perspective(20px) rotateX(1deg);
}

ul.search-result li .search-highlight {
  color: #fff;
  background: #5D8CD3;
}
let searchInput = document.querySelector('.search-input');
searchInput.addEventListener('keyup', search);

const states = [];

(function getData() {
  const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

  fetch(endpoint).then(response => response.json())
                 .then(data => states.push(...data));
})();

function search() {
  let regex = new RegExp(this.value, 'gi');
  let matches = states.filter(stateData => stateData.city.match(regex));
  displayMatches(this.value, matches);
}

function displayMatches(wordToMatch, matches) {
  let list = document.querySelector('ul.search-result'),
      regex = new RegExp(wordToMatch, 'gi');

  if (wordToMatch == '') { return list.innerHTML = ''; }

  let listItems = matches.map(stateData => {
    let cityName = stateData.city.replace(regex, `<span class="search-highlight">${wordToMatch}</span>`),
        stateName = stateData.state.replace(regex, `<span class="search-highlight">${wordToMatch}</span>`),
        population = Number(stateData.population).toLocaleString();

    return `
      <li>
        <span>${cityName}, ${stateName}</span>
        <span>${population}</span>
      </li>
    `;
  }).join('');

  list.innerHTML = listItems;
}