

class Countdown {
  constructor(el){
    this.el = el;
    this.targetDate = new Date(el.getAttribute("date-time"));
    this.createCountDownParts()
    this.countdownFunction();
    this.countdownLoopId = setInterval(this.countdownFunction.bind(this), 1000)
  }
  createCountDownParts(){
    ["الأيام", "الساعات", "الدقائق", "الثواني"].forEach(part => {
      const partEl = document.createElement("div");
      partEl.classList.add("part", part);
      const textEl = document.createElement("div");
      textEl.classList.add("text");
      textEl.innerText = part;
      const numberEl = document.createElement("div");
      numberEl.classList.add("number");
      numberEl.innerText = 0;
      partEl.append(numberEl, textEl);
      this.el.append(partEl);
      this[part] = numberEl;
    })
  }

  countdownFunction(){
    const currentDate = new Date();    
    if(currentDate > this.targetDate) return clearInterval(this.intervalId);
    const remaining = this.getRemaining(this.targetDate, currentDate);
    Object.entries(remaining).forEach(([part,value]) => {
      this[part].style.setProperty("--value", value)
      this[part].innerText = value
    })  
  }
  
  getRemaining(target, now){
    let الثواني = Math.floor((target - (now))/1000);
    let الدقائق = Math.floor(الثواني/60);
    let الساعات = Math.floor(الدقائق/60);
    let الأيام = Math.floor(الساعات/24);
    الساعات = الساعات-(الأيام*24);
    الدقائق = الدقائق-(الأيام*24*60)-(الساعات*60);
    الثواني = الثواني-(الأيام*24*60*60)-(الساعات*60*60)-(الدقائق*60);
    return { الأيام, الساعات, الدقائق, الثواني }      
  }

}

const countdownEls= document.querySelectorAll(".countdown") || [];
countdownEls.forEach(countdownEl => new Countdown(countdownEl))