File size: 4,207 Bytes
57da3ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { v4 as uuidv4 } from 'uuid';

export const useStore = create(
  persist(
    (set, get) => ({
      deviceId: null,
      deviceToken: null,
      currentUser: null,
      deviceProfiles: [],
      deviceProfilesLoaded: false,
      users: [],
      listings: [], // Now fetched from backend
      messages: [],
      activeCall: null,
      missedCalls: 0,
      isLoading: false,

      initDevice: () => {
        let id = get().deviceId;
        let token = get().deviceToken;
        if (!id) {
          id = uuidv4();
          token = uuidv4(); // Unique secret for this device
          set({ deviceId: id, deviceToken: token });
        }
        get().fetchDeviceProfiles(id, token);
        return { deviceId: id, deviceToken: token };
      },

      fetchDeviceProfiles: async (deviceId, deviceToken) => {
        try {
          const id = deviceId || get().deviceId;
          const token = deviceToken || get().deviceToken;
          
          if (!id) return;

          const res = await fetch(`/api/users/device/${id}`, {
            headers: { 'x-device-token': token || '' }
          });
          
          if (res.ok) {
            const profiles = await res.json();
            set({ deviceProfiles: profiles, deviceProfilesLoaded: true });
          } else {
            set({ deviceProfilesLoaded: true });
          }
        } catch (err) {
          console.error(err);
          set({ deviceProfilesLoaded: true });
        }
      },

      login: (userRecord) => {
        set({ currentUser: userRecord });
        get().fetchDeviceProfiles(get().deviceId, get().deviceToken);
      },

      logout: () => {
        set({ currentUser: null });
        if (get().deviceId) get().fetchDeviceProfiles(get().deviceId, get().deviceToken);
      },

      // Messaging State
      unreadCount: 0,
      activeChatUser: null,
      showInbox: false,
      startChat: (id, name, selfiePath) => set({ activeChatUser: { id, name, selfiePath }, showInbox: false }),
      closeChat: () => set({ activeChatUser: null }),
      toggleInbox: () => set(state => ({ showInbox: !state.showInbox })),
      setUnreadCount: (count) => set({ unreadCount: count }),
      incrementMissedCalls: () => set(state => ({ missedCalls: state.missedCalls + 1 })),
      resetMissedCalls: () => set({ missedCalls: 0 }),
      fetchUnreadCount: async () => {
        const user = get().currentUser;
        if (!user) return;
        try {
          const res = await fetch(`/api/messages/unread-count/${user.id}`);
          if (res.ok) {
            const data = await res.json();
            set({ unreadCount: data.count });
          }
        } catch (err) { console.error(err); }
      },

      fetchListings: async () => {
        set({ isLoading: true });
        try {
          const res = await fetch('/api/listings');
          if (res.ok) {
            const data = await res.json();
            set({ listings: data });
          }
        } catch (error) {
          console.error("Failed to fetch listings:", error);
        } finally {
          set({ isLoading: false });
        }
      },

      updateListingStatus: (id, status) => {
        set(state => ({
          listings: state.listings.map(l => l.id === id ? { ...l, status } : l)
        }));
      },

      editListingDetails: (id, updates) => {
        set(state => ({
          listings: state.listings.map(l => l.id === id ? { ...l, ...updates } : l)
        }));
      },

      startCall: (receiverId, receiverName, receiverSelfie) => {
        set({
          activeCall: {
            callerId: get().currentUser.id,
            callerName: get().currentUser.name,
            callerSelfie: get().currentUser.selfiePath,
            receiverId,
            receiverName,
            receiverSelfie,
            status: 'ringing'
          }
        });
      },

      endCall: () => set({ activeCall: null })
    }),
    {
      name: 'mandi-storage',
      partialize: (state) => ({ 
        deviceId: state.deviceId, 
        deviceToken: state.deviceToken,
        currentUser: state.currentUser
      }),
    }
  )
);