const ratios = {
    pnd : {
        multiplier: 0.45359,
        transition: 'kg'
    },
    kg : {
        multiplier: 2.20462,
        transition: 'pnd'
    },
    mil: {
        multiplier: 1.60934,
        transition: 'km'
    },
    km : {
        multiplier: 0.62137,
        transition: 'mil'
    },
    inch : {
        multiplier: 2.54,
        transition: 'cm'
    },
    cm : {
        multiplier: 0.3937,
        transition: 'inch'
    }
}

const texts = [
    {
        title: 'Pound(lb.)',
        text: `The pound or pound-mass is a unit of mass used in British imperial and United States customary systems of measurement. Various definitions have been used; the most common today is the international avoirdupois pound, which is legally defined as exactly 0.45359237 kilograms, and which is divided into 16 avoirdupois ounces. The international standard symbol for the avoirdupois pound is lb; an alternative symbol is lbm (for most pound definitions), # (chiefly in the U.S.), and ℔ or ″̶ (specifically for the apothecaries' pound).
        The unit is descended from the Roman libra (hence the abbreviation "lb"). The English word pound is cognate with, among others, German Pfund, Dutch pond, and Swedish pund. These units are historic and are no longer used formally (replaced by the metric system), though informal use of the term to mean 500 grams is still heard across Europe and beyond.
        Usage of the unqualified term pound reflects the historical conflation of mass and weight. This accounts for the modern distinguishing terms pound-mass and pound-force.'`,
        tip: `to get approximate result multiply 'mass' value to 2,205`
    },
    {
        title: 'Mile(mi.)',
        text: `The mile, sometimes the international mile or statute mile to distinguish it from other miles, is a British imperial unit and US customary unit of distance; both are based on the older English unit of length equal to 5,280 English feet, or 1,760 yards. The statute mile was standardised between the British Commonwealth and the United States by an international agreement in 1959, when it was formally redefined with respect to SI units as exactly 1,609.344 metres.
        With qualifiers, mile is also used to describe or translate a wide range of units derived from or roughly equivalent to the Roman mile, such as the nautical mile (now 1.852 km exactly), the Italian mile (roughly 1.852 km), and the Chinese mile (now 500 m exactly). The Romans divided their mile into 5,000 Roman feet but the greater importance of furlongs in Elizabethan-era England meant that the statute mile was made equivalent to 8 furlongs or 5,280 feet in 1593. This form of the mile then spread across the British Empire, some of which continues to employ the mile. The US Geological Survey now employs the metre for official purposes, but legacy data from its 1927 geodetic datum has meant that a separate US survey mile (
        6336/3937km) continues to see some use, although it will be officially phased out in 2022. While most countries replaced the mile with the kilometre when switching to the International System of Units (SI), the international mile continues to be used in some countries, such as Liberia, the United Kingdom, the United States, and a number of countries with fewer than one million inhabitants, most of which are UK or US territories or have close historical ties with the UK or US.`,
        tip: `to get approximate result multiply 'width' value to 1,609`
    },
    {
        title: 'Inch(")',
        text: `The inch (symbol: in or ″) is a unit of length in the British imperial and the United States customary systems of measurement. It is equal to 1/36 yard or 1/12
        of a foot. Derived from the Roman uncia ("twelfth"), the word inch is also sometimes used to translate similar units in other measurement systems, usually understood as deriving from the width of the human thumb.
        Standards for the exact length of an inch have varied in the past, but since the adoption of the international yard during the 1950s and 1960s it has been based on the metric system and defined as exactly 25.4 mm.`,
        tip: `to get approximate result multiply 'length' value to 2,54`
    }
]


const container = document.querySelector('.container')
const reader = document.querySelector('.reader__wrapper')

let currentSlide = 0

function truncateFraction (number) {
    try {
        let strNum = String(number).split('.')
        if(strNum[1].length > 3) {
            strNum[1] = strNum[1].slice(0, 3)
        }
        return Number(strNum.join('.'))
    } catch (e) {
        return number
    }
}

function isValidInput (value) {
    if(value < 0 || value > 999999999999999999999) {
        return true
    } else {
        return false
    }
}

function invokeError(bool, element, dependent) {
    try {
        if(bool) {
            if(element.getElementsByTagName('small')[0]) {
                element.getElementsByTagName('small')[0].remove()
            }
            dependent.setAttribute('disabled', true)
            setBackgroundColor('gold', dependent.closest('div'))
            setBackgroundColor('red', element.closest('div'))
            element.insertAdjacentHTML('beforeend', `
                <small>Invalid value given</small>
            `)
        } else {
            dependent.removeAttribute('disabled')
            setBackgroundColor('transparent', dependent.closest('div'), element.closest('div'))
            element.getElementsByTagName('small')[0].remove()
            element.style.backgoundColor = transparent;
        }
    } catch(e) {
        return;
    }
}

function setBackgroundColor (color, ...elements) {
    elements.forEach(element => element.setAttribute('style', `background-color: ${color}`))
}

container.addEventListener('input', (e) => {
    invokeError(isValidInput(e.target.value), e.target.closest('div'), document.getElementById(ratios[`${e.target.id}`].transition))
    document.getElementById(ratios[`${e.target.id}`].transition).value = truncateFraction(e.target.value * ratios[`${e.target.id}`].multiplier)
})

reader.addEventListener('click', (e) => {
    switch(e.target.id) {
        case 'goleft':
            if(currentSlide <= 0) {
                currentSlide = texts.length - 1
            } else {
                currentSlide--
            }
            break;
            
        case 'goright':
            if(currentSlide >= texts.length - 1) {
                currentSlide = 0
            } else {
                currentSlide++
            }
            break;
    }
    reader.getElementsByTagName('h2')[0].innerHTML = texts[currentSlide].title
    reader.getElementsByTagName('p')[0].innerHTML = texts[currentSlide].text
    reader.getElementsByTagName('p')[1].remove()
    reader.getElementsByTagName('article')[0].insertAdjacentHTML('beforeend', `
        <p><strong>Tip:</strong> ${texts[currentSlide].tip}</p>
    `)
    setBackgroundColor('gold', reader.getElementsByTagName('strong')[0])
    reader.getElementsByTagName('strong')[0].style.color = 'black';
})
