File size: 24,888 Bytes
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7859a
 
 
 
98cd950
 
 
6c7859a
 
790eee5
6c7859a
 
 
 
 
 
790eee5
6c7859a
 
 
 
790eee5
6c7859a
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
98cd950
 
d02cadc
98cd950
 
 
d02cadc
6c7859a
 
98cd950
790eee5
 
 
 
 
 
 
98cd950
 
790eee5
98cd950
 
 
d02cadc
 
98cd950
 
 
d02cadc
 
 
 
 
 
 
 
 
790eee5
98cd950
790eee5
98cd950
 
d02cadc
 
98cd950
 
 
790eee5
98cd950
790eee5
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7859a
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
790eee5
98cd950
 
790eee5
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
98cd950
 
 
 
6c7859a
790eee5
 
 
6c7859a
98cd950
6c7859a
98cd950
 
 
 
d02cadc
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
98cd950
790eee5
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
98cd950
790eee5
98cd950
 
 
 
 
 
 
 
d02cadc
98cd950
d02cadc
 
 
98cd950
 
 
 
 
 
 
 
d02cadc
98cd950
 
 
d02cadc
98cd950
 
d02cadc
98cd950
 
 
d02cadc
98cd950
 
 
 
 
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
/* ============================================

   IVY'S RSS HUB — Sidebar Module

   Search, Bookmarks, Trending, Favorites, Calendar

   ============================================ */

/**

 * SidebarManager - Handles all sidebar functionality

 */
class SidebarManager {
    constructor(app) {
        this.app = app;

        // State
        this.bookmarks = this.loadBookmarks();
        this.favoriteSources = this.loadFavorites();
        this.allArticles = [];
        this.searchDebounceTimer = null;
        this.trendingCache = null; // Cache for trending topics
        this.trendingCacheKey = null; // Cache key based on article count

        // DOM Elements
        this.elements = {
            sidebar: document.getElementById("sidebar"),
            sidebarToggle: document.getElementById("sidebar-toggle"),
            // Search
            searchInput: document.getElementById("search-input"),
            searchClear: document.getElementById("search-clear"),
            searchResults: document.getElementById("search-results"),
            // Bookmarks
            bookmarksList: document.getElementById("bookmarks-list"),
            btnClearBookmarks: document.getElementById("btn-clear-bookmarks"),
            // Trending
            trendingTags: document.getElementById("trending-tags"),
            // Favorites
            favoritesList: document.getElementById("favorites-list"),
            // Calendar
            calendarGrid: document.getElementById("calendar-grid")
        };

        this.init();
    }

    /**

     * Initialize sidebar

     */
    init() {
        this.setupEventListeners();
        this.setupCollapsibleSections();
        this.renderBookmarks();
        this.renderFavorites();
        this.renderCalendar();
    }

    /**

     * Cleanup method (call on app destroy if needed)

     */
    destroy() {
        if (this.searchDebounceTimer) {
            clearTimeout(this.searchDebounceTimer);
            this.searchDebounceTimer = null;
        }
    }

    /**

     * Setup event listeners

     */
    setupEventListeners() {
        // Sidebar toggle (mobile)
        this.elements.sidebarToggle?.addEventListener("click", () => {
            this.elements.sidebar.classList.toggle("open");
        });

        // Close sidebar when clicking outside (mobile)
        document.addEventListener("click", e => {
            if (window.innerWidth <= 1100) {
                if (
                    !this.elements.sidebar.contains(e.target) &&
                    !this.elements.sidebarToggle.contains(e.target) &&
                    this.elements.sidebar.classList.contains("open")
                ) {
                    this.elements.sidebar.classList.remove("open");
                }
            }
        });

        // Search with debounce for performance
        this.elements.searchInput?.addEventListener("input", e => {
            clearTimeout(this.searchDebounceTimer);
            this.searchDebounceTimer = setTimeout(() => {
                this.handleSearch(e.target.value);
            }, 150);
        });

        this.elements.searchClear?.addEventListener("click", () => {
            this.elements.searchInput.value = "";
            this.handleSearch("");
        });

        // Clear bookmarks with double-click protection
        this.elements.btnClearBookmarks?.addEventListener("click", e => {
            // Use data attribute for confirmation state
            if (e.target.dataset.confirmClear === "true") {
                this.bookmarks = [];
                this.saveBookmarks();
                this.renderBookmarks();
                e.target.textContent = "Clear All";
                e.target.dataset.confirmClear = "false";
                e.target.setAttribute("aria-label", "Clear all bookmarks");
                // Refresh main feed to update bookmark icons
                if (this.app) this.app.renderFeeds();
                this.app?.showToast("All bookmarks cleared", "info");
            } else {
                e.target.textContent = "Click again to confirm";
                e.target.dataset.confirmClear = "true";
                e.target.setAttribute("aria-label", "Click again to confirm clearing all bookmarks");
                // Reset after 3 seconds
                setTimeout(() => {
                    e.target.textContent = "Clear All";
                    e.target.dataset.confirmClear = "false";
                    e.target.setAttribute("aria-label", "Clear all bookmarks");
                }, 3000);
            }
        });
    }

