<template>
  <UModal
    v-model:open="isOpen"
    :dismissible="dismissible"
    :ui="{
      overlay: 'bg-[--parch]/60 backdrop-blur-sm',
      content: 'bg-[--bg] border border-dashed border-[--border] rounded-none shadow-none max-w-[480px]',
      header: 'hidden',
      body: 'p-0',
      footer: 'hidden',
    }"
  >
    <template #body>
      <div class="modal">
        <!-- Close button -->
        <button class="modal-close" @click="resetAndClose">&times;</button>

        <!-- Header -->
        <div class="modal-header">
          <div class="modal-overline">Ghost Guild</div>
          <div class="modal-title">{{ loginModalOptions.title || 'Sign in to continue' }}</div>
          <div class="modal-meta">{{ loginModalOptions.description || 'Enter your email to receive a secure login link' }}</div>
        </div>

        <!-- Body -->
        <div class="modal-body">
          <!-- Success State -->
          <div v-if="loginSuccess" class="success-state">
            <div class="success-icon">✓</div>
            <h3>Check your email</h3>
            <p>We've sent a magic link to <strong>{{ loginForm.email }}</strong>. Click the link to sign in.</p>
          </div>

          <!-- Login Form -->
          <form v-else @submit.prevent="handleLogin">
            <div class="field">
              <label>Email Address</label>
              <input
                v-model="loginForm.email"
                type="email"
                placeholder="your.email@example.com"
                required
              />
            </div>

            <div class="info-box">
              We'll send you a secure magic link. No password needed.
            </div>

            <!-- Error -->
            <div v-if="loginError" class="error-box">
              {{ loginError }}
            </div>

            <button
              type="submit"
              class="btn btn-primary submit-btn"
              :disabled="!isLoginFormValid || isLoggingIn"
            >
              {{ isLoggingIn ? 'Sending...' : 'Send magic link' }}
            </button>
          </form>

          <!-- Join Link -->
          <div v-if="!loginSuccess" class="join-link">
            Not a member? <NuxtLink to="/join" @click="resetAndClose">Join Ghost Guild</NuxtLink>
          </div>
        </div>

        <!-- Footer (success only) -->
        <div v-if="loginSuccess" class="modal-footer">
          <button class="btn" @click="resetAndClose">Close</button>
        </div>
      </div>
    </template>
  </UModal>
</template>

<script setup>
const props = defineProps({
  dismissible: { type: Boolean, default: true },
})

const emit = defineEmits(['success', 'close'])

const { showLoginModal, loginModalOptions, hideLoginModal } = useLoginModal()

const isOpen = computed({
  get: () => showLoginModal.value,
  set: (value) => {
    if (!value) {
      hideLoginModal()
      emit('close')
    }
  },
})

const loginForm = reactive({ email: '' })
const isLoggingIn = ref(false)
const loginSuccess = ref(false)
const loginError = ref('')

const isLoginFormValid = computed(() => {
  return loginForm.email && loginForm.email.includes('@')
})

const handleLogin = async () => {
  if (isLoggingIn.value) return
  isLoggingIn.value = true
  loginError.value = ''

  try {
    const response = await $fetch('/api/auth/login', {
      method: 'POST',
      body: { email: loginForm.email },
    })
    if (response.success) {
      loginSuccess.value = true
      emit('success', { email: loginForm.email })
    }
  } catch (err) {
    console.error('Login error:', err)
    if (err.statusCode === 500) {
      loginError.value = 'Failed to send login email. Please try again later.'
    } else {
      loginError.value = err.statusMessage || 'Something went wrong. Please try again.'
    }
  } finally {
    isLoggingIn.value = false
  }
}

const resetAndClose = () => {
  loginForm.email = ''
  loginSuccess.value = false
  loginError.value = ''
  isOpen.value = false
}

watch(isOpen, (newValue) => {
  if (newValue) {
    loginForm.email = ''
    loginSuccess.value = false
    loginError.value = ''
  }
})
</script>

<style scoped>
.modal {
  position: relative;
}

.modal-close {
  position: absolute;
  top: 20px;
  right: 24px;
  background: none;
  border: none;
  font-family: 'Commit Mono', monospace;
  font-size: 16px;
  color: var(--text-faint);
  cursor: pointer;
  padding: 4px 8px;
  line-height: 1;
  transition: color 0.15s;
}
.modal-close:hover { color: var(--text); }

.modal-header {
  padding: 24px 28px 0;
}

.modal-overline {
  font-family: 'Brygada 1918', serif;
  font-size: 14px;
  font-weight: 600;
  color: var(--candle);
  margin-bottom: 12px;
}

.modal-title {
  font-family: 'Brygada 1918', serif;
  font-size: 22px;
  font-weight: 500;
  color: var(--text-bright);
  line-height: 1.25;
  margin-bottom: 8px;
  padding-right: 32px;
}

.modal-meta {
  font-size: 12px;
  color: var(--text-dim);
}

.modal-body {
  padding: 20px 28px;
}

.modal-footer {
  padding: 16px 28px;
  border-top: 1px dashed var(--border);
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.info-box {
  font-size: 11px;
  color: var(--text-faint);
  padding: 10px 14px;
  border: 1px dashed var(--border);
  margin-bottom: 16px;
  line-height: 1.6;
}

.error-box {
  font-size: 12px;
  color: var(--ember);
  padding: 10px 14px;
  border: 1px dashed var(--ember);
  margin-bottom: 16px;
}

.submit-btn {
  width: 100%;
  text-align: center;
}

.success-state {
  text-align: center;
  padding: 12px 0;
}
.success-icon {
  width: 48px;
  height: 48px;
  border: 2px dashed var(--candle);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
  font-size: 20px;
  color: var(--candle);
}
.success-state h3 {
  font-family: 'Brygada 1918', serif;
  font-size: 18px;
  font-weight: 500;
  color: var(--text-bright);
  margin-bottom: 8px;
}
.success-state p {
  font-size: 12px;
  color: var(--text-dim);
  line-height: 1.7;
}
.success-state strong {
  color: var(--text);
}

.join-link {
  text-align: center;
  padding-top: 16px;
  border-top: 1px dashed var(--border);
  font-size: 12px;
  color: var(--text-faint);
}
.join-link a {
  color: var(--candle);
}
</style>
