<template>
  <div>
    <PageHeader
      title="New Update"
      subtitle="Share what you're working on, learning, or thinking about"
      theme="stone"
      size="medium"
    />

    <section class="py-12 px-4">
      <UContainer class="px-4">
        <div class="max-w-3xl">
          <UpdateForm
            :submitting="submitting"
            :error="error"
            submit-label="Post Update"
            @submit="handleSubmit"
            @cancel="handleCancel"
          />

          <!-- Success Message -->
          <div
            v-if="success"
            class="mt-6 bg-green-500/10 border border-green-500/30 rounded-lg p-4"
          >
            <p class="text-green-300">✓ Update posted successfully!</p>
          </div>
        </div>
      </UContainer>
    </section>
  </div>
</template>

<script setup>
const { isAuthenticated, checkMemberStatus } = useAuth();

const submitting = ref(false);
const error = ref(null);
const success = ref(false);

// Check authentication
onMounted(async () => {
  if (!isAuthenticated.value) {
    const authenticated = await checkMemberStatus();
    if (!authenticated) {
      await navigateTo("/login");
    }
  }
});

const handleSubmit = async (formData) => {
  submitting.value = true;
  error.value = null;
  success.value = false;

  try {
    const update = await $fetch("/api/updates", {
      method: "POST",
      body: formData,
    });

    success.value = true;

    // Redirect to the update after a short delay
    setTimeout(() => {
      navigateTo(`/updates/${update._id}`);
    }, 1000);
  } catch (err) {
    console.error("Failed to create update:", err);
    error.value =
      err.data?.statusMessage || "Failed to post update. Please try again.";
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  navigateTo("/updates");
};

useHead({
  title: "New Update - Ghost Guild",
});
</script>
