<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { playerAvatarUrl, randomAvatarKey } from '@thebet365/shared';
import api from '../../api';
import PlayerAvatarModal from '../../components/PlayerAvatarModal.vue';
import GoldSpinner from '../../components/GoldSpinner.vue';
import { usePlayerProfile } from '../../composables/usePlayerProfile';
import { useAuthStore } from '../../stores/auth';

const { t } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const { loadProfile, setAvatarKey, profileRaw, avatarUrl } = usePlayerProfile();

const username = ref('');
const viewablePassword = ref('');
const passwordVisible = ref(false);
const phone = ref('');
const email = ref('');
const avatarModalOpen = ref(false);
const passwordChangeOpen = ref(false);
const oldPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const message = ref('');
const error = ref('');
const saving = ref(false);

const allowPasswordChange = computed(
  () => profileRaw.value?.preferences?.allowPasswordChange ?? true,
);
const allowUsernameChange = computed(
  () => profileRaw.value?.preferences?.allowUsernameChange ?? false,
);

const canTogglePassword = computed(() => !!viewablePassword.value);
const passwordInputType = computed(() =>
  passwordVisible.value && canTogglePassword.value ? 'text' : 'password',
);

const displayAvatarUrl = computed(() => {
  if (avatarUrl.value) return avatarUrl.value;
  const seed = profileRaw.value?.username ?? auth.user?.username;
  return seed ? playerAvatarUrl(randomAvatarKey(seed)) : null;
});

function syncFromProfile() {
  const user = profileRaw.value;
  username.value = user?.username ?? auth.user?.username ?? '';
  viewablePassword.value = user?.preferences?.viewablePassword ?? '';
  phone.value = user?.preferences?.phone ?? '';
  email.value = user?.preferences?.email ?? '';
}

async function loadEditData() {
  await loadProfile(true);
  syncFromProfile();
}

onMounted(loadEditData);

async function saveProfile() {
  saving.value = true;
  error.value = '';
  message.value = '';
  try {
    await api.patch('/player/profile', { username: username.value, phone: phone.value, email: email.value });
    message.value = t('profile.save_success') || '保存成功';
    await loadProfile(true);
    syncFromProfile();
  } catch (e: any) {
    error.value = e?.response?.data?.message ?? t('common.error');
  } finally {
    saving.value = false;
  }
}

async function savePassword() {
  if (newPassword.value !== confirmPassword.value) {
    error.value = t('profile.password_mismatch') || '两次密码不一致';
    return;
  }
  saving.value = true;
  error.value = '';
  message.value = '';
  try {
    await api.post('/player/profile/change-password', { oldPassword: oldPassword.value, newPassword: newPassword.value });
    message.value = t('profile.password_changed') || '密码修改成功';
    passwordChangeOpen.value = false;
    oldPassword.value = '';
    newPassword.value = '';
    confirmPassword.value = '';
  } catch (e: any) {
    error.value = e?.response?.data?.message ?? t('common.error');
  } finally {
    saving.value = false;
  }
}

async function onAvatarSelect(key: string | null) {
  avatarModalOpen.value = false;
  await setAvatarKey(key);
}
</script>

