<script setup lang="ts">
const auth = useDngAuth()
const displayName = ref('')
const savedDisplayName = ref('')
const loading = ref(true)
const saving = ref(false)
const signingOut = ref(false)
const error = ref('')
const success = ref('')

const email = computed(() => auth.session.value?.user.email ?? '')
const hasChanges = computed(() => displayName.value.trim() !== savedDisplayName.value)

function messageFrom(cause: unknown, fallback: string) {
  const value = cause as { data?: { msg?: string; message?: string; error_description?: string }; message?: string }
  return value.data?.msg ?? value.data?.message ?? value.data?.error_description ?? value.message ?? fallback
}

onMounted(async () => {
  try {
    const session = await auth.restore()
    if (!session) {
      await navigateTo('/auth/sign-in', { replace: true })
      return
    }
    const value = session.user.user_metadata?.display_name
    savedDisplayName.value = typeof value === 'string' && value.trim() ? value.trim() : session.user.email?.split('@')[0] ?? 'Adventurer'
    displayName.value = savedDisplayName.value
  } catch (cause) {
    error.value = messageFrom(cause, 'Could not load your profile.')
  } finally {
    loading.value = false
  }
})

async function saveProfile() {
  error.value = ''
  success.value = ''
  const nextDisplayName = displayName.value.trim()
  if (nextDisplayName.length < 2 || nextDisplayName.length > 80) {
    error.value = 'Display name must contain between 2 and 80 characters.'
    return
  }

  saving.value = true
  try {
    await auth.updateProfile(nextDisplayName)
    displayName.value = nextDisplayName
    savedDisplayName.value = nextDisplayName
    success.value = 'PROFILE UPDATED.'
  } catch (cause) {
    error.value = messageFrom(cause, 'Could not update your profile.')
  } finally {
    saving.value = false
  }
}

async function leave() {
  signingOut.value = true
  error.value = ''
  try {
    await auth.signOut()
    await navigateTo('/', { replace: true })
  } catch (cause) {
    error.value = messageFrom(cause, 'Could not sign out.')
    signingOut.value = false
  }
}
</script>

<template>
  <AppShell section="ACCOUNT">
    <div class="profile-page noise">
      <section class="profile-intro">
        <p class="kicker">PLAYER IDENTITY</p>
        <h1>YOUR PROFILE<span>.</span></h1>
        <p>Manage how your party sees you and control access to your account.</p>
      </section>

      <section class="profile-card">
        <div class="identity-mark" aria-hidden="true">{{ savedDisplayName.slice(0, 2).toUpperCase() || 'D&G' }}</div>
        <div class="profile-content">
          <small>ACCOUNT DETAILS</small>
          <form v-if="!loading" class="profile-form" @submit.prevent="saveProfile">
            <label>DISPLAY NAME<input v-model="displayName" name="name" autocomplete="name" minlength="2" maxlength="80" required placeholder="How your party sees you"></label>
            <label>EMAIL<input :value="email" name="email" type="email" autocomplete="email" readonly></label>
            <p class="field-note">Your email is fixed to protect campaign ownership. Use password recovery if you need new credentials.</p>
            <p v-if="error" class="form-message error" role="alert">{{ error }}</p>
            <p v-if="success" class="form-message success" role="status">{{ success }}</p>
            <div class="profile-actions">
              <button class="save-button" :disabled="saving || signingOut || !hasChanges">{{ saving ? 'SAVING…' : 'SAVE PROFILE →' }}</button>
              <NuxtLink to="/auth/forgot-password">RESET PASSWORD</NuxtLink>
            </div>
          </form>
          <p v-else class="loading-state">RECEIVING ACCOUNT DETAILS…</p>
        </div>
      </section>

      <section class="session-card">
        <div><small>SESSION CONTROL</small><h2>LEAVE THE TABLE.</h2><p>Sign out on this device. Your worlds and campaign progress stay saved.</p></div>
        <button :disabled="signingOut || loading" @click="leave">{{ signingOut ? 'SIGNING OUT…' : 'SIGN OUT' }}</button>
      </section>
    </div>
  </AppShell>
