<template>
  <Teleport to="body">
    <div
      v-if="step"
      class="tutorial-root"
      role="dialog"
      aria-modal="true"
      :aria-labelledby="titleId"
      :aria-describedby="bodyId"
    >
      <!-- Spotlight: four dim rectangles forming a hole around the anchor. -->
      <template v-if="anchorRect">
        <div class="dim" :style="dimTopStyle" />
        <div class="dim" :style="dimBottomStyle" />
        <div class="dim" :style="dimLeftStyle" />
        <div class="dim" :style="dimRightStyle" />
        <div class="ring" :style="ringStyle" aria-hidden="true" />
        <!-- Transparent blocker over the highlighted element so it cannot be
             clicked/interacted with while this step is active. -->
        <div class="anchor-blocker" :style="blockerStyle" aria-hidden="true" />
      </template>
      <div v-else class="dim dim-full" />

      <!-- Coach mark card -->
      <div
        ref="cardEl"
        class="card"
        :class="{
          'card-sheet': isMobile,
          'card-floating': !isMobile && !!anchorRect,
          'card-center': !anchorRect && !isMobile,
        }"
        :style="cardStyle"
        @keydown="handleKeydown"
        tabindex="-1"
      >
        <h3 :id="titleId" class="title">{{ step.def.title }}</h3>
        <p :id="bodyId" class="body" aria-live="polite">{{ step.def.body }}</p>
        <div class="actions">
          <button type="button" class="btn btn-skip" @click="onSkip" ref="skipBtn">
            Cancel
          </button>
          <button type="button" class="btn btn-primary" @click="onPrimary" ref="primaryBtn">
            {{ primaryLabel }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { activeStep, dismissActive, skipSession, type ActiveStep } from './controller'

const MOBILE_BREAKPOINT = 600
const CARD_MAX_WIDTH = 320
const CARD_MARGIN = 12

const cardEl = ref<HTMLElement | null>(null)
const primaryBtn = ref<HTMLElement | null>(null)
const skipBtn = ref<HTMLElement | null>(null)
const anchorRect = ref<DOMRect | null>(null)
const cardSize = ref<{ width: number; height: number }>({ width: CARD_MAX_WIDTH, height: 160 })
const viewport = ref<{ w: number; h: number }>({
  w: typeof window !== 'undefined' ? window.innerWidth : 1024,
  h: typeof window !== 'undefined' ? window.innerHeight : 768,
})
const step = computed<ActiveStep | null>(() => activeStep.value)
const titleId = 'tutorial-title'
const bodyId = 'tutorial-body'

const isMobile = computed(() => viewport.value.w <= MOBILE_BREAKPOINT)

const primaryLabel = computed(() => {
  const def = step.value?.def
  if (!def) return 'Continue'
  if (def.ctaLabel) return def.ctaLabel
  return 'Continue'
})

function resolveAnchor(): HTMLElement | null {
  const s = step.value
  if (!s || !s.anchor) return null
  return typeof s.anchor === 'function' ? s.anchor() : s.anchor
}

function measureAnchor() {
  const el = resolveAnchor()
  if (!el) {
    anchorRect.value = null
    return
  }
  const rect = el.getBoundingClientRect()
  anchorRect.value = rect
}

function measureCard() {
  const el = cardEl.value
  if (!el) return
  const rect = el.getBoundingClientRect()
  cardSize.value = { width: rect.width, height: rect.height }
}

function measureAll() {
  viewport.value = { w: window.innerWidth, h: window.innerHeight }
  measureAnchor()
  measureCard()
}

const dimTopStyle = computed(() => {
  const r = anchorRect.value
  if (!r) return {}
  return {
    top: '0px',
    left: '0px',
    width: '100%',
    height: `${Math.max(0, r.top - 6)}px`,
  }
})
const dimBottomStyle = computed(() => {
  const r = anchorRect.value
  if (!r) return {}
  return {
    top: `${r.bottom + 6}px`,
    left: '0px',
    width: '100%',
    height: `${Math.max(0, viewport.value.h - r.bottom - 6)}px`,
  }
})
const dimLeftStyle = computed(() => {
  const r = anchorRect.value
  if (!r) return {}
  return {
    top: `${Math.max(0, r.top - 6)}px`,
    left: '0px',
    width: `${Math.max(0, r.left - 6)}px`,
    height: `${r.height + 12}px`,
  }
})
const dimRightStyle = computed(() => {
  const r = anchorRect.value
  if (!r) return {}
  return {
    top: `${Math.max(0, r.top - 6)}px`,
    left: `${r.right + 6}px`,
    width: `${Math.max(0, viewport.value.w - r.right - 6)}px`,
    height: `${r.height + 12}px`,
  }
})

const ringStyle = computed(() => {
  const r = anchorRect.value
  if (!r) return {}
  return {
    top: `${r.top - 6}px`,
    left: `${r.left - 6}px`,
    width: `${r.width + 12}px`,
    height: `${r.height + 12}px`,
  }
})

const blockerStyle = computed(() => {
  const r = anchorRect.value
  if (!r) return {}
  return {
    top: `${r.top - 6}px`,
    left: `${r.left - 6}px`,
    width: `${r.width + 12}px`,
    height: `${r.height + 12}px`,
  }
})

const cardStyle = computed(() => {
  if (isMobile.value) return {}
  const r = anchorRect.value
  if (!r) return {}
  const { w: vw, h: vh } = viewport.value
  const { width: cw, height: ch } = cardSize.value
  const preferred = step.value?.def.placement ?? 'auto'

  const spaceBelow = vh - r.bottom - CARD_MARGIN
  const spaceAbove = r.top - CARD_MARGIN
  const placeBelow =
    preferred === 'below' ||
    (preferred !== 'above' && spaceBelow >= ch + CARD_MARGIN) ||
    spaceAbove < ch + CARD_MARGIN

  const top = placeBelow
    ? Math.min(r.bottom + CARD_MARGIN, vh - ch - CARD_MARGIN)
    : Math.max(CARD_MARGIN, Math.min(r.top - ch - CARD_MARGIN, vh - ch - CARD_MARGIN))

  const anchorCenterX = r.left + r.width / 2
  let left = anchorCenterX - cw / 2
  left = Math.max(CARD_MARGIN, Math.min(left, vw - cw - CARD_MARGIN))

  return { top: `${top}px`, left: `${left}px` }
})

function trapFocus(e: KeyboardEvent) {
  if (e.key !== 'Tab') return
  const focusables = [skipBtn.value, primaryBtn.value].filter(
    (el): el is HTMLElement => el !== null,
  )
  if (focusables.length === 0) return
  const first = focusables[0]!
  const last = focusables[focusables.length - 1]!
  if (e.shiftKey && document.activeElement === first) {
    e.preventDefault()
    last.focus()
  } else if (!e.shiftKey && document.activeElement === last) {
    e.preventDefault()
    first.focus()
  }
}

function handleKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    e.preventDefault()
    onPrimary()
    return
  }
  trapFocus(e)
}

