<template>
  <div v-if="show && routine" class="overlay-backdrop" @click.self="$emit('close')">
    <section class="overlay-panel" aria-modal="true" role="dialog">
      <header class="overlay-header">
        <img
          v-if="routine.image_url"
          :src="routine.image_url"
          :alt="routine.name"
          class="routine-image"
        />
        <p class="routine-question">
          {{ isPending ? 'This routine is pending' : 'Did you complete' }}
        </p>
        <h3 class="routine-name">{{ routine.name }}{{ isPending ? '' : '?' }}</h3>
      </header>

      <!-- Pending-cancel view -->
      <template v-if="isPending">
        <div class="overlay-body pending-body">
          <p class="pending-message">
            This routine is pending confirmation.<br />Would you like to cancel?
          </p>
        </div>
        <footer class="overlay-actions">
          <button type="button" class="btn btn-secondary" @click="$emit('close')">No</button>
          <button type="button" class="btn btn-primary" @click="$emit('cancel-pending')">
            Yes
          </button>
        </footer>
      </template>

      <!-- Normal complete view -->
      <template v-else>
        <div class="overlay-body">
          <div v-if="loading" class="empty-state">Loading tasks...</div>
          <div v-else-if="routine.items.length === 0" class="empty-state">
            No routine tasks found.
          </div>
          <div v-else class="scroll-wrapper" ref="scrollWrapper">
            <div class="task-scroll">
              <button
                v-for="item in resolvedItems"
                :key="item.id"
                type="button"
                class="task-card"
                :title="item.name"
                @click="$emit('task-click', item)"
              >
                <img
                  v-if="item.image_url"
                  :src="item.image_url"
                  :alt="item.name"
                  class="task-image"
                />
                <span class="task-name">{{ item.name }}</span>
              </button>
            </div>
          </div>
        </div>
        <footer class="overlay-actions">
          <button type="button" class="btn btn-secondary" @click="$emit('close')">No</button>
          <button
            v-if="canComplete"
            type="button"
            class="btn btn-primary"
            @click="$emit('complete')"
          >
            Yes!
          </button>
        </footer>
      </template>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { ChildRoutine, RoutineItem } from '@/common/models'
import { getCachedImageUrl } from '@/common/imageCache'

const props = defineProps<{
  show: boolean
  routine: ChildRoutine | null
  canComplete: boolean
  isPending?: boolean
}>()

defineEmits<{
  close: []
  complete: []
  'cancel-pending': []
  'task-click': [item: RoutineItem]
}>()

const loading = ref(false)
const resolvedItems = ref<(RoutineItem & { image_url?: string })[]>([])

// Resolve images when routine changes
watch(
  () => props.routine,
  async (newRoutine) => {
    if (!newRoutine?.items.length) {
      resolvedItems.value = []
      return
    }

    loading.value = true
    const itemsWithImages = await Promise.all(
      newRoutine.items.map(async (item) => {
        let image_url: string | undefined
        if (item.image_id) {
          try {
            image_url = await getCachedImageUrl(item.image_id)
          } catch {
            image_url = undefined
          }
        }
        return { ...item, image_url }
      }),
    )
    resolvedItems.value = itemsWithImages
    loading.value = false
  },
  { immediate: true },
)
</script>

<style scoped>
.overlay-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  z-index: 1100;
}

.overlay-panel {
  width: min(92vw, 600px);
  max-height: min(85vh, 720px);
  display: flex;
  flex-direction: column;
  background: var(--modal-bg, #fff);
  border-radius: 16px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.28);
  overflow: hidden;
}

.overlay-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 0.5rem;
  padding: 1.5rem 1.25rem 1rem;
  border-bottom: 1px solid var(--form-input-border, rgba(0, 0, 0, 0.08));
}

.routine-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 14px;
  background: var(--info-image-bg);
  margin-bottom: 0.25rem;
}

.routine-question {
  margin: 0;
  color: var(--modal-message-color, #555);
  font-size: 1rem;
  font-weight: 500;
}

.routine-name {
  margin: 0.15rem 0 0;
  color: var(--btn-primary, #667eea);
  font-size: 1.2rem;
  font-weight: 700;
}

.overlay-body {
  flex: 1 1 auto;
  overflow: hidden;
  padding: 1rem 1.25rem;
}

.pending-body {
  overflow: visible;
}

.pending-message {
  text-align: center;
  color: var(--modal-message-color, #333);
  font-size: 1rem;
  line-height: 1.6;
  padding: 0.5rem 0;
  margin: 0;
}

.tasks-heading {
  display: none;
}

.empty-state {
  color: var(--loading-color, #888);
  text-align: center;
  padding: 2rem 1rem;
}

.scroll-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
  scroll-behavior: smooth;
  width: 100%;
  -webkit-overflow-scrolling: touch;
}

.scroll-wrapper::-webkit-scrollbar {
  height: 6px;
}

.scroll-wrapper::-webkit-scrollbar-track {
  background: transparent;
}

.scroll-wrapper::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.15);
  border-radius: 3px;
}

.scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

.task-scroll {
  display: flex;
  gap: 0.75rem;
  min-width: min-content;
  padding: 0.5rem 0;
}

.task-card {
  position: relative;
  background: var(--list-item-bg-good, rgba(200, 230, 201, 0.3));
  border-radius: 8px;
  padding: 0.75rem;
  min-width: 120px;
  max-width: 160px;
  width: 100%;
  text-align: center;
  flex-shrink: 0;
  cursor: pointer;
  user-select: none;
  border: 1px solid var(--list-item-border-good, rgba(100, 180, 100, 0.3));
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  transition:
    transform 0.18s ease,
    box-shadow 0.18s ease;
  -webkit-tap-highlight-color: transparent;
}

@media (hover: hover) {
  .task-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 18px rgba(0, 0, 0, 0.12);
  }
}

.task-card:active {
  transform: scale(0.97);
}

.task-image {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 6px;
  display: block;
}

.task-name {
  display: block;
  color: var(--form-label, #222);
  font-size: 0.9rem;
  font-weight: 700;
  line-height: 1.2;
  word-break: break-word;
}

.overlay-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  padding: 1rem 1.25rem 1.25rem;
  border-top: 1px solid var(--form-input-border, rgba(0, 0, 0, 0.08));
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 600;
  transition: opacity 0.2s;
}

.btn-secondary {
  background: var(--btn-secondary, #f0f0f0);
  color: var(--btn-secondary-text, #333);
}

.btn-secondary:hover {
  opacity: 0.8;
}

.btn-primary {
  background: var(--btn-primary, #667eea);
  color: #fff;
}

.btn-primary:hover {
  opacity: 0.9;
}

@media (max-width: 480px) {
  .overlay-panel {
    width: min(94vw, 600px);
    max-height: 88vh;
  }

  .overlay-header {
    align-items: flex-start;
  }

  .overlay-actions {
    gap: 0.75rem;
  }

  .task-card {
    min-width: 100px;
    max-width: 140px;
    padding: 0.6rem;
  }

  .task-image {
    width: 50px;
    height: 50px;
  }

  .task-name {
    font-size: 0.8rem;
  }
}
</style>
