import { writable, derived } from "svelte/store";
import { CHARACTER_STATES, type CharacterState } from "$lib/types/states";

function createCharacterStore() {
  const { subscribe, set } = writable<CharacterState>("idle");

  let stateTimeout: ReturnType<typeof setTimeout> | null = null;

  return {
    subscribe,
    setState: (state: CharacterState) => {
      if (stateTimeout) {
        clearTimeout(stateTimeout);
        stateTimeout = null;
      }
      set(state);
    },
    setTemporaryState: (state: CharacterState, durationMs: number = 2000) => {
      if (stateTimeout) {
        clearTimeout(stateTimeout);
      }
      set(state);
      stateTimeout = setTimeout(() => {
        set("idle");
        stateTimeout = null;
      }, durationMs);
    },
    reset: () => {
      if (stateTimeout) {
        clearTimeout(stateTimeout);
        stateTimeout = null;
      }
      set("idle");
    },
  };
}

export const characterState = createCharacterStore();

export const characterInfo = derived(characterState, ($state) => CHARACTER_STATES[$state]);