    /**

     * Setup collapsible sections

     */
    setupCollapsibleSections() {
        document.querySelectorAll(".sidebar-title.collapsible").forEach(title => {
            title.addEventListener("click", () => {
                const targetId = title.dataset.target;
                const content = document.getElementById(targetId);
                if (content) {
                    title.classList.toggle("collapsed");
                    content.classList.toggle("collapsed");
                }
            });
        });
    }

    /**

     * Update sidebar with new article data

     */
    updateWithArticles(feedResults) {
        // Collect all articles
        this.allArticles = feedResults
            .filter(r => r.status === "success" && r.feed)
            .flatMap(result =>
                result.feed.items.map(item => ({
                    ...item,
                    sourceName: result.name,
                    sourceIcon: result.icon,
                    sourceId: result.id
                }))
            );

        // Update components
        this.renderTrendingTopics();
        this.renderCalendar();
        this.renderFavorites();
    }

    /* ============================================

       SEARCH

       ============================================ */

    handleSearch(query) {
        // Clear any pending debounce
        if (this.searchDebounceTimer) {
            clearTimeout(this.searchDebounceTimer);
            this.searchDebounceTimer = null;
        }

        if (!query || query.length < 2) {
            this.elements.searchResults.innerHTML =
                '<span class="search-hint">Type at least 2 characters to search...</span>';
            return;
        }

        // Show loading indicator immediately for better UX
        this.elements.searchResults.innerHTML =
            '<span class="search-hint"><span class="search-spinner"></span> Searching...</span>';

        // Guard against empty allArticles
        if (!this.allArticles || this.allArticles.length === 0) {
            this.elements.searchResults.innerHTML =
                '<span class="search-hint">No articles loaded yet. Please wait...</span>';
            return;
        }

        const queryLower = query.toLowerCase();
        const results = this.allArticles
            .filter(article => article.title && article.title.toLowerCase().includes(queryLower))
            .slice(0, 20);

        if (results.length === 0) {
            this.elements.searchResults.innerHTML =
                '<span class="search-hint">No results found for "' + this.escapeHtml(query) + '"</span>';
            return;
        }

        // Show count in results header
        const countText =
            results.length === 20 ? "20+ results" : `${results.length} result${results.length > 1 ? "s" : ""}`;

        this.elements.searchResults.innerHTML =
            `<div class="search-count">${countText} for "${this.escapeHtml(query)}"</div>` +
            results
                .map(
                    article => `

            <a class="search-result-item" href="${this.escapeHtml(article.link)}" target="_blank" rel="noopener">

                ${this.highlightMatch(article.title, query)}

                <div class="search-result-source">${article.sourceIcon} ${this.escapeHtml(article.sourceName)}</div>

            </a>

        `
                )
                .join("");
    }

    highlightMatch(text, query) {
        // First escape the text for HTML display
        const escaped = this.escapeHtml(text);
        // Escape the query for use in regex (not HTML escape, regex escape)
        const regexSafeQuery = this.escapeRegex(query);
        // Also need to escape HTML entities in the escaped text for matching
        const escapedQueryForMatch = this.escapeHtml(query);
        const regexSafeEscapedQuery = this.escapeRegex(escapedQueryForMatch);
        const regex = new RegExp(`(${regexSafeEscapedQuery})`, "gi");
        return escaped.replace(regex, "<mark>$1</mark>");
    }

    escapeRegex(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }

