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

/** 初见场景：对方发来的第一条抖音私信（文案可改此处） */
const DM_BODY =
  '您好，刷到您的抖音，想问一下成电读博很辛苦吗？我男朋友博一，一天忙的只回不超过五条信息，课题组真的压力很大事情很多吗？谢谢[流泪]'

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 replySent = ref(false)

/** typing → shown */
const revealPhase = ref<'typing' | 'shown'>('typing')
let revealTimer: ReturnType<typeof setTimeout> | undefined

function scheduleReveal() {
  if (revealTimer) clearTimeout(revealTimer)
  if (reduceMotion.value === 'reduce') {
    revealPhase.value = 'shown'
    return
  }
  revealPhase.value = 'typing'
  revealTimer = setTimeout(() => {
    revealPhase.value = 'shown'
    revealTimer = undefined
  }, 2200) // 稍微延长一点输入时间，增加期待感
}

watch(reduceMotion, scheduleReveal, { immediate: true })

onBeforeUnmount(() => {
  if (revealTimer) clearTimeout(revealTimer)
})

const capMotionClass = computed(() =>
  reduceMotion.value === 'reduce' ? '' : 'fm-cap-bob',
)

const tasselMotionClass = computed(() =>
  reduceMotion.value === 'reduce' ? '' : 'fm-tassel-sway',
)

const gridMotionClass = computed(() =>
  reduceMotion.value === 'reduce' ? '' : 'fm-uestc-grid',
)

/** 将 [流泪] 显示为表情，其余保持原文 */
const dmDisplayParts = computed(() => {
  const s = DM_BODY
  const idx = s.indexOf('[流泪]')
  if (idx === -1) return [{ type: 'text' as const, text: s }]
  return [
    { type: 'text' as const, text: s.slice(0, idx) },
    { type: 'tear' as const },
    { type: 'text' as const, text: s.slice(idx + '[流泪]'.length) },
  ]
})

function toggleReply() {
  if (revealPhase.value === 'typing') return
  replySent.value = !replySent.value
}
</script>

