<template>
  <ModalDialog v-if="visible" title="Want to see what your child sees?" @close="onLater">
    <div class="modal-message">
      Take a quick peek at child mode so you can show them how it works.
    </div>
    <div class="modal-actions">
      <button class="btn btn-secondary" @click="onNoThanks">No thanks</button>
      <button class="btn btn-secondary" @click="onLater">Maybe later</button>
      <button class="btn btn-primary" @click="onYes">Yes, show me</button>
    </div>
  </ModalDialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import ModalDialog from '@/components/shared/ModalDialog.vue'
import {
  tutorialEnabled,
  tutorialProgress,
  tutorialReady,
  markStepSeen,
  maybeShow,
} from './controller'

const router = useRouter()

// "Maybe later" is session-only: don't persist, just don't re-prompt this session.
const dismissedThisSession = ref(false)

const prereqsMet = computed(() => {
  const p = tutorialProgress.value
  return !!p['has-created-child'] && !!p['has-created-chore'] && !!p['has-created-reward']
})

const visible = computed(() => {
  if (!tutorialEnabled.value) return false
  if (!tutorialReady.value) return false
  if (dismissedThisSession.value) return false
  if (tutorialProgress.value['child-mode-tour-offer']) return false
  return prereqsMet.value
})

// Avoid showing the modal on top of an active coach mark — wait for it to clear.
const showWhenIdle = ref(false)
watch(visible, (v) => {
  showWhenIdle.value = v
})

function onYes() {
  void markStepSeen('child-mode-tour-offer')
  router.push('/child')
  // Fire the overview step once we're on /child. anchorSelector resolves the anchor.
  setTimeout(() => maybeShow('child-mode-overview'), 400)
}

function onLater() {
  dismissedThisSession.value = true
}

function onNoThanks() {
  void markStepSeen('child-mode-tour-offer')
}
</script>

<style scoped>
.modal-message {
  font-size: 1rem;
  color: var(--text-primary, #222);
}
.modal-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  justify-content: flex-end;
  margin-top: 1rem;
}
.btn {
  border: none;
  border-radius: 8px;
  padding: 0.5rem 0.95rem;
  font-size: 0.92rem;
  font-weight: 500;
  cursor: pointer;
}
.btn-secondary {
  background: var(--btn-secondary, #f3f3f3);
  color: var(--btn-secondary-text, #666);
}
.btn-secondary:hover {
  background: var(--btn-secondary-hover, #e2e8f0);
}
.btn-primary {
  background: var(--btn-primary, #667eea);
  color: #fff;
}
.btn-primary:hover {
  background: var(--btn-primary-hover, #5a67d8);
}
</style>
