<template>
  <div class="min-h-screen flex flex-col">
    <SharedHeader />

    <main class="flex-1 flex items-center justify-center p-6">
      <div class="w-full max-w-md rounded-xl border bg-background p-6 text-center">
        <span
          :class="
            errorMessage
              ? 'i-material-symbols:error-outline text-destructive'
              : 'i-line-md:loading-twotone-loop text-primary'
          "
          class="mx-auto mb-4 block text-4xl"
        />
        <h1 class="text-xl font-semibold">
          {{ errorMessage ? "Could not import the resume" : "Opening in Oh My CV" }}
        </h1>
        <p class="mt-2 text-sm text-muted-foreground">
          {{
            errorMessage ||
            "Creating a local editable copy of your tailored Markdown resume…"
          }}
        </p>
        <UiButton v-if="errorMessage" class="mt-5" as-child>
          <NuxtLink to="/dashboard">Return to dashboard</NuxtLink>
        </UiButton>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup>
type PendingSignalResume = {
  name: string;
  markdown: string;
  createdAt: string;
};

const errorMessage = ref("");

onMounted(async () => {
  const raw = localStorage.getItem("signal:pending-ohmycv");
  if (!raw) {
    errorMessage.value =
      "No tailored resume is waiting to be imported. Return to Signal and tailor a resume first.";
    return;
  }

  try {
    const pending = JSON.parse(raw) as PendingSignalResume;
    if (!pending.markdown?.trim()) throw new Error("The tailored Markdown is empty.");

    const resume = await storageService.createResume();
    if (!resume) throw new Error("Oh My CV could not create a local resume.");

    const updated = await storageService.updateResume({
      id: resume.id,
      name: pending.name || "Signal tailored resume",
      markdown: pending.markdown
    });
    if (!updated) throw new Error("Oh My CV could not save the tailored Markdown.");

    localStorage.removeItem("signal:pending-ohmycv");
    await navigateTo(`/editor/${resume.id}`);
  } catch (error) {
    errorMessage.value =
      error instanceof Error
        ? error.message
        : "The tailored resume could not be imported.";
  }
});
</script>
