const useUserStore = Pinia.defineStore({
	id: "user",
	state: () => ({
		user: null,
		login: null,
	}),
	persist: true,
	storage: localStorage,
	actions: {
		async setLoginUser(form) {
			const login = await axios.post("/guest/login_json", {
				login: form,
			});
			this.login = login.data.data.result;
			this.updateWordPressMenu();
			return login;
		},
		async setSyncUser() {
			try {
				const user = await axios.get(
					"/vendor/agents/show_lean?origin=guest",
					{headers: {SearchAndStayApiToken: "null"}},
				);
				this.user = user.data.data;
				document.cookie = `user=${JSON.stringify(user)}; path=/`;
				this.updateWordPressMenu();
			} catch (e) {
				console.log(e);
			}
		},
		setLogout() {
			this.user = null;
			this.login = null;
			// Clear the user cookie on logout
			document.cookie = 'user=; path=/';
			this.updateWordPressMenu();
		},
		setLoginSocialMedias(data) {
			this.login = data;
			this.updateWordPressMenu();
		},
		async setSignUpUser(form) {
			const signUp = await axios.post("/guest/quick_store", form);
			this.login = signUp.data.data.result;
			this.updateWordPressMenu();
			return signUp;
		},
		async setTwoFactor(form) {
			const twoFactor = await axios.post("/two_factor_auth", {
				two_factor_auth_user_codes: form,
			});
			this.login = twoFactor.data.data.result;
			this.updateWordPressMenu();
			return twoFactor;
		},
		updateWordPressMenu() {
			// Wait for DOM to be ready
			if (document.readyState === 'loading') {
				document.addEventListener('DOMContentLoaded', () => this._updateMenuText());
			} else {
				this._updateMenuText();
			}
		},
		_updateMenuText() {
			const userName = this.user ? 
				(this.user.first_name + (this.user.last_name ? ' ' + this.user.last_name : '')) : 
				'Login';
			
			// Find menu items with class 'guest btn' and update their text
			const menuItems = document.querySelectorAll('.guest.btn, .menu-item-guest');
			menuItems.forEach(item => {
				const link = item.querySelector('a');
				if (link) {
					link.textContent = userName;
				} else {
					item.textContent = userName;
				}
			});
		},
		async twoFactorSetedUp() {
			if (!this.user.seted_up) {
				const store = useValidationEmail()
				try {
					await axios.post("/guest/two_authentication/dispatch_email", {
						guests: { email: this.user.login },
					});
					store.modalValidationEmail = true;
					return
				} catch (e) {
					console.log(e);
				}
			}
		}
	},
	getters: {
		getUser: (state) => state.user,
		getLogin: (state) => state.login,
	},
});
//
// const userDataFromCookie = document.cookie.replace(/(?:(?:^|.*;\s*)userData\s*=\s*([^;]*).*$)|^.*$/, "$1");
//
// if (userDataFromCookie) {
//     useUserStore().setSyncUser(JSON.parse(userDataFromCookie));
// }
window.useUserStore = useUserStore;
