<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';

import { $t } from '@easyflow/locales';

import { useEasyFlowModal } from '@easyflow-core/popup-ui';

interface Props {
  // 轮询时间，分钟
  checkUpdatesInterval?: number;
  // 检查更新的地址
  checkUpdateUrl?: string;
}

defineOptions({ name: 'CheckUpdates' });

const props = withDefaults(defineProps<Props>(), {
  checkUpdatesInterval: 1,
  checkUpdateUrl: import.meta.env.BASE_URL || '/',
});

let isCheckingUpdates = false;
let versionCheckController: AbortController | null = null;
const VERSION_CHECK_TIMEOUT_MS = 10_000;
const currentVersionTag = ref('');
const lastVersionTag = ref('');
const timer = ref<ReturnType<typeof setInterval>>();

const [UpdateNoticeModal, modalApi] = useEasyFlowModal({
  closable: false,
  closeOnPressEscape: false,
  closeOnClickModal: false,
  onConfirm() {
    lastVersionTag.value = currentVersionTag.value;
    window.location.reload();
    // handleSubmitLogout();
  },
});

async function getVersionTag() {
  const controller = new AbortController();
  versionCheckController = controller;
  const timeout = setTimeout(
    () => controller.abort(),
    VERSION_CHECK_TIMEOUT_MS,
  );
  try {
    if (
      location.hostname === 'localhost' ||
      location.hostname === '127.0.0.1'
    ) {
      return null;
    }
    const response = await fetch(props.checkUpdateUrl, {
      cache: 'no-cache',
      method: 'HEAD',
      redirect: 'manual',
      signal: controller.signal,
    });

    return (
      response.headers.get('etag') || response.headers.get('last-modified')
    );
  } catch (error) {
    if (!controller.signal.aborted) {
      console.error('Failed to fetch version tag', error);
    }
    return null;
  } finally {
    clearTimeout(timeout);
    if (versionCheckController === controller) {
      versionCheckController = null;
    }
  }
}

async function checkForUpdates() {
  const versionTag = await getVersionTag();
  if (!versionTag) {
    return;
  }

  // 首次运行时不提示更新
  if (!lastVersionTag.value) {
    lastVersionTag.value = versionTag;
    return;
  }

  if (lastVersionTag.value !== versionTag && versionTag) {
    stop();
    handleNotice(versionTag);
  }
}

async function runUpdateCheck() {
  if (isCheckingUpdates) return;
  isCheckingUpdates = true;
  try {
    await checkForUpdates();
  } finally {
    isCheckingUpdates = false;
  }
}

function handleNotice(versionTag: string) {
  currentVersionTag.value = versionTag;
  modalApi.open();
}

function start() {
  stop();
  if (props.checkUpdatesInterval <= 0) {
    return;
  }

  // 每 checkUpdatesInterval(默认值为1) 分钟检查一次
  timer.value = setInterval(
    () => void runUpdateCheck(),
    props.checkUpdatesInterval * 60 * 1000,
  );
}

function handleVisibilitychange() {
  if (document.hidden) {
    stop();
  } else {
    // 恢复窗口时只重启轮询，避免与旧浏览器的首帧重绘争抢资源。
    start();
  }
}

function stop() {
  if (timer.value !== undefined) {
    clearInterval(timer.value);
    timer.value = undefined;
  }
  versionCheckController?.abort();
  versionCheckController = null;
}

onMounted(() => {
  start();
  document.addEventListener('visibilitychange', handleVisibilitychange);
});

onUnmounted(() => {
  stop();
  document.removeEventListener('visibilitychange', handleVisibilitychange);
});
</script>
<template>
  <UpdateNoticeModal
    :cancel-text="$t('common.cancel')"
    :confirm-text="$t('common.refresh')"
    :fullscreen-button="false"
    :title="$t('ui.widgets.checkUpdatesTitle')"
    centered
    content-class="px-8 min-h-10"
    footer-class="border-none mb-3 mr-3"
    header-class="border-none"
  >
    {{ $t('ui.widgets.checkUpdatesDescription') }}
  </UpdateNoticeModal>
</template>