<template>
  <div
    class="relative mx-auto max-w-lg overflow-x-hidden rounded-3xl bg-gradient-to-br px-3 pb-8 pt-5 sm:px-5 sm:pb-10 sm:pt-8"
    :class="theme.gradient"
  >
    <div
      class="pointer-events-none absolute -right-10 top-[15%] h-56 w-56 rounded-full bg-cyan-400/20 blur-[3rem]"
      aria-hidden="true"
    />
    <div
      class="pointer-events-none absolute -left-12 bottom-[25%] h-48 w-48 rounded-full bg-fuchsia-500/15 blur-[3rem]"
      aria-hidden="true"
    />

    <p
      class="relative z-[1] mb-4 flex items-center justify-center gap-3 text-[11px] font-bold uppercase tracking-[0.35em] text-slate-500/80"
    >
      <span class="h-px w-6 bg-gradient-to-r from-transparent to-slate-400/50" aria-hidden="true" />
      初见 · 屏幕那头
      <span class="h-px w-6 bg-gradient-to-l from-transparent to-slate-400/50" aria-hidden="true" />
    </p>

    <div class="relative z-[1] mx-auto mb-8 max-w-[min(100%,370px)]">
      <div
        class="overflow-hidden rounded-[2.5rem] border-[6px] border-[#1e293b] bg-black p-[2px] shadow-[0_25px_50px_-12px_rgba(15,23,42,0.6),inset_0_2px_8px_rgba(255,255,255,0.15)] ring-1 ring-slate-800/80"
      >
        <div class="relative overflow-hidden rounded-[2.2rem] bg-slate-950">
          
          <div
            class="relative flex h-10 items-center justify-between px-5 text-[11px] font-semibold text-slate-100"
            aria-hidden="true"
          >
            <span class="w-12 tracking-wider">9:41</span>
            
            <div class="absolute left-1/2 top-2 h-5 w-24 -translate-x-1/2 rounded-full bg-black shadow-[inset_0_-1px_2px_rgba(255,255,255,0.15)]">
              <div class="absolute right-2.5 top-1/2 h-2.5 w-2.5 -translate-y-1/2 rounded-full bg-[#0a0a0a] shadow-[inset_0_1px_1px_rgba(255,255,255,0.1)]"></div>
            </div>

            <div class="flex w-12 justify-end gap-1.5">
              <svg class="h-3 w-4 opacity-90" viewBox="0 0 16 12" fill="currentColor"><path d="M1 9h2V5H1v4zm3 0h2V3H4v6zm3 0h2V1H7v8zm3 0h2V7h-2v2zm3-4v4h2V5h-2z"/></svg>
              <svg class="h-3 w-5 opacity-90" viewBox="0 0 20 12" fill="currentColor"><rect x="1" y="2" width="16" height="8" rx="2" stroke="currentColor" fill="none"/><rect x="2" y="3" width="12" height="6" rx="1"/><path d="M18 5v2a1 1 0 000-2z"/></svg>
            </div>
          </div>

          <header
            class="flex items-center justify-between border-b border-slate-800/80 bg-slate-950/80 px-4 pb-3 pt-1 backdrop-blur-md"
          >
            <span class="flex h-6 w-6 items-center justify-center rounded-full text-lg text-slate-300 hover:bg-slate-800" aria-hidden="true">‹</span>
            <span class="text-[15px] font-bold tracking-wide text-slate-100">私信</span>
            <span class="flex h-6 w-6 items-center justify-center gap-[3px]" aria-hidden="true">
              <span class="h-1.5 w-1.5 rounded-full bg-slate-400" />
              <span class="h-1.5 w-1.5 rounded-full bg-slate-400" />
              <span class="h-1.5 w-1.5 rounded-full bg-slate-400" />
            </span>
          </header>

          <div
            class="pointer-events-none absolute right-1 top-20 z-20 sm:right-3 sm:top-24"
            :class="capMotionClass"
            aria-hidden="true"
          >
            <svg
              class="h-16 w-16 drop-shadow-[0_8px_16px_rgba(0,0,0,0.6)] sm:h-[4.5rem] sm:w-[4.5rem]"
              viewBox="0 0 80 88"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path d="M40 8 L72 22 L40 36 L8 22 Z" fill="#0f172a" stroke="#334155" stroke-width="1.5" />
              <path d="M8 22 L40 36 L40 52 L8 38 Z" fill="#1e293b" stroke="#475569" stroke-width="1.2" />
              <path d="M72 22 L40 36 L40 52 L72 38 Z" fill="#334155" stroke="#64748b" stroke-width="1.2" />
              <circle cx="40" cy="22" r="3.5" fill="#f59e0b" />
              <g :class="tasselMotionClass" style="transform-origin: 56px 28px">
                <path
                  d="M56 28 Q62 48 58 68"
                  stroke="#fbbf24"
                  stroke-width="2.5"
                  stroke-linecap="round"
                  fill="none"
                />
                <circle cx="58" cy="70" r="4.5" fill="#f59e0b" stroke="#b45309" stroke-width="1" />
              </g>
            </svg>
          </div>

          <div class="relative min-h-[300px] bg-gradient-to-b from-slate-900 to-[#080c14] px-4 pb-6 pt-4">
            
            <div
              class="relative mb-5 overflow-hidden rounded-2xl border border-cyan-500/30 bg-slate-900/90 px-3.5 py-3 shadow-[0_4px_12px_rgba(6,182,212,0.1),inset_0_1px_0_rgba(255,255,255,0.1)]"
            >
              <div
                class="uestc-circuit-grid pointer-events-none absolute inset-0 opacity-30 mix-blend-screen"
                :class="gridMotionClass"
                aria-hidden="true"
              />
              <div class="relative flex items-center gap-3">
                <div
                  class="flex h-11 w-11 shrink-0 flex-col items-center justify-center rounded-xl bg-gradient-to-br from-cyan-500 via-cyan-600 to-blue-900 text-[10px] font-black leading-tight text-white shadow-lg ring-1 ring-cyan-300/50"
                >
                  <span class="tracking-widest">UESTC</span>
                  <span class="mt-0.5 h-[2px] w-5 rounded-full bg-cyan-200/60"></span>
                </div>
                <div class="min-w-0">
                  <p class="font-brush text-[1.1rem] leading-tight text-cyan-50 drop-shadow-sm">电子科技大学</p>
                  <p class="mt-1 flex items-center gap-1.5 text-[9px] font-bold tracking-[0.15em] text-cyan-400/80">
                    <span class="h-1.5 w-1.5 rounded-full bg-cyan-400 animate-pulse"></span>
                    清水河校区
                  </p>
                </div>
              </div>
            </div>

            <div class="flex gap-3">
              <div class="relative h-10 w-10 shrink-0">
                <div class="absolute inset-0 animate-ping rounded-full bg-rose-500/30 opacity-75"></div>
                <div
                  class="relative flex h-full w-full items-center justify-center rounded-full bg-gradient-to-br from-rose-400 to-fuchsia-600 text-[13px] font-bold text-white shadow-[0_2px_8px_rgba(225,29,72,0.4)] ring-2 ring-white/10"
                  aria-hidden="true"
                >
                  陌
                </div>
              </div>

              <div class="min-w-0 flex-1 pt-0.5">
                <p class="mb-1.5 pl-1 text-[11px] font-medium text-slate-400">陌生人消息</p>

                <div
                  v-if="revealPhase === 'typing'"
                  class="relative inline-flex items-center gap-1.5 rounded-2xl rounded-tl-sm border border-slate-700/60 bg-slate-800/90 px-4 py-3 shadow-md backdrop-blur-sm"
                  aria-live="polite"
                >
                  <span class="fm-dot h-1.5 w-1.5 rounded-full bg-slate-300" />
                  <span class="fm-dot fm-dot-d1 h-1.5 w-1.5 rounded-full bg-slate-300" />
                  <span class="fm-dot fm-dot-d2 h-1.5 w-1.5 rounded-full bg-slate-300" />
                </div>

                <div
                  v-else
                  class="relative rounded-2xl rounded-tl-sm border border-slate-600/40 bg-slate-800/95 px-4 py-3.5 text-[14px] leading-[1.7] text-slate-100 shadow-[0_4px_15px_rgba(0,0,0,0.3)]"
                  :class="reduceMotion === 'reduce' ? '' : 'fm-bubble-in'"
                >
                  <template v-for="(part, i) in dmDisplayParts" :key="i">
                    <span v-if="part.type === 'text'" class="tracking-wide">{{ part.text }}</span>
                    <span v-else class="inline-block px-1 text-xl leading-none translate-y-0.5" title="流泪">😭</span>
                  </template>
                </div>
                
                <p class="mt-2.5 pl-1 text-[10px] text-slate-500/80 font-medium tracking-wide">
                  对方已通过「视频推荐」发起会话
                </p>

                <div class="mt-3 flex items-start justify-between gap-3 pl-1">
                  <button
                    type="button"
                    class="rounded-full border border-cyan-400/25 bg-cyan-400/10 px-3 py-1.5 text-[10px] font-semibold tracking-[0.18em] text-cyan-200 transition hover:bg-cyan-400/18 disabled:cursor-default disabled:opacity-45"
                    :disabled="revealPhase === 'typing'"
                    @click="toggleReply"
                  >
                    {{ replySent ? '撤回心动回复' : '回一句试试' }}
                  </button>
                  <span class="text-[10px] text-slate-500/78">
                    {{ revealPhase === 'typing' ? '正在输入中…' : '轻点按钮，故事就会继续一点。' }}
                  </span>
                </div>

                <div
                  v-if="replySent"
                  class="mt-3 flex justify-end"
                >
                  <div
                    class="max-w-[84%] rounded-2xl rounded-tr-sm border border-cyan-300/25 bg-gradient-to-br from-cyan-500/18 to-blue-500/16 px-4 py-3 text-right text-[13px] leading-[1.72] text-cyan-50 shadow-[0_10px_22px_rgba(6,182,212,0.12)]"
                    :class="reduceMotion === 'reduce' ? '' : 'fm-reply-pop'"
                  >
                    读博会辛苦，但你这样认真来问的人，也会被认真回答。
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="absolute bottom-2 left-1/2 h-1 w-1/3 -translate-x-1/2 rounded-full bg-slate-600/50"></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-slate-200/70 bg-gradient-to-b from-[#fffdfa] to-slate-50/50 px-5 py-6 shadow-[0_15px_35px_-10px_rgba(30,41,59,0.15)] ring-1 ring-white/80 sm:px-6 sm:py-7"
      >
        <div
          class="mb-4 h-1 w-12 rounded-full bg-gradient-to-r from-cyan-400 to-fuchsia-400"
          aria-hidden="true"
        />
        <div
          class="text-[15px] leading-[1.8] tracking-wide text-slate-800 [&_a]:font-bold [&_a]:text-fuchsia-600 [&_a]:underline [&_a]:decoration-fuchsia-300 [&_a]:underline-offset-4 [&_blockquote]:border-l-4 [&_blockquote]:border-fuchsia-300/60 [&_blockquote]:bg-fuchsia-50/40 [&_blockquote]:py-1 [&_blockquote]:pl-3 [&_blockquote]:text-slate-600 [&_code]:rounded [&_code]:bg-slate-100 [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:font-mono [&_strong]:text-slate-900 [&_p+p]:mt-4"
          v-html="bodyHtml"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.uestc-circuit-grid {
  background-image: 
    linear-gradient(90deg, rgba(34, 211, 238, 0.4) 1px, transparent 1px),
    linear-gradient(rgba(34, 211, 238, 0.4) 1px, transparent 1px),
    radial-gradient(circle at center, rgba(34, 211, 238, 0.8) 1.5px, transparent 1.5px);
  background-size: 14px 14px, 14px 14px, 28px 28px;
  background-position: 0 0, 0 0, 7px 7px;
}

.fm-cap-bob {
  animation: fm-cap-bob 4s ease-in-out infinite;
}

@keyframes fm-cap-bob {
  0%,
  100% {
    transform: translateY(0) rotate(-3deg);
  }
  50% {
    transform: translateY(-6px) rotate(3deg);
  }
}

.fm-tassel-sway {
  animation: fm-tassel-sway 2.2s ease-in-out infinite;
}

@keyframes fm-tassel-sway {
  0%,
  100% {
    transform: rotate(-5deg);
  }
  50% {
    transform: rotate(8deg);
  }
}

.fm-uestc-grid {
  animation: fm-uestc-grid 20s linear infinite;
}

@keyframes fm-uestc-grid {
  0% {
    background-position: 0 0, 0 0, 7px 7px;
  }
  100% {
    background-position: 140px 140px, 140px 140px, 147px 147px;
  }
}

.fm-dot {
  animation: fm-dot 1.2s ease-in-out infinite;
}

.fm-dot-d1 {
  animation-delay: 0.2s;
}

.fm-dot-d2 {
  animation-delay: 0.4s;
}

@keyframes fm-dot {
  0%,
  80%,
  100% {
    transform: translateY(0);
    opacity: 0.3;
  }
  40% {
    transform: translateY(-4px);
    opacity: 1;
  }
}

.fm-bubble-in {
  animation: fm-bubble-in 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) both;
  transform-origin: top left;
}

@keyframes fm-bubble-in {
  0% {
    opacity: 0;
    transform: translateY(15px) scale(0.9);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.fm-reply-pop {
  animation: fm-reply-pop 0.42s cubic-bezier(0.22, 1, 0.36, 1) both;
  transform-origin: top right;
}

@keyframes fm-reply-pop {
  0% {
    opacity: 0;
    transform: translateY(12px) scale(0.92);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 撕纸边缘容器补充 */
.nepal-torn-panel {
  border-radius: 4px 4px 16px 16px;
}
</style>
