import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '../api';

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '');
  const user = ref<{ id?: string; username?: string; locale?: string } | null>(
    JSON.parse(localStorage.getItem('user') || 'null'),
  );

  const loginPromptVisible = ref(false);
  const loginReturnTo = ref('');

  function showLoginPrompt(returnTo?: string) {
    loginReturnTo.value = returnTo || '';
    loginPromptVisible.value = true;
  }

  function hideLoginPrompt() {
    loginPromptVisible.value = false;
  }

  async function login(username: string, password: string, countryCode?: string) {
    const dial = countryCode?.replace(/\D/g, '');
    const { data } = await api.post('/player/auth/login', {
      username,
      password,
      ...(dial ? { countryCode: dial } : {}),
    });
    token.value = data.data.token;
    user.value = data.data.user;
    localStorage.setItem('token', token.value);
    localStorage.setItem('user', JSON.stringify(user.value));
    const returnTo = loginReturnTo.value;
    loginReturnTo.value = '';
    loginPromptVisible.value = false;
    return returnTo;
  }

  async function register(
    username: string,
    phone: string,
    countryCode: string,
    password: string,
    smsCode: string,
    sessionId: string,
    inviteCode?: string,
  ) {
    const locale = localStorage.getItem('locale') || 'zh-CN';
    const code = inviteCode?.trim();
    const dial = countryCode.replace(/\D/g, '');
    const { data } = await api.post('/player/auth/register', {
      username: username.trim(),
      phone,
      countryCode: dial,
      password,
      smsCode,
      sessionId,
      locale,
      ...(code ? { inviteCode: code } : {}),
    });
    token.value = data.data.token;
    user.value = data.data.user;
    localStorage.setItem('token', token.value);
    localStorage.setItem('user', JSON.stringify(user.value));
    loginReturnTo.value = '';
    loginPromptVisible.value = false;
  }

  function logout() {
    token.value = '';
    user.value = null;
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }

  return {
    token, user, login, register, logout,
    loginPromptVisible, loginReturnTo,
    showLoginPrompt, hideLoginPrompt,
  };
});
