<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { Button } from '@/components/ui/button'
import { useTabStore } from '@/pinia/tab'
import { useKvStore } from '@/pinia/kv'
import { useUiPrefsStore } from '@/pinia/uiPrefs'
import {
  BarChart3,
  Calculator,
  Check,
  Languages,
  X
} from 'lucide-vue-next'
import { getIndustryDisplayName, industryTypeList } from '@/sql'
import { initializeProjectFactorStates, initializeProjectScaleState } from '@/lib/projectWorkspace'
import {
  buildProjectUrl,
  DEFAULT_PROJECT_ID,
  FORCE_HOME_QUERY_KEY,
  NEW_PROJECT_QUERY_KEY,
  OPEN_PROJECT_DIALOG_QUERY_KEY,
  PROJECT_TAB_ID,
  QUICK_PROJECT_ID,
  QUICK_CONSULT_CATEGORY_FACTOR_KEY,
  QUICK_CONTRACT_FALLBACK_NAME,
  QUICK_CONTRACT_ID,
  QUICK_CONTRACT_META_KEY,
  QUICK_MAJOR_FACTOR_KEY,
  QUICK_PROJECT_INFO_KEY,
  readCurrentProjectId,
  writeProjectIdToUrl,
  setPendingHomeImportFile,
  writeWorkspaceMode
} from '@/lib/workspace'
import { createProject, listProjects, upsertProject } from '@/lib/projectRegistry'
import { createProjectKvAdapter } from '@/lib/projectKvStore'
import { collectActiveProjectSessionLocks } from '@/lib/projectSessionLock'

interface QuickProjectInfoState {
  projectIndustry?: string
  projectName?: string
  preparedBy?: string
  reviewedBy?: string
  preparedCompany?: string
  preparedDate?: string
}

interface QuickContractMetaState {
  id?: string
  name?: string
  updatedAt?: string
}

interface ProjectInfoState {
  projectIndustry?: string
  projectName?: string
  preparedBy?: string
  reviewedBy?: string
  preparedCompany?: string
  preparedDate?: string
}

const PROJECT_INFO_KEY = 'xm-base-info-v1'
const PROJECT_CONSULT_CATEGORY_FACTOR_KEY = 'xm-consult-category-factor-v1'
const PROJECT_MAJOR_FACTOR_KEY = 'xm-major-factor-v1'
const PROJECT_SCALE_KEY = 'xm-info-v3'
const getActiveProjectId = () => readCurrentProjectId()

const tabStore = useTabStore()
const kvStore = useKvStore()
const uiPrefsStore = useUiPrefsStore()
const { t, locale } = useI18n()
const projectDialogOpen = ref(false)
const projectIndustry = ref(String(industryTypeList[0]?.id || ''))
const projectSubmitting = ref(false)
const quickIndustry = ref(String(industryTypeList[0]?.id || ''))
const quickContractName = ref(QUICK_CONTRACT_FALLBACK_NAME)
const quickSubmitting = ref(false)
const homeImportInputRef = ref<HTMLInputElement | null>(null)
const homeImportConfirmOpen = ref(false)
const pendingHomeImportFile = ref<File | null>(null)
const pendingHomeImportFileName = ref('')
const existingProjectDialogOpen = ref(false)
const existingProjects = ref<Array<{ id: string; name: string; updatedAt: string }>>([])
const existingProjectLoading = ref(false)
const hasExistingProjects = ref(false)
const openedProjectIds = ref<string[]>([])
let existingProjectPollTimer: ReturnType<typeof setInterval> | null = null
const RELATED_FILES_URL = 'https://www.lianzhong.com.cn/file'
const localeBadge = computed(() => (locale.value === 'en-US' ? 'EN' : '中'))
const toggleLocale = () => {
  const next = locale.value === 'en-US' ? 'zh-CN' : 'en-US'
  uiPrefsStore.setLocale(next as 'zh-CN' | 'en-US')
}

const openRelatedFiles = () => {
  window.open(RELATED_FILES_URL, '_blank', 'noopener')
}
const resolveProjectRegistryName = (projectIdRaw: string) => {
  const projectId = String(projectIdRaw || '').trim()
  if (projectId !== DEFAULT_PROJECT_ID) return undefined
  return t('xmInfo.defaultProjectName')
}