<template>
  <div class="desktop-account-page">
    <main class="account-main">
      <div class="edit-layout">
        <div class="page-header">
          <button type="button" class="back-btn" @click="router.back()">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
              <line x1="19" y1="12" x2="5" y2="12"></line>
              <polyline points="12 19 5 12 12 5"></polyline>
            </svg>
            <span>{{ t('common.back') || '返回' }}</span>
          </button>
          <h1 class="page-title">{{ t('profile.edit_title') }}</h1>
        </div>

        <!-- Avatar section -->
        <div class="edit-card">
          <div class="card-title">{{ t('profile.avatar') || '头像' }}</div>
          <div class="avatar-row">
            <img
              v-if="displayAvatarUrl"
              :src="displayAvatarUrl"
              alt="avatar"
              class="avatar-img"
            />
            <div v-else class="avatar-placeholder">
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
            </div>
            <button type="button" class="change-avatar-btn" @click="avatarModalOpen = true">
              {{ t('profile.change_avatar') || '更换头像' }}
            </button>
          </div>
        </div>

        <!-- Basic info -->
        <div class="edit-card">
          <div class="card-title">{{ t('profile.basic_info') || '基础信息' }}</div>

          <div v-if="message" class="success-msg">{{ message }}</div>
          <div v-if="error" class="error-msg">{{ error }}</div>

          <div class="field-group">
            <div class="field">
              <label class="field-label">{{ t('profile.username') || '用户名' }}</label>
              <input
                v-model="username"
                type="text"
                class="field-input"
                :disabled="!allowUsernameChange"
              />
              <p v-if="!allowUsernameChange" class="field-hint">{{ t('profile.username_locked') || '用户名不可修改' }}</p>
            </div>

            <div class="field">
              <label class="field-label">{{ t('profile.phone') || '手机号' }}</label>
              <input v-model="phone" type="text" class="field-input" />
            </div>

            <div class="field">
              <label class="field-label">Email</label>
              <input v-model="email" type="email" class="field-input" />
            </div>
          </div>

          <button type="button" class="save-btn" :disabled="saving" @click="saveProfile">
            <GoldSpinner v-if="saving" :size="18" />
            <span v-else>{{ t('common.save') || '保存' }}</span>
          </button>
        </div>

        <!-- Password change -->
        <div v-if="allowPasswordChange" class="edit-card">
          <div class="card-title">
            {{ t('profile.change_password') || '修改密码' }}
            <button
              type="button"
              class="toggle-btn"
              @click="passwordChangeOpen = !passwordChangeOpen"
            >
              {{ passwordChangeOpen ? (t('common.collapse') || '收起') : (t('common.expand') || '展开') }}
            </button>
          </div>

          <div v-show="passwordChangeOpen" class="field-group">
            <div class="field">
              <label class="field-label">{{ t('profile.old_password') || '当前密码' }}</label>
              <input v-model="oldPassword" type="password" class="field-input" autocomplete="current-password" />
            </div>
            <div class="field">
              <label class="field-label">{{ t('profile.new_password') || '新密码' }}</label>
              <input v-model="newPassword" type="password" class="field-input" autocomplete="new-password" />
            </div>
            <div class="field">
              <label class="field-label">{{ t('profile.confirm_password') || '确认密码' }}</label>
              <input v-model="confirmPassword" type="password" class="field-input" autocomplete="new-password" />
            </div>
            <button type="button" class="save-btn" :disabled="saving" @click="savePassword">
              <GoldSpinner v-if="saving" :size="18" />
              <span v-else>{{ t('profile.change_password') || '修改密码' }}</span>
            </button>
          </div>
        </div>
      </div>

      <PlayerAvatarModal
        :open="avatarModalOpen"
        :model-value="profileRaw?.preferences?.avatarKey ?? null"
        @close="avatarModalOpen = false"
        @confirm="(key) => { avatarModalOpen = false; if (key !== undefined) setAvatarKey(key); }"
      />
    </main>
  </div>
</template>

<style scoped>
.desktop-account-page { display: flex; flex-direction: column; min-height: 0; flex: 1; width: 100%; }

.account-main { flex: 1; min-width: 0; padding: 24px 28px; overflow-y: auto; }
.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid var(--desktop-border);
  background: rgba(255, 255, 255, 0.03);
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: var(--border-gold-soft);
  color: var(--primary-light);
}

.back-btn svg {
  transition: transform 0.2s ease;
}

.back-btn:hover svg {
  transform: translateX(-2px);
}

.page-title { font-size: 18px; font-weight: 800; color: var(--primary-light); margin: 0; }

.edit-layout {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 560px;
  margin: 0 auto;
}

.edit-card {
  background: var(--bg-card);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 10px;
  padding: 20px;
}

.card-title {
  font-size: 12px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.06em;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--desktop-border);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-img {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--border-gold-soft);
}

.avatar-placeholder {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: #1a1a1a;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
  border: 2px solid var(--desktop-border);
}

.change-avatar-btn {
  padding: 7px 16px;
  border-radius: 6px;
  border: 1px solid var(--desktop-border);
  background: transparent;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s;
}

.change-avatar-btn:hover { border-color: var(--border-gold-soft); color: var(--primary-light); }

.field-group { display: flex; flex-direction: column; gap: 14px; margin-bottom: 16px; }

.field { display: flex; flex-direction: column; gap: 6px; }

.field-label {
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.06em;
}

.field-input {
  padding: 10px 14px;
  border-radius: 6px;
  border: 1px solid var(--desktop-border);
  background: #111;
  color: var(--text);
  font-size: 14px;
  font-weight: 600;
  outline: none;
  transition: border-color 0.2s;
}

.field-input:focus { border-color: var(--border-gold-soft); }
.field-input:disabled { opacity: 0.45; cursor: not-allowed; }

.field-hint { font-size: 11px; color: var(--text-muted); margin: 0; }

.success-msg { padding: 10px 14px; border-radius: 6px; background: rgba(52,199,89,0.1); color: #4cd964; font-size: 13px; font-weight: 700; margin-bottom: 14px; }
.error-msg { padding: 10px 14px; border-radius: 6px; background: rgba(255,69,58,0.1); color: #ff453a; font-size: 13px; font-weight: 700; margin-bottom: 14px; }

.save-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 9px 24px;
  border-radius: 6px;
  background: var(--primary);
  color: #111;
  font-size: 13px;
  font-weight: 800;
  border: none;
  cursor: pointer;
  transition: opacity 0.2s;
}

.save-btn:hover:not(:disabled) { opacity: 0.88; }
.save-btn:disabled { opacity: 0.45; cursor: default; }

.toggle-btn {
  background: none;
  border: none;
  color: var(--primary-light);
  font-size: 12px;
  font-weight: 700;
  cursor: pointer;
  text-transform: none;
  letter-spacing: 0;
}
</style>
