<script setup lang="ts">
import { until } from "@vueuse/core";

const app = useAppStore();
const store = useSettingsStore();
const confirmationModal = useConfirmationModal();
const { onRender } = useScreen();
const { assets } = useAssets();
const renderingModeAssets =
  assets.images.settings.bottomScreen.options.renderingMode;

const { selected, selectorPosition } = useButtonNavigation({
  buttons: {
    _3dMode: [11, 27, 233, 74],
    _2dMode: [11, 91, 233, 74],
  },
  initialButton: app.settings.renderingMode === "3d" ? "_3dMode" : "_2dMode",
  navigation: {
    _3dMode: { down: "_2dMode" },
    _2dMode: { up: "_3dMode" },
  },
  selectorAnimation: {
    ease: "none",
    duration: 0.065,
  },
});

const handleCancel = () => {
  store.closeSubMenu();
};

const handleConfirm = () => {
  const mode = selected.value === "_3dMode" ? "3d" : "2d";
  app.setRenderingMode(mode);

  const showConfirmation = () => {
    confirmationModal.open({
      text:
        mode === "3d"
          ? $t("settings.options.startUp.confirmation3d")
          : $t("settings.options.startUp.confirmation2d"),
      onClosed: () => {
        store.closeSubMenu();
      },
      timeout: 2000,
    });
  };

  until(() => app.ready)
    .toBeTruthy()
    .then(showConfirmation);
};

onRender((ctx) => {
  assets.images.home.topScreen.background.draw(ctx, 0, 0);

  ctx.font = "10px NDS10";
  ctx.textBaseline = "top";

  const drawButton = (
    title: string,
    logo: AtlasImage,
    y: number,
    active: boolean,
  ) => {
    ctx.save();
    ctx.translate(16, y);

    if (active) {
      renderingModeAssets.buttonActive.draw(ctx, 0, 0, { colored: true });
    } else {
      renderingModeAssets.button.draw(ctx, 0, 0);
    }

    const buttonWidth = renderingModeAssets.button.rect.width;

    ctx.fillStyle = "#000000";
    fillImageTextHCentered(ctx, logo, title, 0, 4, buttonWidth, 4);

    ctx.fillStyle = "#282828";
    const text = $t("settings.options.startUp.autoStart");
    fillTextHCenteredMultiline(ctx, text, 0, y, buttonWidth, 15);

    ctx.restore();
  };

  drawButton(
    $t("settings.options.startUp.3dMode"),
    renderingModeAssets._3dMode,
    32,
    selected.value === "_3dMode",
  );
  drawButton(
    $t("settings.options.startUp.2dMode"),
    renderingModeAssets._2dMode,
    96,
    selected.value === "_2dMode",
  );
});
</script>

<template>
  <CommonButtons
    :y-offset="confirmationModal.buttonsYOffset"
    :b-label="$t('common.cancel')"
    :a-label="$t('common.confirm')"
    @activate-b="handleCancel"
    @activate-a="handleConfirm"
  />

  <CommonButtonSelector :rect="selectorPosition" />
</template>