    /* ============================================

       BOOKMARKS

       ============================================ */

    loadBookmarks() {
        try {
            return JSON.parse(localStorage.getItem("ivy-rss-bookmarks") || "[]");
        } catch {
            return [];
        }
    }

    saveBookmarks() {
        localStorage.setItem("ivy-rss-bookmarks", JSON.stringify(this.bookmarks));
    }

    addBookmark(article) {
        // Check if already bookmarked
        if (this.bookmarks.find(b => b.link === article.link)) {
            return false;
        }

        this.bookmarks.unshift({
            title: article.title,
            link: article.link,
            source: article.sourceName || "Unknown",
            savedAt: new Date().toISOString()
        });

        // Limit to 50 bookmarks
        if (this.bookmarks.length > 50) {
            this.bookmarks = this.bookmarks.slice(0, 50);
        }

        this.saveBookmarks();
        this.renderBookmarks();
        return true;
    }

    removeBookmark(link) {
        this.bookmarks = this.bookmarks.filter(b => b.link !== link);
        this.saveBookmarks();
        this.renderBookmarks();
    }

    isBookmarked(link) {
        return this.bookmarks.some(b => b.link === link);
    }

    renderBookmarks() {
        // Update bookmark count badge
        const countBadge = document.getElementById("bookmark-count");
        if (countBadge) {
            countBadge.textContent = this.bookmarks.length > 0 ? `(${this.bookmarks.length})` : "";
        }

        if (this.bookmarks.length === 0) {
            this.elements.bookmarksList.innerHTML =
                '<span class="empty-hint">No bookmarks yet. Click ⭐ on articles to save them.</span>';
            return;
        }

        this.elements.bookmarksList.innerHTML = this.bookmarks
            .map(
                bookmark => `

            <div class="bookmark-item">

                <a class="bookmark-link" href="${this.escapeHtml(bookmark.link)}" target="_blank" rel="noopener">

                    ${this.escapeHtml(this.truncate(bookmark.title, 60))}

                </a>

                <button class="bookmark-remove" data-link="${this.escapeAttr(bookmark.link)}" onclick="sidebar.removeBookmarkFromElement(this)" title="Remove" aria-label="Remove bookmark">×</button>

            </div>

        `
            )
            .join("");
    }

    /**

     * Remove bookmark from button element (uses data-link)

     */
    removeBookmarkFromElement(element) {
        const link = element.dataset.link;
        if (link) {
            this.removeBookmark(link);
            // Refresh main feed view to update star icons
            if (this.app) this.app.renderFeeds();
        }
    }

    /* ============================================

       TRENDING TOPICS

       ============================================ */

