import { makeAutoObservable, runInAction } from "mobx";

const COLOR_WHITE = { h: 151, s: 0, l: 100 };
const COLOR_GREEN = { h: 151, s: 100, l: 22 };

const TRANSITION_DURATION = 60000;
const TICK_INTERVAL = 100;
const TICK_STEP = TICK_INTERVAL / TRANSITION_DURATION;

interface ColorStore {
  currentColor: string;
  setCurrentColor: (color: string) => void;
  startColorAnimation: () => void;
  stopColorAnimation: () => void;
}

class ColorStore implements ColorStore {
  currentColor: string = "#fff";
  private progress: number = 0;
  private direction: number = 1;
  private tickInterval: ReturnType<typeof setInterval> | null = null;

  constructor() {
    makeAutoObservable(this);
  }

  setCurrentColor = (color: string) => {
    this.currentColor = color;
  };

  private interpolateColor(progress: number): string {
    const h = Math.round(COLOR_WHITE.h + (COLOR_GREEN.h - COLOR_WHITE.h) * progress);
    const s = Math.round(COLOR_WHITE.s + (COLOR_GREEN.s - COLOR_WHITE.s) * progress);
    const l = Math.round(COLOR_WHITE.l + (COLOR_GREEN.l - COLOR_WHITE.l) * progress);
    return `hsl(${h}, ${s}%, ${l}%)`;
  }

  startColorAnimation = () => {
    if (this.tickInterval) return;

    this.tickInterval = globalThis.setInterval(() => {
      runInAction(() => {
        this.progress += TICK_STEP * this.direction;

        if (this.progress >= 1) {
          this.progress = 1;
          this.direction = -1;
        } else if (this.progress <= 0) {
          this.progress = 0;
          this.direction = 1;
        }

        this.currentColor = this.interpolateColor(this.progress);
      });
    }, TICK_INTERVAL);
  };

  stopColorAnimation = () => {
    if (this.tickInterval) {
      clearInterval(this.tickInterval);
      this.tickInterval = null;
    }
  };

  dispose = () => {
    this.stopColorAnimation();
  };
}

export const colorStore = new ColorStore();
export { ColorStore };