<script setup lang="ts">
const router = useRouter();
const { user, registerWithEmail, signInWithGoogle, isLoading, error } = useAuth();
const loginModal = useLoginModal();

const email = ref("");
const password = ref("");
const confirmPassword = ref("");
const isSubmitting = ref(false);
const localError = ref<string | null>(null);

const isProcessing = computed(() => isSubmitting.value || isLoading.value);
const combinedError = computed(() => localError.value || error.value || null);

const redirectIfAuthenticated = (maybeUser: unknown) => {
  if (!process.client) {
    return;
  }
  if (maybeUser) {
    router.replace("/");
  }
};

watch(
  () => user.value,
  (currentUser) => {
    if (currentUser) {
      redirectIfAuthenticated(currentUser);
    }
  },
  { immediate: true }
);

const handleRegister = async () => {
  if (!process.client) {
    return;
  }

  localError.value = null;

  if (!email.value.trim()) {
    localError.value = "Email is required.";
    return;
  }

  if (password.value.length < 6) {
    localError.value = "Password must be at least 6 characters.";
    return;
  }

  if (password.value !== confirmPassword.value) {
    localError.value = "Passwords do not match.";
    return;
  }

  try {
    isSubmitting.value = true;
    await registerWithEmail(email.value.trim(), password.value);
    await router.replace("/");
  } catch (err: any) {
    localError.value = err?.message ?? "Registration failed. Please try again.";
  } finally {
    isSubmitting.value = false;
  }
};

const handleGoogleRegister = async () => {
  if (!process.client) {
    return;
  }

  try {
    isSubmitting.value = true;
    await signInWithGoogle();
    await router.replace("/");
  } catch (err: any) {
    localError.value = err?.message ?? "Google sign-in failed. Please try again.";
  } finally {
    isSubmitting.value = false;
  }
};

const goToSignIn = async () => {
  if (!process.client) {
    return;
  }

  loginModal.value = true;
  await router.push("/");
};
</script>

<template>
  <main class="min-h-screen bg-white pb-16 text-slate-900">
    <AppNavbar />

    <section class="mx-auto flex max-w-md flex-col gap-8 px-4 pt-16">
      <header class="space-y-3 text-center">
        <p class="text-sm uppercase tracking-[0.35em] text-slate-600">Create Account</p>
        <h1 class="text-3xl font-semibold text-slate-900">Join TableJerseys</h1>
        <p class="text-sm text-slate-600">
          Sign up with email and password to save your designs and return to them anytime.
        </p>
      </header>

      <form class="space-y-5 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm" @submit.prevent="handleRegister">
        <div class="space-y-1">
          <label for="email" class="block text-sm font-medium text-slate-700">Email</label>
          <input
            id="email"
            v-model="email"
            type="email"
            required
            autocomplete="email"
            class="w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-slate-900 focus:border-slate-900 focus:outline-none focus:ring-2 focus:ring-slate-900/20"
          />
        </div>

        <div class="space-y-1">
          <label for="password" class="block text-sm font-medium text-slate-700">Password</label>
          <input
            id="password"
            v-model="password"
            type="password"
            required
            autocomplete="new-password"
            minlength="6"
            class="w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-slate-900 focus:border-slate-900 focus:outline-none focus:ring-2 focus:ring-slate-900/20"
          />
          <p class="text-xs text-slate-500">Minimum 6 characters.</p>
        </div>

        <div class="space-y-1">
          <label for="confirm-password" class="block text-sm font-medium text-slate-700">Confirm Password</label>
          <input
            id="confirm-password"
            v-model="confirmPassword"
            type="password"
            required
            autocomplete="new-password"
            minlength="6"
            class="w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-slate-900 focus:border-slate-900 focus:outline-none focus:ring-2 focus:ring-slate-900/20"
          />
        </div>

        <button
          type="submit"
          :disabled="isProcessing"
          class="w-full rounded-md border-2 border-slate-900 bg-slate-900 px-4 py-2 text-sm font-semibold text-white transition hover:bg-white hover:text-slate-900 disabled:opacity-60"
        >
          {{ isProcessing ? "Creating account..." : "Create account" }}
        </button>

        <div class="my-2 flex items-center gap-3 text-xs uppercase tracking-[0.2em] text-slate-500">
          <div class="flex-1 border-t border-slate-200"></div>
          <span>or</span>
          <div class="flex-1 border-t border-slate-200"></div>
        </div>

        <button
          type="button"
          :disabled="isProcessing"
          class="w-full rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
          @click="handleGoogleRegister"
        >
          Continue with Google
        </button>

        <p v-if="combinedError" class="rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
          {{ combinedError }}
        </p>
      </form>

      <p class="text-center text-sm text-slate-600">
        Already have an account?
        <NuxtLink
          to="/"
          class="text-slate-900 font-semibold hover:text-slate-700"
          @click.prevent="goToSignIn"
        >
          Sign in instead
        </NuxtLink>
      </p>
    </section>
  </main>
</template>