const writeCleanProjectUrl = (projectIdRaw: string) => {
  try {
    const href = buildProjectUrl(projectIdRaw, { forceHome: false, newProject: false })
    window.history.replaceState({}, '', href)
  } catch {
    writeProjectIdToUrl(projectIdRaw)
  }
}

const navigateToWorkspace = (projectIdRaw: string, mode: 'project' | 'quick') => {
  const projectId = String(projectIdRaw || '').trim()
  if (!projectId) return false
  writeWorkspaceMode(mode)
  const currentProjectId = getActiveProjectId()
  const shouldReloadApp = mode === 'project' && currentProjectId !== projectId
  if (shouldReloadApp) {
    window.location.href = buildProjectUrl(projectId, { forceHome: false, newProject: false })
    return false
  }
  writeCleanProjectUrl(projectId)
  return true
}

const getTodayDateString = () => {
  const now = new Date()
  const year = String(now.getFullYear())
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const formatProjectEditedTime = (value: string) => {
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  const pad = (num: number) => String(num).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

const enterProjectCalc = () => {
  const projectId = getActiveProjectId()
  upsertProject(projectId, resolveProjectRegistryName(projectId))
  if (!navigateToWorkspace(projectId, 'project')) return
  tabStore.enterWorkspace({
    id: PROJECT_TAB_ID,
    title: t('home.projectCalcTab'),
    componentName: 'ProjectCalcView'
  })
  tabStore.hasCompletedSetup = true
}

const loadProjectDefaults = async () => {
  const savedInfo = await kvStore.getItem<ProjectInfoState>(PROJECT_INFO_KEY)
  projectIndustry.value =
    typeof savedInfo?.projectIndustry === 'string' && savedInfo.projectIndustry.trim()
      ? savedInfo.projectIndustry.trim()
      : String(industryTypeList[0]?.id || '')
}

const openProjectCalc = async () => {
 
  projectDialogOpen.value = true
}

const syncExistingProjectOpenedState = (projectIds: string[]) => {
  openedProjectIds.value = Array.from(collectActiveProjectSessionLocks(projectIds))
}

const isExistingProjectOpened = (projectIdRaw: string) => {
  const projectId = String(projectIdRaw || '').trim()
  return projectId ? openedProjectIds.value.includes(projectId) : false
}

const refreshExistingProjects = async (options?: { showLoading?: boolean }) => {
  if (options?.showLoading !== false) {
    existingProjectLoading.value = true
  }
  try {
    const projects = listProjects()
      .filter(item => item.id !== QUICK_PROJECT_ID)
      .sort((a, b) => {
        const left = new Date(a.updatedAt).getTime()
        const right = new Date(b.updatedAt).getTime()
        return (Number.isFinite(right) ? right : 0) - (Number.isFinite(left) ? left : 0)
      })
    existingProjects.value = projects.map(project => ({
      id: project.id,
      name: project.name,
      updatedAt: project.updatedAt
    }))
    hasExistingProjects.value = projects.length > 0
    syncExistingProjectOpenedState(projects.map(project => project.id))
  } finally {
    if (options?.showLoading !== false) {
      existingProjectLoading.value = false
    }
  }
}

const stopExistingProjectPolling = () => {
  if (existingProjectPollTimer == null) return
  clearInterval(existingProjectPollTimer)
  existingProjectPollTimer = null
}

const startExistingProjectPolling = () => {
  stopExistingProjectPolling()
  existingProjectPollTimer = setInterval(() => {
    if (!existingProjectDialogOpen.value) return
    void refreshExistingProjects({ showLoading: false })
  }, 3000)
}

const openExistingProjectDialog = async () => {
  projectDialogOpen.value = false
  existingProjectDialogOpen.value = true
  await refreshExistingProjects()
  startExistingProjectPolling()
}

const closeExistingProjectDialog = () => {
  existingProjectDialogOpen.value = false
  stopExistingProjectPolling()
}

const enterExistingProject = (projectIdRaw: string) => {
  const projectId = String(projectIdRaw || '').trim()
  if (!projectId || isExistingProjectOpened(projectId)) return
  upsertProject(projectId, resolveProjectRegistryName(projectId))
  if (!navigateToWorkspace(projectId, 'project')) return
  tabStore.enterWorkspace({
    id: PROJECT_TAB_ID,
    title: t('home.projectCalcTab'),
    componentName: 'ProjectCalcView'
  })
  tabStore.hasCompletedSetup = true
  closeExistingProjectDialog()
}

const closeProjectCalcDialog = () => {
  projectDialogOpen.value = false
}

const confirmProjectCalc = async () => {
  const industry = projectIndustry.value.trim()
  if (!industry) return

  projectSubmitting.value = true
  try {
    const project = createProject(t('xmInfo.defaultProjectName'))
    const kvAdapter = createProjectKvAdapter(project.id)
    await kvAdapter.setItem<ProjectInfoState>(PROJECT_INFO_KEY, {
      projectIndustry: industry,
      projectName: t('xmInfo.defaultProjectName'),
      preparedBy: '',
      reviewedBy: '',
      preparedCompany: '',
      preparedDate: getTodayDateString()
    })
    await initializeProjectFactorStates(
      kvAdapter,
      industry,
      PROJECT_CONSULT_CATEGORY_FACTOR_KEY,
      PROJECT_MAJOR_FACTOR_KEY
    )
    await initializeProjectScaleState(kvAdapter, industry, PROJECT_SCALE_KEY)
    writeWorkspaceMode('project')
    window.location.href = buildProjectUrl(project.id, { forceHome: false, newProject: false })
  } finally {
    projectSubmitting.value = false
    projectDialogOpen.value = false
  }
}

const loadQuickDefaults = async () => {
  const [savedInfo, savedMeta] = await Promise.all([
    kvStore.getItem<QuickProjectInfoState>(QUICK_PROJECT_INFO_KEY),
    kvStore.getItem<QuickContractMetaState>(QUICK_CONTRACT_META_KEY)
  ])

  quickIndustry.value =
    typeof savedInfo?.projectIndustry === 'string' && savedInfo.projectIndustry.trim()
      ? savedInfo.projectIndustry.trim()
      : String(industryTypeList[0]?.id || '')
  quickContractName.value =
    typeof savedMeta?.name === 'string' && savedMeta.name.trim()
      ? savedMeta.name.trim()
      : QUICK_CONTRACT_FALLBACK_NAME
}

const enterQuickCalc = (contractName: string) => {
  if (!navigateToWorkspace(QUICK_PROJECT_ID, 'quick')) return
  tabStore.enterWorkspace({
    id: `contract-${QUICK_CONTRACT_ID}`,
    title: t('home.quickCalcTab'),
    componentName: 'QuickCalcWorkbenchView',
    props: {
      contractId: QUICK_CONTRACT_ID,
      contractName,
      projectInfoKey: QUICK_PROJECT_INFO_KEY,
      projectScaleKey: null,
      projectConsultCategoryFactorKey: QUICK_CONSULT_CATEGORY_FACTOR_KEY,
      projectMajorFactorKey: QUICK_MAJOR_FACTOR_KEY
    }
  })
  tabStore.hasCompletedSetup = true
}

const openQuickCalc = () => {
  window.alert(t('home.cards.developing'))
}

const handleHomeImportChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  pendingHomeImportFile.value = file
  pendingHomeImportFileName.value = file.name
  homeImportConfirmOpen.value = true
  input.value = ''
}

const openHomeImport = () => {
  homeImportInputRef.value?.click()
}

const cancelHomeImportConfirm = () => {
  homeImportConfirmOpen.value = false
  pendingHomeImportFile.value = null
  pendingHomeImportFileName.value = ''
}

const confirmHomeImport = async () => {
  const file = pendingHomeImportFile.value
  if (!file) return
  await setPendingHomeImportFile(file, { skipWorkspaceConfirm: true })
  const targetProject = createProject(t('xmInfo.defaultProjectName'))
  writeWorkspaceMode('project')
  window.location.href = buildProjectUrl(targetProject.id, { forceHome: false, newProject: false })
  cancelHomeImportConfirm()
}

const handleHomeWindowFocus = () => {
  if (!existingProjectDialogOpen.value) return
  void refreshExistingProjects({ showLoading: false })
}

const handleHomeVisibilityChange = () => {
  if (document.visibilityState !== 'visible') return
  handleHomeWindowFocus()
}

onMounted(() => {
  void refreshExistingProjects()
  void loadProjectDefaults()
  void loadQuickDefaults()
  window.addEventListener('focus', handleHomeWindowFocus)
  document.addEventListener('visibilitychange', handleHomeVisibilityChange)
  try {
    const url = new URL(window.location.href)
    const isNewProject = url.searchParams.get(NEW_PROJECT_QUERY_KEY) === '1'
    if (isNewProject) {
      const projectId = getActiveProjectId()
      upsertProject(projectId, resolveProjectRegistryName(projectId))
      const openProjectDialog = url.searchParams.get(OPEN_PROJECT_DIALOG_QUERY_KEY) !== '0'
      if (openProjectDialog) {
        void openProjectCalc()
      }
      url.searchParams.delete(NEW_PROJECT_QUERY_KEY)
      url.searchParams.delete(OPEN_PROJECT_DIALOG_QUERY_KEY)
      url.searchParams.delete(FORCE_HOME_QUERY_KEY)
      window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`)
    }
  } catch {
    // ignore url parsing errors
  }
})

onBeforeUnmount(() => {
  stopExistingProjectPolling()
  window.removeEventListener('focus', handleHomeWindowFocus)
  document.removeEventListener('visibilitychange', handleHomeVisibilityChange)
})
</script>

<template>
  <input ref="homeImportInputRef" type="file" accept=".zw" class="sr-only" @change="handleHomeImportChange" />
  <div class="home-entry relative flex min-h-full items-center justify-center overflow-hidden px-4 py-8 lg:py-10">
    <div class="pointer-events-none absolute inset-0 bg-[url('/background.png')] bg-cover bg-center bg-no-repeat" />
    <div class="pointer-events-none absolute inset-0 bg-white/78" />
    <div
      class="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_80%_60%_at_50%_-10%,rgba(59,130,246,0.08),transparent_70%)]"
    />
    <div class="relative w-full max-w-[1240px]">
      <div class="absolute right-0 top-0 z-10">
        <button
          type="button"
          class="inline-flex h-8 cursor-pointer items-center justify-center gap-1.5 rounded-full border border-slate-200/80 bg-white/85 px-3 text-xs text-slate-600 shadow-sm backdrop-blur transition hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-200"
          @click="toggleLocale"
        >
          <Languages class="h-3.5 w-3.5" />
          <span>{{ localeBadge }}</span>
        </button>
      </div>

      <div class="home-title text-center">
        <h1
          class="text-2xl font-semibold tracking-tight text-slate-900 lg:text-3xl"
          style="font-family: HarmonyOS_Sans_SC, 'Microsoft YaHei', sans-serif; font-weight: 300; white-space: pre-line;"
        >
          {{ t('home.title') }}
        </h1>
        <p class="mt-1.5 text-sm text-slate-500">{{ t('home.subtitle') }}</p>
      </div>

      <div class="mt-5 grid items-stretch gap-4 md:grid-cols-2 xl:grid-cols-4">
        <section
          class="home-card-base home-entry-item home-entry-item--1 relative overflow-hidden rounded-2xl bg-[#dc2626] p-7 text-white shadow-[0_24px_60px_rgba(153,27,27,0.35)]"
        >
          <div class="pointer-events-none absolute -right-20 -top-16 h-56 w-56 rounded-full bg-white/12 blur-2xl" />
          <div class="pointer-events-none absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-white/8 blur-3xl" />
          <div v-for="index in 10" :key="index" :class="`home-hero-meteor home-hero-meteor--${index}`" />
          <div class="relative inline-flex h-11 w-11 items-center justify-center rounded-xl bg-white/15 ring-1 ring-white/35">
            <BarChart3 class="h-5 w-5" />
          </div>
          <h2 class="relative mt-8 whitespace-pre-line text-xl font-semibold leading-tight tracking-tight">
            {{ t('home.cards.heroTitle') }}
          </h2>
          <p class="relative mt-2 text-sm text-red-200/90">{{ t('home.cards.heroSubTitle') }}</p>
          <div class="relative mt-6 h-px bg-white/20" />
          <p class="relative mt-4 whitespace-pre-line text-xs leading-5 text-red-200/80">{{ t('home.cards.heroDesc') }}</p>
        </section>

        <article
          role="button"
          tabindex="0"
          class="home-card-base home-entry-item home-entry-item--2 group flex cursor-pointer flex-col justify-between rounded-xl border border-slate-200/80 bg-white/95 px-5 py-5 shadow-[0_4px_20px_rgba(15,23,42,0.06)] backdrop-blur-sm transition-all duration-200 hover:-translate-y-0.5 hover:shadow-[0_12px_32px_rgba(15,23,42,0.12)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-200"
          @click="openProjectCalc"
          @keydown.enter.prevent="openProjectCalc"
          @keydown.space.prevent="openProjectCalc"
        >
          <div>
            <div class="inline-flex h-11 w-11 items-center justify-center rounded-xl border border-blue-100 bg-blue-50/80 text-blue-600 shadow-sm transition-transform duration-200 group-hover:scale-105">
              <BarChart3 class="h-5 w-5" />
            </div>
            <h3 class="mt-4 text-base font-semibold text-slate-900">{{ t('home.cards.projectBudget') }}</h3>
            <p class="mt-1.5 text-xs leading-5 text-slate-500">{{ t('home.cards.projectBudgetDesc') }}</p>
          </div>
          <div class="mt-4 flex flex-wrap items-center justify-end gap-2">
            <button
              v-if="hasExistingProjects"
              type="button"
              class="cursor-pointer rounded-md border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 transition hover:border-slate-300 hover:bg-slate-50 hover:text-slate-700"
              @click.stop="openExistingProjectDialog"
            >
              {{ t('home.cards.pickExisting') }}
            </button>
            <button
              type="button"
              class="cursor-pointer rounded-md bg-blue-600 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-blue-700"
              @click.stop="openProjectCalc"
            >
              <span class="flex items-center gap-1">
                {{ t('home.cards.enter') }}
                <svg class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
              </span>
            </button>
          </div>
        </article>

        <article
          role="button"
          tabindex="0"
          class="home-card-base home-entry-item home-entry-item--3 group flex cursor-pointer flex-col justify-between rounded-xl border border-slate-200/80 bg-white/95 px-5 py-5 shadow-[0_4px_20px_rgba(15,23,42,0.06)] backdrop-blur-sm transition-all duration-200 hover:-translate-y-0.5 hover:shadow-[0_12px_32px_rgba(15,23,42,0.12)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-200"
          @click="openQuickCalc"
          @keydown.enter.prevent="openQuickCalc"
          @keydown.space.prevent="openQuickCalc"
        >
          <div>
            <div class="inline-flex h-11 w-11 items-center justify-center rounded-xl border border-amber-100 bg-amber-50/80 text-amber-600 shadow-sm transition-transform duration-200 group-hover:scale-105">
              <Calculator class="h-5 w-5" />
            </div>
            <h3 class="mt-4 text-base font-semibold text-slate-900">{{ t('home.cards.quickCalc') }}</h3>
            <p class="mt-1.5 text-xs leading-5 text-slate-500">{{ t('home.cards.quickCalcDesc') }}</p>
          </div>
          <div class="mt-4 flex items-center text-xs font-medium text-slate-400 transition-colors group-hover:text-slate-600">
            <span>{{ t('home.cards.developing') }}</span>
            <svg class="ml-1 h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
          </div>
        </article>

        <article
          role="button"
          tabindex="0"
          class="home-card-base home-entry-item home-entry-item--4 group flex cursor-pointer flex-col justify-between rounded-xl border border-slate-200/80 bg-white/95 px-5 py-5 shadow-[0_4px_20px_rgba(15,23,42,0.06)] backdrop-blur-sm transition-all duration-200 hover:-translate-y-0.5 hover:shadow-[0_12px_32px_rgba(15,23,42,0.12)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-200"
          @click="openRelatedFiles"
          @keydown.enter.prevent="openRelatedFiles"
          @keydown.space.prevent="openRelatedFiles"
        >
          <div>
            <div class="inline-flex h-11 w-11 items-center justify-center rounded-xl border border-emerald-100 bg-emerald-50/80 shadow-sm transition-transform duration-200 group-hover:scale-105">
              <svg
                viewBox="0 0 1024 1024"
                class="h-6 w-6"
                xmlns="http://www.w3.org/2000/svg"
                aria-hidden="true"
              >
                <path
                  d="M271.146667 128h-85.333334a64 64 0 0 0-64 64v640a64 64 0 0 0 64 64h85.333334a64 64 0 0 0 64-64V192a64 64 0 0 0-64-64z m21.333333 704a21.333333 21.333333 0 0 1-21.333333 21.333333h-85.333334a21.333333 21.333333 0 0 1-21.333333-21.333333V320h128z m0-554.666667h-128V192a21.333333 21.333333 0 0 1 21.333333-21.333333h85.333334a21.333333 21.333333 0 0 1 21.333333 21.333333zM901.12 808.533333L789.333333 178.346667a64 64 0 0 0-74.026666-51.84l-84.053334 14.72a64 64 0 0 0-44.16 31.146666A64 64 0 0 0 527.146667 128h-85.333334a64 64 0 0 0-64 64v640a64 64 0 0 0 64 64h85.333334a64 64 0 0 0 64-64V279.253333l99.84 566.4a64 64 0 0 0 74.24 51.84l84.053333-14.72a64 64 0 0 0 51.84-74.24zM548.48 832a21.333333 21.333333 0 0 1-21.333333 21.333333h-85.333334a21.333333 21.333333 0 0 1-21.333333-21.333333V320h128z m0-554.666667h-128V192a21.333333 21.333333 0 0 1 21.333333-21.333333h85.333334a21.333333 21.333333 0 0 1 21.333333 21.333333z m73.386667-69.333333A21.333333 21.333333 0 0 1 640 183.253333l83.2-14.72a21.333333 21.333333 0 0 1 24.746667 17.28l14.933333 84.053334-126.08 21.333333z m219.946666 632.746667l-84.053333 14.72a21.333333 21.333333 0 0 1-24.746667-17.28L644.266667 334.08l125.866666-21.333333 88.96 504.106666a21.333333 21.333333 0 0 1-17.28 23.893334z"
                  fill="#e0db84"
                />
              </svg>
            </div>
            <h3 class="mt-4 text-base font-semibold text-slate-900">{{ t('home.cards.relatedFiles') }}</h3>
            <p class="mt-1.5 text-xs leading-5 text-slate-500">{{ t('home.cards.relatedFilesDesc') }}</p>
          </div>
          <div class="mt-4 flex items-center text-xs font-medium text-slate-400 transition-colors group-hover:text-slate-600">
            <span>{{ t('home.cards.openRelatedFiles') }}</span>
            <svg class="ml-1 h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
          </div>
        </article>
      </div>
    </div>
  </div>

  <div
    v-if="existingProjectDialogOpen"
    class="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-4"
    @click.self="closeExistingProjectDialog"
  >
    <div class="w-full max-w-lg rounded-3xl border border-slate-200/60 bg-white shadow-2xl">
      <div class="flex items-start justify-between border-b border-slate-100 px-6 pt-6 pb-4">
        <div>
          <h3 class="text-xl font-bold text-[#1a1a1a]">{{ t('home.dialog.chooseExistingProject') }}</h3>
          <p class="mt-1.5 text-base text-[#666]">{{ t('home.dialog.chooseExistingProjectDesc') }}</p>
        </div>
        <button
          type="button"
          class="flex h-8 w-8 items-center justify-center rounded-full text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
          @click="closeExistingProjectDialog"
        >
          <X class="h-5 w-5" />
        </button>
      </div>

      <div class="max-h-80 space-y-3 overflow-auto px-6 py-5">
        <div
          v-if="!existingProjectLoading && existingProjects.length === 0"
          class="rounded-lg border border-dashed border-slate-200 bg-slate-50 px-3 py-5 text-center text-sm text-slate-500"
        >
          {{ t('home.dialog.noProjectYet') }}
        </div>
        <button
          v-for="project in existingProjects"
          :key="project.id"
          type="button"
          :disabled="isExistingProjectOpened(project.id)"
          class="flex w-full items-center justify-between rounded-xl border border-slate-200 bg-white px-4 py-3.5 text-left transition hover:border-slate-300 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60"
          @click="enterExistingProject(project.id)"
        >
          <div class="min-w-0 flex-1">
            <div class="text-base font-medium text-[#1a1a1a]">
              {{ project.name }}
            </div>
            <div class="mt-1 text-sm text-[#888]">{{ project.id }}</div>
          </div>
          <div class="shrink-0 pl-4 text-sm text-[#888]">
            {{ t('tab.toolbar.lastEdited', { time: formatProjectEditedTime(project.updatedAt) }) }}
          </div>
        </button>
      </div>

      <div class="flex items-center justify-end gap-3 border-t border-slate-100 px-6 pt-4 pb-6">
        <button
          type="button"
          class="cursor-pointer rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-base font-medium text-[#666] transition hover:border-slate-300 hover:bg-slate-50"
          @click="closeExistingProjectDialog"
        >
          {{ t('common.cancel') }}
        </button>
      </div>
    </div>
  </div>

  <div
    v-if="projectDialogOpen"
    class="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-4"
    @click.self="closeProjectCalcDialog"
  >
    <div class="w-full max-w-lg rounded-3xl border border-slate-200/60 bg-white shadow-2xl">
      <div class="flex items-start justify-between border-b border-slate-100 px-6 pt-6 pb-4">
        <div>
          <h3 class="text-xl font-bold text-[#1a1a1a]">{{ t('home.dialog.newProject') }}</h3>
          <p class="mt-1.5 text-base text-[#666]">选择工程行业后，进入项目计算页面</p>
        </div>
        <button
          type="button"
          class="flex h-8 w-8 items-center justify-center rounded-full text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
          @click="closeProjectCalcDialog"
        >
          <X class="h-5 w-5" />
        </button>
      </div>

      <div class="px-6 pt-5 pb-4">
        <h4 class="mb-3 text-base font-semibold text-[#1a1a1a]">{{ t('home.dialog.industry') }}</h4>
        <div class="space-y-3">
          <button
            v-for="item in industryTypeList"
            :key="`project-${item.id}`"
            type="button"
            :class="[
              'flex w-full items-center justify-between rounded-xl border px-4 py-3.5 text-left transition',
              projectIndustry === String(item.id)
                ? 'border-[#1a1a1a] bg-white text-[#1a1a1a] shadow-sm'
                : 'border-slate-200 bg-white text-[#1a1a1a] hover:border-slate-300'
            ]"
            @click="projectIndustry = String(item.id)"
          >
            <span class="text-base">{{ getIndustryDisplayName(item.id, locale) }}</span>
            <div
              :class="[
                'flex h-5 w-5 items-center justify-center rounded-md border transition',
                projectIndustry === String(item.id)
                  ? 'border-[#1a1a1a] bg-[#1a1a1a] text-white'
                  : 'border-slate-300 bg-white'
              ]"
            >
              <Check v-if="projectIndustry === String(item.id)" class="h-3.5 w-3.5" />
            </div>
          </button>
        </div>
      </div>

      <div class="flex items-center justify-end gap-3 border-t border-slate-100 px-6 pt-4 pb-6">
        <button
          type="button"
          class="cursor-pointer rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-base font-medium text-[#666] transition hover:border-slate-300 hover:bg-slate-50"
          @click="closeProjectCalcDialog; openExistingProjectDialog()"
        >
          {{ t('home.cards.pickExisting') }}
        </button>
        <button
          type="button"
          :disabled="projectSubmitting || !projectIndustry"
          class="cursor-pointer rounded-lg bg-[#1a1a1a] px-5 py-2.5 text-base font-medium text-white transition hover:bg-[#2a2a2a] disabled:cursor-not-allowed disabled:opacity-50"
          @click="confirmProjectCalc"
        >
          {{ projectSubmitting ? t('home.dialog.entering') : t('home.dialog.enterProjectCalc') }}
        </button>
      </div>
    </div>
  </div>

  <div
    v-if="homeImportConfirmOpen"
    class="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-4"
    @click.self="cancelHomeImportConfirm"
  >
    <div class="w-full max-w-md rounded-xl border bg-background shadow-2xl">
      <div class=" px-5 py-4">
        <h3 class="text-base font-semibold text-foreground">{{ t('home.dialog.confirmImport') }}</h3>
        <p class="mt-1 text-sm text-muted-foreground">
          {{ t('home.dialog.confirmImportDesc', { file: pendingHomeImportFileName || t('home.cards.pickFile') }) }}
        </p>
      </div>
      <div class="flex items-center justify-end gap-2 px-5 py-4">
        <Button variant="outline" @click="cancelHomeImportConfirm">{{ t('common.cancel') }}</Button>
        <Button variant="destructive" @click="confirmHomeImport">{{ t('home.dialog.confirmImportAction') }}</Button>
      </div>
    </div>
  </div>

</template>

<style scoped>
.home-hero {
  animation: none;
}
.home-card-base {
  min-height: 248px;
}
.home-title {
  animation: fade-up 0.45s cubic-bezier(0.22, 1, 0.36, 1) 0.15s both;
  max-width: 520px;
  margin: 0 auto;
  padding: 18px 24px;
  border: 1px solid rgba(148, 163, 184, 0.26);
  border-radius: 20px;
  background-image: radial-gradient(ellipse 80% 60% at 50% -10%, rgba(59, 130, 246, 0.06), transparent 70%);
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.05);
}
.home-entry-item {
  animation: fade-up 0.45s cubic-bezier(0.22, 1, 0.36, 1) both;
}
.home-entry-item--1 { animation-delay: 0.2s; }
.home-entry-item--2 { animation-delay: 0.3s; }
.home-entry-item--3 { animation-delay: 0.4s; }
.home-entry-item--4 { animation-delay: 0.5s; }
.home-entry-item--5 { animation-delay: 0.6s; }

@keyframes hero-in {
  from { opacity: 0; transform: translateX(-20px) scale(0.97); }
  to { opacity: 1; transform: translateX(0) scale(1); }
}
.home-hero-meteor {
  pointer-events: none;
  position: absolute;
  width: 120px;
  height: 1px;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.65), rgba(255, 255, 255, 0));
  transform: rotate(-28deg);
  opacity: 0;
  filter: drop-shadow(0 0 6px rgba(255, 255, 255, 0.45));
  animation: hero-meteor 3.8s linear infinite;
}
.home-hero-meteor--1 {
  top: 16%;
  right: -30%;
  animation-delay: 0s;
}
.home-hero-meteor--2 {
  top: 38%;
  right: -40%;
  animation-delay: 1.2s;
}
.home-hero-meteor--3 {
  top: 62%;
  right: -35%;
  animation-delay: 2.2s;
}
.home-hero-meteor--4 {
  top: 24%;
  right: -45%;
  animation-delay: 0.6s;
}
.home-hero-meteor--5 {
  top: 50%;
  right: -28%;
  animation-delay: 1.7s;
}
.home-hero-meteor--6 {
  top: 74%;
  right: -42%;
  animation-delay: 2.8s;
}
.home-hero-meteor--7 {
  top: 10%;
  right: -48%;
  animation-delay: 0.35s;
}
.home-hero-meteor--8 {
  top: 31%;
  right: -26%;
  animation-delay: 1.05s;
}
.home-hero-meteor--9 {
  top: 56%;
  right: -50%;
  animation-delay: 2.45s;
}
.home-hero-meteor--10 {
  top: 82%;
  right: -30%;
  animation-delay: 3.15s;
}
@keyframes hero-meteor {
  0% { transform: translate3d(0, 0, 0) rotate(-28deg); opacity: 0; }
  8% { opacity: 0.9; }
  34% { opacity: 0.9; }
  42% { opacity: 0; }
  100% { transform: translate3d(-340px, 220px, 0) rotate(-28deg); opacity: 0; }
}
@keyframes fade-up {
  from { opacity: 0; transform: translateY(16px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
