<template>
  <div class="register-container">
    <div class="register-box">
      <div class="logo-section">
        <div class="logo-container">
          <img src="/logo.png" alt="Logo" class="logo" />
          <div class="logo-text">KnockOut Whist</div>
        </div>
      </div>

      <div class="content-section">
        <h1 class="title">Create Account</h1>
        <p class="subtitle">Join the ultimate card game experience</p>

        <q-form @submit.prevent="onSubmit" class="form-section">
          <q-input
            v-model="username"
            label="Username"
            filled
            color="primary"
            label-color="grey-6"
            :error="!!errorMessage"
            :error-message="errorMessage"
            class="form-input"
            lazy-rules
            :rules="[
              val => !!val && val.trim().length > 0 || 'Username is required',
              val => val && val.trim().length >= 3 || 'Username must be at least 3 characters',
              val => val && val.trim().length <= 30 || 'Username must be less than 30 characters',
              val => /^[a-zA-Z0-9_-]+$/.test(val) || 'Username can only contain letters, numbers, underscores, and hyphens'
            ]"
          >
            <template v-slot:prepend>
              <q-icon name="person" color="grey-6" />
            </template>
          </q-input>

          <q-input
            v-model="password"
            label="Password"
            filled
            type="password"
            color="primary"
            label-color="grey-6"
            :error="!!errorMessage"
            :error-message="errorMessage"
            class="form-input"
            lazy-rules
            :rules="[
              val => !!val || 'Password is required',
              val => val && val.length >= 6 || 'Password must be at least 6 characters'
            ]"
          >
            <template v-slot:prepend>
              <q-icon name="lock" color="grey-6" />
            </template>
          </q-input>

          <q-input
            v-model="confirmPassword"
            label="Confirm Password"
            filled
            type="password"
            color="primary"
            label-color="grey-6"
            :error="!!errorMessage"
            :error-message="errorMessage"
            class="form-input"
            lazy-rules
            :rules="[
              val => !!val || 'Password confirmation is required',
              val => val === password || 'Passwords do not match'
            ]"
          >
            <template v-slot:prepend>
              <q-icon name="lock_outline" color="grey-6" />
            </template>
          </q-input>

          <div class="action-buttons">
            <q-btn
              type="submit"
              label="Create Account"
              color="primary"
              class="submit-btn"
              :loading="inProgress"
              size="md"
              rounded
            />
          </div>
        </q-form>

        <div class="divider-section">
          <div class="divider">
            <span class="divider-text">Or register with</span>
          </div>
        </div>

        <div class="social-buttons">
          <q-btn
            @click="loginWithProvider('discord')"
            class="social-btn discord-btn"
            size="md"
            rounded
            icon="discord"
            label="Discord"
          />
          <q-btn
            @click="loginWithProvider('keycloak')"
            class="social-btn keycloak-btn"
            size="md"
            rounded
            icon="emoji_people"
            label="Keycloak"
          />
        </div>

        <div class="login-link">
          <span class="login-text">Already have an account?</span>
          <q-btn
            flat
            color="primary"
            label="Login"
            @click="goToLogin"
            class="login-btn"
            size="md"
            dense
          />
        </div>
      </div>
    </div>
    <vue-particles
      id="particles-js"
      :options='options'
    />
  </div>
</template>

<script lang="ts" setup>
import { useQuasar } from 'quasar'
import { ref } from 'vue'
import axios from "axios"
import router from "@/router"

const api = window?.__RUNTIME_CONFIG__?.API_URL
const $q = useQuasar()

const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const inProgress = ref(false)
const errorMessage = ref('')

