Jake Vanderwerf
2026-05-12 16cb63b05910055c31dca821c86f2eb815da99e3
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
class ReferralAdmin {
    constructor() {
        this.a11y = window.jvbA11y;
        this.referral = window.jvbReferral;
        this.hasCopy = navigator.clipboard && navigator.clipboard.writeText;
        this.initElements();
        this.initListeners();
 
    }
 
    initElements() {
        this.selectors = {
            copyBtn: '.copy-btn',
            invite: 'form.invite',
            adminList: '.items-list.referral',
            dash: '.replace .referral-dashboard',
            list: '.referrals-list'
        }
        this.ui = window.uiFromSelectors(this.selectors);
 
        this.tabs = null;
        if (this.ui.dash) {
            this.tabs =window.jvbTabs.registerTab(this.ui.dash);
            this.initViewController();
        }
        if (this.ui.invite) {
            this.formController = window.jvbForm;
            this.formConfig = this.formController.registerForm(
                this.ui.invite,
                {
                    autosave: true,
                    endpoint: 'referrals',
                    formStatus: false,
                }
            );
 
            this.formController.subscribe((event, payload) => {
                if (event !== 'form-submit') return;
 
                const formData = {
                    ...payload.data,   // ← THIS is your form data
                    action: 'invite'
                };
 
                window.jvbQueue.addToQueue({
                    endpoint: 'referrals',
                    data: formData,
                    title: 'Submitting invitations',
                });
 
                this.formController.clearForm(this.formConfig.id);
                let button = document.querySelector('.referral-dashboard button[type="submit"]');
                let original = button.innerHTML;
                button.innerText = 'Invites sent to server. In line for processing.';
                window.debouncer.schedule(
                    'referral-submit',
                    function() {
                        button.innerHTML = original;
                    },
                    3000
                );
 
            });
        }
 
    }
 
    initListeners() {
        this.clickHandler = this.handleClick.bind(this);
        document.addEventListener('click', this.clickHandler);
        if (window.jvbQueue) {
            window.jvbQueue.subscribe(this.handleQueueEvent.bind(this));
        }
    }
 
    handleClick(e) {
        const target = e.target.closest('.copy-btn');
        if (target) {
            this.handleCopyClick(target);
        }
    }
 
    handleCopyClick(button) {
        const targetId = button.dataset.target;
        const codeElement = button.closest('.row').querySelector(`#${targetId}`);
 
        if (!codeElement) return;
 
        const text = codeElement.textContent.trim();
 
        // Try clipboard API first
        if (this.hasCopy) {
            navigator.clipboard.writeText(text).then(() => {
                button.classList.toggle('success');
                setTimeout(() => {
                    button.classList.remove('success');
                }, 1500);
            });
        }
    }
 
    initViewController() {
        if (!this.referral.listStore || !this.ui.adminList) return;
 
        this.view = new window.jvbViews(this.ui.adminList, this.referral.listStore);
        this.view.subscribe((event, data) => {
            switch(event) {
                case 'item-action':
                    this.handleItemAction(data);
                    break;
                case 'bulk-action':
                    this.handleBulkAction(data);
                    break;
            }
        });
    }
 
    /**
     * Handle item actions (remove, resend)
     */
    handleItemAction(data) {
        const { action, itemId } = data;
 
        switch(action) {
            case 'remove':
                this.removeReferral(itemId);
                break;
            case 'resend':
                this.resendInvite(itemId);
                break;
        }
    }
 
    /**
     * Remove referral from list
     */
    async removeReferral(id) {
        if (!confirm('Remove this referral from your list?')) return;
 
        try {
            const response = await fetch(`${jvbSettings.api}referrals`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.auth.getNonce()
                },
                body: JSON.stringify({
                    action: 'remove',
                    referral_id: id
                })
            });
 
            const result = await response.json();
 
