import gsap from "gsap";

export type HomeButton =
  | "projects"
  | "contact"
  | "gallery"
  | "theme"
  | "settings"
  | "achievements";

export const useHomeStore = defineStore("home", {
  state: () => ({
    intro: {
      statusBarY: -20,
      stage1Opacity: 0,
      topScreenOpacity: 0,
    },

    outro: {
      buttonOffsetY: 0,
      stage1Opacity: 1,
      stage2Opacity: 1,
      animateTop: false,
    },

    selectedButton: "projects" as HomeButton,

    isIntro: true,
    isOutro: false,
  }),

  actions: {
    reset() {
      const app = useAppStore();
      if (app.previousScreen === "achievements") {
        return;
      }

      const selectedButton = this.selectedButton;
      this.$reset();
      this.selectedButton = selectedButton;
      this.animateIntro();
    },

    animateIntro() {
      this.isIntro = true;

      const app = useAppStore();

      const timeline = gsap.timeline({
        onComplete: () => {
          this.isIntro = false;
        },
      });

      timeline.fromTo(
        this.intro,
        { stage1Opacity: 0 },
        {
          stage1Opacity: 1,
          duration: 0.5,
          ease: "none",
        },
        0,
      );

      if (app.previousScreen !== "settings") {
        timeline
          .fromTo(
            this.intro,
            { topScreenOpacity: 0 },
            {
              topScreenOpacity: 1,
              duration: 0.5,
              ease: "none",
            },
            0,
          )
          .fromTo(
            this.intro,
            { statusBarY: -20 },
            {
              statusBarY: 0,
              duration: 0.15,
              ease: "none",
            },
            0.35,
          );
      } else {
        this.intro.topScreenOpacity = 1;
        this.intro.statusBarY = 0;
      }
    },

    animateOutro(to: AppScreen) {
      if (to === "achievements") {
        const achievementsScreen = useAchievementsScreen();
        achievementsScreen.animateFadeToBlackIntro();
        return;
      }

      this.isOutro = true;
      this.outro.animateTop = to !== "settings";

      const timeline = gsap.timeline({
        onComplete: () => {
          this.isOutro = false;

          const app = useAppStore();
          if (to === "gallery") {
            app.navigateTo("gallery");
          } else {
            app.navigateTo(to);
          }
        },
      });

      timeline
        .fromTo(
          this.outro,
          { stage2Opacity: 1 },
          {
            stage2Opacity: 0,
            duration: 0.16,
            ease: "none",
          },
          0,
        )
        .fromTo(
          this.outro,
          {
            buttonOffsetY: 0,
            stage1Opacity: 1,
          },
          {
            buttonOffsetY: -200,
            stage1Opacity: 0,
            duration: 0.4,
            ease: "none",
          },
          0.08,
        );
    },
  },
});