    renderTrendingTopics() {
        // Check cache - only recalculate if article count changed
        const cacheKey = this.allArticles.length;
        if (this.trendingCache && this.trendingCacheKey === cacheKey) {
            this.elements.trendingTags.innerHTML = this.trendingCache;
            return;
        }

        // Extract keywords from titles
        const wordCounts = {};
        const stopWords = new Set([
            "the",
            "a",
            "an",
            "and",
            "or",
            "but",
            "in",
            "on",
            "at",
            "to",
            "for",
            "of",
            "with",
            "by",
            "from",
            "is",
            "are",
            "was",
            "were",
            "be",
            "been",
            "have",
            "has",
            "had",
            "do",
            "does",
            "did",
            "will",
            "would",
            "could",
            "should",
            "may",
            "might",
            "must",
            "can",
            "this",
            "that",
            "these",
            "those",
            "it",
            "its",
            "as",
            "if",
            "when",
            "where",
            "how",
            "what",
            "which",
            "who",
            "whom",
            "why",
            "not",
            "no",
            "yes",
            "all",
            "any",
            "both",
            "each",
            "few",
            "more",
            "most",
            "other",
            "some",
            "such",
            "than",
            "too",
            "very",
            "just",
            "also",
            "now",
            "new",
            "like",
            "your",
            "you",
            "we",
            "they",
            "he",
            "she",
            "his",
            "her",
            "their",
            "our",
            "le",
            "la",
            "les",
            "de",
            "du",
            "des",
            "un",
            "une",
            "et",
            "ou",
            "pour",
            "avec",
            "sur",
            "dans",
            "par",
            "plus",
            "que",
            "qui",
            "est",
            "son",
            "sa",
            "ses",
            "ce",
            "cette",
            "ces",
            "en",
            "au",
            "aux",
            "ne",
            "pas",
            "se",
            "si",
            "il",
            "elle",
            "ils",
            "nous",
            "vous",
            "être",
            "avoir",
            "fait",
            "faire",
            "après",
            "avant",
            "tout",
            "tous",
            "comment"
        ]);

        this.allArticles.forEach(article => {
            const words = article.title
                .toLowerCase()
                .replace(/[^\w\sàâäéèêëïîôùûüç-]/g, " ")
                .split(/\s+/)
                .filter(word => word.length > 3 && !stopWords.has(word) && !/^\d+$/.test(word));

            words.forEach(word => {
                wordCounts[word] = (wordCounts[word] || 0) + 1;
            });
        });

        // Sort by count and take top 15
        const trending = Object.entries(wordCounts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 15);

        if (trending.length === 0) {
            this.elements.trendingTags.innerHTML = '<span class="empty-hint">No trending topics yet.</span>';
            return;
        }

        const maxCount = trending[0][1];

        const html = trending
            .map(([word, count]) => {
                const isHot = count >= maxCount * 0.7;
                return `

                <button class="trending-tag ${isHot ? "hot" : ""}"

                        onclick="sidebar.filterByTag('${this.escapeHtml(word)}')"

                        onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();sidebar.filterByTag('${this.escapeHtml(word)}')}"

                        tabindex="0"

                        role="button"

                        aria-label="Filter by ${this.escapeHtml(word)}, ${count} articles">

                    ${word}

                    <span class="tag-count" aria-hidden="true">${count}</span>

                </button>

            `;
            })
            .join("");

        // Cache the result
        this.trendingCache = html;
        this.trendingCacheKey = cacheKey;
        this.elements.trendingTags.innerHTML = html;
    }

    filterByTag(tag) {
        this.elements.searchInput.value = tag;
        this.handleSearch(tag);
    }

    /* ============================================

       FAVORITE SOURCES

       ============================================ */

    loadFavorites() {
        try {
            return JSON.parse(localStorage.getItem("ivy-rss-favorites") || "[]");
        } catch {
            return [];
        }
    }

    saveFavorites() {
        localStorage.setItem("ivy-rss-favorites", JSON.stringify(this.favoriteSources));
    }

    toggleFavoriteSource(sourceId, sourceName, sourceIcon) {
        const index = this.favoriteSources.findIndex(f => f.id === sourceId);

        if (index >= 0) {
            this.favoriteSources.splice(index, 1);
        } else {
            this.favoriteSources.push({
                id: sourceId,
                name: sourceName,
                icon: sourceIcon
            });
        }

        this.saveFavorites();
        this.renderFavorites();
        return index < 0; // Returns true if added
    }

    isSourceFavorite(sourceId) {
        return this.favoriteSources.some(f => f.id === sourceId);
    }

    renderFavorites() {
        if (this.favoriteSources.length === 0) {
            this.elements.favoritesList.innerHTML =
                '<span class="empty-hint">No favorite sources. Click ⭐ on source headers.</span>';
            return;
        }

        // Get article counts per source
        const sourceCounts = {};
        this.allArticles.forEach(article => {
            sourceCounts[article.sourceId] = (sourceCounts[article.sourceId] || 0) + 1;
        });

        this.elements.favoritesList.innerHTML = this.favoriteSources
            .map(
                source => `

            <div class="favorite-source" onclick="sidebar.scrollToSource('${source.id}')" role="button" tabindex="0" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();sidebar.scrollToSource('${source.id}')}">

                <span class="favorite-icon" aria-hidden="true">${source.icon}</span>

                <span class="favorite-name">${this.escapeHtml(source.name)}</span>

                <span class="favorite-count" aria-label="${sourceCounts[source.id] || 0} articles">${sourceCounts[source.id] || 0}</span>

                <button class="favorite-remove" onclick="event.stopPropagation(); sidebar.toggleFavoriteSource('${source.id}')" title="Remove from favorites" aria-label="Remove ${this.escapeHtml(source.name)} from favorites">×</button>

            </div>

        `
            )
            .join("");
    }

