summaryrefslogtreecommitdiff
path: root/internal/handlers/handlers.go
blob: e4d6457c3bbfda836d01056f5e403a86eda78fe4 (plain)
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
package handlers

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"path/filepath"
	"sort"
	"strings"
	"sync"
	"time"

	"task-dashboard/internal/api"
	"task-dashboard/internal/auth"
	"task-dashboard/internal/config"
	"task-dashboard/internal/models"
	"task-dashboard/internal/store"
)

// Handler holds dependencies for HTTP handlers
type Handler struct {
	store           *store.Store
	todoistClient   api.TodoistAPI
	trelloClient    api.TrelloAPI
	planToEatClient api.PlanToEatAPI
	config          *config.Config
	templates       *template.Template
}

// New creates a new Handler instance
func New(s *store.Store, todoist api.TodoistAPI, trello api.TrelloAPI, planToEat api.PlanToEatAPI, cfg *config.Config) *Handler {
	// Parse templates including partials
	tmpl, err := template.ParseGlob(filepath.Join(cfg.TemplateDir, "*.html"))
	if err != nil {
		log.Printf("Warning: failed to parse templates: %v", err)
	}

	// Also parse partials
	tmpl, err = tmpl.ParseGlob(filepath.Join(cfg.TemplateDir, "partials", "*.html"))
	if err != nil {
		log.Printf("Warning: failed to parse partial templates: %v", err)
	}

	return &Handler{
		store:           s,
		todoistClient:   todoist,
		trelloClient:    trello,
		planToEatClient: planToEat,
		config:          cfg,
		templates:       tmpl,
	}
}

// HandleDashboard renders the main dashboard view
func (h *Handler) HandleDashboard(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Extract tab query parameter for state persistence
	tab := r.URL.Query().Get("tab")
	if tab == "" {
		tab = "tasks"
	}

	// Aggregate data from all sources
	dashboardData, err := h.aggregateData(ctx, false)
	if err != nil {
		http.Error(w, "Failed to load dashboard data", http.StatusInternalServerError)
		log.Printf("Error aggregating data: %v", err)
		return
	}

	// Render template
	if h.templates == nil {
		http.Error(w, "Templates not loaded", http.StatusInternalServerError)
		return
	}

	// Wrap dashboard data with active tab for template
	data := struct {
		*models.DashboardData
		ActiveTab string
		CSRFToken string
	}{
		DashboardData: dashboardData,
		ActiveTab:     tab,
		CSRFToken:     auth.GetCSRFTokenFromContext(ctx),
	}

	if err := h.templates.ExecuteTemplate(w, "index.html", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering template: %v", err)
	}
}