            if (result.success) {
                // Refresh DataStore
                if (this.referral.listStore) this.referral.listStore.fetch();
                if (this.referral.statsStore) this.referral.statsStore.fetch();
                this.a11y?.announce('Referral removed');
            }
        } catch (error) {
            console.error('Error removing referral:', error);
        }
    }
 
    /**
     * Resend invite email
     */
    async resendInvite(id) {
        try {
            const response = await fetch(`${jvbSettings.api}referrals`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.auth.getNonce()
                },
                body: JSON.stringify({
                    action: 'resend',
                    referral_id: id
                })
            });
 
            const result = await response.json();
 
            if (result.success) {
                this.a11y?.announce('Invitation resent');
            } else {
                alert(result.message || 'Cannot resend yet. Wait 7 days between invites.');
            }
        } catch (error) {
            console.error('Error resending invite:', error);
        }
    }
 
    /***************************
    BACKEND stuff
     ***************************/
    handleQueueEvent(event, data) {
        if (event !== 'operation-complete') return;
        if (!data.details) return; // Not our operation
 
        // Check if it's our invite operation
        if (data.details.successful || data.details.failed) {
            this.showInviteResults(data.details);
        }
    }
 
    // showInviteResults(details) {
    //  const successful = details.successful?.length || 0;
    //  const failed = details.failed?.length || 0;
    //
    //  if (failed === 0) {
    //      this.a11y?.announce(`All ${successful} invitations sent successfully!`);
    //      // Clear the form
    //      this.ui.invite?.reset();
    //  } else {
    //      // Show which ones failed
    //      const failureList = details.failed
    //          .map(f => `• ${f.name} (${f.email}): ${f.reason}`)
    //          .join('\n');
    //
    //      const message = `${successful} sent, ${failed} failed:\n${failureList}`;
    //
    //      // Show in a modal or persistent notification
    //      alert(message); // Or use a nicer notification system
    //  }
    // }
 
    showInviteResults(details) {
        if (!this.ui.invite) return;
 
        const tagListField = this.ui.invite.querySelector('[data-field="invite"]');
        if (!tagListField) return;
 
        const tagList = tagListField.querySelector('.tag-list');
        if (!tagList) return;
 
        // Map results by email for easy lookup
        const resultMap = new Map();
 
        details.successful?.forEach(item => {
            resultMap.set(item.email, { status: 'success', name: item.name });
        });
 
        details.failed?.forEach(item => {
            resultMap.set(item.email, {
                status: 'error',
                name: item.name,
                reason: item.reason
            });
        });
 
        // Update each tag with status
        const tags = tagList.querySelectorAll('.tag');
        tags.forEach(tag => {
            const tagData = JSON.parse(tag.dataset.value || '{}');
            const result = resultMap.get(tagData.email);
 
            if (result) {
                this.updateTagStatus(tag, result);
            }
        });
 
        // Show summary notification
        this.showInviteSummary(details);
    }
 
    updateTagStatus(tag, result) {
        // Remove existing status
        tag.classList.remove('success', 'error');
        const existingIcon = tag.querySelector('.status-icon');
        if (existingIcon) existingIcon.remove();
 
        // Add new status
        tag.classList.add(result.status);
 
        const icon = document.createElement('span');
        icon.className = 'status-icon';
        icon.innerHTML = result.status === 'success'
            ? window.jvbIcon('check-circle', { size: 14 })
            : window.jvbIcon('warning-circle', { size: 14 });
 
        if (result.reason) {
            icon.title = result.reason;
        }
 
        // Insert icon before the remove button
        const removeBtn = tag.querySelector('.remove-tag');
        if (removeBtn) {
            tag.insertBefore(icon, removeBtn);
        } else {
            tag.appendChild(icon);
        }
    }
 
    showInviteSummary(details) {
        const successful = details.successful?.length || 0;
        const failed = details.failed?.length || 0;
 
        let message = `Invites sent! ${successful} successful`;
        if (failed > 0) {
            message += `, ${failed} failed`;
        }
 
        // Show in form status or as toast notification
        if (this.formController) {
            this.formController.showStatus(this.ui.invite, 'submitted', message);
        }
 
        // Optionally show detailed failures
        if (failed > 0) {
            this.showFailureDetails(details.failed);
        }
    }
 
    showFailureDetails(failed) {
        // Create a details element or modal showing why each failed
        const detailsHTML = `
        <details class="invite-failures" open>
            <summary>${failed.length} invitation(s) failed - click for details</summary>
            <ul>
                ${failed.map(item => `
                    <li>
                        <strong>${window.escapeHtml(item.name)}</strong>
                        (${window.escapeHtml(item.email)}):
                        <em>${window.escapeHtml(item.reason)}</em>
                    </li>
                `).join('')}
            </ul>
        </details>
    `;
 
        // Insert after the form or in a notification area
        const statusArea = this.ui.invite.querySelector('.fstatus');
        if (statusArea) {
            const existingDetails = statusArea.querySelector('.invite-failures');
            if (existingDetails) existingDetails.remove();
            statusArea.insertAdjacentHTML('beforeend', detailsHTML);
        }
    }
}
 
document.addEventListener('DOMContentLoaded', async function () {
    window.auth.subscribe((event) => {
        if (event === 'auth-loaded') {
            window.jvbAdminReferral = new ReferralAdmin();
        }
    });
});