
let quotes_array=[];
var loadedScripts = {};
let firstdata=false;
function readCookiesAndMerge() {    
  let mergedJson = '';
for (let i = 0; i < 25; i++) {
    const cookieName = 'yy_quotes_' + i;
    const chunk = decodeURIComponent(g(cookieName));

    if (chunk !== null) {
        mergedJson += chunk;
    } else {
break;
    }
}
firstdata=true;
return mergedJson;
}
function loadScript(Font_Name, scriptName) {
  return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', `javascript/typingdata/Lesson/${Font_Name}/${scriptName}.js`, true);
      xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                  var script = document.createElement('script');
                  script.textContent = xhr.responseText;
                  document.head.appendChild(script);

                  const mergedData = readCookiesAndMerge(); // Make sure this function is defined

                  if (mergedData !== null) {
                      quotes_array = JSON.parse(mergedData);
                  }

                  function countTotalCharacters(array) {
                      let nonEmptyString = array.filter(quote => quote.trim() !== "").join("");
                      let characterCount = nonEmptyString.length;
                      return characterCount;
                  }

                  totalCharacterCount = countTotalCharacters(quotes_array);

                  var clearScript = document.createElement('script');
                  clearScript.src = cdn+'javascript/typing/cleardata.js';
                  document.head.appendChild(clearScript);

                  resolve(); // Resolve the promise when all tasks are done
              } else {
                  reject(new Error(`Failed to load script: ${scriptName}`));
              }
          }
      };
      xhr.send();
  });
}


let syslanguage=false;
let total_mistake = document.querySelector(".total_mistake");
let timer_text = document.querySelector(".curr_time");
let accuracy_text = document.querySelector(".curr_accuracy");
let cpm_text = document.querySelector(".curr_cpm");
let wpm_text = document.querySelector(".curr_wpm");
let quote_text = document.querySelector(".quote");
let input_area = document.querySelector(".input_area");
let restart_btn = document.querySelector(".restart_btn");
//let cpm_group = document.querySelector(".cpm");
//let wpm_group = document.querySelector(".wpm");
let WPMbox = document.querySelector(".WPMbox");
let startbtn = document.querySelector(".startbtn");
let play = document.querySelector(".play");
let pause = document.querySelector(".pause");
let error_group = document.querySelector(".errors");
let accuracy_group = document.querySelector(".accuracy");
let completepopmsg = document.querySelector(".completepopmsg");
let TT_O_Time = document.getElementById("TT_O_Time");
let TT_O_Accuracy = document.getElementById("TT_O_Accuracy");
let TT_O_Speed = document.getElementById("TT_O_Speed");
let TT_O_Mistake = document.getElementById("TT_O_Mistake");
const main_TToutput = document.getElementById("main-TToutput");
const main_TTinput = document.getElementById("Keyboard");
const TT_editBtn = document.getElementById("TT_rate-edit");

const TTselectedratelanguage = document.getElementById("TTselectedratelanguage");
var TT_post = document.getElementById('TT_Thanksratepost');
var TT_widget = document.getElementById('TT_Rate-star-widget');

let timeLeft = TIME_LIMIT;
let timeElapsed = 0;
let total_errors = 0;
let errors = 0;
let color = "";
let accuracy = 0;
let characterTyped = 0;
let current_quote = "";
let curr_input = "";
let quoteNo = 0;
let timer = null;
let words = TT_s.split("%E2%98%BB");
var isPaused = true;
var scolor = false;
var mistake = 0;
document.querySelector('input[name="TT_rate"]').addEventListener("change", function() {
  document.getElementById('TT_selectedRating').value = this.value;
});
const TT_storedRatedData = localStorage.getItem('ratedata');
const TT_ratedData = TT_storedRatedData ? JSON.parse(TT_storedRatedData) : {};  

const TThasRated = TT_ratedData[`TT_${Font_Name}_Is_rated`] === true;
TTselectedratelanguage.value = `TT_${Font_Name}`;
if (TThasRated) {
TT_widget.style.display = 'none'
}else{  
TT_widget.style.display = 'block'
}
document.querySelector("#btn_TT_ratepost").addEventListener("click", function(event) {
  event.preventDefault(); // Prevent default form submission

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://www.typingpoint.com/api/rating.cshtml', true);
  xhr.onload = function() {
    if (xhr.status === 200) {
      var data = JSON.parse(xhr.responseText);
      if (data.success) {
        TT_ratedData[`TT_${Font_Name}_Is_rated`] = true;
        localStorage.setItem('ratedata', JSON.stringify(TT_ratedData));
       const TThasRated = TT_ratedData[`TT_${Font_Name}_Is_rated`] === true;

if (TThasRated) {
TT_widget.style.display = 'none'
}else{  
TT_widget.style.display = 'block'
}
      } else {
        console.error('Error: Invalid JSON response');
      }
    } else {
      console.error('Error:', xhr.statusText);
    }
  };
  xhr.onerror = function() {
    console.error('Request failed');
  };
  
  var formData = new FormData(document.getElementById('TT_ratingForm'));
  xhr.send(formData);
});