// HandleRefresh forces a refresh of all data
func (h *Handler) HandleRefresh(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Force refresh by passing true
	data, err := h.aggregateData(ctx, true)
	if err != nil {
		http.Error(w, "Failed to refresh data", http.StatusInternalServerError)
		log.Printf("Error refreshing data: %v", err)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(data)
}

// HandleGetTasks returns tasks as JSON
func (h *Handler) HandleGetTasks(w http.ResponseWriter, r *http.Request) {
	tasks, err := h.store.GetTasks()
	if err != nil {
		http.Error(w, "Failed to get tasks", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(tasks)
}

// HandleGetMeals returns meals as JSON
func (h *Handler) HandleGetMeals(w http.ResponseWriter, r *http.Request) {
	startDate := time.Now()
	endDate := startDate.AddDate(0, 0, 7)

	meals, err := h.store.GetMeals(startDate, endDate)
	if err != nil {
		http.Error(w, "Failed to get meals", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(meals)
}

// HandleGetBoards returns Trello boards with cards as JSON
func (h *Handler) HandleGetBoards(w http.ResponseWriter, r *http.Request) {
	boards, err := h.store.GetBoards()
	if err != nil {
		http.Error(w, "Failed to get boards", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(boards)
}

// HandleTasksTab renders the tasks tab content (Trello + Todoist + PlanToEat)
func (h *Handler) HandleTasksTab(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	data, err := h.aggregateData(ctx, false)
	if err != nil {
		http.Error(w, "Failed to load tasks", http.StatusInternalServerError)
		log.Printf("Error loading tasks tab: %v", err)
		return
	}

	if err := h.templates.ExecuteTemplate(w, "tasks-tab", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering tasks tab: %v", err)
	}
}

// HandleRefreshTab refreshes and re-renders the specified tab
func (h *Handler) HandleRefreshTab(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Force refresh
	data, err := h.aggregateData(ctx, true)
	if err != nil {
		http.Error(w, "Failed to refresh", http.StatusInternalServerError)
		log.Printf("Error refreshing tab: %v", err)
		return
	}

	if err := h.templates.ExecuteTemplate(w, "tasks-tab", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering refreshed tab: %v", err)
	}
}

// aggregateData fetches and caches data from all sources
func (h *Handler) aggregateData(ctx context.Context, forceRefresh bool) (*models.DashboardData, error) {
	data := &models.DashboardData{
		LastUpdated: time.Now(),
		Errors:      make([]string, 0),
	}

	var wg sync.WaitGroup
	var mu sync.Mutex

	// Fetch Trello boards (PRIORITY - most important)
	wg.Add(1)
	go func() {
		defer wg.Done()
		boards, err := h.fetchBoards(ctx, forceRefresh)
		mu.Lock()
		defer mu.Unlock()
		if err != nil {
			data.Errors = append(data.Errors, "Trello: "+err.Error())
		} else {
			data.Boards = boards
		}
	}()

	// Fetch Todoist tasks
	wg.Add(1)
	go func() {
		defer wg.Done()
		tasks, err := h.fetchTasks(ctx, forceRefresh)
		mu.Lock()
		defer mu.Unlock()
		if err != nil {
			data.Errors = append(data.Errors, "Todoist: "+err.Error())
		} else {
			// Sort tasks: earliest due date first, nil last, then by priority (descending)
			sort.Slice(tasks, func(i, j int) bool {
				// Handle nil due dates (push to end)
				if tasks[i].DueDate == nil && tasks[j].DueDate != nil {
					return false
				}
				if tasks[i].DueDate != nil && tasks[j].DueDate == nil {
					return true
				}

				// Both have due dates, sort by date
				if tasks[i].DueDate != nil && tasks[j].DueDate != nil {
					if !tasks[i].DueDate.Equal(*tasks[j].DueDate) {
						return tasks[i].DueDate.Before(*tasks[j].DueDate)
					}
				}

				// Same due date (or both nil), sort by priority (descending)
				return tasks[i].Priority > tasks[j].Priority
			})
			data.Tasks = tasks
		}
	}()

	// Fetch Todoist projects
	wg.Add(1)
	go func() {
		defer wg.Done()
		projects, err := h.todoistClient.GetProjects(ctx)
		mu.Lock()
		defer mu.Unlock()
		if err != nil {
			log.Printf("Failed to fetch projects: %v", err)
		} else {
			data.Projects = projects
		}
	}()

	// Fetch PlanToEat meals (if configured)
	if h.planToEatClient != nil {
		wg.Add(1)
		go func() {
			defer wg.Done()
			meals, err := h.fetchMeals(ctx, forceRefresh)
			mu.Lock()
			defer mu.Unlock()
			if err != nil {
				data.Errors = append(data.Errors, "PlanToEat: "+err.Error())
			} else {
				data.Meals = meals
			}
		}()
	}

	wg.Wait()

	// Filter Trello cards into tasks based on heuristic
	var trelloTasks []models.Card
	for _, board := range data.Boards {
		for _, card := range board.Cards {
			listNameLower := strings.ToLower(card.ListName)
			isTask := card.DueDate != nil ||
				strings.Contains(listNameLower, "todo") ||
				strings.Contains(listNameLower, "doing") ||
				strings.Contains(listNameLower, "progress") ||
				strings.Contains(listNameLower, "task")

			if isTask {
				trelloTasks = append(trelloTasks, card)
			}
		}
	}

	// Sort trelloTasks: earliest due date first, nil last, then by board name
	sort.Slice(trelloTasks, func(i, j int) bool {
		// Both have due dates: compare dates
		if trelloTasks[i].DueDate != nil && trelloTasks[j].DueDate != nil {
			if !trelloTasks[i].DueDate.Equal(*trelloTasks[j].DueDate) {
				return trelloTasks[i].DueDate.Before(*trelloTasks[j].DueDate)
			}
			// Same due date, fall through to board name comparison
		}

		// Only one has due date: that one comes first
		if trelloTasks[i].DueDate != nil && trelloTasks[j].DueDate == nil {
			return true
		}
		if trelloTasks[i].DueDate == nil && trelloTasks[j].DueDate != nil {
			return false
		}

		// Both nil or same due date: sort by board name
		return trelloTasks[i].BoardName < trelloTasks[j].BoardName
	})

	data.TrelloTasks = trelloTasks

	return data, nil
}

// fetchTasks fetches tasks from cache or API using incremental sync
func (h *Handler) fetchTasks(ctx context.Context, forceRefresh bool) ([]models.Task, error) {
	cacheKey := store.CacheKeyTodoistTasks
	syncService := "todoist"

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			return h.store.GetTasks()
		}
	}

	// Get stored sync token (empty string means full sync)
	syncToken, err := h.store.GetSyncToken(syncService)
	if err != nil {
		log.Printf("Failed to get sync token, will do full sync: %v", err)
		syncToken = ""
	}

	// Force full sync if requested
	if forceRefresh {
		syncToken = ""
	}

	// Fetch using Sync API
	syncResp, err := h.todoistClient.Sync(ctx, syncToken)
	if err != nil {
		// Try to return cached data even if stale
		cachedTasks, cacheErr := h.store.GetTasks()
		if cacheErr == nil && len(cachedTasks) > 0 {
			return cachedTasks, nil
		}
		return nil, err
	}

	// Build project map from sync response
	projectMap := api.BuildProjectMapFromSync(syncResp.Projects)

	// Process sync response
	if syncResp.FullSync {
		// Full sync: replace all tasks
		tasks := api.ConvertSyncItemsToTasks(syncResp.Items, projectMap)
		if err := h.store.SaveTasks(tasks); err != nil {
			log.Printf("Failed to save tasks to cache: %v", err)
		}
	} else {
		// Incremental sync: merge changes
		var deletedIDs []string
		for _, item := range syncResp.Items {
			if item.IsDeleted || item.IsCompleted {
				deletedIDs = append(deletedIDs, item.ID)
			} else {
				// Upsert active task
				task := h.convertSyncItemToTask(item, projectMap)
				if err := h.store.UpsertTask(task); err != nil {
					log.Printf("Failed to upsert task %s: %v", item.ID, err)
				}
			}
		}
		// Delete removed tasks
		if len(deletedIDs) > 0 {
			if err := h.store.DeleteTasksByIDs(deletedIDs); err != nil {
				log.Printf("Failed to delete tasks: %v", err)
			}
		}
	}

	// Store the new sync token
	if err := h.store.SetSyncToken(syncService, syncResp.SyncToken); err != nil {
		log.Printf("Failed to save sync token: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return h.store.GetTasks()
}

// convertSyncItemToTask converts a sync item to a Task model
func (h *Handler) convertSyncItemToTask(item api.SyncItemResponse, projectMap map[string]string) models.Task {
	task := models.Task{
		ID:          item.ID,
		Content:     item.Content,
		Description: item.Description,
		ProjectID:   item.ProjectID,
		ProjectName: projectMap[item.ProjectID],
		Priority:    item.Priority,
		Completed:   false,
		Labels:      item.Labels,
		URL:         fmt.Sprintf("https://todoist.com/showTask?id=%s", item.ID),
	}

	if item.AddedAt != "" {
		if createdAt, err := time.Parse(time.RFC3339, item.AddedAt); err == nil {
			task.CreatedAt = createdAt
		}
	}

	if item.Due != nil {
		var dueDate time.Time
		var err error
		if item.Due.Datetime != "" {
			dueDate, err = time.Parse(time.RFC3339, item.Due.Datetime)
		} else if item.Due.Date != "" {
			dueDate, err = time.Parse("2006-01-02", item.Due.Date)
		}
		if err == nil {
			task.DueDate = &dueDate
		}
	}

	return task
}

// fetchMeals fetches meals from cache or API
func (h *Handler) fetchMeals(ctx context.Context, forceRefresh bool) ([]models.Meal, error) {
	cacheKey := store.CacheKeyPlanToEatMeals

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			startDate := time.Now()
			endDate := startDate.AddDate(0, 0, 7)
			return h.store.GetMeals(startDate, endDate)
		}
	}

	// Fetch from API
	meals, err := h.planToEatClient.GetUpcomingMeals(ctx, 7)
	if err != nil {
		// Try to return cached data even if stale
		startDate := time.Now()
		endDate := startDate.AddDate(0, 0, 7)
		cachedMeals, cacheErr := h.store.GetMeals(startDate, endDate)
		if cacheErr == nil && len(cachedMeals) > 0 {
			return cachedMeals, nil
		}
		return nil, err
	}

	// Save to cache
	if err := h.store.SaveMeals(meals); err != nil {
		log.Printf("Failed to save meals to cache: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return meals, nil
}

// fetchBoards fetches Trello boards from cache or API
func (h *Handler) fetchBoards(ctx context.Context, forceRefresh bool) ([]models.Board, error) {
	cacheKey := store.CacheKeyTrelloBoards

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			return h.store.GetBoards()
		}
	}

	// Fetch from API
	boards, err := h.trelloClient.GetBoardsWithCards(ctx)
	if err != nil {
		// Try to return cached data even if stale
		cachedBoards, cacheErr := h.store.GetBoards()
		if cacheErr == nil && len(cachedBoards) > 0 {
			return cachedBoards, nil
		}
		return nil, err
	}

	// Save to cache
	if err := h.store.SaveBoards(boards); err != nil {
		log.Printf("Failed to save boards to cache: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return boards, nil
}

// HandleCreateCard creates a new Trello card
func (h *Handler) HandleCreateCard(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Parse form data
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		log.Printf("Error parsing form: %v", err)
		return
	}

	boardID := r.FormValue("board_id")
	listID := r.FormValue("list_id")
	name := r.FormValue("name")

	if boardID == "" || listID == "" || name == "" {
		http.Error(w, "Missing required fields", http.StatusBadRequest)
		return
	}

	// Create the card
	_, err := h.trelloClient.CreateCard(ctx, listID, name, "", nil)
	if err != nil {
		http.Error(w, "Failed to create card", http.StatusInternalServerError)
		log.Printf("Error creating card: %v", err)
		return
	}

	// Force refresh to get updated data
	data, err := h.aggregateData(ctx, true)
	if err != nil {
		http.Error(w, "Failed to refresh data", http.StatusInternalServerError)
		log.Printf("Error refreshing data: %v", err)
		return
	}

	// Find the specific board
	var targetBoard *models.Board
	for i := range data.Boards {
		if data.Boards[i].ID == boardID {
			targetBoard = &data.Boards[i]
			break
		}
	}

	if targetBoard == nil {
		http.Error(w, "Board not found", http.StatusNotFound)
		return
	}

	// Render the updated board
	if err := h.templates.ExecuteTemplate(w, "trello-board", targetBoard); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering board template: %v", err)
	}
}

// HandleCompleteCard marks a Trello card as complete
func (h *Handler) HandleCompleteCard(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Parse form data
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		log.Printf("Error parsing form: %v", err)
		return
	}

	cardID := r.FormValue("card_id")

	if cardID == "" {
		http.Error(w, "Missing card_id", http.StatusBadRequest)
		return
	}

	// Mark card as closed (complete)
	updates := map[string]interface{}{
		"closed": true,
	}

	if err := h.trelloClient.UpdateCard(ctx, cardID, updates); err != nil {
		http.Error(w, "Failed to complete card", http.StatusInternalServerError)
		log.Printf("Error completing card: %v", err)
		return
	}

	// Return empty response (card will be removed from DOM)
	w.WriteHeader(http.StatusOK)
}

// HandleCreateTask creates a new Todoist task
func (h *Handler) HandleCreateTask(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Parse form data
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		log.Printf("Error parsing form: %v", err)
		return
	}

	content := r.FormValue("content")
	projectID := r.FormValue("project_id")

	if content == "" {
		http.Error(w, "Missing content", http.StatusBadRequest)
		return
	}

	// Create the task
	_, err := h.todoistClient.CreateTask(ctx, content, projectID, nil, 0)
	if err != nil {
		http.Error(w, "Failed to create task", http.StatusInternalServerError)
		log.Printf("Error creating task: %v", err)
		return
	}

	// Force refresh to get updated tasks
	tasks, err := h.fetchTasks(ctx, true)
	if err != nil {
		http.Error(w, "Failed to refresh tasks", http.StatusInternalServerError)
		log.Printf("Error refreshing tasks: %v", err)
		return
	}

	// Fetch projects for the dropdown
	projects, err := h.todoistClient.GetProjects(ctx)
	if err != nil {
		log.Printf("Failed to fetch projects: %v", err)
		projects = []models.Project{}
	}

	// Prepare data for template rendering
	data := struct {
		Tasks    []models.Task
		Projects []models.Project
	}{
		Tasks:    tasks,
		Projects: projects,
	}

	// Render the updated task list
	if err := h.templates.ExecuteTemplate(w, "todoist-tasks", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering todoist tasks template: %v", err)
	}
}

// HandleCompleteTask marks a Todoist task as complete
func (h *Handler) HandleCompleteTask(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Parse form data
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		log.Printf("Error parsing form: %v", err)
		return
	}

	taskID := r.FormValue("task_id")

	if taskID == "" {
		http.Error(w, "Missing task_id", http.StatusBadRequest)
		return
	}

	// Mark task as complete
	if err := h.todoistClient.CompleteTask(ctx, taskID); err != nil {
		http.Error(w, "Failed to complete task", http.StatusInternalServerError)
		log.Printf("Error completing task: %v", err)
		return
	}

	// Return empty response (task will be removed from DOM)
	w.WriteHeader(http.StatusOK)
}

// HandleCompleteAtom handles completion of a unified task (Atom)
func (h *Handler) HandleCompleteAtom(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		log.Printf("Error parsing form: %v", err)
		return
	}

	id := r.FormValue("id")
	source := r.FormValue("source")

	if id == "" || source == "" {
		http.Error(w, "Missing id or source", http.StatusBadRequest)
		return
	}

	var err error
	switch source {
	case "todoist":
		err = h.todoistClient.CompleteTask(ctx, id)
	case "trello":
		// Archive the card (closed = true)
		updates := map[string]interface{}{
			"closed": true,
		}
		err = h.trelloClient.UpdateCard(ctx, id, updates)
	default:
		http.Error(w, "Unknown source: "+source, http.StatusBadRequest)
		return
	}

	if err != nil {
		http.Error(w, "Failed to complete task", http.StatusInternalServerError)
		log.Printf("Error completing atom (source=%s, id=%s): %v", source, id, err)
		return
	}

	// Remove from local cache
	switch source {
	case "todoist":
		if err := h.store.DeleteTask(id); err != nil {
			log.Printf("Warning: failed to delete task from cache: %v", err)
		}
	case "trello":
		if err := h.store.DeleteCard(id); err != nil {
			log.Printf("Warning: failed to delete card from cache: %v", err)
		}
	}

	// Return 200 OK with empty body to remove the element from DOM
	w.WriteHeader(http.StatusOK)
}

// HandleUnifiedAdd creates a task in Todoist or a card in Trello from the Quick Add form
func (h *Handler) HandleUnifiedAdd(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		return
	}

	title := r.FormValue("title")
	source := r.FormValue("source")
	dueDateStr := r.FormValue("due_date")

	if title == "" {
		http.Error(w, "Title is required", http.StatusBadRequest)
		return
	}

	// Parse due date if provided (use local timezone)
	var dueDate *time.Time
	if dueDateStr != "" {
		parsed, err := time.ParseInLocation("2006-01-02", dueDateStr, time.Local)
		if err == nil {
			dueDate = &parsed
		}
	}

	switch source {
	case "todoist":
		_, err := h.todoistClient.CreateTask(ctx, title, "", dueDate, 1)
		if err != nil {
			http.Error(w, "Failed to create Todoist task", http.StatusInternalServerError)
			log.Printf("Error creating Todoist task: %v", err)
			return
		}
		// Invalidate cache so fresh data is fetched
		h.store.InvalidateCache(store.CacheKeyTodoistTasks)

	case "trello":
		listID := r.FormValue("list_id")
		if listID == "" {
			http.Error(w, "List is required for Trello", http.StatusBadRequest)
			return
		}
		_, err := h.trelloClient.CreateCard(ctx, listID, title, "", dueDate)
		if err != nil {
			http.Error(w, "Failed to create Trello card", http.StatusInternalServerError)
			log.Printf("Error creating Trello card: %v", err)
			return
		}
		// Invalidate cache so fresh data is fetched
		h.store.InvalidateCache(store.CacheKeyTrelloBoards)

	default:
		http.Error(w, "Invalid source", http.StatusBadRequest)
		return
	}

	// Trigger a refresh of the tasks tab via HTMX
	w.Header().Set("HX-Trigger", "refresh-tasks")
	w.WriteHeader(http.StatusOK)
}

