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3bd7
 
6f719f6
8ef3bd7
6f719f6
8ef3bd7
6f719f6
 
 
 
 
 
 
8ef3bd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// Global State Management
const AppState = {
    currentUser: {
        id: 1,
        name: 'Admin User',
        email: 'admin@proflow.com',
        role: 'admin',
        avatar: 'http://static.photos/people/200x200/1'
    },
    notifications: [
        { id: 1, type: 'approval', message: 'New service order requires approval', read: false, time: '2 hours ago' },
        { id: 2, type: 'user', message: 'New analyst registration pending', read: true, time: '1 day ago' },
        { id: 3, type: 'project', message: 'Project deadline approaching', read: false, time: '3 days ago' }
    ]
};

// API Service
const ApiService = {
    baseUrl: 'https://jsonplaceholder.typicode.com',
    
    async get(endpoint) {
        try {
            const response = await fetch(`${this.baseUrl}/${endpoint}`);
            return await response.json();
        } catch (error) {
            console.error('API Error:', error);
            throw error;
        }
    },
    
    async post(endpoint, data) {
        try {
            const response = await fetch(`${this.baseUrl}/${endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            return await response.json();
        } catch (error) {
            console.error('API Error:', error);
            throw error;
        }
    }
};
// Modern Notification System
class NotificationManager {
  static show(message, type = 'info', options = {}) {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 px-6 py-4 rounded-xl shadow-lg slide-in flex items-start space-x-3 ${type === 'success' ? 'bg-emerald-500' : type === 'error' ? 'bg-rose-500' : type === 'warning' ? 'bg-amber-500' : 'bg-blue-500'} text-white`;
    
    const iconMap = {
      success: 'check-circle',
      error: 'alert-circle',
      warning: 'alert-triangle',
      info: 'info'
    };
    
    notification.innerHTML = `
      <i data-feather="${iconMap[type] || 'info'}" class="w-5 h-5 flex-shrink-0"></i>
      <div>
        <p class="font-medium">${options.title || type.toUpperCase()}</p>
        <p class="text-sm opacity-90">${message}</p>
      </div>
      <button class="absolute top-2 right-2 opacity-70 hover:opacity-100">
        <i data-feather="x" class="w-4 h-4"></i>
      </button>
    `;
    
    document.body.appendChild(notification);
    feather.replace();
    
    // Auto-dismiss
    const timeout = options.timeout || 5000;
    let dismissTimeout = setTimeout(() => {
      notification.classList.add('fade-out');
      setTimeout(() => notification.remove(), 200);
    }, timeout);
    
    // Manual dismiss
    const dismissBtn = notification.querySelector('button');
    dismissBtn.addEventListener('click', () => {
      clearTimeout(dismissTimeout);
      notification.classList.add('fade-out');
      setTimeout(() => notification.remove(), 200);
    });
    
    // Hover to pause
    notification.addEventListener('mouseenter', () => {
      clearTimeout(dismissTimeout);
    });
    
    notification.addEventListener('mouseleave', () => {
      dismissTimeout = setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => notification.remove(), 200);
      }, 1000);
    });
  }
  
  static showError(message, options = {}) {
    this.show(message, 'error', options);
  }
  
  static showSuccess(message, options = {}) {
    this.show(message, 'success', options);
  }
  
  static showWarning(message, options = {}) {
    this.show(message, 'warning', options);
  }
  
  static showInfo(message, options = {}) {
    this.show(message, 'info', options);
  }
}
// Form Validation
class FormValidator {
    static validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
    
    static validatePhone(phone) {
        const re = /^[\+]?[1-9][\d]{0,15}$/;
        return re.test(phone.replace(/\D/g, ''));
    }
    
    static validateRequired(value) {
        return value && value.trim().length > 0;
    }
    
    static validatePassword(password) {
        return password && password.length >= 8;
    }
}

// Date and Time Utilities
class DateTimeUtils {
    static formatDate(date) {
        return new Date(date).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }
    
    static formatTime(date) {
        return new Date(date).toLocaleTimeString('en-US', {
            hour: '2-digit',
            minute: '2-digit'
        });
    }
    
