<script setup lang="ts">
import { usePreferredReducedMotion } from '@vueuse/core'
import { computed, onBeforeUnmount, ref } from 'vue'
import type { Memory } from '../api/client'
import { getStandardNepalTheme } from '../constants/nepalThemes'
import PolaroidCard from './PolaroidCard.vue'
import { renderMarkdown } from '../utils/renderMarkdown'

const props = defineProps<{
  memory: Memory
}>()

const bodyHtml = computed(() => renderMarkdown(props.memory.main_text))
const theme = computed(() => getStandardNepalTheme(props.memory.nepal_art_style))
const reduceMotion = usePreferredReducedMotion()
const ikeaItems = ['热狗', '桌子', '盘子', '杯子']
const cartStage = ref(0)
const flyingItem = ref<string | null>(null)
const flightKey = ref(0)
const newestItem = ref<string | null>(null)
let flightTimer: ReturnType<typeof setTimeout> | undefined

const activeItems = computed(() => ikeaItems.slice(0, cartStage.value))
const cartVisualItems = computed(() =>
  activeItems.value.map((item, index) => ({
    item,
    style: {
      left: `${14 + index * 14}%`,
      bottom: `${40 + (index % 2) * 12}px`,
      transform: `rotate(${index % 2 === 0 ? -8 : 7}deg)`,
    },
  })),
)

function triggerFlight(item: string) {
  newestItem.value = item
  if (reduceMotion.value === 'reduce') return
  if (flightTimer) clearTimeout(flightTimer)
  flightKey.value += 1
  flyingItem.value = item
  flightTimer = setTimeout(() => {
    flyingItem.value = null
    flightTimer = undefined
  }, 820)
}

function setCartStage(nextStage: number, item?: string) {
  cartStage.value = nextStage
  if (item) triggerFlight(item)
  else if (nextStage === 0) newestItem.value = null
}

function advanceCart() {
  if (cartStage.value >= ikeaItems.length) {
    setCartStage(0)
    return
  }
  const item = ikeaItems[cartStage.value]
  setCartStage(cartStage.value + 1, item)
}

function chooseItem(index: number) {
  const nextStage = index + 1
  const item = ikeaItems[index]
  setCartStage(nextStage, item)
}

onBeforeUnmount(() => {
  if (flightTimer) clearTimeout(flightTimer)
})
</script>

