<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAppUpdate } from '../composables/useAppUpdate.js'
import ModalDialog from './ModalDialog.vue'

const route = useRoute()
const { needRefresh, updating, dismissed, applyUpdate, dismiss } = useAppUpdate()

// Never interrupt a workout: hidden on the execution route, shows
// automatically once the user navigates away.
const show = computed(
  () => needRefresh.value && !dismissed.value && route.name !== 'session-execute',
)

// While updating the modal is not dismissible: no title means ModalDialog
// renders no header close button, and onClose swallows Escape/backdrop.
function onClose() {
  if (!updating.value) dismiss()
}
</script>

<template>
  <ModalDialog v-if="show" :title="updating ? '' : $t('appUpdate.title')" @close="onClose">
    <div data-testid="app-update-modal">
      <template v-if="!updating">
        <p class="modal-message">{{ $t('appUpdate.body') }}</p>
        <div class="modal-actions">
          <button class="btn" data-testid="app-update-later" @click="dismiss">
            {{ $t('appUpdate.later') }}
          </button>
          <button class="btn btn-primary" data-testid="app-update-now" @click="applyUpdate">
            {{ $t('appUpdate.updateNow') }}
          </button>
        </div>
      </template>
      <div v-else class="updating-state" data-testid="app-update-updating">
        <span class="spinner"></span>
        <p class="modal-message">{{ $t('appUpdate.updating') }}</p>
      </div>
    </div>
  </ModalDialog>
</template>

<style scoped>
.modal-message {
  margin-bottom: 12px;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid var(--border-color);
}

.updating-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
}

.updating-state .modal-message {
  margin: 0;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border-color);
  border-top-color: var(--btn-primary-bg);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
