<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-100">
    <div class="w-full max-w-md bg-white p-8 rounded-2xl shadow-xl">
      <h1 class="text-2xl font-bold text-center mb-6">Create Your Account</h1>

      <form @submit.prevent="signUpWithEmail" class="space-y-4">
        <input
          v-model="name"
          type="text"
          placeholder="Name"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <input
          v-model="email"
          type="email"
          placeholder="Email"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <input
          v-model="password"
          type="password"
          placeholder="Password"
          class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <button
          type="submit"
          class="w-full bg-green-600 text-white py-2 rounded-md hover:bg-green-700 transition"
        >
          Sign Up
        </button>
      </form>

      <div class="mt-6 border-t pt-4">
        <p class="text-center text-gray-500 mb-4">or sign up with</p>

        <div class="space-y-3">
          <button
            @click="signUpWithOAuth('github')"
            class="w-full flex items-center justify-center bg-gray-800 text-white py-2 rounded-md hover:bg-gray-900 transition"
          >
            GitHub
          </button>
          <button
            @click="signUpWithOAuth('facebook')"
            class="w-full flex items-center justify-center bg-blue-700 text-white py-2 rounded-md hover:bg-blue-800 transition"
          >
            Facebook
          </button>
        </div>
      </div>

      <p class="text-center mt-6 text-gray-500">
        Already have an account?
        <NuxtLink to="SignIn" class="text-blue-600 hover:underline">Login</NuxtLink>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Client, Account, ID } from 'appwrite'

const client = new Client()
client.setEndpoint('https://cloud.appwrite.io/v1').setProject('67e1445400053dca1d9b')

const account = new Account(client)

const name = ref('')
const email = ref('')
const password = ref('')

const signUpWithEmail = async () => {
  try {
    await account.create(ID.unique(), email.value, password.value, name.value)
    alert('Account created successfully! Redirecting to login...')
    navigateTo('/SignIn')
  } catch (error) {
    alert('Signup failed: ' + error.message)
  }
}

const signUpWithOAuth = (provider) => {
  account.createOAuth2Session(
    provider,
    'http://localhost:3000', // ✅ success redirect
    'http://localhost:3000/SignUp' // ❌ failure redirect (back to signup)
  )
}
</script>
