<template>
  <div class="p-6">
    <h2 class="kestrel-page-heading mb-4">
      Account
    </h2>

    <section
      v-if="user"
      class="mb-8"
    >
      <h3 class="kestrel-section-label">
        Profile photo
      </h3>
      <div class="kestrel-card flex items-center gap-4 p-4">
        <div class="flex h-16 w-16 shrink-0 overflow-hidden rounded-full border border-kestrel-border bg-kestrel-border">
          <img
            v-if="user.avatar_url"
            :src="`${user.avatar_url}${avatarBust ? `?t=${avatarBust}` : ''}`"
            alt=""
            class="h-full w-full object-cover"
          >
          <span
            v-else
            class="flex h-full w-full items-center justify-center text-lg font-medium text-kestrel-text"
          >
            {{ accountInitials }}
          </span>
        </div>
        <div class="flex flex-wrap gap-2">
          <label class="kestrel-btn-secondary cursor-pointer">
            <input
              type="file"
              accept="image/jpeg,image/png"
              class="sr-only"
              :disabled="avatarLoading"
              @change="onAvatarFileChange"
            >
            {{ avatarLoading ? 'Uploading…' : 'Upload' }}
          </label>
          <button
            type="button"
            class="kestrel-btn-secondary disabled:opacity-50"
            :disabled="avatarLoading || !user.avatar_url"
            @click="onRemoveAvatar"
          >
            Remove
          </button>
        </div>
      </div>
    </section>

    <section class="mb-8">
      <h3 class="kestrel-section-label">
        Profile
      </h3>
      <div class="kestrel-card p-4">
        <template v-if="user">
          <dl class="space-y-2 text-sm">
            <div>
              <dt class="text-kestrel-muted">
                Identifier
              </dt>
              <dd class="mt-0.5 font-medium text-kestrel-text">
                {{ user.identifier }}
              </dd>
            </div>
            <div>
              <dt class="text-kestrel-muted">
                Role
              </dt>
              <dd class="mt-0.5 font-medium text-kestrel-text">
                {{ user.role }}
              </dd>
            </div>
            <div>
              <dt class="text-kestrel-muted">
                Sign-in method
              </dt>
              <dd class="mt-0.5 font-medium text-kestrel-text">
                {{ user.auth_provider === 'oidc' ? 'OIDC' : 'Local' }}
              </dd>
            </div>
          </dl>
          <p class="mt-3 text-xs text-kestrel-muted">
            Admins can manage all users on the Members page.
          </p>
        </template>
        <p
          v-else
          class="text-sm text-kestrel-muted"
        >
          Sign in to see your profile.
        </p>
      </div>
    </section>

    <section
      v-if="user"
      class="mb-8"
    >
      <h3 class="kestrel-section-label">
        ATAK / device password
      </h3>
      <div class="kestrel-card p-4">
        <p class="mb-3 text-sm text-kestrel-muted">
          {{ user.auth_provider === 'oidc' ? 'Set a password to use when connecting from ATAK (check "Use Authentication" and enter your KestrelOS username and this password).' : 'Optionally set a separate password for ATAK; otherwise use your login password.' }}
        </p>
        <p
          v-if="cotPasswordSuccess"
          class="mb-3 text-sm text-green-400"
        >
          ATAK password saved.
        </p>
        <p
          v-if="cotPasswordError"
          class="mb-3 text-sm text-red-400"
        >
          {{ cotPasswordError }}
        </p>
        <form
          class="space-y-3"
          @submit.prevent="onSetCotPassword"
        >
          <div>
            <label
              for="account-cot-password"
              class="kestrel-label"
            >ATAK password</label>
            <input
              id="account-cot-password"
              v-model="cotPassword"
              type="password"
              autocomplete="new-password"
              class="kestrel-input"
              :placeholder="user.auth_provider === 'oidc' ? 'Set password for ATAK' : 'Optional'"
            >
          </div>
          <div>
            <label
              for="account-cot-password-confirm"
              class="kestrel-label"
            >Confirm ATAK password</label>
            <input
              id="account-cot-password-confirm"
              v-model="cotPasswordConfirm"
              type="password"
              autocomplete="new-password"
              class="kestrel-input"
            >
          </div>
          <button
            type="submit"
            class="rounded bg-kestrel-accent px-4 py-2 text-sm font-medium text-kestrel-bg transition-opacity hover:opacity-90 disabled:opacity-50"
            :disabled="cotPasswordLoading"
          >
            {{ cotPasswordLoading ? 'Saving…' : 'Save ATAK password' }}
          </button>
        </form>
      </div>
    </section>

    <section
      v-if="user?.auth_provider === 'local'"
      class="mb-8"
    >
      <h3 class="kestrel-section-label">
        Change password
      </h3>
      <div class="kestrel-card p-4">
        <p
          v-if="passwordSuccess"
          class="mb-3 text-sm text-green-400"
        >
          Password updated.
        </p>
        <p
          v-if="passwordError"
          class="mb-3 text-sm text-red-400"
        >
          {{ passwordError }}
        </p>
        <form
          class="space-y-3"
          @submit.prevent="onChangePassword"
        >
          <div>
            <label
              for="account-current-password"
              class="kestrel-label"
            >Current password</label>
            <input
              id="account-current-password"
              v-model="currentPassword"
              type="password"
              autocomplete="current-password"
              class="kestrel-input"
            >
          </div>
          <div>
            <label
              for="account-new-password"
              class="kestrel-label"
            >New password</label>
            <input
              id="account-new-password"
              v-model="newPassword"
              type="password"
              autocomplete="new-password"
              class="kestrel-input"
            >
          </div>
          <div>
            <label
              for="account-confirm-password"
              class="kestrel-label"
            >Confirm new password</label>
            <input
              id="account-confirm-password"
              v-model="confirmPassword"
              type="password"
              autocomplete="new-password"
              class="kestrel-input"
            >
          </div>
          <button
            type="submit"
            class="rounded bg-kestrel-accent px-4 py-2 text-sm font-medium text-kestrel-bg transition-opacity hover:opacity-90 disabled:opacity-50"
            :disabled="passwordLoading"
          >
            {{ passwordLoading ? 'Updating…' : 'Update password' }}
          </button>
        </form>
      </div>
    </section>
  </div>
