/**
 * 注册流程状态管理
 * 使用 Zustand 纯内存状态，不持久化到 AsyncStorage
 */

import { create } from 'zustand';

export type RegisterStep = 0 | 1 | 2;

export interface RegisterFormData {
  email: string;
  verificationCode: string;
  username: string;
  nickname: string;
  phone: string;
  password: string;
  confirmPassword: string;
}

interface RegisterState {
  // 当前步骤: 0=邮箱, 1=验证码, 2=用户信息
  currentStep: RegisterStep;

  // 表单数据
  formData: RegisterFormData;

  // 倒计时（秒）
  countdown: number;

  // 步骤完成状态
  completedSteps: Record<RegisterStep, boolean>;

  // Actions
  setCurrentStep: (step: RegisterStep) => void;
  updateFormData: (data: Partial<RegisterFormData>) => void;
  setCountdown: (seconds: number) => void;
  decrementCountdown: () => void;
  markStepCompleted: (step: RegisterStep) => void;
  resetRegisterData: () => void;
  goToNextStep: () => void;
  goToPrevStep: () => void;
}

const initialFormData: RegisterFormData = {
  email: '',
  verificationCode: '',
  username: '',
  nickname: '',
  phone: '',
  password: '',
  confirmPassword: '',
};

const initialCompletedSteps: Record<RegisterStep, boolean> = {
  0: false,
  1: false,
  2: false,
};

export const useRegisterStore = create<RegisterState>((set) => ({
  currentStep: 0,
  formData: initialFormData,
  countdown: 0,
  completedSteps: initialCompletedSteps,

  setCurrentStep: (step) => set({ currentStep: step }),

  updateFormData: (data) =>
    set((state) => ({
      formData: { ...state.formData, ...data },
    })),

  setCountdown: (seconds) => set({ countdown: seconds }),

  decrementCountdown: () =>
    set((state) => ({
      countdown: state.countdown > 0 ? state.countdown - 1 : 0,
    })),

  markStepCompleted: (step) =>
    set((state) => ({
      completedSteps: { ...state.completedSteps, [step]: true },
    })),

  resetRegisterData: () =>
    set({
      currentStep: 0,
      formData: initialFormData,
      countdown: 0,
      completedSteps: initialCompletedSteps,
    }),

  goToNextStep: () =>
    set((state) => {
      if (state.currentStep < 2) {
        return { currentStep: (state.currentStep + 1) as RegisterStep };
      }
      return state;
    }),

  goToPrevStep: () =>
    set((state) => {
      if (state.currentStep > 0) {
        return { currentStep: (state.currentStep - 1) as RegisterStep };
      }
      return state;
    }),
}));

// 导出便捷 hooks
export const useRegisterStep = () => useRegisterStore((state) => state.currentStep);
export const useRegisterFormData = () => useRegisterStore((state) => state.formData);
export const useRegisterCountdown = () => useRegisterStore((state) => state.countdown);
