import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  static targets = ['days', 'hours', 'minutes', 'seconds'];

  connect() {
    const targetDate = this.element.dataset.countdownTargetDate;
    this.targetDate = new Date(targetDate).getTime();

    this.updateTimer();
    this.timer = setInterval(() => this.updateTimer(), 1000);
  }

  disconnect() {
    clearInterval(this.timer);
  }

  updateTimer() {
    const now = new Date().getTime();
    const timeLeft = this.targetDate - now;

    if (timeLeft < 0) {
      clearInterval(this.timer);
      this.daysTarget.textContent = '0';
      this.hoursTarget.textContent = '0';
      this.minutesTarget.textContent = '0';
      this.secondsTarget.textContent = '0';
      return;
    }

    const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

    this.daysTarget.textContent = days;
    this.hoursTarget.textContent = hours;
    this.minutesTarget.textContent = minutes;
    this.secondsTarget.textContent = seconds;
  }
};
