<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToast } from 'primevue/usetoast'
import Dialog from 'primevue/dialog'
import LocationPicker from '@/components/LocationPicker.vue'
import {
  fetchQrInfoApi,
  updatePersonProfileApi,
  updatePetProfileApi,
  updateGoodsInfoApi,
  updateLinkInfoApi,
  verifyMaintenanceCodeApi,
  verifyMaintenanceCodeInfoApi,
  uploadFile,
  fetchRecentScanRecordsApi
} from '@/services/api'

const route = useRoute()
const router = useRouter()
const toast = useToast()

// Pull QR code from route params
const qrCode = ref(route.params.qrCode?.toString().trim() || '')
const queryInput = ref(qrCode.value)

const loading = reactive({
  info: false,
  saving: false,
  verifying: false,
  photo: false
})

const qrDetail = ref(null)
const profile = ref(null)
const infoStatus = reactive({
  state: qrCode.value ? 'loading' : 'idle',
  message: ''
})

const maintenanceCode = ref('')
const maintenancePassed = ref(false)
const showMaintenancePanel = ref(false)
const showMaintenanceDialog = ref(false)
const viewMaintenanceCode = ref('')
const loadingViewVerification = ref(false)
const isEditing = ref(false)
const showLocationDialog = ref(false)
const showLocationViewDialog = ref(false)
const showScanRecordsDialog = ref(false)
const showScanRecordsMaintenanceDialog = ref(false)
const scanRecordsMaintenanceCode = ref('')
const verifiedMaintenanceCode = ref('')
const scanRecords = ref(null)
const loadingScanRecords = ref(false)

const FORM_KEY_MAP = Object.freeze({
  person: [
    'photoUrl',
    'name',
    'gender',
    'phone',
    'specialNote',
    'emergencyContactName',
    'emergencyContactPhone',
    'emergencyContactEmail',
    'location',
    'isVisible'
  ],
  pet: ['photoUrl', 'name', 'contactName', 'contactPhone', 'contactEmail', 'location', 'remark', 'isVisible'],
  goods: ['photoUrl', 'name', 'contactName', 'contactPhone', 'contactEmail', 'location', 'remark', 'isVisible'],
  link: ['jumpUrl', 'linkRemark', 'isVisible']
})

const DEFAULT_FORM_STATE = Object.freeze({
  photoUrl: '',
  name: '',
  gender: 'unknown',
  phone: '',
  specialNote: '',
  emergencyContactName: '',
  emergencyContactPhone: '',
  emergencyContactEmail: '',
  remark: {},
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  location: '',
  isVisible: true,
  jumpUrl: '',
  linkRemark: ''
})

const createDefaultFormState = () => ({
  ...DEFAULT_FORM_STATE,
  remark: { ...DEFAULT_FORM_STATE.remark }
})

const formData = ref(createDefaultFormState())

const profileApiMap = Object.freeze({
  person: updatePersonProfileApi,
  pet: updatePetProfileApi,
  goods: updateGoodsInfoApi,
  link: updateLinkInfoApi
})

const MAX_PHOTO_SIZE = 15 * 1024 * 1024
const DEFAULT_NAME_BY_TYPE = Object.freeze({
  person: 'Person',
  pet: 'Pet',
  goods: 'Item'
})

const qrType = computed(() => qrDetail.value?.qrType || 'person')
const isPerson = computed(() => qrType.value === 'person')
const isPet = computed(() => qrType.value === 'pet')
const isGoods = computed(() => qrType.value === 'goods')
const isLink = computed(() => qrType.value === 'link')
const hasProfile = computed(() => Boolean(profile.value))
const isFirstFill = computed(() => {
  // 优先判断 isVisible，如果不可见则不认为是第一次使用
  if (qrDetail.value?.isVisible === false) {
    return false
  }
  // 如果 isActivated 为 false 或 undefined，则认为是第一次填写
  return Boolean(qrDetail.value) && !qrDetail.value?.isActivated
})
const heroTitle = computed(() => {
  if (!qrDetail.value) return 'Contact Card'
  if (isPerson.value) return 'Person Card'
  if (isPet.value) return 'Pet Card'
  if (isGoods.value) return 'Item Card'
  if (isLink.value) return 'Link Card'
  return 'Contact Card'
})

const getActiveFormKeys = () => FORM_KEY_MAP[qrType.value] || FORM_KEY_MAP.person

const parseError = (error) => {
  return (
    error?.response?.data?.message ||
    error?.data?.message ||
    error?.detail ||
    error?.message ||
    error?.error ||
    (typeof error === 'string' ? error : '') ||
    'Request failed'
  )
}

const resetForm = (source = null) => {
  const nextState = createDefaultFormState()
  if (source) {
    // 对于 link 类型，特殊处理
    if (isLink.value) {
      nextState.jumpUrl = source.jumpUrl ?? ''
      nextState.linkRemark = source.remark ?? ''
      nextState.isVisible = source.isVisible !== undefined ? source.isVisible : true
    } else {
      getActiveFormKeys().forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          // 对于布尔值，直接使用值（包括 false）
          if (key === 'isVisible') {
            nextState[key] = source[key] !== undefined ? source[key] : true
          } else if (key === 'remark') {
            // 处理 remark 字段：如果是字符串，尝试解析为 JSON 对象
            const value = source[key]
            if (typeof value === 'string' && value.trim()) {
              try {
                const parsed = JSON.parse(value)
                if (typeof parsed === 'object' && parsed !== null) {
                  nextState[key] = parsed
                } else {
                  // 如果解析结果不是对象，将其作为第一个备注
                  nextState[key] = { '1': value }
                }
              } catch (e) {
                // 如果解析失败，将字符串作为第一个备注
                nextState[key] = value ? { '1': value } : { '1': '' }
              }
            } else if (typeof value === 'object' && value !== null) {
              // 确保对象至少有一个字段
              const keys = Object.keys(value)
              if (keys.length === 0) {
                nextState[key] = { '1': '' }
              } else {
                nextState[key] = value
              }
            } else {
              nextState[key] = { '1': '' }
            }
          } else {
            nextState[key] = source[key] ?? DEFAULT_FORM_STATE[key] ?? ''
          }
        }
      })
    }
  }
  // 如果 source 中没有 isVisible，则从 qrDetail 中获取
  if (!source || !Object.prototype.hasOwnProperty.call(source, 'isVisible')) {
    if (qrDetail.value && Object.prototype.hasOwnProperty.call(qrDetail.value, 'isVisible')) {
      nextState.isVisible = qrDetail.value.isVisible !== false
    }
  }
  formData.value = nextState
}

const setDocumentTitle = () => {
  if (typeof document === 'undefined') return
  // 如果没有二维码或没有详情，只显示 Emergency QR
  if (!qrCode.value || !qrDetail.value) {
    document.title = 'Emergency QR'
    return
  }
  if (isLink.value) {
    const linkUrl = profile.value?.jumpUrl || 'Link Information'
    document.title = `${linkUrl} | Link QR`
    return
  }
  const defaultName = DEFAULT_NAME_BY_TYPE[qrType.value] || DEFAULT_NAME_BY_TYPE.person
  const name = profile.value?.name || defaultName
  document.title = `${name} | Emergency QR`
}

const fetchQrDetails = async () => {
  if (!qrCode.value) return
  loading.info = true
  infoStatus.state = 'loading'
  infoStatus.message = ''
  try {
    const data = await fetchQrInfoApi(qrCode.value)
    qrDetail.value = data
    
    // 如果是 link 类型且已激活且有 jumpUrl，直接跳转
    if (data.qrType === 'link' && data.isActivated && data.info?.jumpUrl) {
      window.location.href = data.info.jumpUrl
      return
    }
    
    if (data.isVisible === false) {
      infoStatus.state = 'notVisible'
      infoStatus.message = 'QR code information is not visible'
      profile.value = null
      resetForm()
      setDocumentTitle()
      return
    }
    profile.value = data.info || null
    resetForm(profile.value)
    infoStatus.state = 'ready'
    setDocumentTitle()
  } catch (error) {
    infoStatus.state = 'error'
    infoStatus.message = parseError(error)
  } finally {
    loading.info = false
  }
}

