import { z } from "zod/mini";
import type * as THREE from "three";

const STORAGE_ID = "app_settings";

const settingsSchema = z.object({
  color: z.object({
    col: z.number(),
    row: z.number(),
  }),
});

type Settings = z.infer<typeof settingsSchema>;

const defaultSettings = (): Settings => ({
  color: { col: 0, row: 0 },
});

export const useAppStore = defineStore("app", {
  state: () => {
    let settings: Settings;
    const stored = localStorage.getItem(STORAGE_ID);
    try {
      settings = settingsSchema.parse(JSON.parse(stored ?? ""));
    } catch {
      settings = defaultSettings();
    }

    return {
      booted: false,
      settings,
      screen: "home" as AppScreen,
      camera: null as THREE.Camera | null,
    };
  },

  actions: {
    setColor(col: number, row: number) {
      this.settings.color = { col, row };
    },

    navigateTo(screen: AppScreen) {
      this.screen = screen;

      const achievements = useAchievementsStore();

      switch (screen) {
        case "projects":
          achievements.unlock("projects_visit");
          break;

        case "gallery":
          achievements.unlock("gallery_visit");
          break;

        case "contact":
          achievements.unlock("contact_visit");
          break;
      }
    },

    setCamera(camera: THREE.Camera) {
      this.camera = camera;
    },

    save() {
      localStorage.setItem(STORAGE_ID, JSON.stringify(this.settings));
    },
  },

  getters: {
    color: (state) => ({
      col: state.settings.color.col,
      row: state.settings.color.row,
      hex: APP_COLORS[state.settings.color.row]![state.settings.color.col]!,
    }),
  },
});
