const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const wotd = document.querySelector('#wotd');
const today = new Date();
let entry;
try {
  let day = today.getDate().toString();
  if (day.length === 1) {
    day = '0' + day;
  }
  let month = (today.getMonth() + 1).toString();
  if (month.length === 1) {
    month = '0' + month;
  }
  fetch(`./wotd/${today.getFullYear()}.${month}.${day}.json`)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP response ${response.status} ${response.statusText}`);
    }
    return response.json();
  })
  .then(entry => {
    if (entry) {
      wotd.classList.add('loaded');
      wotd.querySelector('.title').textContent = 'Word of the day';
      wotd.querySelector('.date').textContent = today.getDate() + ' ' + months[today.getMonth()] + ' ' + today.getFullYear();
      wotd.querySelector('.definiendum').textContent = entry.word;
      wotd.querySelector('.pronunciation').textContent = entry.pronunciation;
      let definitionHTML = '';
      for (const definitionEntry of entry.definitions) {
        definitionHTML += `<h3 class='part-of-speech'>${definitionEntry.part}</h3>`;
        definitionHTML += `<ul class='definitions'>`;
        for (const definition of definitionEntry.definitions) {
          definitionHTML += `<li class='definition'>${definition}</li>`
        }
        definitionHTML += `</ul>`;
      }
      wotd.innerHTML += definitionHTML;
    }
  });
} catch (e) {
  console.error('Word of the Day error:', e);
}
