-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
810 lines (702 loc) · 30.6 KB
/
Copy pathscript.js
File metadata and controls
810 lines (702 loc) · 30.6 KB
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
/* ══════════════════════════════════════════════════════════════
TECH BACKGROUND CANVAS — Partículas conectadas (login overlay)
══════════════════════════════════════════════════════════════ */
(function initTechCanvas() {
const canvas = document.getElementById('tech-bg-canvas');
if (!canvas) return;
const ctx = canvas.getContext('2d');
const NUM_PARTICLES = 70;
const MAX_DIST = 160;
const SPEED = 0.35;
let W, H, particles;
/* Paleta de azul escuro tech */
const COLORS = [
'rgba(0, 160, 255, ',
'rgba(0, 100, 220, ',
'rgba(30, 180, 255, ',
'rgba(0, 60, 180, ',
'rgba(80, 200, 255, ',
];
function resize() {
W = canvas.width = canvas.offsetWidth;
H = canvas.height = canvas.offsetHeight;
}
function rand(min, max) { return Math.random() * (max - min) + min; }
function createParticle() {
return {
x: rand(0, W),
y: rand(0, H),
vx: rand(-SPEED, SPEED),
vy: rand(-SPEED, SPEED),
r: rand(1.2, 2.8),
col: COLORS[Math.floor(Math.random() * COLORS.length)],
alpha: rand(0.35, 0.85),
};
}
function init() {
resize();
particles = Array.from({ length: NUM_PARTICLES }, createParticle);
}
function draw() {
ctx.clearRect(0, 0, W, H);
/* Linhas de conexão */
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const a = particles[i], b = particles[j];
const dx = a.x - b.x, dy = a.y - b.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < MAX_DIST) {
const strength = 1 - dist / MAX_DIST;
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.strokeStyle = `rgba(0, 130, 255, ${strength * 0.20})`;
ctx.lineWidth = strength * 1.2;
ctx.stroke();
}
}
}
/* Partículas */
particles.forEach(p => {
/* Glow exterior */
const grd = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, p.r * 6);
grd.addColorStop(0, p.col + (p.alpha * 0.6) + ')');
grd.addColorStop(1, p.col + '0)');
ctx.beginPath();
ctx.arc(p.x, p.y, p.r * 6, 0, Math.PI * 2);
ctx.fillStyle = grd;
ctx.fill();
/* Ponto central */
ctx.beginPath();
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
ctx.fillStyle = p.col + p.alpha + ')';
ctx.fill();
/* Movimento */
p.x += p.vx;
p.y += p.vy;
if (p.x < -10) { p.x = W + 10; }
if (p.x > W + 10) { p.x = -10; }
if (p.y < -10) { p.y = H + 10; }
if (p.y > H + 10) { p.y = -10; }
});
requestAnimationFrame(draw);
}
/* Só roda enquanto o overlay estiver visível */
function startIfVisible() {
const overlay = document.getElementById('login-overlay');
if (overlay && overlay.style.display !== 'none') {
requestAnimationFrame(draw);
}
}
window.addEventListener('resize', () => { resize(); });
init();
requestAnimationFrame(draw);
})();
/* ══════════════════════════════════════════════════════════════
AUTH — constantes e estado
══════════════════════════════════════════════════════════════ */
const GOOGLE_CLIENT_ID =
'502453864922-4p67id2no5lgq012m1hc7kt31ou8u6uk.apps.googleusercontent.com';
const GOOGLE_SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/calendar.readonly',
'openid', 'profile', 'email'
].join(' ');
let _tokenClient = null;
let _accessToken = null;
let _emailChart = null; // referência ao Chart.js
let _weekOffset = 0; // 0 = semana atual, -1 = semana passada, +1 = próxima
/* ── Inicializa token client (lazy, ao clicar no botão) ── */
function _initTokenClient() {
_tokenClient = google.accounts.oauth2.initTokenClient({
client_id: GOOGLE_CLIENT_ID,
scope: GOOGLE_SCOPES,
callback: async (resp) => {
if (resp.error) {
console.error('[Auth] Erro OAuth:', resp);
alert(`Erro de autenticação: ${resp.error}\n\nVerifique se http://localhost:8000 está nas Origens JavaScript autorizadas do seu Client ID no Google Cloud Console.`);
_resetSignInButton();
return;
}
_accessToken = resp.access_token;
await _onLoginSuccess();
},
error_callback: (err) => {
console.error('[Auth] Erro GSI:', err);
if (err.type === 'popup_closed') {
// usuário fechou o popup — apenas reabilita o botão
_resetSignInButton();
return;
}
alert(`Não foi possível abrir o login Google.\n\nCausa: ${err.type}\n\nCertifique-se de que:\n• http://localhost:8000 está nas Origens JavaScript autorizadas\n• As APIs Gmail e Google Calendar estão habilitadas no projeto`);
_resetSignInButton();
}
});
}
/* ══════════════════════════════════════════════════════════════
HANDLERS PÚBLICOS (chamados pelo HTML)
══════════════════════════════════════════════════════════════ */
function handleGoogleLogin() {
const btnText = document.querySelector('.btn-signin-text');
const btnLoading = document.querySelector('.btn-signin-loading');
const btn = document.getElementById('google-signin-btn');
btnText.style.display = 'none';
btnLoading.style.display = 'inline';
btn.disabled = true;
// GSI pode ainda estar carregando (script async)
if (!window.google?.accounts?.oauth2) {
// Aguarda até 4s
let tries = 0;
const wait = setInterval(() => {
tries++;
if (window.google?.accounts?.oauth2) {
clearInterval(wait);
_doRequestToken();
} else if (tries > 8) {
clearInterval(wait);
_resetSignInButton();
alert('Não foi possível carregar a biblioteca Google. Verifique sua conexão e tente novamente.');
}
}, 500);
return;
}
_doRequestToken();
}
function _doRequestToken() {
if (!_tokenClient) _initTokenClient();
console.log('[Auth] Client ID:', GOOGLE_CLIENT_ID);
console.log('[Auth] Scopes:', GOOGLE_SCOPES);
console.log('[Auth] GSI carregado?', !!window.google?.accounts?.oauth2);
console.log('[Auth] Solicitando token de acesso…');
// 'select_account' garante que o popup do Google sempre abre
_tokenClient.requestAccessToken({ prompt: 'select_account' });
}
function _resetSignInButton() {
const btnText = document.querySelector('.btn-signin-text');
const btnLoading = document.querySelector('.btn-signin-loading');
const btn = document.getElementById('google-signin-btn');
btnText.style.display = 'inline';
btnLoading.style.display = 'none';
btn.disabled = false;
}
function handleSignOut() {
if (_accessToken) {
google.accounts.oauth2.revoke(_accessToken, () => {});
_accessToken = null;
}
// Volta para o overlay de login
document.getElementById('login-overlay').style.display = 'flex';
document.getElementById('user-profile').style.display = 'none';
document.getElementById('email-data-source').style.display = 'none';
document.getElementById('calendar-data-source').style.display = 'none';
_resetSignInButton();
// Restaura dados mock
_updateEmailChartData([24, 38, 17, 45, 31, 9, 6]);
renderAgenda(MOCK_EVENTS);
}
/* ══════════════════════════════════════════════════════════════
FLUXO PÓS-LOGIN
══════════════════════════════════════════════════════════════ */
async function _onLoginSuccess() {
// Mostra o dashboard imediatamente (tira o overlay)
document.getElementById('login-overlay').style.display = 'none';
document.querySelector('.wrapper').classList.add('data-loading');
try {
const [userInfo, gmailCounts, calendarItems] = await Promise.all([
_fetchUserInfo(),
_fetchGmailWeekCounts(),
_fetchCalendarWeekEvents()
]);
_showUserProfile(userInfo);
_updateEmailChartData(gmailCounts);
_updateAgendaWithCalendar(calendarItems);
// Extrai eventos de hoje para o today strip
const todayEvents = _getTodayEvents(calendarItems);
renderTodayReminder(todayEvents);
document.getElementById('email-data-source').style.display = 'flex';
document.getElementById('calendar-data-source').style.display = 'flex';
} catch (err) {
console.error('[Dashboard] Erro ao buscar dados da API:', err);
} finally {
document.querySelector('.wrapper').classList.remove('data-loading');
}
}
/* ══════════════════════════════════════════════════════════════
API FETCHERS
══════════════════════════════════════════════════════════════ */
async function _apiFetch(url) {
const resp = await fetch(url, {
headers: { Authorization: `Bearer ${_accessToken}` }
});
if (!resp.ok) {
const err = await resp.json().catch(() => ({}));
throw new Error(`[API ${resp.status}] ${err?.error?.message || url}`);
}
return resp.json();
}
/* ── Navega entre semanas ── */
async function navigateWeek(delta, jumpToToday = false) {
if (jumpToToday) {
_weekOffset = 0;
} else {
_weekOffset += delta;
}
// Atualiza botão "Hoje" (desabilitado quando está na semana atual)
const todayBtn = document.getElementById('week-today-btn');
if (todayBtn) todayBtn.disabled = (_weekOffset === 0);
if (_accessToken) {
document.querySelector('.wrapper').classList.add('data-loading');
try {
const [gmailCounts, calendarItems] = await Promise.all([
_fetchGmailWeekCounts(),
_fetchCalendarWeekEvents()
]);
_updateEmailChartData(gmailCounts);
_updateAgendaWithCalendar(calendarItems);
} catch(e) {
console.error('[navigateWeek] Erro:', e);
} finally {
document.querySelector('.wrapper').classList.remove('data-loading');
}
} else {
// Sem login: re-renderiza agenda mock e atualiza label de datas
renderAgenda(MOCK_EVENTS);
}
}
/* ── Extrai eventos de hoje de uma lista do Calendar ── */
function _getTodayEvents(items) {
const today = new Date(); today.setHours(0,0,0,0);
return items
.filter(ev => {
if (ev.status === 'cancelled') return false;
const raw = ev.start?.dateTime || ev.start?.date;
if (!raw) return false;
const d = new Date(raw); d.setHours(0,0,0,0);
return d.getTime() === today.getTime();
})
.map(ev => ({
type: ev.start?.date && !ev.start?.dateTime ? 'todo' : 'meeting',
time: ev.start?.dateTime
? new Date(ev.start.dateTime).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })
: null,
title: ev.summary || '(sem título)'
}))
.sort((a, b) => (a.time || '99:99').localeCompare(b.time || '99:99'));
}
/* ── Renderiza o today strip ── */
function renderTodayReminder(todayEvents = []) {
const evContainer = document.getElementById('today-strip-events');
const dateEl = document.getElementById('today-strip-date');
if (!evContainer) return;
// Data de hoje
const today = new Date();
const dateStr = today.toLocaleDateString('pt-BR', { weekday: 'short', day: '2-digit', month: 'short' });
if (dateEl) dateEl.textContent = dateStr.replace('.', '').toUpperCase();
evContainer.innerHTML = '';
// Tarefas pendentes do task list
const pending = tasks.filter(t => !t.done);
if (pending.length > 0) {
const pill = document.createElement('span');
pill.className = 'today-pill today-pill-task';
pill.title = pending.map(t => t.text).join('\n');
pill.textContent = `✓ ${pending.length} tarefa${pending.length > 1 ? 's' : ''} pendente${pending.length > 1 ? 's' : ''}`;
evContainer.appendChild(pill);
} else if (tasks.length > 0) {
const pill = document.createElement('span');
pill.className = 'today-pill today-pill-done';
pill.textContent = '✓ Todas as tarefas concluídas!';
evContainer.appendChild(pill);
}
// Eventos de hoje
if (!_accessToken) {
const pill = document.createElement('span');
pill.className = 'today-pill today-pill-empty';
pill.textContent = '🔒 Faça login para ver sua agenda';
evContainer.appendChild(pill);
} else if (todayEvents.length === 0) {
const pill = document.createElement('span');
pill.className = 'today-pill today-pill-empty';
pill.textContent = 'Sem eventos hoje ✶';
evContainer.appendChild(pill);
} else {
todayEvents.forEach(ev => {
const pill = document.createElement('span');
pill.className = `today-pill today-pill-${ev.type}`;
pill.textContent = ev.time ? `⏱ ${ev.time} ${ev.title}` : ev.title;
pill.title = ev.title;
evContainer.appendChild(pill);
});
}
// Se não há nada no strip ainda
if (evContainer.children.length === 0) {
const pill = document.createElement('span');
pill.className = 'today-pill today-pill-empty';
pill.textContent = 'Adicione tarefas para começar!';
evContainer.appendChild(pill);
}
}
/* ── Perfil do usuário logado ── */
async function _fetchUserInfo() {
return _apiFetch('https://www.googleapis.com/oauth2/v2/userinfo');
}
/* ── Contagem de e-mails por dia (semana atual) ── */
async function _fetchGmailWeekCounts() {
const dates = getWeekDates();
const counts = await Promise.all(dates.map(async (date) => {
const after = _toGmailDate(date);
const next = new Date(date.getTime() + 86_400_000);
const before = _toGmailDate(next);
const q = encodeURIComponent(`in:inbox after:${after} before:${before}`);
try {
const data = await _apiFetch(
`https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=1&q=${q}`
);
return data.resultSizeEstimate || 0;
} catch {
return 0;
}
}));
return counts; // [seg, ter, qua, qui, sex, sáb, dom]
}
/* ── Formata data para query Gmail: YYYY/MM/DD ── */
function _toGmailDate(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}/${m}/${d}`;
}
/* ── Eventos do Google Calendar na semana atual ── */
async function _fetchCalendarWeekEvents() {
const dates = getWeekDates();
const start = new Date(dates[0]); start.setHours(0, 0, 0, 0);
const end = new Date(dates[6]); end.setHours(23, 59, 59, 999);
const params = new URLSearchParams({
timeMin: start.toISOString(),
timeMax: end.toISOString(),
singleEvents: 'true',
orderBy: 'startTime',
maxResults: '250'
});
const data = await _apiFetch(
`https://www.googleapis.com/calendar/v3/calendars/primary/events?${params}`
);
return data.items || [];
}
/* ══════════════════════════════════════════════════════════════
UI UPDATERS
══════════════════════════════════════════════════════════════ */
function _showUserProfile(user) {
const profile = document.getElementById('user-profile');
const avatar = document.getElementById('user-avatar');
const name = document.getElementById('user-name');
avatar.src = user.picture || '';
avatar.alt = user.name || '';
name.textContent = user.given_name || user.name || user.email || '';
profile.style.display = 'flex';
}
/* ── Atualiza dados do gráfico de e-mails ── */
function _updateEmailChartData(counts) {
if (!_emailChart) return;
const total = counts.reduce((a, b) => a + b, 0);
const totalEl = document.getElementById('email-total');
if (totalEl) totalEl.textContent = `${total} e-mails no total`;
_emailChart.data.datasets[0].data = counts;
_emailChart.update('active');
}
/* ── Converte eventos do Calendar → estrutura interna e re-renderiza ── */
function _updateAgendaWithCalendar(items) {
const dates = getWeekDates();
const byDay = Array.from({ length: 7 }, () => []);
items.forEach(ev => {
if (ev.status === 'cancelled') return;
const startRaw = ev.start?.dateTime || ev.start?.date;
if (!startRaw) return;
const evDate = new Date(startRaw);
evDate.setHours(0, 0, 0, 0);
const idx = dates.findIndex(d => {
const dc = new Date(d); dc.setHours(0, 0, 0, 0);
return dc.getTime() === evDate.getTime();
});
if (idx === -1) return;
const isAllDay = Boolean(ev.start?.date && !ev.start?.dateTime);
const timeStr = ev.start?.dateTime
? new Date(ev.start.dateTime).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })
: null;
byDay[idx].push({
type: isAllDay ? 'todo' : 'meeting',
time: timeStr,
title: ev.summary || '(sem título)'
});
});
renderAgenda(byDay);
}
/* ══════════════════════════════════════════════════════════════
AGENDA SEMANAL
══════════════════════════════════════════════════════════════ */
const MOCK_EVENTS = [
/* Seg */ [
{ type: 'meeting', time: '09:00', title: 'Standup de equipe' },
{ type: 'task', title: 'Revisar relatório mensal' },
{ type: 'todo', title: 'Responder e-mails pendentes' }
],
/* Ter */ [
{ type: 'meeting', time: '10:00', title: 'Alinhamento de produto' },
{ type: 'meeting', time: '15:30', title: 'One-on-one com gestora' },
{ type: 'task', title: 'Atualizar planilha de métricas' }
],
/* Qua */ [
{ type: 'meeting', time: '09:00', title: 'Standup de equipe' },
{ type: 'meeting', time: '14:00', title: 'Review do sprint' },
{ type: 'todo', title: 'Preparar apresentação de sexta' }
],
/* Qui */ [
{ type: 'meeting', time: '11:00', title: 'Reunião com fornecedor' },
{ type: 'task', title: 'Fechar proposta comercial' },
{ type: 'todo', title: 'Revisar documentação técnica' }
],
/* Sex */ [
{ type: 'meeting', time: '09:00', title: 'Standup de equipe' },
{ type: 'meeting', time: '13:00', title: 'Apresentação para diretoria' },
{ type: 'task', title: 'Planning da próxima semana' }
],
/* Sáb */ [{ type: 'todo', title: 'Organizar backlog pessoal' }],
/* Dom */ []
];
const DAY_NAMES = ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'];
/* ── Retorna as 7 datas da semana deslocada por _weekOffset (seg → dom) ── */
function getWeekDates() {
const today = new Date();
const dow = today.getDay(); // 0 = dom
const diff = (dow === 0) ? -6 : 1 - dow; // ajusta para segunda
const monday = new Date(today);
monday.setDate(today.getDate() + diff + (_weekOffset * 7));
return Array.from({ length: 7 }, (_, i) => {
const d = new Date(monday);
d.setDate(monday.getDate() + i);
return d;
});
}
/* ── Renderiza (ou re-renderiza) a grade de agenda ── */
function renderAgenda(eventsByDay) {
const grid = document.getElementById('agenda-grid');
const rangeEl = document.getElementById('week-range');
if (!grid) return;
grid.innerHTML = ''; // limpa antes de re-renderizar
const dates = getWeekDates();
const today = new Date(); today.setHours(0, 0, 0, 0);
const fmt = d => d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
if (rangeEl) rangeEl.textContent = `${fmt(dates[0])} – ${fmt(dates[6])}`;
dates.forEach((date, i) => {
const dc = new Date(date); dc.setHours(0, 0, 0, 0);
const isToday = dc.getTime() === today.getTime();
const isWeekend = i >= 5;
const events = eventsByDay[i] || [];
const col = document.createElement('div');
col.className = 'agenda-day'
+ (isToday ? ' is-today' : '')
+ (isWeekend ? ' is-weekend' : '');
col.innerHTML = `
<div class="agenda-day-head">
<span class="agenda-day-name">${DAY_NAMES[i]}</span>
<span class="agenda-day-date">${String(date.getDate()).padStart(2, '0')}</span>
${isToday ? '<span class="today-badge">hoje</span>' : ''}
</div>
<div class="agenda-events" id="ev-${i}"></div>`;
grid.appendChild(col);
const evContainer = col.querySelector(`#ev-${i}`);
if (events.length === 0) {
evContainer.innerHTML = '<span class="agenda-empty">Dia livre ✦</span>';
return;
}
events.forEach(ev => {
const el = document.createElement('div');
el.className = `agenda-event ev-${ev.type}`;
el.innerHTML = `
${ev.time ? `<span class="agenda-event-time">⏱ ${ev.time}</span>` : ''}
<span class="agenda-event-title">${escHtml(ev.title)}</span>`;
evContainer.appendChild(el);
});
});
}
// Render inicial com dados mock
renderAgenda(MOCK_EVENTS);
/* ══════════════════════════════════════════════════════════════
GRÁFICO — E-MAILS DA SEMANA
══════════════════════════════════════════════════════════════ */
(function initEmailChart() {
const dias = ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'];
const mockEmails = [24, 38, 17, 45, 31, 9, 6];
const total = mockEmails.reduce((a, b) => a + b, 0);
const totalEl = document.getElementById('email-total');
if (totalEl) totalEl.textContent = `${total} e-mails no total`;
const ctx = document.getElementById('emailChart');
if (!ctx) return;
const chartCtx = ctx.getContext('2d');
const grad = chartCtx.createLinearGradient(0, 0, 0, 220);
grad.addColorStop(0, 'rgba(0,240,255,0.80)');
grad.addColorStop(1, 'rgba(0,240,255,0.06)');
_emailChart = new Chart(ctx, {
type: 'bar',
data: {
labels: dias,
datasets: [{
label: 'E-mails recebidos',
data: mockEmails,
backgroundColor: grad,
borderColor: 'rgba(0,240,255,0.60)',
borderWidth: 1,
borderRadius: 3,
borderSkipped: false
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: '#131313',
borderColor: 'rgba(0,240,255,0.25)',
borderWidth: 1,
titleColor: '#00F0FF',
bodyColor: '#e2e2e2',
padding: 10,
callbacks: { label: c => ` ${c.parsed.y} e-mails` }
}
},
scales: {
x: {
grid: { color: 'rgba(255,255,255,0.04)' },
ticks: { color: '#b9cacb', font: { family: "'Inter', sans-serif", size: 12 } },
border: { color: 'transparent' }
},
y: {
beginAtZero: true,
grid: { color: 'rgba(255,255,255,0.04)' },
ticks: { color: '#b9cacb', font: { family: "'Inter', sans-serif", size: 11 }, stepSize: 10 },
border: { color: 'transparent', dash: [4, 4] }
}
}
}
});
})();
/* ══════════════════════════════════════════════════════════════
RELÓGIO & DATA
══════════════════════════════════════════════════════════════ */
function updateClock() {
const now = new Date();
const hh = String(now.getHours()).padStart(2, '0');
const mm = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
document.getElementById('clock').textContent = `${hh}:${mm}:${ss}`;
const dateStr = now.toLocaleDateString('pt-BR', {
weekday: 'long', day: '2-digit', month: 'long', year: 'numeric'
});
document.getElementById('date-display').textContent =
dateStr.charAt(0).toUpperCase() + dateStr.slice(1);
}
updateClock();
setInterval(updateClock, 1000);
/* ══════════════════════════════════════════════════════════════
TAREFAS
══════════════════════════════════════════════════════════════ */
let tasks = JSON.parse(localStorage.getItem('dash-tasks') || '[]');
function saveTasks() { localStorage.setItem('dash-tasks', JSON.stringify(tasks)); }
function renderTasks() {
const list = document.getElementById('task-list');
const empty = document.getElementById('task-empty');
const done = tasks.filter(t => t.done).length;
const total = tasks.length;
document.getElementById('task-counter').textContent = `${done} / ${total}`;
document.getElementById('task-progress').style.width =
total ? `${(done / total) * 100}%` : '0%';
if (total === 0) { empty.style.display = 'block'; return; }
empty.style.display = 'none';
list.innerHTML = '';
tasks.forEach((task, i) => {
const item = document.createElement('div');
item.className = 'task-item' + (task.done ? ' done' : '');
item.innerHTML = `
<div class="task-check" onclick="toggleTask(${i})"></div>
<span class="task-label" onclick="toggleTask(${i})">${escHtml(task.text)}</span>
<button class="task-delete" onclick="deleteTask(${i})" title="Remover">×</button>`;
list.appendChild(item);
});
}
function addTask() {
const input = document.getElementById('task-input');
const text = input.value.trim();
if (!text) return;
tasks.push({ text, done: false });
saveTasks(); renderTasks();
input.value = ''; input.focus();
}
function toggleTask(i) { tasks[i].done = !tasks[i].done; saveTasks(); renderTasks(); renderTodayReminder(); }
function deleteTask(i) { tasks.splice(i, 1); saveTasks(); renderTasks(); renderTodayReminder(); }
document.getElementById('task-input').addEventListener('keydown', e => {
if (e.key === 'Enter') addTask();
});
renderTasks();
// Inicializa o today strip com as tarefas já disponíveis
renderTodayReminder();
/* ══════════════════════════════════════════════════════════════
METAS DO SPRINT
══════════════════════════════════════════════════════════════ */
let goals = JSON.parse(localStorage.getItem('dash-goals') || '[]');
function saveGoals() { localStorage.setItem('dash-goals', JSON.stringify(goals)); }
function renderGoals() {
const list = document.getElementById('goal-list');
const empty = document.getElementById('goal-empty');
if (goals.length === 0) { empty.style.display = 'block'; return; }
empty.style.display = 'none';
list.innerHTML = '';
goals.forEach((goal, i) => {
const item = document.createElement('div');
item.className = 'goal-item' + (goal.done ? ' done-g' : '');
item.innerHTML = `
<div class="goal-bullet" onclick="toggleGoal(${i})" title="Marcar como concluída"></div>
<textarea class="goal-text" rows="1"
oninput="autoResize(this);updateGoalText(${i},this.value)"
onfocus="this.select()">${escHtml(goal.text)}</textarea>
<button class="goal-delete" onclick="deleteGoal(${i})" title="Remover">×</button>`;
list.appendChild(item);
autoResize(item.querySelector('textarea'));
});
}
function addGoal() {
goals.push({ text: 'Nova meta…', done: false });
saveGoals(); renderGoals();
const areas = document.querySelectorAll('.goal-text');
const last = areas[areas.length - 1];
if (last) { last.focus(); last.select(); }
}
function toggleGoal(i) { goals[i].done = !goals[i].done; saveGoals(); renderGoals(); }
function updateGoalText(i, val) { goals[i].text = val; saveGoals(); }
function deleteGoal(i) { goals.splice(i, 1); saveGoals(); renderGoals(); }
function autoResize(el) { el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; }
renderGoals();
/* ══════════════════════════════════════════════════════════════
NOTAS RÁPIDAS
══════════════════════════════════════════════════════════════ */
const notesEl = document.getElementById('notes');
const badge = document.getElementById('saved-badge');
let saveTimer;
notesEl.value = localStorage.getItem('dash-notes') || '';
notesEl.addEventListener('input', () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
localStorage.setItem('dash-notes', notesEl.value);
badge.classList.add('show');
setTimeout(() => badge.classList.remove('show'), 1800);
}, 600);
});
/* ══════════════════════════════════════════════════════════════
UTILS
══════════════════════════════════════════════════════════════ */
function escHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}