'use strict'

/**
 * utils.js
 */
;(() => {
  window.jsUtils = {
    BREAKPOINT_DESKTOP: '(min-width: 1024px)',
    MOBILE_WIDTH: 360,
    DESKTOP_WIDTH: 1920,

    /**
     * show html element
     * @param {HTMLElement} el
     */
    showEl(el) {
      if (!(el instanceof Node)) return
      el.removeAttribute('hidden')
    },

    /**
     * hide html element
     * @param {HTMLElement} el
     */
    hideEl(el) {
      if (!(el instanceof Node)) return
      el.setAttribute('hidden', 'hidden')
    },

    /**
     * Example: 'балл', 'балла', 'баллов'
     * @param {number} number
     * @param {string} one
     * @param {string} few
     * @param {string} many
     * @returns
     */
    pluralize(number, one, few, many) {
      const lastDigit = number % 10
      const lastTwoDigits = number % 100

      switch (true) {
        case lastDigit === 1:
        case lastTwoDigits !== 11:
          return one
        case lastDigit >= 2:
        case lastDigit <= 4:
        case !(lastTwoDigits >= 12 && lastTwoDigits <= 14):
          return few
        default:
          return many
      }
    },

    /**
     * get random integer
     * @param {number} min
     * @param {number} max
     * @returns {number}
     */
    randomInteger(min, max) {
      const rand = min + Math.random() * (max + 1 - min)
      return Math.floor(rand)
    },

    /**
     * @param {(...args: any[]) => T} func
     * @param {number} delay
     * @returns {(...args: any[]) => void}
     */
    throttle(func, delay) {
      let lastCall = 0

      return function (...args) {
        const now = new Date().getTime()

        if (now - lastCall >= delay) {
          lastCall = now
          func.apply(this, args)
        }
      }
    },

    detectSafari() {
      return /^((?!chrome|android|crios|fxios).)*safari/i.test(
        navigator.userAgent
      )
    }
  }
})()