</template>

<style scoped>
.profile-page{min-height:calc(100vh - 76px);padding:clamp(42px,6vw,86px) clamp(20px,6vw,88px)}
.profile-intro{max-width:760px}.kicker{margin:0;font:500 9px var(--mono);letter-spacing:.2em;color:var(--acid)}.profile-intro h1{margin:14px 0 12px;font:600 clamp(44px,6vw,82px)/1 var(--display);letter-spacing:-.06em}.profile-intro h1 span{color:var(--acid)}.profile-intro>p:last-child{color:var(--muted);line-height:1.7}
.profile-card{display:grid;grid-template-columns:minmax(220px,.7fr) minmax(0,1.3fr);max-width:1050px;margin-top:52px;border:1px solid var(--line);background:#0e0e0d}.identity-mark{min-height:460px;display:grid;place-items:center;border-right:1px solid var(--line);background:radial-gradient(circle at 50% 50%,#303018 0 3%,#15170c 17%,#090909 64%);color:var(--acid);font:600 clamp(48px,7vw,92px) var(--display);letter-spacing:-.08em}.profile-content{padding:clamp(30px,5vw,58px)}.profile-content>small,.session-card small{font:600 8px var(--mono);letter-spacing:.17em;color:var(--acid)}
.profile-form{display:grid;gap:18px;margin-top:30px}.profile-form label{display:grid;gap:9px;font:600 8px var(--mono);letter-spacing:.13em;color:#b5b5ae}.profile-form input{width:100%;min-height:50px;padding:0 15px;border:1px solid #373732;background:#090909;color:var(--ink);font:12px var(--body);outline:none}.profile-form input:focus{border-color:var(--acid)}.profile-form input[readonly]{color:var(--muted);cursor:not-allowed}.field-note{margin:0;color:var(--muted);font-size:11px;line-height:1.65}.form-message{margin:0;padding:12px 14px;font:500 9px/1.55 var(--mono)}.form-message.error{border:1px solid #6b372e;background:#221310;color:#ffab98}.form-message.success{border:1px solid #526425;background:#151a0d;color:var(--acid)}.profile-actions{display:flex;align-items:center;gap:20px;margin-top:8px}.profile-actions button{min-height:50px;padding:0 22px;border:0;background:var(--acid);color:#080808;font:700 9px var(--mono);letter-spacing:.12em}.profile-actions button:disabled{opacity:.45;cursor:not-allowed}.profile-actions a{color:var(--muted);font:600 8px var(--mono);letter-spacing:.1em}.loading-state{margin-top:30px;color:var(--muted);font:500 9px var(--mono);letter-spacing:.12em}
.session-card{display:flex;align-items:center;justify-content:space-between;gap:30px;max-width:1050px;margin-top:18px;padding:30px clamp(28px,4vw,46px);border:1px solid var(--line);background:#0c0c0b}.session-card h2{margin:12px 0 8px;font:600 clamp(20px,3vw,30px) var(--display);letter-spacing:-.04em}.session-card p{margin:0;color:var(--muted);font-size:12px;line-height:1.6}.session-card button{min-width:150px;min-height:46px;border:1px solid #6b372e;background:transparent;color:#ffab98;font:600 9px var(--mono);letter-spacing:.12em}.session-card button:disabled{opacity:.45;cursor:wait}
@media(max-width:760px){.profile-card{grid-template-columns:1fr}.identity-mark{min-height:210px;border-right:0;border-bottom:1px solid var(--line)}.session-card{align-items:flex-start;flex-direction:column}.session-card button{width:100%}}
@media(max-width:520px){.profile-intro h1{font-size:clamp(36px,13vw,54px)}.profile-content{padding:28px 22px}.profile-actions{align-items:stretch;flex-direction:column}.profile-actions button{width:100%}.profile-actions a{text-align:center}.session-card{padding:26px 22px}}
</style>