function onPrimary() {
  dismissActive(true)
}

function onSkip() {
  skipSession()
}

// Re-measure on scroll/resize while a step is active.
function onScroll() {
  measureAnchor()
}
function onResize() {
  measureAll()
}

let resizeObserver: ResizeObserver | null = null
let rafId: number | null = null

function startTracking() {
  window.addEventListener('resize', onResize)
  window.addEventListener('scroll', onScroll, true)
  if (typeof ResizeObserver !== 'undefined' && cardEl.value) {
    resizeObserver = new ResizeObserver(() => measureCard())
    resizeObserver.observe(cardEl.value)
  }
  // rAF for cases where anchor shifts (animated FAB, etc.)
  const tick = () => {
    measureAnchor()
    rafId = requestAnimationFrame(tick)
  }
  rafId = requestAnimationFrame(tick)
}

function stopTracking() {
  window.removeEventListener('resize', onResize)
  window.removeEventListener('scroll', onScroll, true)
  resizeObserver?.disconnect()
  resizeObserver = null
  if (rafId !== null) cancelAnimationFrame(rafId)
  rafId = null
}

watch(
  step,
  async (val) => {
    if (!val) {
      stopTracking()
      anchorRect.value = null
      return
    }
    await nextTick()
    // Scroll the anchor into view before measuring so the spotlight and card
    // are positioned correctly. Use 'auto' for synchronous scroll — smooth
    // scroll races the first measure and can leave the card off-screen.
    const el = resolveAnchor()
    if (el) {
      const pos = getComputedStyle(el).position
      const rect = el.getBoundingClientRect()
      const isHidden = rect.width === 0 && rect.height === 0
      if (isHidden) {
        anchorRect.value = null
      } else if (pos !== 'fixed') {
        el.scrollIntoView({ behavior: 'auto', block: 'center' })
      }
    }
    // Give the browser one frame to finish the synchronous scroll before
    // measuring anchor and card positions.
    await new Promise((r) => requestAnimationFrame(r))
    measureAll()
    startTracking()
    // Focus primary button for keyboard users (after paint).
    await nextTick()
    primaryBtn.value?.focus()
  },
  { immediate: true },
)

onBeforeUnmount(stopTracking)
</script>

<style scoped>
.tutorial-root {
  position: fixed;
  inset: 0;
  z-index: 10000;
  pointer-events: none;
}

.dim {
  position: fixed;
  background: rgba(0, 0, 0, 0.55);
  pointer-events: auto;
}
.dim-full {
  inset: 0;
}

.ring {
  position: fixed;
  border: 3px solid var(--primary, #667eea);
  border-radius: 12px;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.85) inset;
  pointer-events: none;
  animation: tutorial-pulse 1.6s ease-in-out infinite;
}

.anchor-blocker {
  position: fixed;
  background: transparent;
  pointer-events: auto;
  border-radius: 12px;
  cursor: default;
}

@media (prefers-reduced-motion: reduce) {
  .ring {
    animation: none;
  }
}

@keyframes tutorial-pulse {
  0%,
  100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.04);
    opacity: 0.85;
  }
}

.card {
  position: fixed;
  background: var(--form-bg, #fff);
  color: var(--text-primary, #222);
  border-radius: 14px;
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.35);
  padding: 1rem 1.1rem 0.9rem;
  pointer-events: auto;
  max-width: 320px;
  box-sizing: border-box;
}

.card-floating {
  width: 320px;
}

.card-center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 320px;
}

.card-sheet {
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  max-width: 100%;
  border-radius: 16px 16px 0 0;
  padding: 1rem 1.1rem calc(1rem + env(safe-area-inset-bottom, 0px));
}

.title {
  margin: 0 0 0.4rem;
  font-size: 1.05rem;
  font-weight: 600;
  color: var(--form-heading, #667eea);
}

.body {
  margin: 0 0 0.9rem;
  font-size: 0.95rem;
  line-height: 1.4;
  color: var(--text-primary, #222);
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

.btn {
  border: none;
  border-radius: 8px;
  padding: 0.5rem 0.95rem;
  font-size: 0.92rem;
  font-weight: 500;
  cursor: pointer;
}

.btn-skip {
  background: var(--btn-secondary, #f3f3f3);
  color: var(--btn-secondary-text, #666);
}
.btn-skip: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);
}

.btn:focus-visible {
  outline: 2px solid var(--primary, #667eea);
  outline-offset: 2px;
}
</style>
