<script setup lang="ts">
interface RecentWorkspace {
  path: string
  name: string
}

const props = defineProps<{
  /** Previously-saved workspace path that no longer exists, if any. */
  stalePath?: string | null
  /** List of recently-opened workspace paths from settings. */
  recentPaths?: string[]
}>()

const emit = defineEmits<{
  /** Fires after the workspace is fully initialized. */
  complete: []
}>()

const ws = useWorkspaceStore()

const picking = ref<"new" | "open" | null>(null)
const openingPath = ref<string | null>(null)

const recentWorkspaces = computed<RecentWorkspace[]>(() =>
  (props.recentPaths ?? []).map((p) => ({
    path: p,
    name: p.split("/").filter(Boolean).at(-1) ?? p,
  })),
)

async function handleNew() {
  picking.value = "new"
  try {
    const path = await ws.createWorkspace()
    if (!path) return
    await ws.setWorkspace(path, { isNew: true })
    emit("complete")
  } finally {
    picking.value = null
  }
}

async function handleOpen() {
  picking.value = "open"
  try {
    const path = await ws.pickWorkspace()
    if (!path) return
    await ws.setWorkspace(path)
    emit("complete")
  } finally {
    picking.value = null
  }
}

async function handleOpenRecent(path: string) {
  if (path === props.stalePath) return
  openingPath.value = path
  try {
    await ws.setWorkspace(path)
    emit("complete")
  } finally {
    openingPath.value = null
  }
}
</script>

<template>
  <div class="min-h-screen flex flex-col items-center justify-center bg-default px-6">

    <!-- Ambient glow -->
    <div class="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden="true">
      <div
        class="absolute left-1/2 top-1/3 -translate-x-1/2 -translate-y-1/2
               w-[600px] h-[500px] rounded-full
               bg-(--ui-primary)/5 blur-[140px]"
      />
    </div>

    <div class="relative w-full max-w-md space-y-8">

      <!-- Wordmark -->
      <div class="text-center space-y-1">
        <p class="text-xs font-medium tracking-widest uppercase text-muted/60 select-none">
          Your second brain
        </p>
        <h1 class="text-3xl font-normal tracking-tight text-highlighted">
          Where are your notes?
        </h1>
      </div>

      <!-- Stale path notice -->
      <UAlert
        v-if="stalePath"
        color="warning"
        variant="subtle"
        icon="i-lucide-triangle-alert"
        title="Workspace not found"
        :description="`'${stalePath.split('/').at(-1)}' couldn't be located. Open it again or choose a different folder.`"
      />

      <!-- Primary action tiles -->
      <div class="grid grid-cols-2 gap-3">
        <button
          class="group flex flex-col items-center gap-3 rounded-xl border border-default
                 bg-default hover:bg-elevated hover:border-(--ui-primary)/40
                 px-6 py-8 text-center transition-all duration-150
                 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-(--ui-primary)
                 disabled:opacity-50 disabled:cursor-not-allowed"
          :disabled="picking !== null"
          @click="handleNew"
        >
          <span
            class="w-10 h-10 rounded-lg flex items-center justify-center
                   bg-(--ui-primary)/10 text-(--ui-primary)
                   group-hover:bg-(--ui-primary)/15 transition-colors"
          >
            <UIcon
              name="i-lucide-folder-plus"
              class="w-5 h-5"
              :class="{ 'animate-spin': picking === 'new' }"
            />
          </span>
          <span class="space-y-0.5">
            <span class="block text-sm font-medium text-highlighted">New workspace</span>
            <span class="block text-xs text-muted">Start fresh in a new folder</span>
          </span>
        </button>

        <button
          class="group flex flex-col items-center gap-3 rounded-xl border border-default
                 bg-default hover:bg-elevated hover:border-(--ui-primary)/40
                 px-6 py-8 text-center transition-all duration-150
                 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-(--ui-primary)
                 disabled:opacity-50 disabled:cursor-not-allowed"
          :disabled="picking !== null"
          @click="handleOpen"
        >
          <span
            class="w-10 h-10 rounded-lg flex items-center justify-center
                   bg-(--ui-primary)/10 text-(--ui-primary)
                   group-hover:bg-(--ui-primary)/15 transition-colors"
          >
            <UIcon
              name="i-lucide-folder-open"
              class="w-5 h-5"
              :class="{ 'animate-spin': picking === 'open' }"
            />
          </span>
          <span class="space-y-0.5">
            <span class="block text-sm font-medium text-highlighted">Open folder</span>
            <span class="block text-xs text-muted">Browse to an existing vault</span>
          </span>
        </button>
      </div>

      <!-- Recents -->
      <template v-if="recentWorkspaces.length > 0">
        <div class="flex items-center gap-3">
          <div class="h-px flex-1 bg-(--ui-border)" />
          <span class="text-xs text-muted/60 select-none tracking-wide uppercase">Recent</span>
          <div class="h-px flex-1 bg-(--ui-border)" />
        </div>

        <ul class="space-y-1">
          <li v-for="ws in recentWorkspaces" :key="ws.path">
            <button
              class="group w-full flex items-center gap-3 rounded-lg px-3 py-2.5
                     hover:bg-elevated transition-colors duration-100 text-left
                     focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-(--ui-primary)
                     disabled:opacity-40 disabled:cursor-not-allowed"
              :disabled="openingPath !== null || ws.path === stalePath"
              @click="handleOpenRecent(ws.path)"
            >
              <UIcon
                :name="ws.path === stalePath ? 'i-lucide-triangle-alert' : 'i-lucide-folder-clock'"
                class="w-4 h-4 shrink-0"
                :class="ws.path === stalePath ? 'text-warning' : 'text-muted'"
              />

              <span class="flex-1 min-w-0 space-y-0.5">
                <span
                  class="block text-sm font-medium truncate"
                  :class="ws.path === stalePath ? 'text-muted line-through' : 'text-default'"
                >
                  {{ ws.name }}
                </span>
                <span class="block text-xs text-muted/60 truncate font-mono">
                  {{ ws.path }}
                </span>
              </span>

              <span
                v-if="ws.path === stalePath"
                class="shrink-0 text-xs text-warning/80 font-medium"
              >
                not found
              </span>

              <UIcon
                v-else-if="openingPath === ws.path"
                name="i-lucide-loader"
                class="w-4 h-4 shrink-0 text-muted animate-spin"
              />

              <UIcon
                v-else
                name="i-lucide-arrow-right"
                class="w-4 h-4 shrink-0 text-muted opacity-0 group-hover:opacity-100
                       -translate-x-1 group-hover:translate-x-0 transition-all duration-150"
              />
            </button>
          </li>
        </ul>
      </template>

      <!-- Footer note -->
      <p class="text-center text-xs text-muted/40 select-none">
        Notes stay on your machine. No account needed.
      </p>

    </div>
  </div>
</template>
