window.OTPInput = function OTPInput() {

    const inputs = document.querySelectorAll('#otp > input');

    console.log("Otp", inputs)

    for (let i = 0; i < inputs.length; i++) {
        inputs[i].addEventListener('input', function () {
            if (this.value.length > 1) {
                this.value = this.value[0]; //    
            }
            if (this.value !== '' && i < inputs.length - 1) {
                inputs[i + 1].focus(); //   
            }
        });

        inputs[i].addEventListener('keydown', function (event) {
            if (event.key === 'Backspace') {
                this.value = '';
                if (i > 0) {
                    inputs[i - 1].focus();
                }
            }
        });
    }
}

window.starProgressBar = function startProgressBar(initialTime) {
    let timeLeft = initialTime;
    let interval;

    const progressBarElement = document.getElementById('progress-bar');

    function render() {
        const progressPercentage = (1 - (timeLeft / initialTime)) * 100;
        progressBarElement.style.width = progressPercentage + '%';
    }

    function tick() {
        timeLeft = timeLeft - 1;
        if (timeLeft <= 0) {
            clearInterval(interval);
        }

        render();
    }

    function startProgressBar() {
        interval = setInterval(tick, 1000);
        render();
    }

    startProgressBar();
}

window.signIn = function signIn(key) {

    const body = {signInKey: key}

    return fetch("/panel/auth/signIn", {
        method: 'post',
        body: JSON.stringify(body),
        headers: new Headers({'Content-Type': 'application/json'}),
        cache: 'no-cache',
        credentials: 'same-origin'
    })
        .then(function (response) {

            console.log(response)


        });
}


let mediaRecorder;
let audioChunks = [];

window.startVoiceRecording = function () {
    navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
        mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.ondataavailable = event => {
            audioChunks.push(event.data);
        };
        mediaRecorder.start();
    }).catch(error => console.error('Error accessing microphone:', error));
}

window.stopVoiceRecording = function () {
    return new Promise((resolve, reject) => {
        if (mediaRecorder) {
            mediaRecorder.onstop = () => {
                const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                const reader = new FileReader();
                reader.onloadend = () => {

                    const base64Audio = reader.result.split(',')[1]; // فقط داده‌ی Base64
                    resolve(base64Audio);
                };
                reader.readAsDataURL(audioBlob);
                audioChunks = [];
            };
            mediaRecorder.stop();
        } else {
            reject("MediaRecorder not initialized.");
        }
    });
}


window.stopVoiceRecording = function () {
    return new Promise((resolve, reject) => {
        if (mediaRecorder) {
            mediaRecorder.onstop = () => {
                const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                const reader = new FileReader();
                reader.onloadend = () => {
                    const base64Audio = reader.result.split(',')[1]; // فقط داده‌ی Base64
                    resolve(base64Audio);
                };
                reader.readAsDataURL(audioBlob);
                audioChunks = [];
            };
            mediaRecorder.stop();
        } else {
            reject("MediaRecorder not initialized.");
        }
    });
}


window.startRecordingWave = function(){
    const bar = document.querySelectorAll(".sound-wave > .bar");
    
    for (let i = 0; i < bar.length; i++) {
      bar.forEach((item, j) => {
        // Random move
        item.style.animationDuration = `${Math.random() * (0.7 - 0.2) + 0.2}s`; 
      });
    }
  }
  
  window.getWindowSize = function() {

    return {
            width: window.innerWidth,
            height: window.innerHeight
        };
};

window.accessMicPermission=async function (){
    navigator.mediaDevices.getUserMedia({ audio: true })
        .catch(function(error) {
            console.log(error)
            alert("جهت استفاده از این صفحه لطفا دسترسی های مورد نیاز مرورگر را تایید کنید")
        });
}