function addMistake() {
mistake = mistake+1;
    total_mistake.textContent = mistake;
    total_errors = mistake;
}
function updateQuote() {
  quote_text.textContent = null;
  current_quote = quotes_array[quoteNo];

  // separate each character and make an element 
  // out of each of them to individually style them
  current_quote.split('').forEach(char => {
 
      const charSpan = document.createElement('span')
    charSpan.innerText = char
    quote_text.appendChild(charSpan)

  })

  // roll over to the first quote
  if (quoteNo < quotes_array.length - 1 )
    quoteNo++;
  else
     quoteNo = 0;
scolor = true;
changecolor(scolor);
}


function processCurrentText() {

  // get current input text and split it
  curr_input = input_area.value;

  curr_input_array = curr_input.split('');
  errors = 0;
  
  
  // increment total characters typed
  characterTyped++;
if(color!=""){

    var str_array = color.split('♥');

for(var i = 0; i < str_array.length; i++) {
		document.getElementById(str_array[i]).classList.remove('select');
}	
var elems = document.getElementsByClassName("HelpHand");
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'none';
}	 
  }

  QSArr = quote_text.querySelectorAll('span');
  
  QSArr.forEach((char, index) => {
    let typedChar = curr_input_array[index]

    // characters not currently typed
    if (typedChar == null) {
      char.classList.remove('correct_char');
      char.classList.remove('incorrect_char');

      // correct characters
    } else if (typedChar === char.innerText) {
      char.classList.add('correct_char');
      char.classList.remove('incorrect_char');

      // incorrect characters
    } else {
      char.classList.add('incorrect_char');
      char.classList.remove('correct_char');

      // increment number of errors
    errors++;
    }
  });

var pos = input_area.textLength; 
input_area.setSelectionRange(pos+1, pos+1);
  // display the number of errors
//  error_text.textContent = total_errors + errors;

  // update accuracy text
  let correctCharacters = (characterTyped - (total_errors));
  let accuracyVal = ((correctCharacters / characterTyped) * 100);
  accuracy_text.textContent = Math.round(accuracyVal);
  // if current text is completely typed
  // irrespective of errors
  
  if (curr_input.length === QSArr.length) {
    updateQuote();

    // update total errors
total_errors += errors;

    // clear the input area
    input_area.value = "";
  }else{
	   changecolor();
  }
}

function updateTimer() {
  if (timeLeft > 0) {
    // decrease the current time left
    timeLeft--;

    // increase the time elapsed
    timeElapsed++;

    // update the timer text
    timer_text.textContent = Math.floor(timeLeft / 60) +":"+ timeLeft % 60 +"s";
  }
  else {
  if(color!=""){

    var str_array = color.split('♥');

for(var i = 0; i < str_array.length; i++) {
		document.getElementById(str_array[i]).classList.remove('select');
}
  }
    // finish the game
    finishGame();
  }
}

function finishGame() {
  // stop the timer
  clearInterval(timer);

  // disable the input area
  input_area.disabled = true;

  // show finishing text
  quote_text.textContent = "Click on restart to start a new Lesson.";

  // display restart button
  //restart_btn.style.display = "block";


  cpm = Math.round(((characterTyped / timeElapsed) * 60));
  wpm = Math.round((((characterTyped - total_errors) / 5) / (timeElapsed / 60)))  ;

  // update cpm and wpm text
  cpm_text.textContent = cpm;
  wpm_text.textContent = wpm;

  // display the cpm and wpm
 // cpm_group.style.display = "block !important";
 // wpm_group.style.display = "block !important";
//localStorage.setItem(t,n)
//c("wpm","wpm");
//c("mistake","wpm");
//if(wpm > 20){
// completepopmsg.innerHTML = " Now your typing speed is "+wpm+". You can now go to the next lesson. If you want to next lesson, click the <strong>Next </strong> button ";
//}else{
// completepopmsg.innerHTML = " Now your typing speed is "+wpm+". You should practice this lesson again. If you want to practice again, click the <strong>Try Again </strong> button ";
//}
  //modal_complete.style.display = "block";

    let TT_accuracy = ((characterTyped - total_errors) / characterTyped) * 100;
    TT_accuracy = isNaN(TT_accuracy) ? 0 : Math.round(TT_accuracy);
    TT_O_Accuracy.innerHTML = TT_accuracy + "%";
    TT_O_Time.innerHTML = secondsToTimeFormat(TIME_LIMIT - timeLeft);
    TT_O_Speed.innerHTML = wpm;
    TT_O_Mistake.innerHTML = total_errors;
    main_TTinput.style.display = "none";
    main_TToutput.style.display = "block";
}


