import { CommonModule } from '@angular/common';
import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnDestroy,
} from '@angular/core';

@Component({
  selector: 'app-counters',
  standalone: true,
    imports: [
      CommonModule
  ],
  templateUrl: './counters.component.html',
  styleUrls: ['./counters.component.scss'],
})
export class CountersComponent implements OnInit, OnDestroy {
  @Input() totalMoney!: number;
  @Output() emitData = new EventEmitter<{
    totalMoney: number;
    day: number;
    dateTime: string;
  }>();

  day: number = 1;
  dateTime: string = '00:00';
  private timerInterval: any;
  progressWidth: string = '0%';

  ngOnInit(): void {
    this.loadDayFromSessionStorage();
    this.startTimer();

    window.addEventListener('storage', this.onStorageChange.bind(this));
  }

  ngOnDestroy(): void {
    clearInterval(this.timerInterval);
    window.removeEventListener('storage', this.onStorageChange.bind(this));
  }

  startTimer(): void {
    const totalSecondsInDay = 24 * 60;
    const secondsPerUpdate = 30;
    const updatesPerCycle = totalSecondsInDay / secondsPerUpdate;
    const cycleDuration = 1 * 60 * 1000;
    const startTime = performance.now();

    this.timerInterval = setInterval(() => {
      const elapsedMilliseconds = performance.now() - startTime;
      const completedUpdates = Math.floor(
        (elapsedMilliseconds / cycleDuration) * updatesPerCycle
      );
      const elapsedSeconds = completedUpdates * secondsPerUpdate;
      const hours = Math.floor(elapsedSeconds / 60);
      const minutes = elapsedSeconds % 60;
      this.dateTime = `${this.padTime(hours)}:${this.padTime(minutes)}`;

      let adjustedElapsedSeconds = elapsedSeconds - 7 * 60;
      if (adjustedElapsedSeconds < 0) {
        adjustedElapsedSeconds += totalSecondsInDay;
      }
      const progress = (adjustedElapsedSeconds / totalSecondsInDay) * 100;
      this.progressWidth = `${progress}%`;

      this.emitData.emit({
        totalMoney: this.totalMoney,
        day: this.day,
        dateTime: this.dateTime,
      });

      if (elapsedMilliseconds >= cycleDuration) {
        clearInterval(this.timerInterval);
        this.day++;
        this.saveDayToSessionStorage();
        this.startTimer();
      }
    }, 1000);
  }

  padTime(value: number): string {
    return value < 10 ? `0${value}` : `${value}`;
  }

  saveDayToSessionStorage(): void {
    sessionStorage.setItem('currentDay', this.day.toString());
  }

  loadDayFromSessionStorage(): void {
    const savedDay = sessionStorage.getItem('currentDay');
    if (savedDay !== null) {
      this.day = parseInt(savedDay, 10);
    }
  }

  onStorageChange(event: StorageEvent): void {
    if (event.key === 'currentDay' && event.storageArea === sessionStorage) {
      const newDay = event.newValue ? parseInt(event.newValue, 10) : this.day;
      if (newDay !== this.day) {
        this.day = newDay;
      }
    }
  }
}