const onSubmit = async () => {
  if (inProgress.value) return

  inProgress.value = true
  errorMessage.value = ''

  try {
    const response = await axios.post(`${api}/register`, {
      username: username.value.trim(),
      password: password.value
    })

    if (response.status === 201) {
      $q.notify({
        type: 'positive',
        message: 'Registration successful! Please login.',
        position: 'top'
      })
      router.push('/login')
    }
  } catch (error: any) {
    if (error.response?.status === 409) {
      errorMessage.value = 'Username already taken'
    } else if (error.response?.status === 400) {
      errorMessage.value = error.response.data?.message || 'Invalid input'
    } else {
      errorMessage.value = 'Registration failed. Please try again.'
    }
  } finally {
    inProgress.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const loginWithProvider = (provider: string) => {
  window.location.href = `${api}/auth/${provider}`
}

const options = {
  "particles": {
    "number": {
      "value": 80,
      "density": {
        "enable": true,
        "area": 800
      }
    },
    "color": {
      "value": "#ffffff"
    },
    "shape": {
      "type": "circle",
      "stroke": {
        "width": 0,
        "color": "#000000"
      },
      "polygon": {
        "sides": 5
      }
    },
    "opacity": {
      "value": 0.5,
      "random": false,
      "animation": {
        "enable": false,
        "speed": 1,
        "minimumValue": 0.1,
        "sync": false
      }
    },
    "size": {
      "value": 3,
      "random": true,
      "animation": {
        "enable": false,
        "speed": 40,
        "minimumValue": 0.1,
        "sync": false
      }
    },
    "links": {
      "enable": true,
      "distance": 150,
      "color": "#ffffff",
      "opacity": 0.4,
      "width": 1
    },
    "move": {
      "enable": true,
      "speed": 1,
      "direction": "none",
      "random": false,
      "straight": false,
      "outModes": {
        "default": "out"
      },
      "attract": {
        "enable": false,
        "rotate": {
          "x": 600,
          "y": 1200
        }
      }
    }
  },
  "interactivity": {
    "detectsOn": "canvas",
    "events": {
      "onHover": {
        "enable": false,
        "mode": "repulse"
      },
      "onClick": {
        "enable": false,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 400,
        "links": {
          "opacity": 1
        }
      },
      "bubble": {
        "distance": 400,
        "size": 40,
        "duration": 2,
        "opacity": 8,
        "speed": 3
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      },
      "push": {
        "quantity": 4
      },
      "remove": {
        "quantity": 2
      }
    }
  },
  "detectRetina": true
}
</script>

<style scoped>
.register-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  padding: 1rem;
  box-sizing: border-box;
}

.register-box {
  width: 100%;
  max-width: 420px;
  max-height: calc(100vh - 1rem);
  background: var(--color-background-soft);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.5);
  overflow-y: auto;
  overflow-x: hidden;
  z-index: 2;
  border: 1px solid var(--color-border);
  box-sizing: border-box;
}

.logo-section {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  padding: 2rem;
  text-align: center;
  border-bottom: 1px solid var(--color-border);
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
}

.logo {
  height: 50px;
  width: auto;
  filter: brightness(0) invert(1);
}

.logo-text {
  color: #ffffff;
  font-size: 1.5rem;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.content-section {
  padding: 1.5rem;
}

.title {
  color: var(--color-heading);
  font-size: 1.8rem;
  font-weight: 700;
  text-align: center;
  margin-bottom: 0.5rem;
}

.subtitle {
  color: var(--color-text);
  text-align: center;
  margin-bottom: 2rem;
  font-size: 0.95rem;
  line-height: 1.5;
  opacity: 0.8;
}

.form-section {
  display: flex;
  flex-direction: column;
  margin-bottom: 2rem;
}

.form-input {
  border-radius: 12px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 1rem;
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.divider-section {
  margin: 2rem 0;
}

.divider {
  position: relative;
  text-align: center;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: var(--color-border);
}

.divider-text {
  background: var(--color-background-soft);
  padding: 0 1rem;
  color: var(--color-text);
  font-size: 0.85rem;
  position: relative;
  opacity: 0.7;
}

.social-buttons {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
}

.social-btn {
  flex: 1;
  height: 48px;
  background: var(--color-background-mute);
  border: 2px solid var(--color-border);
  color: var(--color-heading);
  font-weight: 500;
  transition: all 0.3s ease;
}

.social-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.discord-btn:hover {
  border-color: #5865F2;
  background: rgba(88, 101, 242, 0.1);
}

.keycloak-btn:hover {
  border-color: #0088CC;
  background: rgba(0, 136, 204, 0.1);
}

.social-icon {
  margin-right: 0.5rem;
}

.social-text {
  font-weight: 500;
}

.login-link {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.login-text {
  color: var(--color-text);
  font-size: 0.9rem;
  opacity: 0.7;
}

#particles-js {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

@media (max-width: 600px) {
  .register-box {
    max-width: 100%;
    border-radius: 16px;
    max-height: calc(100vh - 1rem);
  }

  .content-section {
    padding: 1rem;
  }

  .title {
    font-size: 1.5rem;
  }

  .social-buttons {
    flex-direction: column;
  }
}
</style>