const handleQrSubmit = () => {
  if (!queryInput.value.trim()) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter a QR code first.', life: 2600 })
    return
  }
  router.push({ name: 'scan', params: { qrCode: queryInput.value.trim() } })
}

const handleVerifyMaintenance = async () => {
  if (!qrCode.value || !maintenanceCode.value) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter the maintenance code.', life: 2400 })
    return
  }
  loading.verifying = true
  try {
    await verifyMaintenanceCodeApi({
      qrCode: qrCode.value,
      maintenanceCode: maintenanceCode.value
    })
    maintenancePassed.value = true
    showMaintenancePanel.value = false
    showMaintenanceDialog.value = false
    isEditing.value = true
    toast.add({ severity: 'success', summary: 'Verified', detail: 'Maintenance editing unlocked.', life: 2600 })
    // Scroll to the form the first time we collect data
    if (isFirstFill.value) {
      setTimeout(scrollToForm, 300)
    }
  } catch (error) {
    maintenancePassed.value = false
    toast.add({ severity: 'error', summary: 'Verification failed', detail: parseError(error), life: 3200 })
  } finally {
    loading.verifying = false
  }
}

const handleVerifyMaintenanceForView = async () => {
  if (!qrCode.value || !viewMaintenanceCode.value) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter the maintenance code.', life: 2400 })
    return
  }
  loadingViewVerification.value = true
  try {
    const data = await verifyMaintenanceCodeInfoApi({
      qrCode: qrCode.value,
      maintenanceCode: viewMaintenanceCode.value
    })
    if (data.valid) {
      // 更新二维码详情和用户信息
      qrDetail.value = {
        ...qrDetail.value,
        ...data,
        isVisible: true // 验证成功后视为可见
      }
      profile.value = data.info || null
      resetForm(profile.value)
      infoStatus.state = 'ready'
      infoStatus.message = ''
      viewMaintenanceCode.value = ''
      setDocumentTitle()
      toast.add({ severity: 'success', summary: 'Verified', detail: data.message || 'Verification successful.', life: 2600 })
    } else {
      throw new Error(data.message || 'Verification failed')
    }
  } catch (error) {
    toast.add({ severity: 'error', summary: 'Verification failed', detail: parseError(error), life: 3200 })
  } finally {
    loadingViewVerification.value = false
  }
}

const isValidUrl = (url) => {
  if (!url || !url.trim()) return true // Empty value is considered valid (optional field)
  try {
    const urlObj = new URL(url)
    return urlObj.protocol === 'http:' || urlObj.protocol === 'https:'
  } catch {
    return false
  }
}

const testJumpUrl = () => {
  const url = formData.value.jumpUrl?.trim()
  if (!url) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter a URL first.', life: 2400 })
    return
  }

  // 验证 URL 格式
  if (isValidUrl(url)) {
    toast.add({ 
      severity: 'success', 
      summary: 'URL Format Valid', 
      detail: 'The URL format is correct and ready to save.', 
      life: 3000 
    })
  } else {
    toast.add({ 
      severity: 'error', 
      summary: 'Invalid URL Format', 
      detail: 'Please check the URL format (must start with http:// or https://).', 
      life: 3200 
    })
  }
}

const buildProfilePayload = () => {
  const payload = {
    qrCode: qrCode.value
  }
  
  // 对于 link 类型，特殊处理
  if (isLink.value) {
    payload.isVisible = formData.value.isVisible !== undefined ? formData.value.isVisible : true
    if (formData.value.jumpUrl && formData.value.jumpUrl.trim()) {
      payload.jumpUrl = formData.value.jumpUrl.trim()
    }
    if (formData.value.linkRemark && formData.value.linkRemark.trim()) {
      payload.remark = formData.value.linkRemark.trim()
    }
    if (maintenanceCode.value) {
      payload.maintenanceCode = maintenanceCode.value
    }
    return payload
  }
  
  getActiveFormKeys().forEach((key) => {
    if (key === 'isVisible') {
      payload[key] = formData.value[key] !== undefined ? formData.value[key] : true
    } else if (key === 'remark') {
      // 将 remark 对象转换为 JSON 字符串
      const remarkObj = formData.value[key] || {}
      // 过滤掉空值
      const filteredRemark = Object.fromEntries(
        Object.entries(remarkObj).filter(([_, value]) => value && value.trim())
      )
      payload[key] = Object.keys(filteredRemark).length > 0 ? JSON.stringify(filteredRemark) : ''
    } else {
      payload[key] = formData.value[key] ?? ''
    }
  })
  if (maintenanceCode.value) {
    payload.maintenanceCode = maintenanceCode.value
  }
  return payload
}

const handleSaveProfile = async () => {
  if (!qrCode.value) return
  
  // 对于 link 类型，验证 URL
  if (isLink.value) {
    if (formData.value.jumpUrl && formData.value.jumpUrl.trim()) {
      if (formData.value.jumpUrl.length > 2000) {
        toast.add({ severity: 'warn', summary: 'Notice', detail: 'Jump URL cannot exceed 2000 characters.', life: 2400 })
        return
      }
      if (!isValidUrl(formData.value.jumpUrl)) {
        toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter a valid URL (must start with http:// or https://).', life: 2400 })
        return
      }
    }
    if (formData.value.linkRemark && formData.value.linkRemark.length > 500) {
      toast.add({ severity: 'warn', summary: 'Notice', detail: 'Remark cannot exceed 500 characters.', life: 2400 })
      return
    }
  }
  
  loading.saving = true
  try {
    const payload = buildProfilePayload()
    const updater = profileApiMap[qrType.value] || profileApiMap.person
    const response = await updater(payload)
    toast.add({ 
      severity: 'success', 
      summary: 'Saved', 
      detail: response?.message || (isLink.value ? 'Link information has been updated.' : 'Profile has been updated.'), 
      life: 3000 
    })
    await fetchQrDetails()
    isEditing.value = false
    maintenancePassed.value = false
    maintenanceCode.value = ''
  } catch (error) {
    toast.add({ severity: 'error', summary: 'Save failed', detail: parseError(error), life: 3200 })
  } finally {
    loading.saving = false
  }
}

const photoInputRef = ref(null)
const triggerPhotoPicker = () => {
  photoInputRef.value?.click?.()
}

const handleImageError = (event) => {
  // Handle broken image preview
  console.warn('Image load failed:', formData.value.photoUrl)
  event.target.style.display = 'none'
}

const handlePhotoChange = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  // Validate mime type
  if (!file.type.startsWith('image/')) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please choose an image file.', life: 2400 })
    return
  }

  // Validate file size (limit 15MB)
  if (file.size > MAX_PHOTO_SIZE) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Image size cannot exceed 15MB.', life: 2400 })
    return
  }

  loading.photo = true
  try {
    const response = await uploadFile(file)
    // Normalize upload response shape
    const url = response?.data?.url || response?.url || ''
    if (url) {
      formData.value.photoUrl = url
      toast.add({ severity: 'success', summary: 'Uploaded', detail: 'Photo has been updated.', life: 2400 })
    } else {
      throw new Error('Image URL not found')
    }
  } catch (error) {
    toast.add({ severity: 'error', summary: 'Upload failed', detail: parseError(error), life: 3200 })
  } finally {
    loading.photo = false
    // Reset input so the same file can trigger change
    if (event.target) {
      event.target.value = ''
    }
  }
}