    scrollToSource(sourceId) {
        const section = document.querySelector(`.source-section[data-source="${sourceId}"]`);
        if (section) {
            section.scrollIntoView({ behavior: "smooth", block: "start" });
            // Flash effect
            section.style.boxShadow = "0 0 0 2px var(--ivy-green)";
            setTimeout(() => {
                section.style.boxShadow = "";
            }, 1500);
        }

        // Close sidebar on mobile
        if (window.innerWidth <= 1100) {
            this.elements.sidebar.classList.remove("open");
        }
    }

    /* ============================================

       CALENDAR

       ============================================ */

    renderCalendar() {
        const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        const today = new Date();
        today.setHours(0, 0, 0, 0); // Normalize to midnight for consistent comparison
        const dayCounts = {};

        // Initialize count for last 7 days
        for (let i = 0; i < 7; i++) {
            const date = new Date(today);
            date.setDate(date.getDate() - i);
            const dateKey = this.getDateKey(date);
            dayCounts[dateKey] = 0;
        }

        // Count articles per day
        this.allArticles.forEach(article => {
            if (article.pubDate) {
                const dateKey = this.getDateKey(article.pubDate);
                if (dateKey in dayCounts) {
                    dayCounts[dateKey]++;
                }
            }
        });

        // Build calendar HTML (last 7 days)
        const calendarHtml = [];
        for (let i = 6; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(date.getDate() - i);
            const dateKey = this.getDateKey(date);
            const count = dayCounts[dateKey] || 0;
            const isToday = i === 0;
            const dayName = days[date.getDay()];
            const dayOfMonth = date.getDate();

            calendarHtml.push(`

                <div class="calendar-day ${isToday ? "active" : ""}"

                     onclick="sidebar.filterByDay(${i})"

                     title="${date.toLocaleDateString()} - ${count} articles"

                     role="button"

                     tabindex="0"

                     aria-pressed="${isToday}"

                     aria-label="${dayName} ${dayOfMonth}, ${count} articles"

                     onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();sidebar.filterByDay(${i})}">

                    <span class="day-name">${dayName}</span>

                    <span class="day-date">${dayOfMonth}</span>

                    <span class="day-count ${count === 0 ? "zero" : ""}">${count}</span>

                </div>

            `);
        }

        this.elements.calendarGrid.innerHTML = calendarHtml.join("");
    }

    /**

     * Get a normalized date key (YYYY-MM-DD) for consistent comparison

     */
    getDateKey(date) {
        const d = new Date(date);
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    }

    filterByDay(daysAgo) {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const targetDate = new Date(today);
        targetDate.setDate(targetDate.getDate() - daysAgo);
        const targetDateKey = this.getDateKey(targetDate);

        // Filter articles from that day using consistent date key
        const dayArticles = this.allArticles.filter(
            article => article.pubDate && this.getDateKey(article.pubDate) === targetDateKey
        );

        if (dayArticles.length === 0) {
            this.elements.searchResults.innerHTML = `<span class="search-hint">No articles from ${targetDate.toLocaleDateString()}</span>`;
        } else {
            this.elements.searchResults.innerHTML = dayArticles
                .slice(0, 20)
                .map(
                    article => `

                <a class="search-result-item" href="${this.escapeHtml(article.link)}" target="_blank" rel="noopener">

                    ${this.escapeHtml(this.truncate(article.title, 80))}

                    <div class="search-result-source">${article.sourceIcon} ${this.escapeHtml(article.sourceName)}</div>

                </a>

            `
                )
                .join("");
        }

        this.elements.searchInput.value = "";

        // Update calendar active state and aria-pressed
        document.querySelectorAll(".calendar-day").forEach((day, index) => {
            const isActive = index === 6 - daysAgo;
            day.classList.toggle("active", isActive);
            day.setAttribute("aria-pressed", isActive);
        });
    }

    /* ============================================

       UTILITIES

       ============================================ */

    escapeHtml(text) {
        return window.IvyUtils.escapeHtml(text);
    }

    /**

     * Escape text for use in HTML attributes (delegates to shared utility)

     */
    escapeAttr(text) {
        return window.IvyUtils.escapeAttr(text);
    }

    truncate(text, maxLength) {
        return window.IvyUtils.truncate(text, maxLength);
    }
}

// Export
window.SidebarManager = SidebarManager;