</template>

<script setup>
const { user, refresh } = useUser()

const avatarBust = ref(0)
const avatarLoading = ref(false)
const currentPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const passwordLoading = ref(false)
const passwordSuccess = ref(false)
const passwordError = ref('')
const cotPassword = ref('')
const cotPasswordConfirm = ref('')
const cotPasswordLoading = ref(false)
const cotPasswordSuccess = ref(false)
const cotPasswordError = ref('')

const accountInitials = computed(() => {
  const id = user.value?.identifier ?? ''
  const parts = id.trim().split(/\s+/)
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase()
  return id.slice(0, 2).toUpperCase() || '?'
})

async function onAvatarFileChange(e) {
  const file = e.target.files?.[0]
  if (!file) return
  avatarLoading.value = true
  try {
    const form = new FormData()
    form.append('avatar', file, file.name)
    await $fetch('/api/me/avatar', { method: 'PUT', body: form, credentials: 'include' })
    avatarBust.value = Date.now()
    await refresh()
  }
  catch {
    // Error surfaced by refresh or network
  }
  finally {
    avatarLoading.value = false
    e.target.value = ''
  }
}

async function onRemoveAvatar() {
  avatarLoading.value = true
  try {
    await $fetch('/api/me/avatar', { method: 'DELETE', credentials: 'include' })
    avatarBust.value = Date.now()
    await refresh()
  }
  finally {
    avatarLoading.value = false
  }
}

async function onChangePassword() {
  passwordError.value = ''
  passwordSuccess.value = false
  if (newPassword.value !== confirmPassword.value) {
    passwordError.value = 'New password and confirmation do not match.'
    return
  }
  if (newPassword.value.length < 1) {
    passwordError.value = 'New password cannot be empty.'
    return
  }
  passwordLoading.value = true
  try {
    await $fetch('/api/me/password', {
      method: 'PUT',
      body: {
        currentPassword: currentPassword.value,
        newPassword: newPassword.value,
      },
      credentials: 'include',
    })
    currentPassword.value = ''
    newPassword.value = ''
    confirmPassword.value = ''
    passwordSuccess.value = true
  }
  catch (e) {
    passwordError.value = e.data?.message ?? e.message ?? 'Failed to update password.'
  }
  finally {
    passwordLoading.value = false
  }
}

async function onSetCotPassword() {
  cotPasswordError.value = ''
  cotPasswordSuccess.value = false
  if (cotPassword.value !== cotPasswordConfirm.value) {
    cotPasswordError.value = 'Password and confirmation do not match.'
    return
  }
  if (cotPassword.value.length < 1) {
    cotPasswordError.value = 'Password cannot be empty.'
    return
  }
  cotPasswordLoading.value = true
  try {
    await $fetch('/api/me/cot-password', {
      method: 'PUT',
      body: { password: cotPassword.value },
      credentials: 'include',
    })
    cotPassword.value = ''
    cotPasswordConfirm.value = ''
    cotPasswordSuccess.value = true
  }
  catch (e) {
    cotPasswordError.value = e.data?.message ?? e.message ?? 'Failed to save ATAK password.'
  }
  finally {
    cotPasswordLoading.value = false
  }
}
</script>
