<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useBackupStatus } from '../composables/useBackupStatus.js'
import ModalDialog from './ModalDialog.vue'

const router = useRouter()
const { visible, daysSinceBackup, lastBackupAt, load, isStale, sessionReminderShown } =
  useBackupStatus()

const showModal = ref(false)

onMounted(async () => {
  await load()
  if (!sessionReminderShown.value) {
    sessionReminderShown.value = true
    if (isStale.value) {
      showModal.value = true
    }
  }
})

watch(
  () => router.currentRoute.value.fullPath,
  async () => {
    await load()
  },
)

function handleClick() {
  router.push('/settings')
}

function dismissModal() {
  showModal.value = false
}

function goToSettings() {
  showModal.value = false
  router.push('/settings')
}
</script>

<template>
  <ModalDialog v-if="showModal" :title="$t('backup.modal.title')" @close="dismissModal">
    <div data-testid="backup-modal">
      <p class="modal-message">
        {{
          lastBackupAt
            ? $t('backup.modal.body', { days: daysSinceBackup })
            : $t('backup.modal.bodyNever')
        }}
      </p>
      <div class="modal-actions">
        <button class="btn" data-testid="backup-modal-dismiss" @click="dismissModal">
          {{ $t('backup.modal.dismiss') }}
        </button>
        <button class="btn btn-primary" data-testid="backup-modal-settings" @click="goToSettings">
          {{ $t('backup.modal.goToSettings') }}
        </button>
      </div>
    </div>
  </ModalDialog>

  <Teleport to="#actionbar-actions" defer>
    <button
      v-if="visible"
      class="backup-reminder-btn"
      data-testid="backup-reminder"
      :title="
        lastBackupAt
          ? $t('backup.reminder.tooltip', { days: daysSinceBackup })
          : $t('backup.reminder.tooltipNever')
      "
      :aria-label="
        lastBackupAt
          ? $t('backup.reminder.tooltip', { days: daysSinceBackup })
          : $t('backup.reminder.tooltipNever')
      "
      @click="handleClick"
    >
      <i class="bi bi-exclamation-triangle-fill"></i>
    </button>
  </Teleport>
</template>

<style scoped>
.backup-reminder-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border: none;
  border-radius: 4px;
  background-color: var(--warning-color, #f0ad4e);
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.backup-reminder-btn i {
  font-size: 16px;
}

.modal-message {
  margin-bottom: 16px;
  line-height: 1.5;
}

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