<template>
  <div
    class="relative mx-auto max-w-lg overflow-hidden rounded-3xl bg-gradient-to-br px-3 pb-8 pt-6 sm:px-5 sm:pb-10 sm:pt-8"
    :class="theme.gradient"
  >
    <div
      class="pointer-events-none absolute -left-12 top-12 h-48 w-48 rounded-full bg-blue-300/20 blur-[3rem]"
      aria-hidden="true"
    />
    <div
      class="pointer-events-none absolute -right-10 bottom-8 h-56 w-56 rounded-full bg-amber-300/16 blur-[3.8rem]"
      aria-hidden="true"
    />

    <div
      class="relative z-[1] mx-auto mb-7 max-w-[min(100%,398px)] overflow-hidden rounded-[2rem] border border-indigo-200/60 bg-[linear-gradient(180deg,#f7faff_0%,#eef4ff_100%)] shadow-[0_24px_56px_-18px_rgba(79,70,229,0.22)]"
    >
      <div class="pointer-events-none absolute inset-0 nepal-fiber opacity-[0.12] mix-blend-multiply" />

      <div class="relative px-5 pb-5 pt-5 sm:px-6 sm:pb-6">
        <div class="flex items-start justify-between gap-4">
          <div>
            <p class="text-[10px] font-semibold uppercase tracking-[0.3em] text-indigo-700/68">
              Blue Box Date / 05.10
            </p>
            <h3 class="mt-2 font-display-cn text-[1.9rem] leading-none text-indigo-950">
              逛宜家的小日子
            </h3>
          </div>
          <div
            class="rounded-2xl border border-indigo-200/70 bg-white/90 px-3 py-2 text-right shadow-[0_8px_20px_rgba(79,70,229,0.12)]"
          >
            <p class="text-[9px] font-semibold tracking-[0.22em] text-indigo-700/70">
              Showroom Mood
            </p>
            <p class="mt-1 font-brush text-xl text-indigo-950">Blue + Yellow</p>
          </div>
        </div>

        <div class="mt-6 rounded-[1.8rem] border border-indigo-200/60 bg-white/72 p-4 shadow-inner">
          <div class="relative overflow-hidden rounded-[1.5rem] bg-gradient-to-b from-[#eaf3ff] via-[#ddeaff] to-[#cfe1ff] px-4 pb-5 pt-5">
            <div class="absolute inset-x-0 top-0 h-12 bg-[#0c5adb]" aria-hidden="true" />
            <div class="absolute right-5 top-4 rounded-full bg-[#f8d548] px-3 py-1 text-[10px] font-black tracking-[0.24em] text-[#0c4ca9]">
              SALE
            </div>
            <Transition name="ikea-fly" mode="out-in">
              <div
                v-if="flyingItem"
                :key="`${flyingItem}-${flightKey}`"
                class="pointer-events-none absolute left-8 top-[5.8rem] z-30 rounded-full border border-indigo-200/80 bg-white/96 px-3 py-1.5 text-[11px] font-semibold text-indigo-950 shadow-[0_12px_22px_rgba(79,70,229,0.18)]"
              >
                {{ flyingItem }}
              </div>
            </Transition>

            <div class="mt-10 grid gap-4 sm:grid-cols-[1fr_0.95fr] sm:items-end">
              <div class="rounded-[1.4rem] border border-white/70 bg-white/80 p-4 shadow-[0_12px_24px_rgba(12,90,219,0.12)]">
                <div class="flex items-center justify-between gap-4">
                  <div class="relative h-20 w-12 rounded-t-full bg-[#ffe083]">
                    <div class="absolute left-1/2 top-[-0.4rem] h-4 w-4 -translate-x-1/2 rounded-full border-2 border-[#0c4ca9] bg-white" />
                    <div class="absolute bottom-0 left-1/2 h-12 w-1.5 -translate-x-1/2 bg-[#0c4ca9]" />
                    <div class="absolute bottom-0 left-1/2 h-4 w-8 -translate-x-1/2 rounded-full bg-[#0c4ca9]" />
                  </div>
                  <div class="flex-1 rounded-[1.2rem] bg-[#f6f9ff] px-3 py-3">
                    <p class="text-[10px] font-semibold uppercase tracking-[0.24em] text-indigo-700/65">
                      Cart List
                    </p>
                    <div class="mt-2 flex flex-wrap gap-2 text-[11px] text-indigo-950/88">
                      <button
                        v-for="item in ikeaItems"
                        :key="item"
                        type="button"
                        class="rounded-full px-2.5 py-1 transition"
                        :class="activeItems.includes(item) ? 'bg-[#93c5fd] text-indigo-950' : 'bg-[#dbeafe] hover:bg-[#c5dcff]'"
                        @click="chooseItem(ikeaItems.indexOf(item))"
                      >
                        {{ item }}
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <div
                class="relative mx-auto h-32 w-[180px]"
                :class="reduceMotion === 'reduce' ? '' : 'ikea-cart-bob'"
              >
                <div class="absolute right-0 top-0 rounded-full bg-[#0c5adb] px-2.5 py-1 text-[10px] font-bold text-white shadow-lg">
                  {{ activeItems.length }}
                </div>
                <div class="absolute bottom-3 left-4 h-14 w-24 rounded-[1.2rem] border-[3px] border-[#0c4ca9] bg-white/90" />
                <div class="absolute bottom-11 left-10 h-8 w-14 rotate-[-12deg] rounded-lg bg-[#f8d548] shadow-[0_8px_16px_rgba(248,213,72,0.3)]" />
                <div class="absolute bottom-12 left-20 h-6 w-10 rounded-full bg-[#ff7a59] shadow-[0_8px_16px_rgba(255,122,89,0.22)]" />
                <div class="absolute bottom-[4.6rem] right-8 h-6 w-8 rounded-full bg-[#f5f5f5] shadow-sm" />
                <div class="absolute bottom-[3.2rem] right-7 h-10 w-10 rounded-b-full rounded-t-[0.7rem] bg-[#0c5adb]" />
                <div class="absolute bottom-3 left-2 h-4 w-4 rounded-full border-[3px] border-[#0c4ca9] bg-white" />
                <div class="absolute bottom-3 left-24 h-4 w-4 rounded-full border-[3px] border-[#0c4ca9] bg-white" />
                <div class="absolute bottom-[4.35rem] left-[6.2rem] h-2 w-12 rounded-full bg-[#0c4ca9]" />
                <div class="absolute bottom-[5.1rem] left-[7rem] h-8 w-1.5 rounded-full bg-[#0c4ca9]" />
                <div
                  v-for="entry in cartVisualItems"
                  :key="entry.item"
                  class="absolute rounded-full border border-white/75 bg-[#fff7cf] px-2.5 py-1 text-[10px] font-semibold text-[#0c4ca9] shadow-[0_8px_16px_rgba(12,90,219,0.16)] transition-all"
                  :class="newestItem === entry.item ? 'ring-2 ring-[#f8d548]/80' : ''"
                  :style="entry.style"
                >
                  {{ entry.item }}
                </div>
              </div>
            </div>
          </div>

          <div class="mt-4 flex flex-wrap justify-center gap-2">
            <span
              v-for="tag in ['热狗和餐具', '一起挑桌子', '一起逛生活']"
              :key="tag"
              class="rounded-full border border-indigo-200 bg-white/88 px-3 py-1.5 text-[11px] font-medium text-indigo-900/82"
            >
              {{ tag }}
            </span>
          </div>

          <div class="mt-4 flex flex-col items-center gap-2">
            <button
              type="button"
              class="rounded-full border border-indigo-200 bg-white/92 px-4 py-2 text-xs font-semibold tracking-[0.18em] text-indigo-950 transition hover:bg-indigo-50"
              @click="advanceCart"
            >
              {{
                cartStage >= ikeaItems.length
                  ? '再逛一圈'
                  : `把${ikeaItems[cartStage]}放进推车`
              }}
            </button>
            <p class="text-center text-[11px] leading-relaxed text-indigo-900/70">
              {{
                activeItems.length
                  ? `推车里现在有：${activeItems.join('、')}`
                  : '轻点一下，把今天想带走的小碎片先放进去。'
              }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <div class="relative z-[1] flex flex-col gap-6 sm:gap-8">
      <PolaroidCard :memory="memory" :index="memory.story_order" compact />

      <div
        class="nepal-torn-panel mx-auto max-w-md border border-indigo-200/70 bg-gradient-to-b from-[#fffefa] to-indigo-50/55 px-5 py-6 shadow-[0_16px_36px_-12px_rgba(79,70,229,0.16)] ring-1 ring-white/80 sm:px-6 sm:py-7"
      >
        <div class="mb-4 h-1 w-14 rounded-full bg-gradient-to-r from-indigo-500 to-amber-400" aria-hidden="true" />
        <div
          class="text-[15px] leading-[1.82] tracking-wide text-indigo-950/88 [&_a]:font-bold [&_a]:text-indigo-700 [&_a]:underline [&_a]:underline-offset-4 [&_blockquote]:border-l-4 [&_blockquote]:border-indigo-300/60 [&_blockquote]:bg-indigo-50/55 [&_blockquote]:py-1 [&_blockquote]:pl-3 [&_blockquote]:text-indigo-900/72 [&_code]:rounded [&_code]:bg-indigo-100/55 [&_code]:px-1.5 [&_strong]:text-indigo-950 [&_p+p]:mt-4"
          v-html="bodyHtml"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.ikea-cart-bob {
  animation: ikea-cart-bob 4.6s ease-in-out infinite;
}

.ikea-fly-enter-active {
  animation: ikea-fly-into-cart 0.8s cubic-bezier(0.22, 1, 0.36, 1) both;
}

.ikea-fly-leave-active {
  transition: opacity 0.14s linear;
}

.ikea-fly-leave-to {
  opacity: 0;
}

@keyframes ikea-fly-into-cart {
  0% {
    opacity: 0;
    transform: translate(0, 0) scale(0.88) rotate(-6deg);
  }
  16% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translate(168px, 92px) scale(0.74) rotate(11deg);
  }
}

@keyframes ikea-cart-bob {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-5px) rotate(-1deg);
  }
}
</style>
