function $_ID(id) {
  return document.getElementById(id)
}

function hide(element) {
  element.classList.add('d-none')
}

function show(element) {
  element.classList.remove('d-none')
}

function getFormData(event) {
  return Object.fromEntries(new FormData(event.target).entries())
}

function loopObject(obj, callback) {
  for (let [key, value] of Object.entries(obj)) {
    callback({ key, value })
  }
}

function ready(callback) {
  document.addEventListener('DOMContentLoaded', callback);
}

async function postData(url = '', data = {}) {
  const response = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
    },
    referrerPolicy: 'no-referrer',
    body: JSON.stringify(data)
  })

  return response.json()
}

function addValidationClasses(item) {
    if (! item) {
        return
    }

    $_ID(item.key).classList.add('form-input-border-error', 'form-control-bordered', 'form-control-bordered-error')
    $_ID(`${item.key}-error-box`).innerHTML = `<strong>${item.value}</strong>`
}

function removeValidationClasess() {
  Array.from(document.getElementsByClassName('form-input-border-error')).forEach(element => {
    element.classList.remove('form-input-border-error', 'form-control-bordered', 'form-control-bordered-error')
  })

  Array.from(document.getElementsByClassName('error-box')).forEach(element => {
    element.innerHTML = ''
  })
}

function showVerificationCodeBox() {
  $_ID('verification-code-box').classList.remove('hidden')
  $_ID('verification-code-box').insertAdjacentHTML('beforeend', `
      <input 
        class="form-control form-input form-input-bordered w-full" 
        id="verification" 
        type="text" 
        name="verification"
        value=""
      >
      <input type="hidden" name="step-verification" value="1">

    <span id="verification-error-box" class="text-red-500 text-italic error-box"></span>
  `)
}

function showPasswordBox() {
  $_ID('username-box').classList.add('hidden')
  $_ID('verification-code-box').innerHTML = ''

  $_ID('reset-password-container').classList.remove('hidden')

  $_ID('password-box').insertAdjacentHTML('beforeend', `
    <input class="form-control form-input form-input-bordered w-full" id="password" type="password" name="password">
    <input type="hidden" name="step-password" value="1">

    <span id="password-error-box" class="text-red-500 text-italic error-box"></span>
  `)
  $_ID('password-confirm-box').insertAdjacentHTML('beforeend', `
    <input class="form-control form-input form-input-bordered w-full" id="password_confirmation" type="password" name="password_confirmation">

    <span id="password_confirmation-error-box" class="text-red-500 text-italic error-box"></span>
  `)
}
