import { defineStore } from "pinia"; import { ref } from "vue"; import { getCurrentUser } from "@/lib/api"; export const useAuthStore = defineStore("auth", () => { const user = ref(null); const isLoading = ref(true); const showCompleteProfile = ref(false); let initialized = false; async function refreshUser() { try { const userData = await getCurrentUser(); user.value = userData; showCompleteProfile.value = !!( userData && (!userData.phone || !userData.shipping_address) ); } catch { user.value = null; showCompleteProfile.value = false; stopPing(); } finally { isLoading.value = false; if (user.value && !pingInterval) startPing(); } } let pingInterval: number | null = null; const unreadMessagesCount = ref(0); function playNotificationSound() { try { const AudioCtx = window.AudioContext || (window as any).webkitAudioContext; if (!AudioCtx) return; const ctx = new AudioCtx(); const osc = ctx.createOscillator(); const gainNode = ctx.createGain(); osc.type = 'sine'; osc.frequency.setValueAtTime(880, ctx.currentTime); // A5 osc.frequency.exponentialRampToValueAtTime(1760, ctx.currentTime + 0.1); // Up to A6 gainNode.gain.setValueAtTime(0, ctx.currentTime); gainNode.gain.linearRampToValueAtTime(0.1, ctx.currentTime + 0.05); gainNode.gain.linearRampToValueAtTime(0, ctx.currentTime + 0.2); osc.connect(gainNode); gainNode.connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + 0.2); } catch (e) { console.warn("Audio disabled or not supported", e); } } function startPing() { import("@/lib/api").then(({ authPing }) => { const doPing = async () => { const res = await authPing(); if (res && res.unread_count !== undefined) { if (res.unread_count > unreadMessagesCount.value) { playNotificationSound(); } unreadMessagesCount.value = res.unread_count; } }; doPing(); // ping immediately pingInterval = window.setInterval(doPing, 30000); }); } function stopPing() { if (pingInterval) { clearInterval(pingInterval); pingInterval = null; } } function init() { if (!initialized) { initialized = true; refreshUser(); } } function setUser(u: any) { user.value = u; } function onProfileComplete() { showCompleteProfile.value = false; refreshUser(); } async function logout() { import("@/lib/api").then(async ({ logoutUser }) => { await logoutUser(); localStorage.removeItem("token"); user.value = null; unreadMessagesCount.value = 0; stopPing(); }); } return { user, isLoading, showCompleteProfile, unreadMessagesCount, init, setUser, refreshUser, onProfileComplete, logout, }; });