function startGame() {
  //resetValues();
  updateQuote();


  // clear old and start a new timer
  clearInterval(timer);
  timer = setInterval(function() {
  if(!isPaused) {
	  updateTimer();
  }
}, 1000);
}
document.querySelector('.startbtn').addEventListener('click', function(e) {
  e.preventDefault(); 
  if (firstdata) {
    startbtn.style.display = "none";
    input_area.disabled = false;
    pause.style.display = "block";
    play.style.display = "none";
    input_area.focus(); 
    document.querySelector(".static_text").removeAttribute("style");
    document.querySelector(".type_text_area").removeAttribute("style");
    startGame();
  } else {
    loadScript(Font_Name, Newless)
      .then(() => {
        startbtn.style.display = "none";
        input_area.disabled = false;
        pause.style.display = "block";
        play.style.display = "none";
        input_area.focus(); 
        document.querySelector(".static_text").removeAttribute("style");
        document.querySelector(".type_text_area").removeAttribute("style");
        startGame();
      })
      .catch((error) => {
        // Handle any errors that occurred during script loading
        console.error('Error loading script:', error);
      });
  }
});

document.querySelector('.pause').addEventListener('click', function(e) {
  e.preventDefault();
  isPaused = true;
  document.querySelector('.play').style.display = "block";
  this.style.display = "none";
  input_area.disabled = true;
});

document.querySelector('.play').addEventListener('click', function(e) {
  e.preventDefault();
  isPaused = false;
  document.querySelector('.pause').style.display = "block";
  this.style.display = "none";
  input_area.disabled = false;
  input_area.focus(); 
});

function changecolor(scolor) {	
	color = "";
  curr_input = input_area.value;
  curr_input_array = curr_input.split('');
qSArr = quote_text.querySelectorAll('span');
 if(scolor==true){
 clrno = 0;
 }else{
  clrno =curr_input_array.length
 }
    let pBtn='';
 let validationchr = false;
 let qSA = qSArr[clrno];
 let qSA1 = qSArr[clrno + 1] ? qSArr[clrno + 1] : undefined; 
 var qSAtext = qSA.textContent || qSA.innerText;
 let qSAtext1 = (qSA1 ? qSA1.textContent : '') || (qSA1 ? qSA1.innerText : '');
 eval(decodeURIComponent(TT_SM));
 if (TT_CC && TT_CC !== '') {
  eval(decodeURIComponent(TT_CC));
};   words.forEach((item, index) => {
	   if(item.split("%E2%98%BA")[1]=="+"){
		   var slc = " ";
	   }else{
		   var slc = decodeURIComponent(item.split("%E2%98%BA")[1]);
	   }
	   if(slc==pBtn){

	 color = decodeURIComponent(item.split("%E2%98%BA")[0]);

	  }
	   });
	    var str_array = color.split('♥');
	   
        var handkey = TT_H.split("%E2%98%BB");
  
for(var i = 0; i < str_array.length; i++) {
if(str_array!=''){
  handkey.forEach((F, index) => {
    if(F.split("%E2%98%BA")[0]==str_array[i]){
      document.getElementById(F.split("%E2%98%BA")[1]).style.display = "block";
    }	
  });
  document.getElementById(str_array[i]).classList.add('select');
}	  
}
}

function resetValues() {
  startbtn.style.display = "block";
  document.querySelectorAll(".HelpHand").forEach(function(element) {
    element.style.display = 'none';
});

document.querySelectorAll('.btnKeyboard').forEach(function(element) {
    element.classList.remove('select');
});
  main_TTinput.style.display = "block";
    main_TToutput.style.display = "none";
 timeLeft = TIME_LIMIT;
  timeElapsed = 0;
  errors = 0;
  mistake = 0;
  total_errors = 0;
  accuracy = 0;
  characterTyped = 0;
  quoteNo = 0;
  isPaused = true;
  pause.style.display = "block";
  play.style.display = "none";

  input_area.value = "";
  quote_text.textContent = 'Click on Start button to start the Lesson.';
  accuracy_text.textContent = 100;
  timer_text.textContent = timeLeft + 's';
  total_mistake.textContent = 0;
  //restart_btn.style.display = "none";
 // cpm_group.style.display = "none";
  //wpm_group.style.display = "none";
  // disable the input area
  input_area.disabled = true;
}

var handkey = TT_H.split("%E2%98%BB");
  
    handkey.forEach((F, index) => {
      document.getElementById(F.split("%E2%98%BA")[0]).classList.add(F.split("%E2%98%BA")[1]);
    });

    function secondsToTimeFormat(seconds = 0) {
  if (typeof seconds !== 'number') {
    return "Invalid input. Please provide a number of seconds.";
  }

  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  const formattedMinutes = String(minutes).padStart(2, '0');
  const formattedSeconds = String(remainingSeconds).padStart(2, '0');
  return formattedMinutes + ":" + formattedSeconds;
}
document.querySelectorAll(".TT_secbtn").forEach(button => {
  button.addEventListener("click", function() {
    // Remove 'secactive' class from all buttons
    document.querySelectorAll('.TT_secbtn').forEach(btn => {
      btn.classList.remove('secactive');
    });

    // Update TIME_LIMIT based on the id of the clicked button
    TIME_LIMIT = parseInt(this.id);

    // Add 'secactive' class to the clicked button
    this.classList.add('secactive');

    // Reset other values or perform additional actions if needed
    resetValues();
  });
});