const scrollToForm = () => {
  const el = document.getElementById('scan-form-section')
  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

const callNumber = (phone) => {
  if (!phone) return
  window.location.href = `tel:${phone}`
}

const sendEmail = (email) => {
  if (!email) return
  window.location.href = `mailto:${email}`
}

const copyInfo = async (value, label = 'info') => {
  const content = value?.toString().trim()
  if (!content) {
    toast.add({ severity: 'info', summary: 'Notice', detail: `Nothing to copy for ${label}.`, life: 2200 })
    return
  }
  try {
    if (navigator?.clipboard?.writeText) {
      await navigator.clipboard.writeText(content)
    } else {
      const textarea = document.createElement('textarea')
      textarea.value = content
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.focus()
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
    }
    toast.add({ severity: 'success', summary: 'Copied', detail: `${label} copied to clipboard.`, life: 2000 })
  } catch (error) {
    console.error('Copy failed', error)
    toast.add({ severity: 'error', summary: 'Copy failed', detail: 'Please copy manually.', life: 2200 })
  }
}

const resetPageState = () => {
  qrDetail.value = null
  profile.value = null
  maintenanceCode.value = ''
  maintenancePassed.value = false
  showMaintenancePanel.value = false
  showMaintenanceDialog.value = false
  viewMaintenanceCode.value = ''
  isEditing.value = false
  infoStatus.state = qrCode.value ? 'loading' : 'idle'
  infoStatus.message = ''
  resetForm()
}

watch(
  () => route.params.qrCode,
  (value) => {
    const normalized = value?.toString().trim() || ''
    queryInput.value = normalized
    qrCode.value = normalized
    resetPageState()
    if (normalized) {
      fetchQrDetails()
    }
  },
  { immediate: true }
)

watch([qrType, profile], () => {
  resetForm(profile.value)
  setDocumentTitle()
})

// Auto open verification dialog on first fill
watch(isFirstFill, (value) => {
  if (value && !maintenancePassed.value) {
    showMaintenanceDialog.value = true
  }
})

const handleOpenLocationDialog = () => {
  showLocationDialog.value = true
}

const handleSaveLocation = (location) => {
  formData.value.location = location
  toast.add({ severity: 'success', summary: 'Saved', detail: 'Address selected.', life: 2400 })
}

const handleOpenLocationView = () => {
  showLocationViewDialog.value = true
}

const openGoogleMaps = () => {
  const location = profile.value?.location
  if (!location) return

  // Try to parse coordinate format (lat, lng)
  const coordsMatch = location.match(/(-?\d+\.?\d*),\s*(-?\d+\.?\d*)/)
  if (coordsMatch) {
    const lat = coordsMatch[1]
    const lng = coordsMatch[2]
    // Open Google Maps with coordinates
    window.open(`https://www.google.com/maps?q=${lat},${lng}`, '_blank')
  } else {
    // Otherwise search by address string
    window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(location)}`, '_blank')
  }
}

const handleOpenScanRecords = () => {
  if (!qrCode.value) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter a QR code first.', life: 2400 })
    return
  }
  showScanRecordsMaintenanceDialog.value = true
}

const fetchScanRecords = async (maintenanceCode) => {
  if (!qrCode.value || !maintenanceCode) return
  loadingScanRecords.value = true
  try {
    const data = await fetchRecentScanRecordsApi(qrCode.value, maintenanceCode)
    scanRecords.value = data
    verifiedMaintenanceCode.value = maintenanceCode
    showScanRecordsMaintenanceDialog.value = false
    showScanRecordsDialog.value = true
    scanRecordsMaintenanceCode.value = ''
  } catch (error) {
    toast.add({ severity: 'error', summary: 'Failed', detail: parseError(error), life: 3200 })
    scanRecords.value = null
  } finally {
    loadingScanRecords.value = false
  }
}

const handleVerifyScanRecordsMaintenance = async () => {
  if (!qrCode.value || !scanRecordsMaintenanceCode.value) {
    toast.add({ severity: 'warn', summary: 'Notice', detail: 'Please enter the maintenance code.', life: 2400 })
    return
  }
  await fetchScanRecords(scanRecordsMaintenanceCode.value)
}

const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatRemark = (remark) => {
  if (!remark) return 'No extra details'
  // 如果是字符串，尝试解析
  if (typeof remark === 'string') {
    if (!remark.trim()) return 'No extra details'
    try {
      const parsed = JSON.parse(remark)
      if (typeof parsed === 'object' && parsed !== null) {
        return Object.values(parsed).filter(v => v && v.trim()).join('\n')
      }
      return remark
    } catch (e) {
      return remark
    }
  }
  // 如果是对象，提取所有值
  if (typeof remark === 'object' && remark !== null) {
    const values = Object.values(remark).filter(v => v && v.trim())
    return values.length > 0 ? values.join('\n') : 'No extra details'
  }
  return 'No extra details'
}

const parseRemarkToArray = (remark) => {
  if (!remark) return []
  // 如果是字符串，尝试解析
  if (typeof remark === 'string') {
    if (!remark.trim()) return []
    try {
      const parsed = JSON.parse(remark)
      if (typeof parsed === 'object' && parsed !== null) {
        // 按索引排序，提取所有非空值
        return Object.entries(parsed)
          .sort(([a], [b]) => parseInt(a) - parseInt(b))
          .map(([_, value]) => value)
          .filter(v => v && v.trim())
      }
      return [remark]
    } catch (e) {
      return [remark]
    }
  }
  // 如果是对象，提取所有值并按索引排序
  if (typeof remark === 'object' && remark !== null) {
    return Object.entries(remark)
      .sort(([a], [b]) => parseInt(a) - parseInt(b))
      .map(([_, value]) => value)
      .filter(v => v && v.trim())
  }
  return []
}

const getRemarkIndexes = () => {
  if (!formData.value.remark || typeof formData.value.remark !== 'object') {
    // 如果 remark 不存在或不是对象，初始化它
    formData.value.remark = { '1': '' }
    return [1]
  }
  const keys = Object.keys(formData.value.remark)
  if (keys.length === 0) {
    // 如果对象为空，初始化一个字段
    formData.value.remark = { '1': '' }
    return [1]
  }
  // 获取所有已存在的索引，并确保至少有一个
  const indexes = keys.map(k => parseInt(k) || 0).filter(k => k > 0).sort((a, b) => a - b)
  if (indexes.length === 0) {
    formData.value.remark = { '1': '' }
    return [1]
  }
  return indexes
}

const getRemarkFieldCount = () => {
  return getRemarkIndexes().length
}

const addRemarkField = () => {
  if (!formData.value.remark || typeof formData.value.remark !== 'object') {
    formData.value.remark = { '1': '' }
  }
  const currentIndexes = getRemarkIndexes()
  if (currentIndexes.length < 4) {
    const nextIndex = currentIndexes.length + 1
    // 确保使用 Vue 的响应式更新
    formData.value.remark = {
      ...formData.value.remark,
      [nextIndex.toString()]: ''
    }
  }
}

const removeRemarkField = (index) => {
  if (!formData.value.remark || typeof formData.value.remark !== 'object') {
    return
  }
  const indexes = getRemarkIndexes()
  if (indexes.length <= 1) {
    // 至少保留一个空字段
    formData.value.remark = { '1': '' }
    return
  }
  // 删除指定索引
  const newRemark = { ...formData.value.remark }
  delete newRemark[index.toString()]
  // 重新整理索引，确保从1开始连续
  const entries = Object.entries(newRemark)
    .map(([_, value], idx) => [(idx + 1).toString(), value || ''])
  formData.value.remark = Object.fromEntries(entries)
}

const openRecordLocation = (record) => {
  if (record.latitude && record.longitude) {
    window.open(`https://www.google.com/maps?q=${record.latitude},${record.longitude}`, '_blank')
  } else if (record.address) {
    window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(record.address)}`, '_blank')
  }
}

onMounted(() => {
  if (!qrCode.value) {
    setDocumentTitle()
  }
})
</script>

<template>
  <div class="scan-page min-h-screen bg-slate-950 text-slate-100">
    <div class="relative isolate px-4 py-10 sm:px-6 lg:px-8">
      <div
        class="pointer-events-none absolute inset-x-0 top-0 -z-10 h-96 bg-gradient-to-br from-cyan-500/20 via-indigo-500/10 to-transparent blur-3xl" />
      <div class="mx-auto max-w-6xl space-y-8">
        <header class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p class="text-xs uppercase tracking-[0.4em] text-cyan-200">Qr emergency link</p>
            <h1 class="mt-2 text-3xl font-semibold text-white sm:text-4xl">
              {{ heroTitle }}
            </h1>
          </div>
        </header>

        <section v-if="!qrCode"
          class="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-xl shadow-cyan-500/10 backdrop-blur">
          <div class="flex items-start gap-4">
            <div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-cyan-500/20">
              <i class="pi pi-qrcode text-2xl text-cyan-300" />
            </div>
            <div class="flex-1">
              <p class="text-lg font-semibold text-white">Welcome to the Emergency QR system</p>
              <p class="mt-2 text-sm text-slate-300">
                Scan the QR code or enter its value below to continue.
              </p>
            </div>
          </div>
          <div class="mt-6 flex flex-col gap-4 sm:flex-row sm:items-start">
            <div class="flex-1 space-y-2">
              <input v-model="queryInput" type="text" placeholder="Enter QR code"
                class="w-full rounded-2xl border border-white/20 bg-white/5 px-5 py-3.5 text-base text-white placeholder:text-slate-400 backdrop-blur-sm transition-all duration-200 focus:border-cyan-400 focus:bg-white/10 focus:outline-none focus:ring-2 focus:ring-cyan-400/30"
                @keyup.enter="handleQrSubmit" />
              <div class="flex items-center gap-2 px-1">
                <svg class="h-4 w-4 flex-shrink-0 text-cyan-400/70" fill="none" viewBox="0 0 24 24"
                  stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span class="text-sm text-slate-400/90">Example: <span
                    class="font-mono text-slate-300/80">QRMIH76J350CE2CF6150A51F4E</span></span>
              </div>
            </div>
            <button type="button"
              class="rounded-2xl bg-gradient-to-r from-cyan-400 to-blue-400 px-8 py-3.5 text-base font-semibold text-slate-900 shadow-lg shadow-cyan-500/30 transition-all duration-200 hover:scale-105 hover:shadow-xl hover:shadow-cyan-500/40 sm:whitespace-nowrap"
              @click="handleQrSubmit">
              View info
            </button>
          </div>
        </section>

        <section v-else class="space-y-6">
          <div v-if="infoStatus.state === 'error'" class="rounded-3xl border border-red-500/40 bg-red-500/10 p-5">
            <p class="text-sm text-red-100">{{ infoStatus.message }}</p>
            <p class="mt-2 text-xs text-red-200">Please double-check the QR code or reach out for assistance.</p>
          </div>

          <div v-if="infoStatus.state === 'notVisible'" class="rounded-3xl border border-amber-500/40 bg-amber-500/10 p-6">
            <div class="flex items-start gap-4">
              <div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-amber-500/20 flex-shrink-0">
                <i class="pi pi-eye-slash text-2xl text-amber-300" />
              </div>
              <div class="flex-1">
                <p class="text-lg font-semibold text-amber-100">{{ infoStatus.message }}</p>
                <p class="mt-2 text-sm text-amber-200">This QR code information has been set to invisible and cannot be viewed.</p>
              </div>
            </div>
          </div>

          <div v-if="infoStatus.state === 'notVisible'" class="rounded-3xl border border-cyan-500/40 bg-cyan-500/10 p-6">
            <div class="flex items-start gap-4">
              <div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-cyan-500/20 flex-shrink-0">
                <i class="pi pi-key text-2xl text-cyan-300" />
              </div>
              <div class="flex-1">
                <p class="text-lg font-semibold text-cyan-100">View with maintenance code</p>
                <p class="mt-2 text-sm text-cyan-200">Enter the maintenance code to view complete information.</p>
                <div class="mt-4 flex flex-col gap-3 sm:flex-row sm:items-end">
                  <div class="flex-1">
                    <label class="mb-1.5 block text-xs font-medium text-cyan-100">Maintenance code</label>
                    <input v-model="viewMaintenanceCode" type="text" maxlength="8"
                      class="w-full rounded-xl border border-cyan-400/40 bg-white/10 px-4 py-2.5 text-sm text-white placeholder:text-cyan-300/60 focus:border-cyan-300 focus:bg-white/15 focus:outline-none focus:ring-2 focus:ring-cyan-300/30"
                      placeholder="Enter maintenance code" @keyup.enter="handleVerifyMaintenanceForView" />
                  </div>
                  <button type="button"
                    class="rounded-xl bg-cyan-500 px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-cyan-600 disabled:opacity-50 sm:whitespace-nowrap"
                    :disabled="loadingViewVerification || !viewMaintenanceCode" @click="handleVerifyMaintenanceForView">
                    <i v-if="loadingViewVerification" class="pi pi-spin pi-spinner mr-2" />
                    <i v-else class="pi pi-check mr-2" />
                    {{ loadingViewVerification ? 'Verifying...' : 'Verify & View' }}
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div v-if="loading.info" class="rounded-3xl border border-white/10 bg-white/5 p-6 text-base text-white">
            Loading QR information...
          </div>

          <!-- Only render details after maintenance verification -->
          <div v-if="infoStatus.state === 'ready' && qrDetail && (maintenancePassed || hasProfile)" class="space-y-6">
            <!-- Link type display -->
            <div v-if="isLink && hasProfile && !isEditing"
              class="rounded-3xl border border-white/10 bg-white text-slate-900 shadow-2xl shadow-cyan-500/10 relative">
              <div class="space-y-6 p-6">
                <!-- Jump URL card -->
                <div
                  class="rounded-2xl border border-slate-200 bg-gradient-to-br from-slate-50 to-white p-5 transition hover:shadow-md">
                  <div class="flex items-center gap-3">
                    <div
                      class="flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 shadow-inner">
                      <i class="pi pi-link text-lg text-emerald-600" />
                    </div>
                    <p class="text-[11px] font-semibold uppercase tracking-[0.35em] text-slate-500">
                      JUMP URL
                    </p>
                  </div>
                  <div class="mt-3">
                    <p v-if="profile.jumpUrl"
                      class="cursor-pointer text-lg font-semibold text-slate-800 break-all mb-4"
                      title="Click to copy link" @click="copyInfo(profile.jumpUrl, 'Link')">
                      {{ profile.jumpUrl }}
                    </p>
                    <p v-else class="text-sm text-slate-500 mb-4">Not set</p>
                    <button v-if="profile.jumpUrl" type="button"
                      class="inline-flex w-full items-center justify-center gap-1.5 rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm font-medium text-emerald-700 transition hover:bg-emerald-100"
                      @click="() => window.open(profile.jumpUrl, '_blank')">
                      <i class="pi pi-external-link" /> Open link
                    </button>
                  </div>
                </div>

                <!-- Remark card -->
                <div v-if="profile.remark"
                  class="rounded-2xl border border-cyan-200/50 bg-gradient-to-br from-cyan-50/80 to-white p-5">
                  <div class="flex items-center gap-2">
                    <div class="flex h-8 w-8 items-center justify-center rounded-full bg-cyan-100">
                      <i class="pi pi-info-circle text-sm text-cyan-600" />
                    </div>
                    <p class="text-xs font-medium uppercase tracking-wider text-slate-500">REMARK</p>
                  </div>
                  <div class="mt-3">
                    <p class="whitespace-pre-wrap text-sm leading-relaxed text-slate-700">
                      {{ profile.remark }}
                    </p>
                  </div>
                </div>

                <!-- Action buttons -->
                <div v-if="!isEditing" class="pt-4 space-y-3">
                  <button type="button"
                    class="w-full flex items-center justify-center gap-2 rounded-xl border border-slate-300 px-5 py-2.5 text-sm font-medium text-yellow-700 transition-all duration-200 hover:border-slate-400 hover:shadow-md"
                    @click="handleOpenScanRecords">
                    <i class="pi pi-history text-xs" />
                    SCAN RECORDS
                  </button>
                  <button type="button"
                    class="w-full flex items-center justify-center gap-2 rounded-xl border border-slate-300 bg-white px-5 py-2.5 text-sm font-medium text-slate-700 transition-all duration-200 hover:border-slate-400 hover:bg-slate-50 hover:shadow-md"
                    @click="showMaintenanceDialog = true">
                    <i class="pi pi-pencil text-xs" />
                    EDIT INFORMATION
                  </button>
                </div>
              </div>
            </div>

            <!-- Other types display -->
            <div v-else-if="hasProfile && !isEditing && !isLink"
              class="rounded-3xl border border-white/10 bg-white text-slate-900 shadow-2xl shadow-cyan-500/10 relative">
              <template v-if="hasProfile">
                <div class="space-y-6 p-6">
                  <div class="flex flex-col items-center gap-4">
                    <div class="relative w-full max-w-md overflow-hidden rounded-2xl bg-slate-100 ring-2 ring-slate-200"
                      style="aspect-ratio: 1/1;">
                      <img v-if="profile?.photoUrl" :src="profile.photoUrl" alt="profile"
                        class="h-full w-full object-cover transition-transform duration-300 hover:scale-105"
                        @error="(e) => e.target.style.display = 'none'" />
                      <div v-else class="flex h-full w-full flex-col items-center justify-center gap-2 text-slate-400">
                        <i class="pi pi-image text-4xl" />
                        <span class="text-sm">No photo</span>
                      </div>
                    </div>
                    <p class="text-xs uppercase tracking-[0.4em] text-slate-400">
                      {{ qrCode }}
                    </p>
                  </div>
                  <div class="space-y-4">
                    <div>
                      <p class="mt-1 text-sm text-slate-500">
                        {{ isPerson ? 'Emergency contact card' : isGoods ? 'Item information' : 'Pet information' }}
                      </p>
                      <p class="text-2xl font-semibold text-slate-900">
                        {{ profile?.name || 'Unnamed' }}
                      </p>
                    </div>
                    <div
                      class="rounded-2xl border border-slate-200 bg-gradient-to-br from-slate-50 to-white p-5 transition hover:shadow-md">
                      <div class="flex items-center gap-3">
                        <div
                          class="flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 shadow-inner">
                          <i class="pi pi-user text-lg text-emerald-600" />
                        </div>
                        <p class="text-[11px] font-semibold uppercase tracking-[0.35em] text-slate-500">{{ isPerson ?
                          'EMERGENCY CONTACT' : 'CONTACT' }}</p>
                      </div>
                      <p class="mt-3 cursor-pointer text-3xl font-semibold leading-tight text-slate-800"
                        title="Click to copy name"
                        @click="copyInfo(isPerson ? profile?.emergencyContactName : profile?.contactName, 'Name')">
                        {{ isPerson ? profile?.emergencyContactName || '-' : profile?.contactName || '-' }}
                      </p>
                      <div class="mt-4 space-y-3 text-sm text-slate-600">
                        <div class="flex items-center gap-3">
                          <i class="pi pi-phone text-lg text-slate-500" />
                          <div class="leading-tight cursor-pointer select-text text-slate-600"
                            title="Click to copy phone"
                            @click="copyInfo(isPerson ? profile?.emergencyContactPhone : profile?.contactPhone, 'Phone')">
                            <p class="text-[10px] uppercase tracking-[0.4em] text-slate-400">PHONE</p>
                            <p class="text-base font-semibold text-slate-700">
                              {{ isPerson ? profile?.emergencyContactPhone || '-' : profile?.contactPhone || '-' }}
                            </p>
                          </div>
                        </div>
                        <div v-if="(isPerson ? profile?.emergencyContactEmail : profile?.contactEmail)"
                          class="flex items-center gap-3">
                          <i class="pi pi-envelope text-lg text-slate-500" />
                          <div class="leading-tight min-w-0 cursor-pointer select-text text-slate-600"
                            title="Click to copy email"
                            @click="copyInfo(isPerson ? profile?.emergencyContactEmail : profile?.contactEmail, 'Email')">
                            <p class="text-[10px] uppercase tracking-[0.4em] text-slate-400">EMAIL</p>
                            <p class="truncate text-base font-semibold text-slate-700">
                              {{ isPerson ? profile?.emergencyContactEmail : profile?.contactEmail }}
                            </p>
                          </div>
                        </div>
                        <div v-if="profile?.location" class="flex items-start gap-3">
                          <i class="pi pi-map-marker text-lg text-slate-500 mt-0.5 flex-shrink-0" />
                          <div class="leading-tight cursor-pointer select-text text-slate-600"
                            title="Click to copy address" @click="copyInfo(profile?.location, 'Address')">
                            <p class="text-[10px] uppercase tracking-[0.4em] text-slate-400">LOCATION</p>
                            <p class="flex-1 break-words whitespace-normal text-base font-medium text-slate-700">
                              {{ profile.location }}
                            </p>
                          </div>
                        </div>
                      </div>
                      <div class="mt-4 grid grid-cols-2 gap-2">
                        <button v-if="profile?.emergencyContactPhone || profile?.contactPhone" type="button"
                          class="inline-flex w-full items-center justify-center gap-1.5 rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-700 transition hover:bg-emerald-100"
                          @click="callNumber(isPerson ? profile?.emergencyContactPhone : profile?.contactPhone)">
                          <i class="pi pi-phone" /> Call
                        </button>
                        <button
                          v-if="(isPerson && profile?.emergencyContactEmail) || (!isPerson && profile?.contactEmail)"
                          type="button"
                          class="inline-flex w-full items-center justify-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 transition hover:bg-blue-100"
                          @click="sendEmail(isPerson ? profile?.emergencyContactEmail : profile?.contactEmail)">
                          <i class="pi pi-envelope" /> Email
                        </button>
                        <button v-if="profile?.location" type="button"
                          class="inline-flex w-full items-center justify-center gap-1.5 rounded-full border border-purple-200 bg-purple-50 px-3 py-1.5 text-xs font-medium text-purple-700 transition hover:bg-purple-100"
                          @click="handleOpenLocationView">
                          <i class="pi pi-map" /> Map
                        </button>
                        <button v-if="profile?.location" type="button"
                          class="inline-flex w-full items-center justify-center gap-1.5 rounded-full border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-medium text-red-700 transition hover:bg-red-100"
                          @click="openGoogleMaps">
                          <i class="pi pi-external-link" /> Google Maps
                        </button>
                      </div>
                    </div>
                    <div class="rounded-2xl border border-cyan-200/50 bg-gradient-to-br from-cyan-50/80 to-white p-5">
                      <div class="flex items-center gap-2">
                        <div class="flex h-8 w-8 items-center justify-center rounded-full bg-cyan-100">
                          <i class="pi pi-info-circle text-sm text-cyan-600" />
                        </div>
                        <p class="text-xs font-medium uppercase tracking-wider text-slate-500">{{ isPerson ? 'Additional notes' : isGoods ? 'Item notes' : 'Extra description' }}</p>
                      </div>
                      <div v-if="isPerson" class="mt-3">
                        <p class="whitespace-pre-wrap text-sm leading-relaxed text-slate-700">
                          {{ profile?.specialNote || 'No extra details' }}
                        </p>
                      </div>
                      <div v-else class="mt-3">
                        <div v-if="parseRemarkToArray(profile?.remark).length === 0" class="text-sm text-slate-500">
                          No extra details
                        </div>
                        <template v-else>
                          <div
                            v-for="(remarkItem, index) in parseRemarkToArray(profile?.remark)"
                            :key="index">
                            <p class="text-sm leading-relaxed text-slate-700 whitespace-pre-wrap">
                              {{ remarkItem }}
                            </p>
                            <div v-if="index < parseRemarkToArray(profile?.remark).length - 1" class="my-3 border-t border-cyan-200/50"></div>
                          </div>
                        </template>
                      </div>
                    </div>
                    <!-- Action buttons -->
                    <div v-if="!isEditing" class="pt-4 space-y-3">
                      <button type="button"
                        class="w-full flex items-center justify-center gap-2 rounded-xl border border-slate-300 px-5 py-2.5 text-sm font-medium text-yellow-700 transition-all duration-200 hover:border-slate-400 hover:shadow-md"
                        @click="handleOpenScanRecords">
                        <i class="pi pi-history text-xs" />
                        SCAN RECORDS
                      </button>
                      <button type="button"
                        class="w-full flex items-center justify-center gap-2 rounded-xl border border-slate-300 bg-white px-5 py-2.5 text-sm font-medium text-slate-700 transition-all duration-200 hover:border-slate-400 hover:bg-slate-50 hover:shadow-md"
                        @click="showMaintenanceDialog = true">
                        <i class="pi pi-pencil text-xs" />
                        EDIT INFORMAION
                      </button>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </section>

        <section v-if="qrCode && maintenancePassed" id="scan-form-section"
          class="rounded-3xl border border-white/10 bg-white p-6 text-slate-900 shadow-2xl shadow-cyan-500/10">
          <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p class="text-xs uppercase tracking-[0.3em] text-slate-400">{{ isLink ? 'Link setup' : 'Profile setup' }}</p>
              <h2 class="mt-1 text-2xl font-semibold text-slate-900">
                {{ isLink ? (hasProfile ? 'Update link' : 'First-time setup') : (hasProfile ? 'Update profile' : 'First-time setup') }}
              </h2>
            </div>
            <p class="text-sm text-slate-500">
              QR Code: <span class="font-mono text-slate-700">{{ qrCode }}</span>
            </p>
          </div>

          <div v-if="isFirstFill" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
            <div class="flex items-start gap-3">
              <i class="pi pi-info-circle text-emerald-600" />
              <div class="flex-1 text-sm text-emerald-700">
                <p class="font-semibold">First-time tip</p>
                <p class="mt-1">
                  This is the first record for this QR code. Once submitted, it becomes active. Keep the maintenance
                  code
                  safe for future edits.
                </p>
              </div>
            </div>
          </div>
          <div v-else class="mt-4 rounded-2xl border border-cyan-200 bg-cyan-50 p-4">
            <div class="flex items-start gap-3">
              <i class="pi pi-check-circle text-cyan-600" />
              <div class="flex-1 text-sm text-cyan-700">
                <p class="font-semibold">Edit mode</p>
                <p class="mt-1">
                  Maintenance code verified. You can now edit the profile—remember to save your changes.
                </p>
              </div>
            </div>
          </div>

          <form class="mt-6 space-y-6" @submit.prevent="handleSaveProfile">
            <!-- Link type form -->
            <template v-if="isLink">
              <div class="space-y-2">
                <label class="block text-sm font-medium text-slate-700">
                  Jump URL
                </label>
                <div class="flex gap-2">
                  <input v-model="formData.jumpUrl" type="url" placeholder="https://example.com"
                    maxlength="2000"
                    class="flex-1 rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm text-slate-900 placeholder:text-slate-400 transition-all duration-200 focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20" />
                  <button v-if="isFirstFill" type="button"
                    class="flex-shrink-0 rounded-lg border border-cyan-500 bg-cyan-500 px-3 py-2 text-xs font-medium text-white shadow-sm transition-all duration-200 hover:bg-cyan-600 hover:border-cyan-600 hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-cyan-500 disabled:hover:shadow-sm whitespace-nowrap"
                    :disabled="!formData.jumpUrl?.trim()"
                    @click="testJumpUrl">
                    <i class="pi pi-check-circle mr-1 text-xs" />
                    Validate
                  </button>
                </div>
                <p class="text-xs text-slate-500">
                  Optional, max 2000 characters, must be a valid URL (must start with http:// or https://)
                  <span v-if="isFirstFill" class="text-cyan-600"> • Click "Validate" to verify the URL format</span>
                </p>
              </div>

              <div class="space-y-2">
                <label class="block text-sm font-medium text-slate-700">
                  Remark
                </label>
                <textarea v-model="formData.linkRemark" placeholder="Enter remark information" maxlength="500" rows="4"
                  class="w-full rounded-2xl border border-slate-300 bg-white px-5 py-3.5 text-base text-slate-900 placeholder:text-slate-400 transition-all duration-200 focus:border-cyan-400 focus:outline-none focus:ring-2 focus:ring-cyan-400/30 resize-none"></textarea>
                <p class="text-xs text-slate-500">
                  Optional, max 500 characters, current: {{ formData.linkRemark.length }}/500
                </p>
              </div>
            </template>

            <!-- Other types form -->
            <template v-else>
            <div class="space-y-4">
              <div>
                <p class="text-sm font-medium text-slate-700">Display photo / item image</p>
                <p class="mt-1 text-xs text-slate-500">Recommended 640×640+, supports JPG/PNG, up to 15MB.</p>
              </div>
              <div
                class="relative w-full max-w-md mx-auto overflow-hidden rounded-2xl bg-slate-100 ring-2 ring-slate-200"
                style="aspect-ratio: 1/1;">
                <img v-if="formData.photoUrl && !loading.photo" :src="formData.photoUrl" alt="profile"
                  class="h-full w-full object-cover transition-opacity duration-200" @error="handleImageError" />
                <div v-if="loading.photo" class="flex h-full w-full items-center justify-center">
                  <i class="pi pi-spin pi-spinner text-4xl text-slate-400" />
                </div>
                <div v-else-if="!formData.photoUrl"
                  class="flex h-full w-full flex-col items-center justify-center gap-2 text-slate-400">
                  <i class="pi pi-image text-5xl" />
                  <span class="text-sm">No image</span>
                </div>
              </div>
              <input ref="photoInputRef" type="file" accept="image/jpeg,image/jpg,image/png,image/webp" class="hidden"
                @change="handlePhotoChange" />
              <div class="flex justify-center gap-3">
                <button type="button"
                  class="rounded-full border border-slate-300 bg-white px-6 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:opacity-50"
                  :disabled="loading.photo" @click="triggerPhotoPicker">
                  <i class="pi mr-2" :class="loading.photo ? 'pi-spin pi-spinner' : 'pi-upload'" />
                  {{ loading.photo ? 'Uploading...' : 'Upload image' }}
                </button>
                <button v-if="formData.photoUrl" type="button"
                  class="rounded-full border border-red-200 bg-red-50 px-4 py-2.5 text-sm font-medium text-red-600 transition hover:bg-red-100"
                  @click="formData.photoUrl = ''">
                  <i class="pi pi-times mr-1" />
                  Clear image
                </button>
              </div>
            </div>

            <div class="grid gap-4 md:grid-cols-2">
              <label class="space-y-2 text-sm">
                <span class="text-slate-500">{{ isPerson ? 'Name' : isGoods ? 'Item name' : 'Pet name' }}</span>
                <input v-model="formData.name" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3"
                  :placeholder="isPerson ? 'e.g. John Doe' : isGoods ? 'e.g. MacBook Pro' : 'e.g. Snowy'" required />
              </label>

              <label v-if="isPerson" class="space-y-2 text-sm">
                <span class="text-slate-500">Gender</span>
                <div class="flex gap-2">
                  <button v-for="option in [
                    { label: 'Male', value: 'male' },
                    { label: 'Female', value: 'female' },
                    { label: 'Prefer not to say', value: 'unknown' }
                  ]" :key="option.value" type="button" class="flex-1 rounded-2xl border px-4 py-3 text-sm"
                    :class="formData.gender === option.value ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 text-slate-500'"
                    @click="formData.gender = option.value">
                    {{ option.label }}
                  </button>
                </div>
              </label>
            </div>

            <div v-if="isPerson" class="grid gap-4 md:grid-cols-2">
              <label class="space-y-2 text-sm">
                <span class="text-slate-500">Owner phone</span>
                <input v-model="formData.phone" type="tel" class="w-full rounded-2xl border border-slate-200 px-4 py-3"
                  required />
              </label>

              <label class="space-y-2 text-sm">
                <span class="text-slate-500">Emergency contact name</span>
                <input v-model="formData.emergencyContactName" type="text"
                  class="w-full rounded-2xl border border-slate-200 px-4 py-3" required />
              </label>

              <label class="space-y-2 text-sm">
                <span class="text-slate-500">Emergency contact phone</span>
                <input v-model="formData.emergencyContactPhone" type="tel"
                  class="w-full rounded-2xl border border-slate-200 px-4 py-3" required />
              </label>

              <label class="space-y-2 text-sm md:col-span-2">
                <span class="text-slate-500">Emergency contact email</span>
                <input v-model="formData.emergencyContactEmail" type="email"
                  class="w-full rounded-2xl border border-slate-200 px-4 py-3" placeholder="Optional" />
              </label>

              <label class="space-y-2 text-sm md:col-span-2">
                <span class="text-slate-500">Address</span>
                <div class="flex gap-2">
                  <input v-model="formData.location" type="text" readonly
                    class="flex-1 rounded-2xl border border-slate-200 px-4 py-3 bg-slate-50 cursor-pointer"
                    placeholder="Click to select address" @click="handleOpenLocationDialog" />
                  <button type="button"
                    class="rounded-2xl border border-slate-300 bg-white px-6 py-3 text-sm font-medium text-slate-700 transition hover:bg-slate-50 whitespace-nowrap"
                    @click="handleOpenLocationDialog">
                    <i class="pi pi-map-marker mr-2" />
                    Select address
                  </button>
                </div>
              </label>
            </div>

            <div v-else class="grid gap-4 md:grid-cols-2">
              <label class="space-y-2 text-sm">
                <span class="text-slate-500">Contact name</span>
                <input v-model="formData.contactName" type="text"
                  class="w-full rounded-2xl border border-slate-200 px-4 py-3" required />
              </label>

              <label class="space-y-2 text-sm">
                <span class="text-slate-500">Contact phone</span>
                <input v-model="formData.contactPhone" type="tel"
                  class="w-full rounded-2xl border border-slate-200 px-4 py-3" required />
              </label>

              <label class="space-y-2 text-sm md:col-span-2">
                <span class="text-slate-500">Contact email</span>
                <input v-model="formData.contactEmail" type="email"
                  class="w-full rounded-2xl border border-slate-200 px-4 py-3" placeholder="Optional" />
              </label>

              <label class="space-y-2 text-sm md:col-span-2">
                <span class="text-slate-500">Contact address</span>
                <div class="flex gap-2">
                  <input v-model="formData.location" type="text" readonly
                    class="flex-1 rounded-2xl border border-slate-200 px-4 py-3 bg-slate-50 cursor-pointer"
                    placeholder="Click to select address" @click="handleOpenLocationDialog" />
                  <button type="button"
                    class="rounded-2xl border border-slate-300 bg-white px-6 py-3 text-sm font-medium text-slate-700 transition hover:bg-slate-50 whitespace-nowrap"
                    @click="handleOpenLocationDialog">
                    <i class="pi pi-map-marker mr-2" />
                    Select address
                  </button>
                </div>
              </label>
            </div>

            <label v-if="isPerson" class="block space-y-2 text-sm">
              <span class="text-slate-500">Additional notes / health tips</span>
              <textarea v-model="formData.specialNote" rows="4"
                class="w-full rounded-2xl border border-slate-200 px-4 py-3"
                placeholder="e.g. allergies, medical needs, carried items" />
            </label>
            <div v-else class="space-y-3">
              <label class="block text-sm">
                <span class="text-slate-500">{{ isGoods ? 'Item notes' : 'Extra remarks' }}</span>
                <p class="mt-1 text-xs text-slate-400">You can add up to 4 remarks</p>
              </label>
              <div class="space-y-3">
                <div v-for="index in getRemarkIndexes()" :key="index" class="flex gap-2 items-start">
                  <div class="flex-1">
                    <textarea
                      v-model="formData.remark[index.toString()]"
                      rows="3"
                      class="w-full rounded-2xl border border-slate-200 px-4 py-3 resize-y min-h-[3rem]"
                      :placeholder="isGoods ? `Item note ${index} (e.g. item features, usage notes)` : `Remark ${index} (e.g. pet habits, health info)`" />
                  </div>
                  <button
                    v-if="index > 1 || (index === 1 && getRemarkIndexes().length > 1)"
                    type="button"
                    class="mt-1 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm font-medium text-red-600 transition hover:bg-red-100 flex-shrink-0"
                    @click="removeRemarkField(index)">
                    <i class="pi pi-times" />
                  </button>
                </div>
              </div>
              <button
                v-if="getRemarkIndexes().length < 4"
                type="button"
                class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
                @click="addRemarkField">
                <i class="pi pi-plus mr-2" />
                Add remark
              </button>
            </div>

            <div class="rounded-2xl border border-slate-200 bg-slate-50 p-5">
              <div class="flex items-center justify-between">
                <div class="flex-1">
                  <p class="text-sm font-medium text-slate-700">Visibility</p>
                  <p class="mt-1 text-xs text-slate-500">When disabled, others will not be able to view information when scanning this QR code</p>
                </div>
                <label class="relative inline-flex items-center cursor-pointer">
                  <input v-model="formData.isVisible" type="checkbox" class="sr-only peer" />
                  <div class="w-11 h-6 bg-slate-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-cyan-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-cyan-600"></div>
                </label>
              </div>
            </div>
            </template>

            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <p class="text-sm text-slate-500">
                Submitted data will sync to the public scan page.
              </p>
              <button type="submit"
                class="rounded-full bg-slate-900 px-8 py-3 text-sm font-semibold text-white hover:bg-slate-800"
                :disabled="loading.saving">
                {{ loading.saving ? 'Saving...' : (isLink ? (hasProfile ? 'Save changes' : 'Submit link') : (hasProfile ? 'Save changes' : 'Submit profile')) }}
              </button>
            </div>
          </form>
        </section>

        <footer class="mt-8 border-t border-white/10 pt-6 text-center">
          <p class="text-xs text-slate-400">
            Data is used solely for emergency contact scenarios. Uploading means you consent to display it when scanned.
          </p>
          <p class="mt-2 text-xs text-slate-500">
            <i class="pi pi-shield text-cyan-400" /> Your privacy stays protected
          </p>
        </footer>
      </div>
    </div>

    <!-- Location picker dialog -->
    <LocationPicker v-model="showLocationDialog" :initial-location="formData.location" @save="handleSaveLocation" />

    <!-- Location preview dialog (read-only) -->
    <LocationPicker v-model="showLocationViewDialog" :initial-location="profile?.location" :closable="true"
      :readonly="true" />

    <!-- Scan records dialog -->
    <Dialog v-model:visible="showScanRecordsDialog" modal :closable="true" :closeOnEscape="true"
      :dismissableMask="true" :style="{ width: '90vw', maxWidth: '800px' }" :draggable="false">
      <template #header>
        <div class="flex items-center gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-full bg-cyan-100">
            <i class="pi pi-history text-lg text-cyan-600" />
          </div>
          <div>
            <h3 class="text-lg font-semibold text-slate-900">Recent Scan Records</h3>
            <p class="text-sm text-slate-500">
              QR Code: <span class="font-mono">{{ qrCode }}</span>
            </p>
          </div>
        </div>
      </template>

      <div class="space-y-4 py-4">
        <div v-if="loadingScanRecords" class="flex items-center justify-center py-8">
          <i class="pi pi-spin pi-spinner text-3xl text-slate-400" />
          <span class="ml-3 text-slate-600">Loading...</span>
        </div>

        <div v-else-if="scanRecords">

          <div v-if="scanRecords.records && scanRecords.records.length > 0" class="space-y-3 max-h-[60vh] overflow-y-auto">
            <div v-for="record in scanRecords.records" :key="record.id"
              class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm hover:shadow-md transition-shadow">
              <div class="flex items-start justify-between gap-4">
                <div class="flex-1 space-y-2">
                  <div class="flex items-center gap-2">
                    <i class="pi pi-clock text-sm text-slate-500" />
                    <span class="text-sm font-medium text-slate-700">Scan Time</span>
                    <span class="text-sm text-slate-600">{{ formatDateTime(record.scanTime) }}</span>
                  </div>

                  <div v-if="record.address" class="flex items-start gap-2">
                    <i class="pi pi-map-marker text-sm text-slate-500 mt-0.5" />
                    <div class="flex-1">
                      <span class="text-sm font-medium text-slate-700">Address</span>
                      <p class="text-sm text-slate-600 break-words">{{ record.address }}</p>
                    </div>
                    <button v-if="record.latitude && record.longitude" type="button"
                      class="ml-2 flex-shrink-0 rounded-lg border border-cyan-200 bg-cyan-50 px-2 py-1 text-xs text-cyan-700 hover:bg-cyan-100 transition"
                      @click="openRecordLocation(record)">
                      <i class="pi pi-external-link mr-1" />
                      Map
                    </button>
                  </div>

                  <div v-if="record.latitude && record.longitude" class="flex items-center gap-2">
                    <i class="pi pi-globe text-sm text-slate-500" />
                    <span class="text-sm text-slate-600">
                      Coordinates: {{ record.latitude }}, {{ record.longitude }}
                    </span>
                  </div>

                  <div v-if="record.ipAddress" class="flex items-center gap-2">
                    <i class="pi pi-desktop text-sm text-slate-500" />
                    <span class="text-sm text-slate-600">IP: {{ record.ipAddress }}</span>
                  </div>

                  <div v-if="record.userAgent" class="flex items-start gap-2">
                    <i class="pi pi-browser text-sm text-slate-500 mt-0.5" />
                    <div class="flex-1">
                      <span class="text-sm font-medium text-slate-700">Device Info</span>
                      <p class="text-xs text-slate-500 break-words mt-0.5">{{ record.userAgent }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="rounded-xl border border-slate-200 bg-slate-50 p-8 text-center">
            <i class="pi pi-inbox text-4xl text-slate-400 mb-3" />
            <p class="text-sm text-slate-600">No scan records</p>
          </div>
        </div>

        <div v-else class="rounded-xl border border-red-200 bg-red-50 p-4">
          <div class="flex items-center gap-2">
            <i class="pi pi-exclamation-triangle text-red-600" />
            <span class="text-sm text-red-700">Failed to load, please try again later</span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-3">
          <button type="button"
            class="rounded-xl border border-slate-300 px-5 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
            @click="showScanRecordsDialog = false">
            Close
          </button>
          <button type="button"
            class="rounded-xl bg-cyan-600 px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-cyan-700 disabled:opacity-50"
            :disabled="loadingScanRecords || !verifiedMaintenanceCode" @click="fetchScanRecords(verifiedMaintenanceCode)">
            <i class="pi pi-refresh mr-2" :class="{ 'pi-spin': loadingScanRecords }" />
            Refresh
          </button>
        </div>
      </template>
    </Dialog>

    <!-- Scan records maintenance code dialog -->
    <Dialog v-model:visible="showScanRecordsMaintenanceDialog" modal :closable="true" :closeOnEscape="true"
      :dismissableMask="true" :style="{ width: '90vw', maxWidth: '450px' }" :draggable="false">
      <template #header>
        <div class="flex items-center gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-full bg-cyan-100">
            <i class="pi pi-lock text-lg text-cyan-600" />
          </div>
          <div>
            <h3 class="text-lg font-semibold text-slate-900">Verification required</h3>
            <p class="text-sm text-slate-500">
              Enter the maintenance code to view scan records.
            </p>
          </div>
        </div>
      </template>

      <div class="space-y-4 py-4">
        <div>
          <label class="mb-2 block text-sm font-medium text-slate-700">Maintenance code</label>
          <input v-model="scanRecordsMaintenanceCode" type="text" maxlength="8"
            class="w-full rounded-xl border border-slate-300 px-4 py-3 text-slate-900 placeholder:text-slate-400 focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
            placeholder="Enter the maintenance code" @keyup.enter="handleVerifyScanRecordsMaintenance" autofocus />
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-3">
          <button type="button"
            class="rounded-xl border border-slate-300 px-5 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
            @click="() => { showScanRecordsMaintenanceDialog = false; scanRecordsMaintenanceCode = '' }">
            Cancel
          </button>
          <button type="button"
            class="rounded-xl bg-cyan-600 px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-cyan-700 disabled:opacity-50"
            :disabled="loadingScanRecords || !scanRecordsMaintenanceCode" @click="handleVerifyScanRecordsMaintenance">
            {{ loadingScanRecords ? 'Verifying...' : 'Verify' }}
          </button>
        </div>
      </template>
    </Dialog>

    <!-- Maintenance code dialog -->
    <Dialog v-model:visible="showMaintenanceDialog" modal :closable="!isFirstFill" :closeOnEscape="!isFirstFill"
      :dismissableMask="!isFirstFill" :style="{ width: '90vw', maxWidth: '450px' }" :draggable="false">
      <template #header>
        <div class="flex items-center gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-full bg-cyan-100">
            <i class="pi pi-lock text-lg text-cyan-600" />
          </div>
          <div>
            <h3 class="text-lg font-semibold text-slate-900">
              {{ isFirstFill ? 'Verification required for first use' : 'Verification required to edit' }}
            </h3>
            <p class="text-sm text-slate-500">
              {{ isFirstFill ? 'Enter the maintenance code that came with the QR tag.' : 'Enter the maintenance code to unlock editing.' }}
            </p>
          </div>
        </div>
      </template>

      <div class="space-y-4 py-4">
        <div>
          <label class="mb-2 block text-sm font-medium text-slate-700">Maintenance code</label>
          <input v-model="maintenanceCode" type="text" maxlength="8"
            class="w-full rounded-xl border border-slate-300 px-4 py-3 text-slate-900 placeholder:text-slate-400 focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
            placeholder="Enter the maintenance code" @keyup.enter="handleVerifyMaintenance" autofocus />
        </div>
        <div v-if="isFirstFill" class="rounded-xl border border-emerald-200 bg-emerald-50 p-3">
          <div class="flex items-start gap-2">
            <i class="pi pi-info-circle text-sm text-emerald-600" />
            <p class="text-xs text-emerald-700">
              This is the first record for this QR code. Verify to begin entering details.
            </p>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end gap-3">
          <button v-if="!isFirstFill" type="button"
            class="rounded-xl border border-slate-300 px-5 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
            @click="showMaintenanceDialog = false">
            Cancel
          </button>
          <button type="button"
            class="rounded-xl bg-cyan-600 px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-cyan-700 disabled:opacity-50"
            :disabled="loading.verifying || !maintenanceCode" @click="handleVerifyMaintenance">
            {{ loading.verifying ? 'Verifying...' : 'Verify' }}
          </button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<style scoped>
.scan-page {
  background-image: radial-gradient(circle at 20% 20%, rgba(14, 165, 233, 0.12), transparent 45%),
    radial-gradient(circle at 80% 0%, rgba(129, 140, 248, 0.12), transparent 50%),
    linear-gradient(135deg, #020617, #030712);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