    static calculateDuration(start, end) {
        const diff = new Date(end) - new Date(start);
        const hours = Math.floor(diff / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        return `${hours}h ${minutes}m`;
    }
    
    static getCurrentDateTime() {
        const now = new Date();
        return now.toISOString().slice(0, 16);
    }
}
// Modern Modal Manager with Animations
class ModalManager {
  static open(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
      modal.classList.remove('hidden');
      modal.classList.add('flex');
      
      const content = modal.querySelector('.modal-content');
      if (content) {
        content.classList.remove('closing');
        content.classList.add('opening');
      }
      
      document.body.style.overflow = 'hidden';
    }
  }
  
  static close(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
      const content = modal.querySelector('.modal-content');
      if (content) {
        content.classList.add('closing');
        content.classList.remove('opening');
        
        content.addEventListener('animationend', () => {
          modal.classList.remove('flex');
          modal.classList.add('hidden');
          document.body.style.overflow = 'auto';
        }, { once: true });
      } else {
        modal.classList.remove('flex');
        modal.classList.add('hidden');
        document.body.style.overflow = 'auto';
      }
    }
  }
  
  static closeAll() {
    document.querySelectorAll('.modal-overlay').forEach(modal => {
      const content = modal.querySelector('.modal-content');
      if (content) {
        content.classList.add('closing');
        content.classList.remove('opening');
        
        content.addEventListener('animationend', () => {
          modal.classList.remove('flex');
          modal.classList.add('hidden');
        }, { once: true });
      } else {
        modal.classList.remove('flex');
        modal.classList.add('hidden');
      }
    });
    document.body.style.overflow = 'auto';
  }
}
// Data Table Manager
class DataTableManager {
    static initialize(tableId, options = {}) {
        const table = document.getElementById(tableId);
        if (!table) return;
        
        // Add search functionality if enabled
        if (options.searchable) {
            const searchInput = document.createElement('input');
            searchInput.type = 'text';
            searchInput.placeholder = 'Search...';
            searchInput.className = 'form-input mb-4';
            searchInput.addEventListener('input', (e) => {
                const searchTerm = e.target.value.toLowerCase();
                const rows = table.querySelectorAll('tbody tr');
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(searchTerm) ? '' : 'none';
                });
            });
            table.parentNode.insertBefore(searchInput, table);
        }
        
        // Add pagination if enabled
        if (options.paginate && options.pageSize) {
            this.addPagination(table, options.pageSize);
        }
    }
    
    static addPagination(table, pageSize) {
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const totalPages = Math.ceil(rows.length / pageSize);
        
        // Hide all rows initially
        rows.forEach(row => row.style.display = 'none');
        
        // Show first page
        this.showPage(rows, 0, pageSize);
        
        // Create pagination controls
        const pagination = document.createElement('div');
        pagination.className = 'flex justify-center items-center space-x-2 mt-4';
        
        for (let i = 0; i < totalPages; i++) {
            const button = document.createElement('button');
            button.textContent = i + 1;
            button.className = 'px-3 py-1 rounded-lg border border-gray-300 hover:bg-gray-50';
            button.addEventListener('click', () => {
                this.showPage(rows, i, pageSize);
                // Update active button
                pagination.querySelectorAll('button').forEach(btn => {
                    btn.classList.remove('bg-primary-600', 'text-white');
                    btn.classList.add('border-gray-300', 'hover:bg-gray-50');
                });
                button.classList.add('bg-primary-600', 'text-white');
                button.classList.remove('border-gray-300', 'hover:bg-gray-50');
            });
            
            if (i === 0) {
                button.classList.add('bg-primary-600', 'text-white');
            }
            
            pagination.appendChild(button);
        }
        
        table.parentNode.appendChild(pagination);
    }
    
    static showPage(rows, pageIndex, pageSize) {
        const start = pageIndex * pageSize;
        const end = start + pageSize;
        
        rows.forEach((row, index) => {
            row.style.display = (index >= start && index < end) ? '' : 'none';
        });
    }
}

// Role-based Access Control
class RBAC {
    static hasPermission(requiredRole) {
        const userRole = AppState.currentUser.role;
        const roleHierarchy = ['analyst', 'manager', 'admin'];
        
        const userIndex = roleHierarchy.indexOf(userRole);
        const requiredIndex = roleHierarchy.indexOf(requiredRole);
        
        return userIndex >= requiredIndex;
    }
    