// HandleGetListsOptions returns HTML options for lists in a given board
func (h *Handler) HandleGetListsOptions(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	boardID := r.URL.Query().Get("board_id")

	if boardID == "" {
		http.Error(w, "board_id is required", http.StatusBadRequest)
		return
	}

	lists, err := h.trelloClient.GetLists(ctx, boardID)
	if err != nil {
		http.Error(w, "Failed to fetch lists", http.StatusInternalServerError)
		log.Printf("Error fetching lists for board %s: %v", boardID, err)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	for _, list := range lists {
		fmt.Fprintf(w, `<option value="%s">%s</option>`, list.ID, list.Name)
	}
}

// HandleGetBugs returns the list of reported bugs
func (h *Handler) HandleGetBugs(w http.ResponseWriter, r *http.Request) {
	bugs, err := h.store.GetBugs()
	if err != nil {
		http.Error(w, "Failed to fetch bugs", http.StatusInternalServerError)
		log.Printf("Error fetching bugs: %v", err)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	if len(bugs) == 0 {
		fmt.Fprint(w, `<p class="text-gray-500 text-sm">No bugs reported yet.</p>`)
		return
	}

	for _, bug := range bugs {
		fmt.Fprintf(w, `<div class="text-sm border-b border-gray-100 py-2">
			<p class="text-gray-900">%s</p>
			<p class="text-gray-400 text-xs">%s</p>
		</div>`, template.HTMLEscapeString(bug.Description), bug.CreatedAt.Format("Jan 2, 3:04 PM"))
	}
}

// HandleReportBug saves a new bug report
func (h *Handler) HandleReportBug(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Invalid form data", http.StatusBadRequest)
		return
	}

	description := strings.TrimSpace(r.FormValue("description"))
	if description == "" {
		http.Error(w, "Description is required", http.StatusBadRequest)
		return
	}

	if err := h.store.SaveBug(description); err != nil {
		http.Error(w, "Failed to save bug", http.StatusInternalServerError)
		log.Printf("Error saving bug: %v", err)
		return
	}

	// Return updated bug list
	h.HandleGetBugs(w, r)
}