import { UserIdentity } from '@/types' const IDENTITY_STORAGE_KEY = 'juntete_identity' const DEVICE_ID_KEY = 'juntete_device_id' export const identityManager = { // Get or create device ID getDeviceId(): string { let deviceId = localStorage.getItem(DEVICE_ID_KEY) if (!deviceId) { deviceId = this.generateDeviceId() localStorage.setItem(DEVICE_ID_KEY, deviceId) } return deviceId }, // Generate a unique device ID generateDeviceId(): string { return `device_${Math.random().toString(36).substr(2, 9)}_${Date.now()}` }, // Save user identity to local storage saveIdentity(identity: UserIdentity): void { try { localStorage.setItem(IDENTITY_STORAGE_KEY, JSON.stringify(identity)) } catch (error) { console.error('Failed to save identity:', error) // Fallback to sessionStorage if localStorage is full try { sessionStorage.setItem(IDENTITY_STORAGE_KEY, JSON.stringify(identity)) } catch (sessionError) { console.error('Failed to save identity to sessionStorage:', sessionError) } } }, // Get user identity from local storage getIdentity(): UserIdentity | null { try { // Try localStorage first const stored = localStorage.getItem(IDENTITY_STORAGE_KEY) if (stored) { const identity = JSON.parse(stored) this.updateLastAccessed(identity) return identity } } catch (error) { console.error('Failed to get identity from localStorage:', error) } try { // Fallback to sessionStorage const stored = sessionStorage.getItem(IDENTITY_STORAGE_KEY) if (stored) { const identity = JSON.parse(stored) this.updateLastAccessed(identity) return identity } } catch (error) { console.error('Failed to get identity from sessionStorage:', error) } return null }, // Update last accessed time updateLastAccessed(identity: UserIdentity): void { identity.lastAccessed = Date.now() this.saveIdentity(identity) }, // Clear identity clearIdentity(): void { localStorage.removeItem(IDENTITY_STORAGE_KEY) sessionStorage.removeItem(IDENTITY_STORAGE_KEY) }, // Check if user is identified for a specific trip isIdentifiedForTrip(tripId: string): boolean { const identity = this.getIdentity() return identity !== null && identity.tripId === tripId }, // Save identity for a trip identifyForTrip(participantName: string, tripId: string): UserIdentity { const deviceId = this.getDeviceId() const identity: UserIdentity = { id: this.generateDeviceId(), participantName, tripId, deviceId, createdAt: Date.now(), lastAccessed: Date.now(), } this.saveIdentity(identity) return identity }, // Switch user identity (for multiple users on same device) switchIdentity(participantName: string, tripId: string): UserIdentity { this.clearIdentity() return this.identifyForTrip(participantName, tripId) }, // Get all stored identities (for multiple user support) getAllIdentities(): UserIdentity[] { // This would be useful for supporting multiple users on the same device // For now, we'll return an empty array as we're using a simple key-based approach return [] }, }