    static checkPermission(requiredRole) {
        if (!this.hasPermission(requiredRole)) {
            NotificationManager.showError('You do not have permission to perform this action');
            return false;
        }
        return true;
    }
}
// Modern DOM Initialization
document.addEventListener('DOMContentLoaded', function() {
  // Initialize feather icons
  if (typeof feather !== 'undefined') {
    feather.replace();
  }
  
  // Initialize data tables with search
  document.querySelectorAll('[data-table="searchable"]').forEach(table => {
    DataTableManager.initialize(table.id, { 
      searchable: true, 
      paginate: true, 
      pageSize: 5,
      sortable: true
    });
  });
  
  // Setup modal close handlers
  document.querySelectorAll('[data-modal-close]').forEach(button => {
    button.addEventListener('click', function() {
      const modalId = this.getAttribute('data-modal-close');
      ModalManager.close(modalId);
    });
  });
  
  // Close modal when clicking outside
  document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function(e) {
      if (e.target === this) {
        ModalManager.closeAll();
      }
    });
  });
  
  // Format all dates with data-date attribute
  document.querySelectorAll('[data-date]').forEach(element => {
    const date = element.getAttribute('data-date');
    if (date) {
      element.textContent = DateTimeUtils.formatDate(date);
    }
  });
  
  // Format all times with data-time attribute
  document.querySelectorAll('[data-time]').forEach(element => {
    const time = element.getAttribute('data-time');
    if (time) {
      element.textContent = DateTimeUtils.formatTime(time);
    }
  });
  
  // Calculate durations
  document.querySelectorAll('[data-duration-start][data-duration-end]').forEach(element => {
    const start = element.getAttribute('data-duration-start');
    const end = element.getAttribute('data-duration-end');
    if (start && end) {
      element.textContent = DateTimeUtils.calculateDuration(start, end);
    }
  });
  
  // Add hover effects to cards
  document.querySelectorAll('.card').forEach(card => {
    card.classList.add('hover-scale');
  });
  
  // Add ripple effect to buttons
  document.querySelectorAll('.btn').forEach(button => {
    button.addEventListener('click', function(e) {
      const rect = this.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      const ripple = document.createElement('span');
      ripple.className = 'ripple-effect';
      ripple.style.left = `${x}px`;
      ripple.style.top = `${y}px`;
      
      this.appendChild(ripple);
      
      setTimeout(() => {
        ripple.remove();
      }, 600);
    });
  });
  
  // Initialize tooltips
  document.querySelectorAll('[data-tooltip]').forEach(element => {
    const tooltip = document.createElement('div');
    tooltip.className = 'tooltip hidden';
    tooltip.textContent = element.getAttribute('data-tooltip');
    document.body.appendChild(tooltip);
    
    element.addEventListener('mouseenter', (e) => {
      const rect = element.getBoundingClientRect();
      tooltip.classList.remove('hidden');
      tooltip.style.left = `${rect.left + rect.width / 2 - tooltip.offsetWidth / 2}px`;
      tooltip.style.top = `${rect.top - tooltip.offsetHeight - 10}px`;
    });
    
    element.addEventListener('mouseleave', () => {
      tooltip.classList.add('hidden');
    });
  });
});
// Modern Utility Exports
window.AppState = AppState;
window.ApiService = ApiService;
window.NotificationManager = NotificationManager;
window.FormValidator = FormValidator;
window.DateTimeUtils = DateTimeUtils;
window.ModalManager = ModalManager;
window.DataTableManager = DataTableManager;
window.RBAC = RBAC;

// Add modern utility functions
window.Utils = {
  debounce: (func, wait) => {
    let timeout;
    return function(...args) {
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(this, args), wait);
    };
  },
  
  throttle: (func, limit) => {
    let inThrottle;
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  },
  
  copyToClipboard: (text) => {
    navigator.clipboard.writeText(text).then(() => {
      NotificationManager.showSuccess('Copied to clipboard!');
    }).catch(() => {
      NotificationManager.showError('Failed to copy text');
    });
  },
  
  formatBytes: (bytes, decimals = 2) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }
};