xref: /plugin/calendar/syntax.php (revision 96df7d3e9a825dddf459ab1ee6077a9886837f17)
1<?php
2/**
3 * DokuWiki Plugin calendar (Syntax Component)
4 * Compact design with integrated event list
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  DokuWiki Community
8 */
9
10if (!defined('DOKU_INC')) die();
11
12class syntax_plugin_calendar extends DokuWiki_Syntax_Plugin {
13
14    public function getType() {
15        return 'substition';
16    }
17
18    public function getPType() {
19        return 'block';
20    }
21
22    public function getSort() {
23        return 155;
24    }
25
26    public function connectTo($mode) {
27        $this->Lexer->addSpecialPattern('\{\{calendar(?:[^\}]*)\}\}', $mode, 'plugin_calendar');
28        $this->Lexer->addSpecialPattern('\{\{eventlist(?:[^\}]*)\}\}', $mode, 'plugin_calendar');
29        $this->Lexer->addSpecialPattern('\{\{eventpanel(?:[^\}]*)\}\}', $mode, 'plugin_calendar');
30    }
31
32    public function handle($match, $state, $pos, Doku_Handler $handler) {
33        $isEventList = (strpos($match, '{{eventlist') === 0);
34        $isEventPanel = (strpos($match, '{{eventpanel') === 0);
35
36        if ($isEventList) {
37            $match = substr($match, 12, -2);
38        } elseif ($isEventPanel) {
39            $match = substr($match, 13, -2);
40        } else {
41            $match = substr($match, 10, -2);
42        }
43
44        $params = array(
45            'type' => $isEventPanel ? 'eventpanel' : ($isEventList ? 'eventlist' : 'calendar'),
46            'year' => date('Y'),
47            'month' => date('n'),
48            'namespace' => '',
49            'daterange' => '',
50            'date' => '',
51            'range' => ''
52        );
53
54        if (trim($match)) {
55            $pairs = preg_split('/\s+/', trim($match));
56            foreach ($pairs as $pair) {
57                if (strpos($pair, '=') !== false) {
58                    list($key, $value) = explode('=', $pair, 2);
59                    $params[trim($key)] = trim($value);
60                } else {
61                    // Handle standalone flags like "today"
62                    $params[trim($pair)] = true;
63                }
64            }
65        }
66
67        return $params;
68    }
69
70    public function render($mode, Doku_Renderer $renderer, $data) {
71        if ($mode !== 'xhtml') return false;
72
73        // Disable caching - theme can change via admin without page edit
74        $renderer->nocache();
75
76        if ($data['type'] === 'eventlist') {
77            $html = $this->renderStandaloneEventList($data);
78        } elseif ($data['type'] === 'eventpanel') {
79            $html = $this->renderEventPanelOnly($data);
80        } else {
81            $html = $this->renderCompactCalendar($data);
82        }
83
84        $renderer->doc .= $html;
85        return true;
86    }
87
88    private function renderCompactCalendar($data) {
89        $year = (int)$data['year'];
90        $month = (int)$data['month'];
91        $namespace = $data['namespace'];
92
93        // Get theme - prefer inline theme= parameter, fall back to admin default
94        $theme = !empty($data['theme']) ? $data['theme'] : $this->getSidebarTheme();
95        $themeStyles = $this->getSidebarThemeStyles($theme);
96        $themeClass = 'calendar-theme-' . $theme;
97
98        // Determine button text color: professional uses white, others use bg color
99        $btnTextColor = ($theme === 'professional') ? '#fff' : $themeStyles['bg'];
100
101        // Check if multiple namespaces or wildcard specified
102        $isMultiNamespace = !empty($namespace) && (strpos($namespace, ';') !== false || strpos($namespace, '*') !== false);
103
104        if ($isMultiNamespace) {
105            $events = $this->loadEventsMultiNamespace($namespace, $year, $month);
106        } else {
107            $events = $this->loadEvents($namespace, $year, $month);
108        }
109        $calId = 'cal_' . md5(serialize($data) . microtime());
110
111        $monthName = date('F Y', mktime(0, 0, 0, $month, 1, $year));
112
113        $prevMonth = $month - 1;
114        $prevYear = $year;
115        if ($prevMonth < 1) {
116            $prevMonth = 12;
117            $prevYear--;
118        }
119
120        $nextMonth = $month + 1;
121        $nextYear = $year;
122        if ($nextMonth > 12) {
123            $nextMonth = 1;
124            $nextYear++;
125        }
126
127        // Get important namespaces from config for highlighting
128        $configFile = DOKU_PLUGIN . 'calendar/sync_config.php';
129        $importantNsList = ['important']; // default
130        if (file_exists($configFile)) {
131            $config = include $configFile;
132            if (isset($config['important_namespaces']) && !empty($config['important_namespaces'])) {
133                $importantNsList = array_map('trim', explode(',', $config['important_namespaces']));
134            }
135        }
136
137        // Container - all styling via CSS variables
138        $html = '<div class="calendar-compact-container ' . $themeClass . '" id="' . $calId . '" data-namespace="' . htmlspecialchars($namespace) . '" data-original-namespace="' . htmlspecialchars($namespace) . '" data-year="' . $year . '" data-month="' . $month . '" data-theme="' . $theme . '" data-theme-styles="' . htmlspecialchars(json_encode($themeStyles)) . '" data-important-namespaces="' . htmlspecialchars(json_encode($importantNsList)) . '">';
139
140        // Inject CSS variables for this calendar instance - all theming flows from here
141        $html .= '<style>
142        #' . $calId . ' {
143            --background-site: ' . $themeStyles['bg'] . ';
144            --background-alt: ' . $themeStyles['cell_bg'] . ';
145            --background-header: ' . $themeStyles['header_bg'] . ';
146            --text-primary: ' . $themeStyles['text_primary'] . ';
147            --text-dim: ' . $themeStyles['text_dim'] . ';
148            --text-bright: ' . $themeStyles['text_bright'] . ';
149            --border-color: ' . $themeStyles['grid_border'] . ';
150            --border-main: ' . $themeStyles['border'] . ';
151            --cell-bg: ' . $themeStyles['cell_bg'] . ';
152            --cell-today-bg: ' . $themeStyles['cell_today_bg'] . ';
153            --shadow-color: ' . $themeStyles['shadow'] . ';
154            --header-border: ' . $themeStyles['header_border'] . ';
155            --header-shadow: ' . $themeStyles['header_shadow'] . ';
156            --grid-bg: ' . $themeStyles['grid_bg'] . ';
157            --btn-text: ' . $btnTextColor . ';
158            --pastdue-color: ' . $themeStyles['pastdue_color'] . ';
159            --pastdue-bg: ' . $themeStyles['pastdue_bg'] . ';
160            --pastdue-bg-strong: ' . $themeStyles['pastdue_bg_strong'] . ';
161            --pastdue-bg-light: ' . $themeStyles['pastdue_bg_light'] . ';
162            --tomorrow-bg: ' . $themeStyles['tomorrow_bg'] . ';
163            --tomorrow-bg-strong: ' . $themeStyles['tomorrow_bg_strong'] . ';
164            --tomorrow-bg-light: ' . $themeStyles['tomorrow_bg_light'] . ';
165        }
166        #event-search-' . $calId . '::placeholder { color: ' . $themeStyles['text_dim'] . '; opacity: 1; }
167        #event-search-' . $calId . '::-webkit-input-placeholder { color: ' . $themeStyles['text_dim'] . '; opacity: 1; }
168        #event-search-' . $calId . '::-moz-placeholder { color: ' . $themeStyles['text_dim'] . '; opacity: 1; }
169        #event-search-' . $calId . ':-ms-input-placeholder { color: ' . $themeStyles['text_dim'] . '; opacity: 1; }
170        </style>';
171
172        // Load calendar JavaScript manually (not through DokuWiki concatenation)
173        $html .= '<script src="' . DOKU_BASE . 'lib/plugins/calendar/calendar-main.js"></script>';
174
175        // Initialize DOKU_BASE for JavaScript
176        $html .= '<script>if(typeof DOKU_BASE==="undefined"){window.DOKU_BASE="' . DOKU_BASE . '";}</script>';
177
178        // Embed events data as JSON for JavaScript access
179        $html .= '<script type="application/json" id="events-data-' . $calId . '">' . json_encode($events) . '</script>';
180
181        // Left side: Calendar
182        $html .= '<div class="calendar-compact-left">';
183
184        // Header with navigation
185        $html .= '<div class="calendar-compact-header">';
186        $html .= '<button class="cal-nav-btn" onclick="navCalendar(\'' . $calId . '\', ' . $prevYear . ', ' . $prevMonth . ', \'' . $namespace . '\')">‹</button>';
187        $html .= '<h3 class="calendar-month-picker" onclick="openMonthPicker(\'' . $calId . '\', ' . $year . ', ' . $month . ', \'' . $namespace . '\')" title="Click to jump to month">' . $monthName . '</h3>';
188        $html .= '<button class="cal-nav-btn" onclick="navCalendar(\'' . $calId . '\', ' . $nextYear . ', ' . $nextMonth . ', \'' . $namespace . '\')">›</button>';
189        $html .= '<button class="cal-today-btn" onclick="jumpToToday(\'' . $calId . '\', \'' . $namespace . '\')">Today</button>';
190        $html .= '</div>';
191
192        // Calendar grid - day name headers as a separate div (avoids Firefox th height issues)
193        $html .= '<div class="calendar-day-headers">';
194        $html .= '<span>S</span><span>M</span><span>T</span><span>W</span><span>T</span><span>F</span><span>S</span>';
195        $html .= '</div>';
196        $html .= '<table class="calendar-compact-grid">';
197        $html .= '<tbody>';
198
199        $firstDay = mktime(0, 0, 0, $month, 1, $year);
200        $daysInMonth = date('t', $firstDay);
201        $dayOfWeek = date('w', $firstDay);
202
203        // Build a map of all events with their date ranges for the calendar grid
204        $eventRanges = array();
205        foreach ($events as $dateKey => $dayEvents) {
206            foreach ($dayEvents as $evt) {
207                $eventId = isset($evt['id']) ? $evt['id'] : '';
208                $startDate = $dateKey;
209                $endDate = isset($evt['endDate']) && $evt['endDate'] ? $evt['endDate'] : $dateKey;
210
211                // Only process events that touch this month
212                $eventStart = new DateTime($startDate);
213                $eventEnd = new DateTime($endDate);
214                $monthStart = new DateTime(sprintf('%04d-%02d-01', $year, $month));
215                $monthEnd = new DateTime(sprintf('%04d-%02d-%02d', $year, $month, $daysInMonth));
216
217                // Skip if event doesn't overlap with current month
218                if ($eventEnd < $monthStart || $eventStart > $monthEnd) {
219                    continue;
220                }
221
222                // Create entry for each day the event spans
223                $current = clone $eventStart;
224                while ($current <= $eventEnd) {
225                    $currentKey = $current->format('Y-m-d');
226
227                    // Check if this date is in current month
228                    $currentDate = DateTime::createFromFormat('Y-m-d', $currentKey);
229                    if ($currentDate && $currentDate->format('Y-m') === sprintf('%04d-%02d', $year, $month)) {
230                        if (!isset($eventRanges[$currentKey])) {
231                            $eventRanges[$currentKey] = array();
232                        }
233
234                        // Add event with span information
235                        $evt['_span_start'] = $startDate;
236                        $evt['_span_end'] = $endDate;
237                        $evt['_is_first_day'] = ($currentKey === $startDate);
238                        $evt['_is_last_day'] = ($currentKey === $endDate);
239                        $evt['_original_date'] = $dateKey; // Keep track of original date
240
241                        // Check if event continues from previous month or to next month
242                        $evt['_continues_from_prev'] = ($eventStart < $monthStart);
243                        $evt['_continues_to_next'] = ($eventEnd > $monthEnd);
244
245                        $eventRanges[$currentKey][] = $evt;
246                    }
247
248                    $current->modify('+1 day');
249                }
250            }
251        }
252
253        $currentDay = 1;
254        $rowCount = ceil(($daysInMonth + $dayOfWeek) / 7);
255
256        for ($row = 0; $row < $rowCount; $row++) {
257            $html .= '<tr>';
258            for ($col = 0; $col < 7; $col++) {
259                if (($row === 0 && $col < $dayOfWeek) || $currentDay > $daysInMonth) {
260                    $html .= '<td class="cal-empty"></td>';
261                } else {
262                    $dateKey = sprintf('%04d-%02d-%02d', $year, $month, $currentDay);
263                    $isToday = ($dateKey === date('Y-m-d'));
264                    $hasEvents = isset($eventRanges[$dateKey]) && !empty($eventRanges[$dateKey]);
265
266                    $classes = 'cal-day';
267                    if ($isToday) $classes .= ' cal-today';
268                    if ($hasEvents) $classes .= ' cal-has-events';
269
270                    $html .= '<td class="' . $classes . '" data-date="' . $dateKey . '" onclick="showDayPopup(\'' . $calId . '\', \'' . $dateKey . '\', \'' . $namespace . '\')">';
271
272                    $dayNumClass = $isToday ? 'day-num day-num-today' : 'day-num';
273                    $html .= '<span class="' . $dayNumClass . '">' . $currentDay . '</span>';
274
275                    if ($hasEvents) {
276                        // Sort events by time (no time first, then by time)
277                        $sortedEvents = $eventRanges[$dateKey];
278                        usort($sortedEvents, function($a, $b) {
279                            $timeA = isset($a['time']) ? $a['time'] : '';
280                            $timeB = isset($b['time']) ? $b['time'] : '';
281
282                            // Events without time go first
283                            if (empty($timeA) && !empty($timeB)) return -1;
284                            if (!empty($timeA) && empty($timeB)) return 1;
285                            if (empty($timeA) && empty($timeB)) return 0;
286
287                            // Sort by time
288                            return strcmp($timeA, $timeB);
289                        });
290
291                        // Show colored stacked bars for each event
292                        $html .= '<div class="event-indicators">';
293                        foreach ($sortedEvents as $evt) {
294                            $eventId = isset($evt['id']) ? $evt['id'] : '';
295                            $eventColor = isset($evt['color']) ? htmlspecialchars($evt['color']) : '#3498db';
296                            $eventTime = isset($evt['time']) ? $evt['time'] : '';
297                            $eventTitle = isset($evt['title']) ? htmlspecialchars($evt['title']) : 'Event';
298                            $originalDate = isset($evt['_original_date']) ? $evt['_original_date'] : $dateKey;
299                            $isFirstDay = isset($evt['_is_first_day']) ? $evt['_is_first_day'] : true;
300                            $isLastDay = isset($evt['_is_last_day']) ? $evt['_is_last_day'] : true;
301
302                            // Check if this event is from an important namespace
303                            $evtNs = isset($evt['namespace']) ? $evt['namespace'] : '';
304                            if (!$evtNs && isset($evt['_namespace'])) {
305                                $evtNs = $evt['_namespace'];
306                            }
307                            $isImportantEvent = false;
308                            foreach ($importantNsList as $impNs) {
309                                if ($evtNs === $impNs || strpos($evtNs, $impNs . ':') === 0) {
310                                    $isImportantEvent = true;
311                                    break;
312                                }
313                            }
314
315                            $barClass = empty($eventTime) ? 'event-bar-no-time' : 'event-bar-timed';
316
317                            // Add classes for multi-day spanning
318                            if (!$isFirstDay) $barClass .= ' event-bar-continues';
319                            if (!$isLastDay) $barClass .= ' event-bar-continuing';
320                            if ($isImportantEvent) {
321                                $barClass .= ' event-bar-important';
322                                if ($isFirstDay) {
323                                    $barClass .= ' event-bar-has-star';
324                                }
325                            }
326
327                            $titlePrefix = $isImportantEvent ? '⭐ ' : '';
328
329                            $html .= '<span class="event-bar ' . $barClass . '" ';
330                            $html .= 'style="background: ' . $eventColor . ';" ';
331                            $html .= 'title="' . $titlePrefix . $eventTitle . ($eventTime ? ' @ ' . $eventTime : '') . '" ';
332                            $html .= 'onclick="event.stopPropagation(); highlightEvent(\'' . $calId . '\', \'' . $eventId . '\', \'' . $originalDate . '\');">';
333                            $html .= '</span>';
334                        }
335                        $html .= '</div>';
336                    }
337
338                    $html .= '</td>';
339                    $currentDay++;
340                }
341            }
342            $html .= '</tr>';
343        }
344
345        $html .= '</tbody></table>';
346        $html .= '</div>'; // End calendar-left
347
348        // Right side: Event list
349        $html .= '<div class="calendar-compact-right">';
350        $html .= '<div class="event-list-header">';
351        $html .= '<div class="event-list-header-content">';
352        $html .= '<h4 id="eventlist-title-' . $calId . '">Events</h4>';
353        if ($namespace) {
354            $html .= '<span class="namespace-badge">' . htmlspecialchars($namespace) . '</span>';
355        }
356        $html .= '</div>';
357
358        // Search bar in header
359        $html .= '<div class="event-search-container-inline">';
360        $html .= '<input type="text" class="event-search-input-inline" id="event-search-' . $calId . '" placeholder="�� Search..." oninput="filterEvents(\'' . $calId . '\', this.value)">';
361        $html .= '<button class="event-search-clear-inline" id="search-clear-' . $calId . '" onclick="clearEventSearch(\'' . $calId . '\')" style="display:none;">✕</button>';
362        $html .= '<button class="event-search-mode-inline" id="search-mode-' . $calId . '" onclick="toggleSearchMode(\'' . $calId . '\', \'' . $namespace . '\')" title="Search this month only">��</button>';
363        $html .= '</div>';
364
365        $html .= '<button class="add-event-compact" onclick="openAddEvent(\'' . $calId . '\', \'' . $namespace . '\')">+ Add</button>';
366        $html .= '</div>';
367
368        $html .= '<div class="event-list-compact" id="eventlist-' . $calId . '">';
369        $html .= $this->renderEventListContent($events, $calId, $namespace, $themeStyles);
370        $html .= '</div>';
371
372        $html .= '</div>'; // End calendar-right
373
374        // Event dialog
375        $html .= $this->renderEventDialog($calId, $namespace, $theme);
376
377        // Month/Year picker dialog (at container level for proper overlay)
378        $html .= $this->renderMonthPicker($calId, $year, $month, $namespace, $theme, $themeStyles);
379
380        $html .= '</div>'; // End container
381
382        return $html;
383    }
384
385    private function renderEventListContent($events, $calId, $namespace, $themeStyles = null) {
386        if (empty($events)) {
387            return '<p class="no-events-msg">No events this month</p>';
388        }
389
390        // Default theme styles if not provided
391        if ($themeStyles === null) {
392            $theme = $this->getSidebarTheme();
393            $themeStyles = $this->getSidebarThemeStyles($theme);
394        } else {
395            $theme = $this->getSidebarTheme();
396        }
397
398        // Get important namespaces from config
399        $configFile = DOKU_PLUGIN . 'calendar/sync_config.php';
400        $importantNsList = ['important']; // default
401        if (file_exists($configFile)) {
402            $config = include $configFile;
403            if (isset($config['important_namespaces']) && !empty($config['important_namespaces'])) {
404                $importantNsList = array_map('trim', explode(',', $config['important_namespaces']));
405            }
406        }
407
408        // Check for time conflicts
409        $events = $this->checkTimeConflicts($events);
410
411        // Sort by date ascending (chronological order - oldest first)
412        ksort($events);
413
414        // Sort events within each day by time
415        foreach ($events as $dateKey => &$dayEvents) {
416            usort($dayEvents, function($a, $b) {
417                $timeA = isset($a['time']) && !empty($a['time']) ? $a['time'] : null;
418                $timeB = isset($b['time']) && !empty($b['time']) ? $b['time'] : null;
419
420                // All-day events (no time) go to the TOP
421                if ($timeA === null && $timeB !== null) return -1; // A before B
422                if ($timeA !== null && $timeB === null) return 1;  // A after B
423                if ($timeA === null && $timeB === null) return 0;  // Both all-day, equal
424
425                // Both have times, sort chronologically
426                return strcmp($timeA, $timeB);
427            });
428        }
429        unset($dayEvents); // Break reference
430
431        // Get today's date for comparison
432        $today = date('Y-m-d');
433        $firstFutureEventId = null;
434
435        // Helper function to check if event is past (with 15-minute grace period for timed events)
436        $isEventPast = function($dateKey, $time) use ($today) {
437            // If event is on a past date, it's definitely past
438            if ($dateKey < $today) {
439                return true;
440            }
441
442            // If event is on a future date, it's definitely not past
443            if ($dateKey > $today) {
444                return false;
445            }
446
447            // Event is today - check time with grace period
448            if ($time && $time !== '') {
449                try {
450                    $currentDateTime = new DateTime();
451                    $eventDateTime = new DateTime($dateKey . ' ' . $time);
452
453                    // Add 15-minute grace period
454                    $eventDateTime->modify('+15 minutes');
455
456                    // Event is past if current time > event time + 15 minutes
457                    return $currentDateTime > $eventDateTime;
458                } catch (Exception $e) {
459                    // If time parsing fails, fall back to date-only comparison
460                    return false;
461                }
462            }
463
464            // No time specified for today's event, treat as future
465            return false;
466        };
467
468        // Build HTML for each event - separate past/completed from future
469        $pastHtml = '';
470        $futureHtml = '';
471        $pastCount = 0;
472
473        foreach ($events as $dateKey => $dayEvents) {
474
475            foreach ($dayEvents as $event) {
476                // Track first future/today event for auto-scroll
477                if (!$firstFutureEventId && $dateKey >= $today) {
478                    $firstFutureEventId = isset($event['id']) ? $event['id'] : '';
479                }
480                $eventId = isset($event['id']) ? $event['id'] : '';
481                $title = isset($event['title']) ? htmlspecialchars($event['title']) : 'Untitled';
482                $timeRaw = isset($event['time']) ? $event['time'] : '';
483                $time = htmlspecialchars($timeRaw);
484                $endTime = isset($event['endTime']) ? htmlspecialchars($event['endTime']) : '';
485                $color = isset($event['color']) ? htmlspecialchars($event['color']) : '#3498db';
486                $description = isset($event['description']) ? $event['description'] : '';
487                $isTask = isset($event['isTask']) ? $event['isTask'] : false;
488                $completed = isset($event['completed']) ? $event['completed'] : false;
489                $endDate = isset($event['endDate']) ? $event['endDate'] : '';
490
491                // Use helper function to determine if event is past (with grace period)
492                $isPast = $isEventPast($dateKey, $timeRaw);
493                $isToday = $dateKey === $today;
494
495                // Check if event should be in past section
496                // EXCEPTION: Uncompleted tasks (isTask && !completed) should stay visible even if past
497                $isPastOrCompleted = ($isPast && (!$isTask || $completed)) || $completed;
498                if ($isPastOrCompleted) {
499                    $pastCount++;
500                }
501
502                // Determine if task is past due (past date, is task, not completed)
503                $isPastDue = $isPast && $isTask && !$completed;
504
505                // Process description for wiki syntax, HTML, images, and links
506                $renderedDescription = $this->renderDescription($description, $themeStyles);
507
508                // Convert to 12-hour format and handle time ranges
509                $displayTime = '';
510                if ($time) {
511                    $timeObj = DateTime::createFromFormat('H:i', $time);
512                    if ($timeObj) {
513                        $displayTime = $timeObj->format('g:i A');
514
515                        // Add end time if present and different from start time
516                        if ($endTime && $endTime !== $time) {
517                            $endTimeObj = DateTime::createFromFormat('H:i', $endTime);
518                            if ($endTimeObj) {
519                                $displayTime .= ' - ' . $endTimeObj->format('g:i A');
520                            }
521                        }
522                    } else {
523                        $displayTime = $time;
524                    }
525                }
526
527                // Format date display with day of week
528                // Use originalStartDate if this is a multi-month event continuation
529                $displayDateKey = isset($event['originalStartDate']) ? $event['originalStartDate'] : $dateKey;
530                $dateObj = new DateTime($displayDateKey);
531                $displayDate = $dateObj->format('D, M j'); // e.g., "Mon, Jan 24"
532
533                // Multi-day indicator
534                $multiDay = '';
535                if ($endDate && $endDate !== $displayDateKey) {
536                    $endObj = new DateTime($endDate);
537                    $multiDay = ' → ' . $endObj->format('D, M j');
538                }
539
540                $completedClass = $completed ? ' event-completed' : '';
541                // Don't grey out past due tasks - they need attention!
542                $pastClass = ($isPast && !$isPastDue) ? ' event-past' : '';
543                $pastDueClass = $isPastDue ? ' event-pastdue' : '';
544                $firstFutureAttr = ($firstFutureEventId === $eventId) ? ' data-first-future="true"' : '';
545
546                // Check if this is an important namespace event
547                $eventNamespace = isset($event['namespace']) ? $event['namespace'] : '';
548                if (!$eventNamespace && isset($event['_namespace'])) {
549                    $eventNamespace = $event['_namespace'];
550                }
551                $isImportantNs = false;
552                foreach ($importantNsList as $impNs) {
553                    if ($eventNamespace === $impNs || strpos($eventNamespace, $impNs . ':') === 0) {
554                        $isImportantNs = true;
555                        break;
556                    }
557                }
558                $importantClass = $isImportantNs ? ' event-important' : '';
559
560                // For all themes: use CSS variables, only keep border-left-color as inline
561                $pastClickHandler = ($isPast && !$isPastDue) ? ' onclick="togglePastEventExpand(this)"' : '';
562                $eventHtml = '<div class="event-compact-item' . $completedClass . $pastClass . $pastDueClass . $importantClass . '" data-event-id="' . $eventId . '" data-date="' . $dateKey . '" style="border-left-color: ' . $color . ' !important;"' . $pastClickHandler . $firstFutureAttr . '>';
563                $eventHtml .= '<div class="event-info">';
564
565                $eventHtml .= '<div class="event-title-row">';
566                // Add star for important namespace events
567                if ($isImportantNs) {
568                    $eventHtml .= '<span class="event-important-star" title="Important">⭐</span> ';
569                }
570                $eventHtml .= '<span class="event-title-compact">' . $title . '</span>';
571                $eventHtml .= '</div>';
572
573                // For past events, hide meta and description (collapsed)
574                // EXCEPTION: Past due tasks should show their details
575                if (!$isPast || $isPastDue) {
576                    $eventHtml .= '<div class="event-meta-compact">';
577                    $eventHtml .= '<span class="event-date-time">' . $displayDate . $multiDay;
578                    if ($displayTime) {
579                        $eventHtml .= ' • ' . $displayTime;
580                    }
581                    // Add TODAY badge for today's events OR PAST DUE for uncompleted past tasks
582                    if ($isPastDue) {
583                        $eventHtml .= ' <span class="event-pastdue-badge" style="background:' . $themeStyles['pastdue_color'] . ' !important; color:white !important; -webkit-text-fill-color:white !important;">' . 'PAST DUE</span>';
584                    } elseif ($isToday) {
585                        $eventHtml .= ' <span class="event-today-badge" style="background:' . $themeStyles['border'] . ' !important; color:' . $themeStyles['bg'] . ' !important; -webkit-text-fill-color:' . $themeStyles['bg'] . ' !important;">' . 'TODAY</span>';
586                    }
587                    // Add namespace badge - ALWAYS show if event has a namespace
588                    $eventNamespace = isset($event['namespace']) ? $event['namespace'] : '';
589                    if (!$eventNamespace && isset($event['_namespace'])) {
590                        $eventNamespace = $event['_namespace']; // Fallback to _namespace for backward compatibility
591                    }
592                    // Show badge if namespace exists and is not empty
593                    if ($eventNamespace && $eventNamespace !== '') {
594                        $eventHtml .= ' <span class="event-namespace-badge" onclick="filterCalendarByNamespace(\'' . $calId . '\', \'' . htmlspecialchars($eventNamespace) . '\')" style="cursor:pointer; background:' . $themeStyles['text_bright'] . ' !important; color:' . $themeStyles['bg'] . ' !important; -webkit-text-fill-color:' . $themeStyles['bg'] . ' !important;" title="Click to filter by this namespace">' . htmlspecialchars($eventNamespace) . '</span>';
595                    }
596
597                    // Add conflict warning if event has time conflicts
598                    if (isset($event['hasConflict']) && $event['hasConflict'] && isset($event['conflictsWith'])) {
599                        $conflictList = [];
600                        foreach ($event['conflictsWith'] as $conflict) {
601                            $conflictText = $conflict['title'];
602                            if (!empty($conflict['time'])) {
603                                // Format time range
604                                $startTimeObj = DateTime::createFromFormat('H:i', $conflict['time']);
605                                $startTimeFormatted = $startTimeObj ? $startTimeObj->format('g:i A') : $conflict['time'];
606
607                                if (!empty($conflict['endTime']) && $conflict['endTime'] !== $conflict['time']) {
608                                    $endTimeObj = DateTime::createFromFormat('H:i', $conflict['endTime']);
609                                    $endTimeFormatted = $endTimeObj ? $endTimeObj->format('g:i A') : $conflict['endTime'];
610                                    $conflictText .= ' (' . $startTimeFormatted . ' - ' . $endTimeFormatted . ')';
611                                } else {
612                                    $conflictText .= ' (' . $startTimeFormatted . ')';
613                                }
614                            }
615                            $conflictList[] = $conflictText;
616                        }
617                        $conflictCount = count($event['conflictsWith']);
618                        $conflictJson = base64_encode(json_encode($conflictList));
619                        $eventHtml .= ' <span class="event-conflict-badge" data-conflicts="' . $conflictJson . '" onmouseenter="showConflictTooltip(this)" onmouseleave="hideConflictTooltip()">⚠️ ' . $conflictCount . '</span>';
620                    }
621
622                    $eventHtml .= '</span>';
623                    $eventHtml .= '</div>';
624
625                    if ($description) {
626                        $eventHtml .= '<div class="event-desc-compact">' . $renderedDescription . '</div>';
627                    }
628                } else {
629                    // Past events: render with display:none for click-to-expand
630                    $eventHtml .= '<div class="event-meta-compact" style="display:none;">';
631                    $eventHtml .= '<span class="event-date-time">' . $displayDate . $multiDay;
632                    if ($displayTime) {
633                        $eventHtml .= ' • ' . $displayTime;
634                    }
635                    $eventNamespace = isset($event['namespace']) ? $event['namespace'] : '';
636                    if (!$eventNamespace && isset($event['_namespace'])) {
637                        $eventNamespace = $event['_namespace'];
638                    }
639                    if ($eventNamespace && $eventNamespace !== '') {
640                        $eventHtml .= ' <span class="event-namespace-badge" onclick="filterCalendarByNamespace(\'' . $calId . '\', \'' . htmlspecialchars($eventNamespace) . '\')" style="cursor:pointer; background:' . $themeStyles['text_bright'] . ' !important; color:' . $themeStyles['bg'] . ' !important; -webkit-text-fill-color:' . $themeStyles['bg'] . ' !important;" title="Click to filter by this namespace">' . htmlspecialchars($eventNamespace) . '</span>';
641                    }
642
643                    // Add conflict warning if event has time conflicts
644                    if (isset($event['hasConflict']) && $event['hasConflict'] && isset($event['conflictsWith'])) {
645                        $conflictList = [];
646                        foreach ($event['conflictsWith'] as $conflict) {
647                            $conflictText = $conflict['title'];
648                            if (!empty($conflict['time'])) {
649                                $startTimeObj = DateTime::createFromFormat('H:i', $conflict['time']);
650                                $startTimeFormatted = $startTimeObj ? $startTimeObj->format('g:i A') : $conflict['time'];
651
652                                if (!empty($conflict['endTime']) && $conflict['endTime'] !== $conflict['time']) {
653                                    $endTimeObj = DateTime::createFromFormat('H:i', $conflict['endTime']);
654                                    $endTimeFormatted = $endTimeObj ? $endTimeObj->format('g:i A') : $conflict['endTime'];
655                                    $conflictText .= ' (' . $startTimeFormatted . ' - ' . $endTimeFormatted . ')';
656                                } else {
657                                    $conflictText .= ' (' . $startTimeFormatted . ')';
658                                }
659                            }
660                            $conflictList[] = $conflictText;
661                        }
662                        $conflictCount = count($event['conflictsWith']);
663                        $conflictJson = base64_encode(json_encode($conflictList));
664                        $eventHtml .= ' <span class="event-conflict-badge" data-conflicts="' . $conflictJson . '" onmouseenter="showConflictTooltip(this)" onmouseleave="hideConflictTooltip()">⚠️ ' . $conflictCount . '</span>';
665                    }
666
667                    $eventHtml .= '</span>';
668                    $eventHtml .= '</div>';
669
670                    if ($description) {
671                        $eventHtml .= '<div class="event-desc-compact" style="display:none;">' . $renderedDescription . '</div>';
672                    }
673                }
674
675                $eventHtml .= '</div>'; // event-info
676
677                // Use stored namespace from event, fallback to passed namespace
678                $buttonNamespace = isset($event['namespace']) ? $event['namespace'] : $namespace;
679
680                $eventHtml .= '<div class="event-actions-compact">';
681                $eventHtml .= '<button class="event-action-btn" onclick="deleteEvent(\'' . $calId . '\', \'' . $eventId . '\', \'' . $dateKey . '\', \'' . $buttonNamespace . '\')">��️</button>';
682                $eventHtml .= '<button class="event-action-btn" onclick="editEvent(\'' . $calId . '\', \'' . $eventId . '\', \'' . $dateKey . '\', \'' . $buttonNamespace . '\')">✏️</button>';
683                $eventHtml .= '</div>';
684
685                // Checkbox for tasks - ON THE FAR RIGHT
686                if ($isTask) {
687                    $checked = $completed ? 'checked' : '';
688                    $eventHtml .= '<input type="checkbox" class="task-checkbox" ' . $checked . ' onclick="toggleTaskComplete(\'' . $calId . '\', \'' . $eventId . '\', \'' . $dateKey . '\', \'' . $buttonNamespace . '\', this.checked)">';
689                }
690
691                $eventHtml .= '</div>';
692
693                // Add to appropriate section
694                if ($isPastOrCompleted) {
695                    $pastHtml .= $eventHtml;
696                } else {
697                    $futureHtml .= $eventHtml;
698                }
699            }
700        }
701
702        // Build final HTML with collapsible past events section
703        $html = '';
704
705        // Add collapsible past events section if any exist
706        if ($pastCount > 0) {
707            $html .= '<div class="past-events-section">';
708            $html .= '<div class="past-events-toggle" onclick="togglePastEvents(\'' . $calId . '\')">';
709            $html .= '<span class="past-events-arrow" id="past-arrow-' . $calId . '">▶</span> ';
710            $html .= '<span class="past-events-label">Past Events (' . $pastCount . ')</span>';
711            $html .= '</div>';
712            $html .= '<div class="past-events-content" id="past-events-' . $calId . '" style="display:none;">';
713            $html .= $pastHtml;
714            $html .= '</div>';
715            $html .= '</div>';
716        }
717
718        // Add future events
719        $html .= $futureHtml;
720
721        return $html;
722    }
723
724    /**
725     * Check for time conflicts between events
726     */
727    private function checkTimeConflicts($events) {
728        // Group events by date
729        $eventsByDate = [];
730        foreach ($events as $date => $dateEvents) {
731            if (!is_array($dateEvents)) continue;
732
733            foreach ($dateEvents as $evt) {
734                if (empty($evt['time'])) continue; // Skip all-day events
735
736                if (!isset($eventsByDate[$date])) {
737                    $eventsByDate[$date] = [];
738                }
739                $eventsByDate[$date][] = $evt;
740            }
741        }
742
743        // Check for overlaps on each date
744        foreach ($eventsByDate as $date => $dateEvents) {
745            for ($i = 0; $i < count($dateEvents); $i++) {
746                for ($j = $i + 1; $j < count($dateEvents); $j++) {
747                    if ($this->eventsOverlap($dateEvents[$i], $dateEvents[$j])) {
748                        // Mark both events as conflicting
749                        $dateEvents[$i]['hasConflict'] = true;
750                        $dateEvents[$j]['hasConflict'] = true;
751
752                        // Store conflict info
753                        if (!isset($dateEvents[$i]['conflictsWith'])) {
754                            $dateEvents[$i]['conflictsWith'] = [];
755                        }
756                        if (!isset($dateEvents[$j]['conflictsWith'])) {
757                            $dateEvents[$j]['conflictsWith'] = [];
758                        }
759
760                        $dateEvents[$i]['conflictsWith'][] = [
761                            'id' => $dateEvents[$j]['id'],
762                            'title' => $dateEvents[$j]['title'],
763                            'time' => $dateEvents[$j]['time'],
764                            'endTime' => isset($dateEvents[$j]['endTime']) ? $dateEvents[$j]['endTime'] : ''
765                        ];
766
767                        $dateEvents[$j]['conflictsWith'][] = [
768                            'id' => $dateEvents[$i]['id'],
769                            'title' => $dateEvents[$i]['title'],
770                            'time' => $dateEvents[$i]['time'],
771                            'endTime' => isset($dateEvents[$i]['endTime']) ? $dateEvents[$i]['endTime'] : ''
772                        ];
773                    }
774                }
775            }
776
777            // Update the events array with conflict information
778            foreach ($events[$date] as &$evt) {
779                foreach ($dateEvents as $checkedEvt) {
780                    if ($evt['id'] === $checkedEvt['id']) {
781                        if (isset($checkedEvt['hasConflict'])) {
782                            $evt['hasConflict'] = $checkedEvt['hasConflict'];
783                        }
784                        if (isset($checkedEvt['conflictsWith'])) {
785                            $evt['conflictsWith'] = $checkedEvt['conflictsWith'];
786                        }
787                        break;
788                    }
789                }
790            }
791        }
792
793        return $events;
794    }
795
796    /**
797     * Check if two events overlap in time
798     */
799    private function eventsOverlap($evt1, $evt2) {
800        if (empty($evt1['time']) || empty($evt2['time'])) {
801            return false; // All-day events don't conflict
802        }
803
804        $start1 = $evt1['time'];
805        $end1 = isset($evt1['endTime']) && !empty($evt1['endTime']) ? $evt1['endTime'] : $evt1['time'];
806
807        $start2 = $evt2['time'];
808        $end2 = isset($evt2['endTime']) && !empty($evt2['endTime']) ? $evt2['endTime'] : $evt2['time'];
809
810        // Convert to minutes for easier comparison
811        $start1Mins = $this->timeToMinutes($start1);
812        $end1Mins = $this->timeToMinutes($end1);
813        $start2Mins = $this->timeToMinutes($start2);
814        $end2Mins = $this->timeToMinutes($end2);
815
816        // Check for overlap: start1 < end2 AND start2 < end1
817        return $start1Mins < $end2Mins && $start2Mins < $end1Mins;
818    }
819
820    /**
821     * Convert HH:MM time to minutes since midnight
822     */
823    private function timeToMinutes($timeStr) {
824        $parts = explode(':', $timeStr);
825        if (count($parts) !== 2) return 0;
826
827        return (int)$parts[0] * 60 + (int)$parts[1];
828    }
829
830    private function renderEventPanelOnly($data) {
831        $year = (int)$data['year'];
832        $month = (int)$data['month'];
833        $namespace = $data['namespace'];
834        $height = isset($data['height']) ? $data['height'] : '400px';
835
836        // Validate height format (must be px, em, rem, vh, or %)
837        if (!preg_match('/^\d+(\.\d+)?(px|em|rem|vh|%)$/', $height)) {
838            $height = '400px'; // Default fallback
839        }
840
841        // Get theme - prefer inline theme= parameter, fall back to admin default
842        $theme = !empty($data['theme']) ? $data['theme'] : $this->getSidebarTheme();        $themeStyles = $this->getSidebarThemeStyles($theme);
843
844        // Check if multiple namespaces or wildcard specified
845        $isMultiNamespace = !empty($namespace) && (strpos($namespace, ';') !== false || strpos($namespace, '*') !== false);
846
847        if ($isMultiNamespace) {
848            $events = $this->loadEventsMultiNamespace($namespace, $year, $month);
849        } else {
850            $events = $this->loadEvents($namespace, $year, $month);
851        }
852        $calId = 'panel_' . md5(serialize($data) . microtime());
853
854        $monthName = date('F Y', mktime(0, 0, 0, $month, 1, $year));
855
856        $prevMonth = $month - 1;
857        $prevYear = $year;
858        if ($prevMonth < 1) {
859            $prevMonth = 12;
860            $prevYear--;
861        }
862
863        $nextMonth = $month + 1;
864        $nextYear = $year;
865        if ($nextMonth > 12) {
866            $nextMonth = 1;
867            $nextYear++;
868        }
869
870        // Determine button text color based on theme
871        $btnTextColor = ($theme === 'professional') ? '#fff' : $themeStyles['bg'];
872
873        // Get important namespaces from config for highlighting
874        $configFile = DOKU_PLUGIN . 'calendar/sync_config.php';
875        $importantNsList = ['important']; // default
876        if (file_exists($configFile)) {
877            $config = include $configFile;
878            if (isset($config['important_namespaces']) && !empty($config['important_namespaces'])) {
879                $importantNsList = array_map('trim', explode(',', $config['important_namespaces']));
880            }
881        }
882
883        $html = '<div class="event-panel-standalone" id="' . $calId . '" data-height="' . htmlspecialchars($height) . '" data-namespace="' . htmlspecialchars($namespace) . '" data-original-namespace="' . htmlspecialchars($namespace) . '" data-theme="' . $theme . '" data-theme-styles="' . htmlspecialchars(json_encode($themeStyles)) . '" data-important-namespaces="' . htmlspecialchars(json_encode($importantNsList)) . '">';
884
885        // Inject CSS variables for this panel instance - same as main calendar
886        $html .= '<style>
887        #' . $calId . ' {
888            --background-site: ' . $themeStyles['bg'] . ';
889            --background-alt: ' . $themeStyles['cell_bg'] . ';
890            --background-header: ' . $themeStyles['header_bg'] . ';
891            --text-primary: ' . $themeStyles['text_primary'] . ';
892            --text-dim: ' . $themeStyles['text_dim'] . ';
893            --text-bright: ' . $themeStyles['text_bright'] . ';
894            --border-color: ' . $themeStyles['grid_border'] . ';
895            --border-main: ' . $themeStyles['border'] . ';
896            --cell-bg: ' . $themeStyles['cell_bg'] . ';
897            --cell-today-bg: ' . $themeStyles['cell_today_bg'] . ';
898            --shadow-color: ' . $themeStyles['shadow'] . ';
899            --header-border: ' . $themeStyles['header_border'] . ';
900            --header-shadow: ' . $themeStyles['header_shadow'] . ';
901            --grid-bg: ' . $themeStyles['grid_bg'] . ';
902            --btn-text: ' . $btnTextColor . ';
903            --pastdue-color: ' . $themeStyles['pastdue_color'] . ';
904            --pastdue-bg: ' . $themeStyles['pastdue_bg'] . ';
905            --pastdue-bg-strong: ' . $themeStyles['pastdue_bg_strong'] . ';
906            --pastdue-bg-light: ' . $themeStyles['pastdue_bg_light'] . ';
907            --tomorrow-bg: ' . $themeStyles['tomorrow_bg'] . ';
908            --tomorrow-bg-strong: ' . $themeStyles['tomorrow_bg_strong'] . ';
909            --tomorrow-bg-light: ' . $themeStyles['tomorrow_bg_light'] . ';
910        }
911        #event-search-' . $calId . '::placeholder { color: ' . $themeStyles['text_dim'] . '; opacity: 1; }
912        </style>';
913
914        // Load calendar JavaScript manually (not through DokuWiki concatenation)
915        $html .= '<script src="' . DOKU_BASE . 'lib/plugins/calendar/calendar-main.js"></script>';
916
917        // Initialize DOKU_BASE for JavaScript
918        $html .= '<script>if(typeof DOKU_BASE==="undefined"){window.DOKU_BASE="' . DOKU_BASE . '";}</script>';
919
920        // Compact two-row header designed for ~500px width
921        $html .= '<div class="panel-header-compact">';
922
923        // Row 1: Navigation and title
924        $html .= '<div class="panel-header-row-1">';
925        $html .= '<button class="panel-nav-btn" onclick="navEventPanel(\'' . $calId . '\', ' . $prevYear . ', ' . $prevMonth . ', \'' . $namespace . '\')">‹</button>';
926
927        // Compact month name (e.g. "Feb 2026" instead of "February 2026 Events")
928        $shortMonthName = date('M Y', mktime(0, 0, 0, $month, 1, $year));
929        $html .= '<h3 class="panel-month-title" onclick="openMonthPickerPanel(\'' . $calId . '\', ' . $year . ', ' . $month . ', \'' . $namespace . '\')" title="Click to jump to month">' . $shortMonthName . '</h3>';
930
931        $html .= '<button class="panel-nav-btn" onclick="navEventPanel(\'' . $calId . '\', ' . $nextYear . ', ' . $nextMonth . ', \'' . $namespace . '\')">›</button>';
932
933        // Namespace badge (if applicable)
934        if ($namespace) {
935            if ($isMultiNamespace) {
936                if (strpos($namespace, '*') !== false) {
937                    $html .= '<span class="panel-ns-badge" style="background:var(--cell-today-bg) !important; color:var(--text-bright) !important; -webkit-text-fill-color:var(--text-bright) !important;" title="' . htmlspecialchars($namespace) . '">' . htmlspecialchars($namespace) . '</span>';
938                } else {
939                    $namespaceList = array_map('trim', explode(';', $namespace));
940                    $nsCount = count($namespaceList);
941                    $html .= '<span class="panel-ns-badge" style="background:var(--cell-today-bg) !important; color:var(--text-bright) !important; -webkit-text-fill-color:var(--text-bright) !important;" title="' . htmlspecialchars(implode(', ', $namespaceList)) . '">' . $nsCount . ' NS</span>';
942                }
943            } else {
944                $isFiltering = ($namespace !== '*' && strpos($namespace, '*') === false && strpos($namespace, ';') === false);
945                if ($isFiltering) {
946                    $html .= '<span class="panel-ns-badge filter-on" style="background:var(--text-bright) !important; color:var(--background-site) !important; -webkit-text-fill-color:var(--background-site) !important;" title="Filtering by ' . htmlspecialchars($namespace) . ' - click to clear" onclick="clearNamespaceFilterPanel(\'' . $calId . '\')">' . htmlspecialchars($namespace) . ' ✕</span>';
947                } else {
948                    $html .= '<span class="panel-ns-badge" style="background:var(--cell-today-bg) !important; color:var(--text-bright) !important; -webkit-text-fill-color:var(--text-bright) !important;" title="' . htmlspecialchars($namespace) . '">' . htmlspecialchars($namespace) . '</span>';
949                }
950            }
951        }
952
953        $html .= '<button class="panel-today-btn" onclick="jumpTodayPanel(\'' . $calId . '\', \'' . $namespace . '\')">Today</button>';
954        $html .= '</div>';
955
956        // Row 2: Search and add button
957        $html .= '<div class="panel-header-row-2">';
958        $html .= '<div class="panel-search-box">';
959        $html .= '<input type="text" class="panel-search-input" id="event-search-' . $calId . '" placeholder="Search this month..." oninput="filterEvents(\'' . $calId . '\', this.value)">';
960        $html .= '<button class="panel-search-clear" id="search-clear-' . $calId . '" onclick="clearEventSearch(\'' . $calId . '\')" style="display:none;">✕</button>';
961        $html .= '<button class="panel-search-mode" id="search-mode-' . $calId . '" onclick="toggleSearchMode(\'' . $calId . '\', \'' . $namespace . '\')" title="Search this month only">��</button>';
962        $html .= '</div>';
963        $html .= '<button class="panel-add-btn" onclick="openAddEventPanel(\'' . $calId . '\', \'' . $namespace . '\')">+ Add</button>';
964        $html .= '</div>';
965
966        $html .= '</div>';
967
968        $html .= '<div class="event-list-compact" id="eventlist-' . $calId . '" style="max-height: ' . htmlspecialchars($height) . ';">';
969        $html .= $this->renderEventListContent($events, $calId, $namespace);
970        $html .= '</div>';
971
972        $html .= $this->renderEventDialog($calId, $namespace, $theme);
973
974        // Month/Year picker for event panel
975        $html .= $this->renderMonthPicker($calId, $year, $month, $namespace, $theme, $themeStyles);
976
977        $html .= '</div>';
978
979        return $html;
980    }
981
982    private function renderStandaloneEventList($data) {
983        $namespace = $data['namespace'];
984        // If no namespace specified, show all namespaces
985        if (empty($namespace)) {
986            $namespace = '*';
987        }
988        $daterange = $data['daterange'];
989        $date = $data['date'];
990        $range = isset($data['range']) ? strtolower($data['range']) : '';
991        $today = isset($data['today']) ? true : false;
992        $sidebar = isset($data['sidebar']) ? true : false;
993        $showchecked = isset($data['showchecked']) ? true : false; // New parameter
994        $noheader = isset($data['noheader']) ? true : false; // New parameter to hide header
995
996        // Handle "range" parameter - day, week, or month
997        if ($range === 'day') {
998            $startDate = date('Y-m-d', strtotime('-30 days')); // Include past 30 days for past due tasks
999            $endDate = date('Y-m-d');
1000            $headerText = 'Today';
1001        } elseif ($range === 'week') {
1002            $startDate = date('Y-m-d', strtotime('-30 days')); // Include past 30 days for past due tasks
1003            $endDateTime = new DateTime();
1004            $endDateTime->modify('+7 days');
1005            $endDate = $endDateTime->format('Y-m-d');
1006            $headerText = 'This Week';
1007        } elseif ($range === 'month') {
1008            $startDate = date('Y-m-01', strtotime('-1 month')); // Include previous month for past due tasks
1009            $endDate = date('Y-m-t'); // Last of current month
1010            $dt = new DateTime();
1011            $headerText = $dt->format('F Y');
1012        } elseif ($sidebar) {
1013            // NEW: Sidebar widget - load current week's events
1014            $weekStartDay = $this->getWeekStartDay(); // Get saved preference
1015
1016            if ($weekStartDay === 'monday') {
1017                // Monday start
1018                $weekStart = date('Y-m-d', strtotime('monday this week'));
1019                $weekEnd = date('Y-m-d', strtotime('sunday this week'));
1020            } else {
1021                // Sunday start (default - US/Canada standard)
1022                $today = date('w'); // 0 (Sun) to 6 (Sat)
1023                if ($today == 0) {
1024                    // Today is Sunday
1025                    $weekStart = date('Y-m-d');
1026                } else {
1027                    // Monday-Saturday: go back to last Sunday
1028                    $weekStart = date('Y-m-d', strtotime('-' . $today . ' days'));
1029                }
1030                $weekEnd = date('Y-m-d', strtotime($weekStart . ' +6 days'));
1031            }
1032
1033            // Load events for the entire week PLUS tomorrow (if tomorrow is outside week)
1034            // PLUS next 2 weeks for Important events
1035            $start = new DateTime($weekStart);
1036            $end = new DateTime($weekEnd);
1037
1038            // Check if we need to extend to include tomorrow
1039            $tomorrowDate = date('Y-m-d', strtotime('+1 day'));
1040            if ($tomorrowDate > $weekEnd) {
1041                // Tomorrow is outside the week, extend end date to include it
1042                $end = new DateTime($tomorrowDate);
1043            }
1044
1045            // Extend 2 weeks into the future for Important events
1046            $twoWeeksOut = date('Y-m-d', strtotime($weekEnd . ' +14 days'));
1047            $end = new DateTime($twoWeeksOut);
1048
1049            $end->modify('+1 day'); // DatePeriod excludes end date
1050            $interval = new DateInterval('P1D');
1051            $period = new DatePeriod($start, $interval, $end);
1052
1053            $isMultiNamespace = !empty($namespace) && (strpos($namespace, ';') !== false || strpos($namespace, '*') !== false);
1054            $allEvents = [];
1055            $loadedMonths = [];
1056
1057            foreach ($period as $dt) {
1058                $year = (int)$dt->format('Y');
1059                $month = (int)$dt->format('n');
1060                $dateKey = $dt->format('Y-m-d');
1061
1062                $monthKey = $year . '-' . $month . '-' . $namespace;
1063
1064                if (!isset($loadedMonths[$monthKey])) {
1065                    if ($isMultiNamespace) {
1066                        $loadedMonths[$monthKey] = $this->loadEventsMultiNamespace($namespace, $year, $month);
1067                    } else {
1068                        $loadedMonths[$monthKey] = $this->loadEvents($namespace, $year, $month);
1069                    }
1070                }
1071
1072                $monthEvents = $loadedMonths[$monthKey];
1073
1074                if (isset($monthEvents[$dateKey]) && !empty($monthEvents[$dateKey])) {
1075                    $allEvents[$dateKey] = $monthEvents[$dateKey];
1076                }
1077            }
1078
1079            // Apply time conflict detection
1080            $allEvents = $this->checkTimeConflicts($allEvents);
1081
1082            $calId = 'sidebar-' . substr(md5($namespace . $weekStart), 0, 8);
1083
1084            // Render sidebar widget and return immediately
1085            $themeOverride = !empty($data['theme']) ? $data['theme'] : null;
1086            return $this->renderSidebarWidget($allEvents, $namespace, $calId, $themeOverride);
1087        } elseif ($today) {
1088            $startDate = date('Y-m-d');
1089            $endDate = date('Y-m-d');
1090            $headerText = 'Today';
1091        } elseif ($daterange) {
1092            list($startDate, $endDate) = explode(':', $daterange);
1093            $start = new DateTime($startDate);
1094            $end = new DateTime($endDate);
1095            $headerText = $start->format('M j') . ' - ' . $end->format('M j, Y');
1096        } elseif ($date) {
1097            $startDate = $date;
1098            $endDate = $date;
1099            $dt = new DateTime($date);
1100            $headerText = $dt->format('l, F j, Y');
1101        } else {
1102            $startDate = date('Y-m-01');
1103            $endDate = date('Y-m-t');
1104            $dt = new DateTime($startDate);
1105            $headerText = $dt->format('F Y');
1106        }
1107
1108        // Load all events in date range
1109        $allEvents = array();
1110        $start = new DateTime($startDate);
1111        $end = new DateTime($endDate);
1112        $end->modify('+1 day');
1113
1114        $interval = new DateInterval('P1D');
1115        $period = new DatePeriod($start, $interval, $end);
1116
1117        // Check if multiple namespaces or wildcard specified
1118        $isMultiNamespace = !empty($namespace) && (strpos($namespace, ';') !== false || strpos($namespace, '*') !== false);
1119
1120        static $loadedMonths = array();
1121
1122        foreach ($period as $dt) {
1123            $year = (int)$dt->format('Y');
1124            $month = (int)$dt->format('n');
1125            $dateKey = $dt->format('Y-m-d');
1126
1127            $monthKey = $year . '-' . $month . '-' . $namespace;
1128
1129            if (!isset($loadedMonths[$monthKey])) {
1130                if ($isMultiNamespace) {
1131                    $loadedMonths[$monthKey] = $this->loadEventsMultiNamespace($namespace, $year, $month);
1132                } else {
1133                    $loadedMonths[$monthKey] = $this->loadEvents($namespace, $year, $month);
1134                }
1135            }
1136
1137            $monthEvents = $loadedMonths[$monthKey];
1138
1139            if (isset($monthEvents[$dateKey]) && !empty($monthEvents[$dateKey])) {
1140                $allEvents[$dateKey] = $monthEvents[$dateKey];
1141            }
1142        }
1143
1144        // Sort events by date (already sorted by dateKey), then by time within each day
1145        foreach ($allEvents as $dateKey => &$dayEvents) {
1146            usort($dayEvents, function($a, $b) {
1147                $timeA = isset($a['time']) && !empty($a['time']) ? $a['time'] : null;
1148                $timeB = isset($b['time']) && !empty($b['time']) ? $b['time'] : null;
1149
1150                // All-day events (no time) go to the TOP
1151                if ($timeA === null && $timeB !== null) return -1; // A before B
1152                if ($timeA !== null && $timeB === null) return 1;  // A after B
1153                if ($timeA === null && $timeB === null) return 0;  // Both all-day, equal
1154
1155                // Both have times, sort chronologically
1156                return strcmp($timeA, $timeB);
1157            });
1158        }
1159        unset($dayEvents); // Break reference
1160
1161        // Simple 2-line display widget
1162        $calId = 'eventlist_' . uniqid();
1163        $theme = !empty($data['theme']) ? $data['theme'] : $this->getSidebarTheme();
1164        $themeStyles = $this->getSidebarThemeStyles($theme);
1165        $isDark = in_array($theme, ['matrix', 'purple', 'pink']);
1166        $btnTextColor = ($theme === 'professional') ? '#fff' : $themeStyles['bg'];
1167
1168        // Theme class for CSS targeting
1169        $themeClass = 'eventlist-theme-' . $theme;
1170
1171        // Container styling - dark themes get border + glow, light themes get subtle border
1172        $containerStyle = 'background:' . $themeStyles['bg'] . ' !important;';
1173        if ($isDark) {
1174            $containerStyle .= ' border:2px solid ' . $themeStyles['border'] . ';';
1175            $containerStyle .= ' border-radius:4px;';
1176            $containerStyle .= ' box-shadow:0 0 10px ' . $themeStyles['shadow'] . ';';
1177        } else {
1178            $containerStyle .= ' border:1px solid ' . $themeStyles['grid_border'] . ';';
1179            $containerStyle .= ' border-radius:4px;';
1180        }
1181
1182        $html = '<div class="eventlist-simple ' . $themeClass . '" id="' . $calId . '" style="' . $containerStyle . '">';
1183
1184        // Inject CSS variables for this eventlist instance
1185        $html .= '<style>
1186        #' . $calId . ' {
1187            --background-site: ' . $themeStyles['bg'] . ';
1188            --background-alt: ' . $themeStyles['cell_bg'] . ';
1189            --text-primary: ' . $themeStyles['text_primary'] . ';
1190            --text-dim: ' . $themeStyles['text_dim'] . ';
1191            --text-bright: ' . $themeStyles['text_bright'] . ';
1192            --border-color: ' . $themeStyles['grid_border'] . ';
1193            --border-main: ' . $themeStyles['border'] . ';
1194            --cell-bg: ' . $themeStyles['cell_bg'] . ';
1195            --cell-today-bg: ' . $themeStyles['cell_today_bg'] . ';
1196            --shadow-color: ' . $themeStyles['shadow'] . ';
1197            --grid-bg: ' . $themeStyles['grid_bg'] . ';
1198            --btn-text: ' . $btnTextColor . ';
1199            --pastdue-color: ' . $themeStyles['pastdue_color'] . ';
1200            --pastdue-bg: ' . $themeStyles['pastdue_bg'] . ';
1201            --pastdue-bg-strong: ' . $themeStyles['pastdue_bg_strong'] . ';
1202            --pastdue-bg-light: ' . $themeStyles['pastdue_bg_light'] . ';
1203            --tomorrow-bg: ' . $themeStyles['tomorrow_bg'] . ';
1204            --tomorrow-bg-strong: ' . $themeStyles['tomorrow_bg_strong'] . ';
1205            --tomorrow-bg-light: ' . $themeStyles['tomorrow_bg_light'] . ';
1206        }
1207        </style>';
1208
1209        // Load calendar JavaScript manually (not through DokuWiki concatenation)
1210        $html .= '<script src="' . DOKU_BASE . 'lib/plugins/calendar/calendar-main.js"></script>';
1211
1212        // Initialize DOKU_BASE for JavaScript
1213        $html .= '<script>if(typeof DOKU_BASE==="undefined"){window.DOKU_BASE="' . DOKU_BASE . '";}</script>';
1214
1215        // Add compact header with date and clock for "today" mode (unless noheader is set)
1216        if ($today && !empty($allEvents) && !$noheader) {
1217            $todayDate = new DateTime();
1218            $displayDate = $todayDate->format('D, M j, Y'); // "Fri, Jan 30, 2026"
1219            $currentTime = $todayDate->format('g:i:s A'); // "2:45:30 PM"
1220
1221            $html .= '<div class="eventlist-today-header">';
1222            $html .= '<span class="eventlist-today-clock" id="clock-' . $calId . '">' . $currentTime . '</span>';
1223            $html .= '<div class="eventlist-bottom-info">';
1224            $html .= '<span class="eventlist-weather"><span id="weather-icon-' . $calId . '">��️</span> <span id="weather-temp-' . $calId . '">--°</span></span>';
1225            $html .= '<span class="eventlist-today-date">' . $displayDate . '</span>';
1226            $html .= '</div>';
1227
1228            // Three CPU/Memory bars (all update live)
1229            $html .= '<div class="eventlist-stats-container">';
1230
1231            // 5-minute load average (green, updates every 2 seconds)
1232            $html .= '<div class="eventlist-cpu-bar" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $calId . '(\'green\')" onmouseout="hideTooltip_' . $calId . '(\'green\')">';
1233            $html .= '<div class="eventlist-cpu-fill" id="cpu-5min-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_bright'] . ' !important;"></div>';
1234            $html .= '<div class="system-tooltip" id="tooltip-green-' . $calId . '" style="display:none;"></div>';
1235            $html .= '</div>';
1236
1237            // Real-time CPU (purple, updates with 5-sec average)
1238            $html .= '<div class="eventlist-cpu-bar eventlist-cpu-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $calId . '(\'purple\')" onmouseout="hideTooltip_' . $calId . '(\'purple\')">';
1239            $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-purple" id="cpu-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['border'] . ' !important;"></div>';
1240            $html .= '<div class="system-tooltip" id="tooltip-purple-' . $calId . '" style="display:none;"></div>';
1241            $html .= '</div>';
1242
1243            // Real-time Memory (orange, updates)
1244            $html .= '<div class="eventlist-cpu-bar eventlist-mem-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $calId . '(\'orange\')" onmouseout="hideTooltip_' . $calId . '(\'orange\')">';
1245            $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-orange" id="mem-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_primary'] . ' !important;"></div>';
1246            $html .= '<div class="system-tooltip" id="tooltip-orange-' . $calId . '" style="display:none;"></div>';
1247            $html .= '</div>';
1248
1249            $html .= '</div>';
1250            $html .= '</div>';
1251
1252            // Add JavaScript to update clock and weather
1253            $html .= '<script>
1254(function() {
1255    // Update clock every second
1256    function updateClock() {
1257        const now = new Date();
1258        let hours = now.getHours();
1259        const minutes = String(now.getMinutes()).padStart(2, "0");
1260        const seconds = String(now.getSeconds()).padStart(2, "0");
1261        const ampm = hours >= 12 ? "PM" : "AM";
1262        hours = hours % 12 || 12;
1263        const timeStr = hours + ":" + minutes + ":" + seconds + " " + ampm;
1264        const clockEl = document.getElementById("clock-' . $calId . '");
1265        if (clockEl) clockEl.textContent = timeStr;
1266    }
1267    setInterval(updateClock, 1000);
1268
1269    // Fetch weather - uses default location, click weather to get local
1270    var userLocationGranted = false;
1271    var userLat = 38.5816;  // Sacramento default
1272    var userLon = -121.4944;
1273
1274    function fetchWeatherData(lat, lon) {
1275        fetch("https://api.open-meteo.com/v1/forecast?latitude=" + lat + "&longitude=" + lon + "&current_weather=true&temperature_unit=fahrenheit")
1276            .then(response => response.json())
1277            .then(data => {
1278                if (data.current_weather) {
1279                    const temp = Math.round(data.current_weather.temperature);
1280                    const weatherCode = data.current_weather.weathercode;
1281                    const icon = getWeatherIcon(weatherCode);
1282                    const iconEl = document.getElementById("weather-icon-' . $calId . '");
1283                    const tempEl = document.getElementById("weather-temp-' . $calId . '");
1284                    if (iconEl) iconEl.textContent = icon;
1285                    if (tempEl) tempEl.innerHTML = temp + "&deg;";
1286                }
1287            })
1288            .catch(error => {
1289                console.log("Weather fetch error:", error);
1290            });
1291    }
1292
1293    function updateWeather() {
1294        fetchWeatherData(userLat, userLon);
1295    }
1296
1297    // Allow user to click weather to get local weather (requires user gesture)
1298    function requestLocalWeather() {
1299        if (userLocationGranted) return; // Already have permission
1300
1301        if ("geolocation" in navigator) {
1302            navigator.geolocation.getCurrentPosition(function(position) {
1303                userLat = position.coords.latitude;
1304                userLon = position.coords.longitude;
1305                userLocationGranted = true;
1306                fetchWeatherData(userLat, userLon);
1307            }, function(error) {
1308                console.log("Geolocation denied or unavailable, using default location");
1309            });
1310        }
1311    }
1312
1313    // Add click handler to weather widget for local weather
1314    setTimeout(function() {
1315        var weatherEl = document.querySelector("#weather-icon-' . $calId . '");
1316        if (weatherEl) {
1317            weatherEl.style.cursor = "pointer";
1318            weatherEl.title = "Click for local weather";
1319            weatherEl.addEventListener("click", requestLocalWeather);
1320        }
1321    }, 100);
1322
1323    // WMO Weather interpretation codes
1324    function getWeatherIcon(code) {
1325        const icons = {
1326            0: "☀️",   // Clear sky
1327            1: "��️",   // Mainly clear
1328            2: "⛅",   // Partly cloudy
1329            3: "☁️",   // Overcast
1330            45: "��️",  // Fog
1331            48: "��️",  // Depositing rime fog
1332            51: "��️",  // Light drizzle
1333            53: "��️",  // Moderate drizzle
1334            55: "��️",  // Dense drizzle
1335            61: "��️",  // Slight rain
1336            63: "��️",  // Moderate rain
1337            65: "⛈️",  // Heavy rain
1338            71: "��️",  // Slight snow
1339            73: "��️",  // Moderate snow
1340            75: "❄️",  // Heavy snow
1341            77: "��️",  // Snow grains
1342            80: "��️",  // Slight rain showers
1343            81: "��️",  // Moderate rain showers
1344            82: "⛈️",  // Violent rain showers
1345            85: "��️",  // Slight snow showers
1346            86: "❄️",  // Heavy snow showers
1347            95: "⛈️",  // Thunderstorm
1348            96: "⛈️",  // Thunderstorm with slight hail
1349            99: "⛈️"   // Thunderstorm with heavy hail
1350        };
1351        return icons[code] || "��️";
1352    }
1353
1354    // Update weather immediately and every 10 minutes
1355    updateWeather();
1356    setInterval(updateWeather, 600000);
1357
1358    // CPU load history for 4-second rolling average
1359    const cpuHistory = [];
1360    const CPU_HISTORY_SIZE = 2; // 2 samples × 2 seconds = 4 seconds
1361
1362    // Store latest system stats for tooltips
1363    let latestStats = {
1364        load: {"1min": 0, "5min": 0, "15min": 0},
1365        uptime: "",
1366        memory_details: {},
1367        top_processes: []
1368    };
1369
1370    // Tooltip functions
1371    window["showTooltip_' . $calId . '"] = function(color) {
1372        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
1373        if (!tooltip) {
1374            console.log("Tooltip element not found for color:", color);
1375            return;
1376        }
1377
1378
1379        let content = "";
1380
1381        if (color === "green") {
1382            // Green bar: Load averages and uptime
1383            content = "<div class=\"tooltip-title\">CPU Load Average</div>";
1384            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
1385            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
1386            content += "<div>15 min: " + (latestStats.load["15min"] || "N/A") + "</div>";
1387            if (latestStats.uptime) {
1388                content += "<div style=\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_bright'] . ';\">Uptime: " + latestStats.uptime + "</div>";
1389            }
1390            tooltip.style.setProperty("border-color", "' . $themeStyles['text_bright'] . '", "important");
1391            tooltip.style.setProperty("color", "' . $themeStyles['text_bright'] . '", "important");
1392            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_bright'] . '", "important");
1393        } else if (color === "purple") {
1394            // Purple bar: Load averages (short-term) and top processes
1395            content = "<div class=\"tooltip-title\">CPU Load (Short-term)</div>";
1396            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
1397            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
1398            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
1399                content += "<div style=\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['border'] . ';\" class=\"tooltip-title\">Top Processes</div>";
1400                latestStats.top_processes.slice(0, 5).forEach(proc => {
1401                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
1402                });
1403            }
1404            tooltip.style.setProperty("border-color", "' . $themeStyles['border'] . '", "important");
1405            tooltip.style.setProperty("color", "' . $themeStyles['border'] . '", "important");
1406            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['border'] . '", "important");
1407        } else if (color === "orange") {
1408            // Orange bar: Memory details and top processes
1409            content = "<div class=\"tooltip-title\">Memory Usage</div>";
1410            if (latestStats.memory_details && latestStats.memory_details.total) {
1411                content += "<div>Total: " + latestStats.memory_details.total + "</div>";
1412                content += "<div>Used: " + latestStats.memory_details.used + "</div>";
1413                content += "<div>Available: " + latestStats.memory_details.available + "</div>";
1414                if (latestStats.memory_details.cached) {
1415                    content += "<div>Cached: " + latestStats.memory_details.cached + "</div>";
1416                }
1417            } else {
1418                content += "<div>Loading...</div>";
1419            }
1420            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
1421                content += "<div style=\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_primary'] . ';\" class=\"tooltip-title\">Top Processes</div>";
1422                latestStats.top_processes.slice(0, 5).forEach(proc => {
1423                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
1424                });
1425            }
1426            tooltip.style.setProperty("border-color", "' . $themeStyles['text_primary'] . '", "important");
1427            tooltip.style.setProperty("color", "' . $themeStyles['text_primary'] . '", "important");
1428            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_primary'] . '", "important");
1429        }
1430
1431        tooltip.innerHTML = content;
1432        tooltip.style.setProperty("display", "block");
1433        tooltip.style.setProperty("background", "' . $themeStyles['bg'] . '", "important");
1434
1435        // Position tooltip using fixed positioning above the bar
1436        const bar = tooltip.parentElement;
1437        const barRect = bar.getBoundingClientRect();
1438        const tooltipRect = tooltip.getBoundingClientRect();
1439
1440        // Center horizontally on the bar
1441        const left = barRect.left + (barRect.width / 2) - (tooltipRect.width / 2);
1442        // Position above the bar with 8px gap
1443        const top = barRect.top - tooltipRect.height - 8;
1444
1445        tooltip.style.left = left + "px";
1446        tooltip.style.top = top + "px";
1447    };
1448
1449    window["hideTooltip_' . $calId . '"] = function(color) {
1450        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
1451        if (tooltip) {
1452            tooltip.style.display = "none";
1453        }
1454    };
1455
1456    // Update CPU and memory bars every 2 seconds
1457    function updateSystemStats() {
1458        // Fetch real system stats from server
1459        fetch("' . DOKU_BASE . 'lib/plugins/calendar/get_system_stats.php")
1460            .then(response => response.json())
1461            .then(data => {
1462
1463                // Store data for tooltips
1464                latestStats = {
1465                    load: data.load || {"1min": 0, "5min": 0, "15min": 0},
1466                    uptime: data.uptime || "",
1467                    memory_details: data.memory_details || {},
1468                    top_processes: data.top_processes || []
1469                };
1470
1471
1472                // Update green bar (5-minute average) - updates live now!
1473                const greenBar = document.getElementById("cpu-5min-' . $calId . '");
1474                if (greenBar) {
1475                    greenBar.style.width = Math.min(100, data.cpu_5min) + "%";
1476                }
1477
1478                // Add current CPU to history for purple bar
1479                cpuHistory.push(data.cpu);
1480                if (cpuHistory.length > CPU_HISTORY_SIZE) {
1481                    cpuHistory.shift(); // Remove oldest
1482                }
1483
1484                // Calculate 5-second average for CPU
1485                const cpuAverage = cpuHistory.reduce((sum, val) => sum + val, 0) / cpuHistory.length;
1486
1487                // Update CPU bar (purple) with 5-second average
1488                const cpuBar = document.getElementById("cpu-realtime-' . $calId . '");
1489                if (cpuBar) {
1490                    cpuBar.style.width = Math.min(100, cpuAverage) + "%";
1491                }
1492
1493                // Update memory bar (orange) with real data
1494                const memBar = document.getElementById("mem-realtime-' . $calId . '");
1495                if (memBar) {
1496                    memBar.style.width = Math.min(100, data.memory) + "%";
1497                }
1498            })
1499            .catch(error => {
1500                console.log("System stats error:", error);
1501                // Fallback to client-side estimates on error
1502                const cpuFallback = Math.random() * 100;
1503                cpuHistory.push(cpuFallback);
1504                if (cpuHistory.length > CPU_HISTORY_SIZE) {
1505                    cpuHistory.shift();
1506                }
1507                const cpuAverage = cpuHistory.reduce((sum, val) => sum + val, 0) / cpuHistory.length;
1508
1509                const greenBar = document.getElementById("cpu-5min-' . $calId . '");
1510                if (greenBar) greenBar.style.width = Math.min(100, cpuFallback) + "%";
1511
1512                const cpuBar = document.getElementById("cpu-realtime-' . $calId . '");
1513                if (cpuBar) cpuBar.style.width = Math.min(100, cpuAverage) + "%";
1514
1515                let memoryUsage = 0;
1516                if (performance.memory) {
1517                    memoryUsage = (performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit) * 100;
1518                } else {
1519                    memoryUsage = Math.random() * 100;
1520                }
1521                const memBar = document.getElementById("mem-realtime-' . $calId . '");
1522                if (memBar) memBar.style.width = Math.min(100, memoryUsage) + "%";
1523            });
1524    }
1525
1526    // Update immediately and then every 2 seconds
1527    updateSystemStats();
1528    setInterval(updateSystemStats, 2000);
1529})();
1530</script>';
1531        }
1532
1533        if (empty($allEvents)) {
1534            $html .= '<div class="eventlist-simple-empty">';
1535            $html .= '<div class="eventlist-simple-header">' . htmlspecialchars($headerText);
1536            if ($namespace) {
1537                $html .= ' <span class="eventlist-simple-namespace">' . htmlspecialchars($namespace) . '</span>';
1538            }
1539            $html .= '</div>';
1540            $html .= '<div class="eventlist-simple-body">No events</div>';
1541            $html .= '</div>';
1542        } else {
1543            // Calculate today and tomorrow's dates for highlighting
1544            $todayStr = date('Y-m-d');
1545            $tomorrow = date('Y-m-d', strtotime('+1 day'));
1546
1547            foreach ($allEvents as $dateKey => $dayEvents) {
1548                $dateObj = new DateTime($dateKey);
1549                $displayDate = $dateObj->format('D, M j');
1550
1551                // Check if this date is today or tomorrow or past
1552                // Enable highlighting for sidebar mode AND range modes (day, week, month)
1553                $enableHighlighting = $sidebar || !empty($range);
1554                $isToday = $enableHighlighting && ($dateKey === $todayStr);
1555                $isTomorrow = $enableHighlighting && ($dateKey === $tomorrow);
1556                $isPast = $dateKey < $todayStr;
1557
1558                foreach ($dayEvents as $event) {
1559                    // Check if this is a task and if it's completed
1560                    $isTask = !empty($event['isTask']);
1561                    $completed = !empty($event['completed']);
1562
1563                    // ALWAYS skip completed tasks UNLESS showchecked is explicitly set
1564                    if (!$showchecked && $isTask && $completed) {
1565                        continue;
1566                    }
1567
1568                    // Skip past events that are NOT tasks (only show past due tasks from the past)
1569                    if ($isPast && !$isTask) {
1570                        continue;
1571                    }
1572
1573                    // Determine if task is past due (past date, is task, not completed)
1574                    $isPastDue = $isPast && $isTask && !$completed;
1575
1576                    // Line 1: Header (Title, Time, Date, Namespace)
1577                    $todayClass = $isToday ? ' eventlist-simple-today' : '';
1578                    $tomorrowClass = $isTomorrow ? ' eventlist-simple-tomorrow' : '';
1579                    $pastDueClass = $isPastDue ? ' eventlist-simple-pastdue' : '';
1580                    $html .= '<div class="eventlist-simple-item' . $todayClass . $tomorrowClass . $pastDueClass . '">';
1581                    $html .= '<div class="eventlist-simple-header">';
1582
1583                    // Title
1584                    $html .= '<span class="eventlist-simple-title">' . htmlspecialchars($event['title']) . '</span>';
1585
1586                    // Time (12-hour format)
1587                    if (!empty($event['time'])) {
1588                        $timeParts = explode(':', $event['time']);
1589                        if (count($timeParts) === 2) {
1590                            $hour = (int)$timeParts[0];
1591                            $minute = $timeParts[1];
1592                            $ampm = $hour >= 12 ? 'PM' : 'AM';
1593                            $hour = $hour % 12 ?: 12;
1594                            $displayTime = $hour . ':' . $minute . ' ' . $ampm;
1595                            $html .= ' <span class="eventlist-simple-time">' . $displayTime . '</span>';
1596                        }
1597                    }
1598
1599                    // Date
1600                    $html .= ' <span class="eventlist-simple-date">' . $displayDate . '</span>';
1601
1602                    // Badge: PAST DUE, TODAY, or nothing
1603                    if ($isPastDue) {
1604                        $html .= ' <span class="eventlist-simple-pastdue-badge" style="background:' . $themeStyles['pastdue_color'] . ' !important; color:white !important; -webkit-text-fill-color:white !important;">PAST DUE</span>';
1605                    } elseif ($isToday) {
1606                        $html .= ' <span class="eventlist-simple-today-badge" style="background:' . $themeStyles['border'] . ' !important; color:' . $themeStyles['bg'] . ' !important; -webkit-text-fill-color:' . $themeStyles['bg'] . ' !important;">TODAY</span>';
1607                    }
1608
1609                    // Namespace badge (show individual event's namespace)
1610                    $eventNamespace = isset($event['namespace']) ? $event['namespace'] : '';
1611                    if (!$eventNamespace && isset($event['_namespace'])) {
1612                        $eventNamespace = $event['_namespace']; // Fallback to _namespace for multi-namespace loading
1613                    }
1614                    if ($eventNamespace) {
1615                        $html .= ' <span class="eventlist-simple-namespace">' . htmlspecialchars($eventNamespace) . '</span>';
1616                    }
1617
1618                    $html .= '</div>'; // header
1619
1620                    // Line 2: Body (Description only) - only show if description exists
1621                    if (!empty($event['description'])) {
1622                        $html .= '<div class="eventlist-simple-body">' . $this->renderDescription($event['description']) . '</div>';
1623                    }
1624
1625                    $html .= '</div>'; // item
1626                }
1627            }
1628        }
1629
1630        $html .= '</div>'; // eventlist-simple
1631
1632        return $html;
1633    }
1634
1635    private function renderEventDialog($calId, $namespace, $theme = null) {
1636        // Get theme for dialog
1637        if ($theme === null) {
1638            $theme = $this->getSidebarTheme();
1639        }
1640        $themeStyles = $this->getSidebarThemeStyles($theme);
1641
1642        $html = '<div class="event-dialog-compact" id="dialog-' . $calId . '" style="display:none;">';
1643        $html .= '<div class="dialog-overlay" onclick="closeEventDialog(\'' . $calId . '\')"></div>';
1644
1645        // Draggable dialog with theme
1646        $html .= '<div class="dialog-content-sleek" id="dialog-content-' . $calId . '">';
1647
1648        // Header with drag handle and close button
1649        $html .= '<div class="dialog-header-sleek dialog-drag-handle" id="drag-handle-' . $calId . '">';
1650        $html .= '<h3 id="dialog-title-' . $calId . '">Add Event</h3>';
1651        $html .= '<button type="button" class="dialog-close-btn" onclick="closeEventDialog(\'' . $calId . '\')">×</button>';
1652        $html .= '</div>';
1653
1654        // Form content
1655        $html .= '<form id="eventform-' . $calId . '" onsubmit="saveEventCompact(\'' . $calId . '\', \'' . $namespace . '\'); return false;" class="sleek-form">';
1656
1657        // Hidden ID field
1658        $html .= '<input type="hidden" id="event-id-' . $calId . '" name="eventId" value="">';
1659
1660        // 1. TITLE
1661        $html .= '<div class="form-field">';
1662        $html .= '<label class="field-label">�� Title</label>';
1663        $html .= '<input type="text" id="event-title-' . $calId . '" name="title" required class="input-sleek input-compact" placeholder="Event or task title...">';
1664        $html .= '</div>';
1665
1666        // 1.5 NAMESPACE SELECTOR (Searchable with fuzzy matching)
1667        $html .= '<div class="form-field">';
1668        $html .= '<label class="field-label">�� Namespace</label>';
1669
1670        // Hidden field to store actual selected namespace
1671        $html .= '<input type="hidden" id="event-namespace-' . $calId . '" name="namespace" value="">';
1672
1673        // Searchable input
1674        $html .= '<div class="namespace-search-wrapper">';
1675        $html .= '<input type="text" id="event-namespace-search-' . $calId . '" class="input-sleek input-compact namespace-search-input" placeholder="Type to search or leave empty for default..." autocomplete="off">';
1676        $html .= '<div class="namespace-dropdown" id="event-namespace-dropdown-' . $calId . '" style="display:none;"></div>';
1677        $html .= '</div>';
1678
1679        // Store namespaces as JSON for JavaScript
1680        $allNamespaces = $this->getAllNamespaces();
1681        $html .= '<script type="application/json" id="namespaces-data-' . $calId . '">' . json_encode($allNamespaces) . '</script>';
1682
1683        $html .= '</div>';
1684
1685        // 2. DESCRIPTION
1686        $html .= '<div class="form-field">';
1687        $html .= '<label class="field-label">�� Description</label>';
1688        $html .= '<textarea id="event-desc-' . $calId . '" name="description" rows="2" class="input-sleek textarea-sleek textarea-compact" placeholder="Optional details..."></textarea>';
1689        $html .= '</div>';
1690
1691        // 3. START DATE - END DATE (inline)
1692        $html .= '<div class="form-row-group">';
1693
1694        $html .= '<div class="form-field form-field-half">';
1695        $html .= '<label class="field-label-compact">�� Start Date</label>';
1696        $html .= '<input type="date" id="event-date-' . $calId . '" name="date" required class="input-sleek input-date input-compact">';
1697        $html .= '</div>';
1698
1699        $html .= '<div class="form-field form-field-half">';
1700        $html .= '<label class="field-label-compact">�� End Date</label>';
1701        $html .= '<input type="date" id="event-end-date-' . $calId . '" name="endDate" class="input-sleek input-date input-compact" placeholder="Optional">';
1702        $html .= '</div>';
1703
1704        $html .= '</div>'; // End row
1705
1706        // 4. IS REPEATING CHECKBOX
1707        $html .= '<div class="form-field form-field-checkbox form-field-checkbox-compact">';
1708        $html .= '<label class="checkbox-label checkbox-label-compact">';
1709        $html .= '<input type="checkbox" id="event-recurring-' . $calId . '" name="isRecurring" class="recurring-toggle" onchange="toggleRecurringOptions(\'' . $calId . '\')">';
1710        $html .= '<span>�� Repeating Event</span>';
1711        $html .= '</label>';
1712        $html .= '</div>';
1713
1714        // Recurring options (shown when checkbox is checked)
1715        $html .= '<div id="recurring-options-' . $calId . '" class="recurring-options" style="display:none; border:1px solid var(--border-color, #333); border-radius:4px; padding:8px; margin:4px 0; background:var(--background-alt, rgba(0,0,0,0.2));">';
1716
1717        // Row 1: Repeat every [N] [period]
1718        $html .= '<div class="form-row-group" style="margin-bottom:6px;">';
1719
1720        $html .= '<div class="form-field" style="flex:0 0 auto; min-width:0;">';
1721        $html .= '<label class="field-label-compact">Repeat every</label>';
1722        $html .= '<input type="number" id="event-recurrence-interval-' . $calId . '" name="recurrenceInterval" class="input-sleek input-compact" value="1" min="1" max="99" style="width:50px;">';
1723        $html .= '</div>';
1724
1725        $html .= '<div class="form-field" style="flex:1; min-width:0;">';
1726        $html .= '<label class="field-label-compact">&nbsp;</label>';
1727        $html .= '<select id="event-recurrence-type-' . $calId . '" name="recurrenceType" class="input-sleek input-compact" onchange="updateRecurrenceOptions(\'' . $calId . '\')">';
1728        $html .= '<option value="daily">Day(s)</option>';
1729        $html .= '<option value="weekly">Week(s)</option>';
1730        $html .= '<option value="monthly">Month(s)</option>';
1731        $html .= '<option value="yearly">Year(s)</option>';
1732        $html .= '</select>';
1733        $html .= '</div>';
1734
1735        $html .= '</div>'; // End row 1
1736
1737        // Row 2: Weekly options - day of week checkboxes
1738        $html .= '<div id="weekly-options-' . $calId . '" class="weekly-options" style="display:none; margin-bottom:6px;">';
1739        $html .= '<label class="field-label-compact" style="display:block; margin-bottom:4px;">On these days:</label>';
1740        $html .= '<div style="display:flex; flex-wrap:wrap; gap:2px;">';
1741        $dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
1742        foreach ($dayNames as $idx => $day) {
1743            $html .= '<label style="display:inline-flex; align-items:center; padding:2px 6px; background:var(--cell-bg, #1a1a1a); border:1px solid var(--border-color, #333); border-radius:3px; cursor:pointer; font-size:10px;">';
1744            $html .= '<input type="checkbox" name="weekDays[]" value="' . $idx . '" style="margin-right:3px; width:12px; height:12px;">';
1745            $html .= '<span>' . $day . '</span>';
1746            $html .= '</label>';
1747        }
1748        $html .= '</div>';
1749        $html .= '</div>'; // End weekly options
1750
1751        // Row 3: Monthly options - day of month OR ordinal weekday
1752        $html .= '<div id="monthly-options-' . $calId . '" class="monthly-options" style="display:none; margin-bottom:6px;">';
1753        $html .= '<label class="field-label-compact" style="display:block; margin-bottom:4px;">Repeat on:</label>';
1754
1755        // Radio: Day of month vs Ordinal weekday
1756        $html .= '<div style="margin-bottom:6px;">';
1757        $html .= '<label style="display:inline-flex; align-items:center; margin-right:12px; cursor:pointer; font-size:11px;">';
1758        $html .= '<input type="radio" name="monthlyType" value="dayOfMonth" checked onchange="updateMonthlyType(\'' . $calId . '\')" style="margin-right:4px;">';
1759        $html .= 'Day of month';
1760        $html .= '</label>';
1761        $html .= '<label style="display:inline-flex; align-items:center; cursor:pointer; font-size:11px;">';
1762        $html .= '<input type="radio" name="monthlyType" value="ordinalWeekday" onchange="updateMonthlyType(\'' . $calId . '\')" style="margin-right:4px;">';
1763        $html .= 'Weekday pattern';
1764        $html .= '</label>';
1765        $html .= '</div>';
1766
1767        // Day of month input (shown by default)
1768        $html .= '<div id="monthly-day-' . $calId . '" style="display:flex; align-items:center; gap:6px;">';
1769        $html .= '<span style="font-size:11px;">Day</span>';
1770        $html .= '<input type="number" id="event-month-day-' . $calId . '" name="monthDay" class="input-sleek input-compact" value="1" min="1" max="31" style="width:50px;">';
1771        $html .= '<span style="font-size:10px; color:var(--text-dim, #666);">of each month</span>';
1772        $html .= '</div>';
1773
1774        // Ordinal weekday (hidden by default)
1775        $html .= '<div id="monthly-ordinal-' . $calId . '" style="display:none;">';
1776        $html .= '<div style="display:flex; align-items:center; gap:4px; flex-wrap:wrap;">';
1777        $html .= '<select id="event-ordinal-' . $calId . '" name="ordinalWeek" class="input-sleek input-compact" style="width:auto;">';
1778        $html .= '<option value="1">First</option>';
1779        $html .= '<option value="2">Second</option>';
1780        $html .= '<option value="3">Third</option>';
1781        $html .= '<option value="4">Fourth</option>';
1782        $html .= '<option value="5">Fifth</option>';
1783        $html .= '<option value="-1">Last</option>';
1784        $html .= '</select>';
1785        $html .= '<select id="event-ordinal-day-' . $calId . '" name="ordinalDay" class="input-sleek input-compact" style="width:auto;">';
1786        $html .= '<option value="0">Sunday</option>';
1787        $html .= '<option value="1">Monday</option>';
1788        $html .= '<option value="2">Tuesday</option>';
1789        $html .= '<option value="3">Wednesday</option>';
1790        $html .= '<option value="4">Thursday</option>';
1791        $html .= '<option value="5">Friday</option>';
1792        $html .= '<option value="6">Saturday</option>';
1793        $html .= '</select>';
1794        $html .= '<span style="font-size:10px; color:var(--text-dim, #666);">of each month</span>';
1795        $html .= '</div>';
1796        $html .= '</div>';
1797
1798        $html .= '</div>'; // End monthly options
1799
1800        // Row 4: End date
1801        $html .= '<div class="form-row-group">';
1802        $html .= '<div class="form-field">';
1803        $html .= '<label class="field-label-compact">Repeat Until (optional)</label>';
1804        $html .= '<input type="date" id="event-recurrence-end-' . $calId . '" name="recurrenceEnd" class="input-sleek input-date input-compact" placeholder="Optional">';
1805        $html .= '<div style="font-size:9px; color:var(--text-dim, #666); margin-top:2px;">Leave empty for 1 year of events</div>';
1806        $html .= '</div>';
1807        $html .= '</div>'; // End row 4
1808
1809        $html .= '</div>'; // End recurring options
1810
1811        // 5. TIME (Start & End) - COLOR (inline)
1812        $html .= '<div class="form-row-group">';
1813
1814        $html .= '<div class="form-field form-field-half">';
1815        $html .= '<label class="field-label-compact">�� Start Time</label>';
1816        $html .= '<select id="event-time-' . $calId . '" name="time" class="input-sleek input-compact" onchange="updateEndTimeOptions(\'' . $calId . '\')">';
1817        $html .= '<option value="">All day</option>';
1818
1819        // Generate time options in 15-minute intervals
1820        for ($hour = 0; $hour < 24; $hour++) {
1821            for ($minute = 0; $minute < 60; $minute += 15) {
1822                $timeValue = sprintf('%02d:%02d', $hour, $minute);
1823                $displayHour = $hour == 0 ? 12 : ($hour > 12 ? $hour - 12 : $hour);
1824                $ampm = $hour < 12 ? 'AM' : 'PM';
1825                $displayTime = sprintf('%d:%02d %s', $displayHour, $minute, $ampm);
1826                $html .= '<option value="' . $timeValue . '">' . $displayTime . '</option>';
1827            }
1828        }
1829
1830        $html .= '</select>';
1831        $html .= '</div>';
1832
1833        $html .= '<div class="form-field form-field-half">';
1834        $html .= '<label class="field-label-compact">�� End Time</label>';
1835        $html .= '<select id="event-end-time-' . $calId . '" name="endTime" class="input-sleek input-compact">';
1836        $html .= '<option value="">Same as start</option>';
1837
1838        // Generate time options in 15-minute intervals
1839        for ($hour = 0; $hour < 24; $hour++) {
1840            for ($minute = 0; $minute < 60; $minute += 15) {
1841                $timeValue = sprintf('%02d:%02d', $hour, $minute);
1842                $displayHour = $hour == 0 ? 12 : ($hour > 12 ? $hour - 12 : $hour);
1843                $ampm = $hour < 12 ? 'AM' : 'PM';
1844                $displayTime = sprintf('%d:%02d %s', $displayHour, $minute, $ampm);
1845                $html .= '<option value="' . $timeValue . '">' . $displayTime . '</option>';
1846            }
1847        }
1848
1849        $html .= '</select>';
1850        $html .= '</div>';
1851
1852        $html .= '</div>'; // End row
1853
1854        // Color field (new row)
1855        $html .= '<div class="form-row-group">';
1856
1857        $html .= '<div class="form-field form-field-full">';
1858        $html .= '<label class="field-label-compact">�� Color</label>';
1859        $html .= '<div class="color-picker-wrapper">';
1860        $html .= '<select id="event-color-' . $calId . '" name="color" class="input-sleek input-compact color-select" onchange="updateCustomColorPicker(\'' . $calId . '\')">';
1861        $html .= '<option value="#3498db" style="background:#3498db;color:white">�� Blue</option>';
1862        $html .= '<option value="#2ecc71" style="background:#2ecc71;color:white">�� Green</option>';
1863        $html .= '<option value="#e74c3c" style="background:#e74c3c;color:white">�� Red</option>';
1864        $html .= '<option value="#f39c12" style="background:#f39c12;color:white">�� Orange</option>';
1865        $html .= '<option value="#9b59b6" style="background:#9b59b6;color:white">�� Purple</option>';
1866        $html .= '<option value="#e91e63" style="background:#e91e63;color:white">�� Pink</option>';
1867        $html .= '<option value="#1abc9c" style="background:#1abc9c;color:white">�� Teal</option>';
1868        $html .= '<option value="custom">�� Custom...</option>';
1869        $html .= '</select>';
1870        $html .= '<input type="color" id="event-color-custom-' . $calId . '" class="color-picker-input color-picker-compact" value="#3498db" onchange="updateColorFromPicker(\'' . $calId . '\')">';
1871        $html .= '</div>';
1872        $html .= '</div>';
1873
1874        $html .= '</div>'; // End row
1875
1876        // Task checkbox
1877        $html .= '<div class="form-field form-field-checkbox form-field-checkbox-compact">';
1878        $html .= '<label class="checkbox-label checkbox-label-compact">';
1879        $html .= '<input type="checkbox" id="event-is-task-' . $calId . '" name="isTask" class="task-toggle">';
1880        $html .= '<span>�� This is a task (can be checked off)</span>';
1881        $html .= '</label>';
1882        $html .= '</div>';
1883
1884        // Action buttons
1885        $html .= '<div class="dialog-actions-sleek">';
1886        $html .= '<button type="button" class="btn-sleek btn-cancel-sleek" onclick="closeEventDialog(\'' . $calId . '\')">Cancel</button>';
1887        $html .= '<button type="submit" class="btn-sleek btn-save-sleek">�� Save</button>';
1888        $html .= '</div>';
1889
1890        $html .= '</form>';
1891        $html .= '</div>';
1892        $html .= '</div>';
1893
1894        return $html;
1895    }
1896
1897    private function renderMonthPicker($calId, $year, $month, $namespace, $theme = 'matrix', $themeStyles = null) {
1898        // Fallback to default theme if not provided
1899        if ($themeStyles === null) {
1900            $themeStyles = $this->getSidebarThemeStyles($theme);
1901        }
1902
1903        $themeClass = 'calendar-theme-' . $theme;
1904
1905        $html = '<div class="month-picker-overlay ' . $themeClass . '" id="month-picker-overlay-' . $calId . '" style="display:none;" onclick="closeMonthPicker(\'' . $calId . '\')">';
1906        $html .= '<div class="month-picker-dialog" onclick="event.stopPropagation();">';
1907        $html .= '<h4>Jump to Month</h4>';
1908
1909        $html .= '<div class="month-picker-selects">';
1910        $html .= '<select id="month-picker-month-' . $calId . '" class="month-picker-select">';
1911        $monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
1912        for ($m = 1; $m <= 12; $m++) {
1913            $selected = ($m == $month) ? ' selected' : '';
1914            $html .= '<option value="' . $m . '"' . $selected . '>' . $monthNames[$m - 1] . '</option>';
1915        }
1916        $html .= '</select>';
1917
1918        $html .= '<select id="month-picker-year-' . $calId . '" class="month-picker-select">';
1919        $currentYear = (int)date('Y');
1920        for ($y = $currentYear - 5; $y <= $currentYear + 5; $y++) {
1921            $selected = ($y == $year) ? ' selected' : '';
1922            $html .= '<option value="' . $y . '"' . $selected . '>' . $y . '</option>';
1923        }
1924        $html .= '</select>';
1925        $html .= '</div>';
1926
1927        $html .= '<div class="month-picker-actions">';
1928        $html .= '<button class="btn-sleek btn-cancel-sleek" onclick="closeMonthPicker(\'' . $calId . '\')">Cancel</button>';
1929        $html .= '<button class="btn-sleek btn-save-sleek" onclick="jumpToSelectedMonth(\'' . $calId . '\', \'' . $namespace . '\')">Go</button>';
1930        $html .= '</div>';
1931
1932        $html .= '</div>';
1933        $html .= '</div>';
1934
1935        return $html;
1936    }
1937
1938    private function renderDescription($description, $themeStyles = null) {
1939        if (empty($description)) {
1940            return '';
1941        }
1942
1943        // Get theme for link colors if not provided
1944        if ($themeStyles === null) {
1945            $theme = $this->getSidebarTheme();
1946            $themeStyles = $this->getSidebarThemeStyles($theme);
1947        }
1948
1949        $linkColor = '';
1950        $linkStyle = ' class="cal-link"';
1951
1952        // Token-based parsing to avoid escaping issues
1953        $rendered = $description;
1954        $tokens = array();
1955        $tokenIndex = 0;
1956
1957        // Convert DokuWiki image syntax {{image.jpg}} to tokens
1958        $pattern = '/\{\{([^}|]+?)(?:\|([^}]+))?\}\}/';
1959        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
1960        foreach ($matches as $match) {
1961            $imagePath = trim($match[1]);
1962            $alt = isset($match[2]) ? trim($match[2]) : '';
1963
1964            // Handle external URLs
1965            if (preg_match('/^https?:\/\//', $imagePath)) {
1966                $imageHtml = '<img src="' . htmlspecialchars($imagePath) . '" alt="' . htmlspecialchars($alt) . '" class="event-image" />';
1967            } else {
1968                // Handle internal DokuWiki images
1969                $imageUrl = DOKU_BASE . 'lib/exe/fetch.php?media=' . rawurlencode($imagePath);
1970                $imageHtml = '<img src="' . $imageUrl . '" alt="' . htmlspecialchars($alt) . '" class="event-image" />';
1971            }
1972
1973            $token = "\x00TOKEN" . $tokenIndex . "\x00";
1974            $tokens[$tokenIndex] = $imageHtml;
1975            $tokenIndex++;
1976            $rendered = str_replace($match[0], $token, $rendered);
1977        }
1978
1979        // Convert DokuWiki link syntax [[link|text]] to tokens
1980        $pattern = '/\[\[([^|\]]+?)(?:\|([^\]]+))?\]\]/';
1981        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
1982        foreach ($matches as $match) {
1983            $link = trim($match[1]);
1984            $text = isset($match[2]) ? trim($match[2]) : $link;
1985
1986            // Handle external URLs
1987            if (preg_match('/^https?:\/\//', $link)) {
1988                $linkHtml = '<a href="' . htmlspecialchars($link) . '" target="_blank" rel="noopener noreferrer"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
1989            } else {
1990                // Handle internal DokuWiki links with section anchors
1991                $parts = explode('#', $link, 2);
1992                $pagePart = $parts[0];
1993                $sectionPart = isset($parts[1]) ? '#' . $parts[1] : '';
1994
1995                $wikiUrl = DOKU_BASE . 'doku.php?id=' . rawurlencode($pagePart) . $sectionPart;
1996                $linkHtml = '<a href="' . $wikiUrl . '"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
1997            }
1998
1999            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2000            $tokens[$tokenIndex] = $linkHtml;
2001            $tokenIndex++;
2002            $rendered = str_replace($match[0], $token, $rendered);
2003        }
2004
2005        // Convert markdown-style links [text](url) to tokens
2006        $pattern = '/\[([^\]]+)\]\(([^)]+)\)/';
2007        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
2008        foreach ($matches as $match) {
2009            $text = trim($match[1]);
2010            $url = trim($match[2]);
2011
2012            if (preg_match('/^https?:\/\//', $url)) {
2013                $linkHtml = '<a href="' . htmlspecialchars($url) . '" target="_blank" rel="noopener noreferrer"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
2014            } else {
2015                $linkHtml = '<a href="' . htmlspecialchars($url) . '"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
2016            }
2017
2018            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2019            $tokens[$tokenIndex] = $linkHtml;
2020            $tokenIndex++;
2021            $rendered = str_replace($match[0], $token, $rendered);
2022        }
2023
2024        // Convert plain URLs to tokens
2025        $pattern = '/(https?:\/\/[^\s<]+)/';
2026        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
2027        foreach ($matches as $match) {
2028            $url = $match[1];
2029            $linkHtml = '<a href="' . htmlspecialchars($url) . '" target="_blank" rel="noopener noreferrer"' . $linkStyle . '>' . htmlspecialchars($url) . '</a>';
2030
2031            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2032            $tokens[$tokenIndex] = $linkHtml;
2033            $tokenIndex++;
2034            $rendered = str_replace($match[0], $token, $rendered);
2035        }
2036
2037        // NOW escape HTML (tokens are protected)
2038        $rendered = htmlspecialchars($rendered);
2039
2040        // Convert newlines to <br>
2041        $rendered = nl2br($rendered);
2042
2043        // DokuWiki text formatting
2044        // Bold: **text** or __text__
2045        $boldStyle = '';
2046        $rendered = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $rendered);
2047        $rendered = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $rendered);
2048
2049        // Italic: //text//
2050        $rendered = preg_replace('/\/\/(.+?)\/\//', '<em>$1</em>', $rendered);
2051
2052        // Strikethrough: <del>text</del>
2053        $rendered = preg_replace('/&lt;del&gt;(.+?)&lt;\/del&gt;/', '<del>$1</del>', $rendered);
2054
2055        // Monospace: ''text''
2056        $rendered = preg_replace('/&#039;&#039;(.+?)&#039;&#039;/', '<code>$1</code>', $rendered);
2057
2058        // Subscript: <sub>text</sub>
2059        $rendered = preg_replace('/&lt;sub&gt;(.+?)&lt;\/sub&gt;/', '<sub>$1</sub>', $rendered);
2060
2061        // Superscript: <sup>text</sup>
2062        $rendered = preg_replace('/&lt;sup&gt;(.+?)&lt;\/sup&gt;/', '<sup>$1</sup>', $rendered);
2063
2064        // Restore tokens
2065        foreach ($tokens as $i => $html) {
2066            $rendered = str_replace("\x00TOKEN" . $i . "\x00", $html, $rendered);
2067        }
2068
2069        return $rendered;
2070    }
2071
2072    private function loadEvents($namespace, $year, $month) {
2073        $dataDir = DOKU_INC . 'data/meta/';
2074        if ($namespace) {
2075            $dataDir .= str_replace(':', '/', $namespace) . '/';
2076        }
2077        $dataDir .= 'calendar/';
2078
2079        $eventFile = $dataDir . sprintf('%04d-%02d.json', $year, $month);
2080
2081        if (file_exists($eventFile)) {
2082            $json = file_get_contents($eventFile);
2083            return json_decode($json, true);
2084        }
2085
2086        return array();
2087    }
2088
2089    private function loadEventsMultiNamespace($namespaces, $year, $month) {
2090        // Check for wildcard pattern (namespace:*)
2091        if (preg_match('/^(.+):\*$/', $namespaces, $matches)) {
2092            $baseNamespace = $matches[1];
2093            return $this->loadEventsWildcard($baseNamespace, $year, $month);
2094        }
2095
2096        // Check for root wildcard (just *)
2097        if ($namespaces === '*') {
2098            return $this->loadEventsWildcard('', $year, $month);
2099        }
2100
2101        // Parse namespace list (semicolon separated)
2102        // e.g., "team:projects;personal;work:tasks" = three namespaces
2103        $namespaceList = array_map('trim', explode(';', $namespaces));
2104
2105        // Load events from all namespaces
2106        $allEvents = array();
2107        foreach ($namespaceList as $ns) {
2108            $ns = trim($ns);
2109            if (empty($ns)) continue;
2110
2111            $events = $this->loadEvents($ns, $year, $month);
2112
2113            // Add namespace tag to each event
2114            foreach ($events as $dateKey => $dayEvents) {
2115                if (!isset($allEvents[$dateKey])) {
2116                    $allEvents[$dateKey] = array();
2117                }
2118                foreach ($dayEvents as $event) {
2119                    $event['_namespace'] = $ns;
2120                    $allEvents[$dateKey][] = $event;
2121                }
2122            }
2123        }
2124
2125        return $allEvents;
2126    }
2127
2128    private function loadEventsWildcard($baseNamespace, $year, $month) {
2129        // Find all subdirectories under the base namespace
2130        $dataDir = DOKU_INC . 'data/meta/';
2131        if ($baseNamespace) {
2132            $dataDir .= str_replace(':', '/', $baseNamespace) . '/';
2133        }
2134
2135        $allEvents = array();
2136
2137        // First, load events from the base namespace itself
2138        if (empty($baseNamespace)) {
2139            // Root wildcard - load from root calendar
2140            $events = $this->loadEvents('', $year, $month);
2141            foreach ($events as $dateKey => $dayEvents) {
2142                if (!isset($allEvents[$dateKey])) {
2143                    $allEvents[$dateKey] = array();
2144                }
2145                foreach ($dayEvents as $event) {
2146                    $event['_namespace'] = '';
2147                    $allEvents[$dateKey][] = $event;
2148                }
2149            }
2150        } else {
2151            $events = $this->loadEvents($baseNamespace, $year, $month);
2152            foreach ($events as $dateKey => $dayEvents) {
2153                if (!isset($allEvents[$dateKey])) {
2154                    $allEvents[$dateKey] = array();
2155                }
2156                foreach ($dayEvents as $event) {
2157                    $event['_namespace'] = $baseNamespace;
2158                    $allEvents[$dateKey][] = $event;
2159                }
2160            }
2161        }
2162
2163        // Recursively find all subdirectories
2164        $this->findSubNamespaces($dataDir, $baseNamespace, $year, $month, $allEvents);
2165
2166        return $allEvents;
2167    }
2168
2169    private function findSubNamespaces($dir, $baseNamespace, $year, $month, &$allEvents) {
2170        if (!is_dir($dir)) return;
2171
2172        $items = scandir($dir);
2173        foreach ($items as $item) {
2174            if ($item === '.' || $item === '..') continue;
2175
2176            $path = $dir . $item;
2177            if (is_dir($path) && $item !== 'calendar') {
2178                // This is a namespace directory
2179                $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
2180
2181                // Load events from this namespace
2182                $events = $this->loadEvents($namespace, $year, $month);
2183                foreach ($events as $dateKey => $dayEvents) {
2184                    if (!isset($allEvents[$dateKey])) {
2185                        $allEvents[$dateKey] = array();
2186                    }
2187                    foreach ($dayEvents as $event) {
2188                        $event['_namespace'] = $namespace;
2189                        $allEvents[$dateKey][] = $event;
2190                    }
2191                }
2192
2193                // Recurse into subdirectories
2194                $this->findSubNamespaces($path . '/', $namespace, $year, $month, $allEvents);
2195            }
2196        }
2197    }
2198
2199    private function getAllNamespaces() {
2200        $dataDir = DOKU_INC . 'data/meta/';
2201        $namespaces = [];
2202
2203        // Scan for namespaces that have calendar data
2204        $this->scanForCalendarNamespaces($dataDir, '', $namespaces);
2205
2206        // Sort alphabetically
2207        sort($namespaces);
2208
2209        return $namespaces;
2210    }
2211
2212    private function scanForCalendarNamespaces($dir, $baseNamespace, &$namespaces) {
2213        if (!is_dir($dir)) return;
2214
2215        $items = scandir($dir);
2216        foreach ($items as $item) {
2217            if ($item === '.' || $item === '..') continue;
2218
2219            $path = $dir . $item;
2220            if (is_dir($path)) {
2221                // Check if this directory has a calendar subdirectory with data
2222                $calendarDir = $path . '/calendar/';
2223                if (is_dir($calendarDir)) {
2224                    // Check if there are any JSON files in the calendar directory
2225                    $jsonFiles = glob($calendarDir . '*.json');
2226                    if (!empty($jsonFiles)) {
2227                        // This namespace has calendar data
2228                        $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
2229                        $namespaces[] = $namespace;
2230                    }
2231                }
2232
2233                // Recurse into subdirectories
2234                $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
2235                $this->scanForCalendarNamespaces($path . '/', $namespace, $namespaces);
2236            }
2237        }
2238    }
2239
2240    /**
2241     * Render new sidebar widget - Week at a glance itinerary (200px wide)
2242     */
2243    private function renderSidebarWidget($events, $namespace, $calId, $themeOverride = null) {
2244        if (empty($events)) {
2245            return '<div style="width:200px; padding:12px; text-align:center; color:#999; font-size:11px;">No events this week</div>';
2246        }
2247
2248        // Get important namespaces from config
2249        $configFile = DOKU_PLUGIN . 'calendar/sync_config.php';
2250        $importantNsList = ['important']; // default
2251        if (file_exists($configFile)) {
2252            $config = include $configFile;
2253            if (isset($config['important_namespaces']) && !empty($config['important_namespaces'])) {
2254                $importantNsList = array_map('trim', explode(',', $config['important_namespaces']));
2255            }
2256        }
2257
2258        // Calculate date ranges
2259        $todayStr = date('Y-m-d');
2260        $tomorrowStr = date('Y-m-d', strtotime('+1 day'));
2261
2262        // Get week start preference and calculate week range
2263        $weekStartDay = $this->getWeekStartDay();
2264
2265        if ($weekStartDay === 'monday') {
2266            // Monday start
2267            $weekStart = date('Y-m-d', strtotime('monday this week'));
2268            $weekEnd = date('Y-m-d', strtotime('sunday this week'));
2269        } else {
2270            // Sunday start (default - US/Canada standard)
2271            $today = date('w'); // 0 (Sun) to 6 (Sat)
2272            if ($today == 0) {
2273                // Today is Sunday
2274                $weekStart = date('Y-m-d');
2275            } else {
2276                // Monday-Saturday: go back to last Sunday
2277                $weekStart = date('Y-m-d', strtotime('-' . $today . ' days'));
2278            }
2279            $weekEnd = date('Y-m-d', strtotime($weekStart . ' +6 days'));
2280        }
2281
2282        // Group events by category
2283        $todayEvents = [];
2284        $tomorrowEvents = [];
2285        $importantEvents = [];
2286        $weekEvents = []; // For week grid
2287
2288        // Process all events
2289        foreach ($events as $dateKey => $dayEvents) {
2290            // Detect conflicts for events on this day
2291            $eventsWithConflicts = $this->detectTimeConflicts($dayEvents);
2292
2293            foreach ($eventsWithConflicts as $event) {
2294                // Always categorize Today and Tomorrow regardless of week boundaries
2295                if ($dateKey === $todayStr) {
2296                    $todayEvents[] = array_merge($event, ['date' => $dateKey]);
2297                }
2298                if ($dateKey === $tomorrowStr) {
2299                    $tomorrowEvents[] = array_merge($event, ['date' => $dateKey]);
2300                }
2301
2302                // Process week grid events (only for current week)
2303                if ($dateKey >= $weekStart && $dateKey <= $weekEnd) {
2304                    // Initialize week grid day if not exists
2305                    if (!isset($weekEvents[$dateKey])) {
2306                        $weekEvents[$dateKey] = [];
2307                    }
2308
2309                    // Pre-render DokuWiki syntax to HTML for JavaScript display
2310                    $eventWithHtml = $event;
2311                    if (isset($event['title'])) {
2312                        $eventWithHtml['title_html'] = $this->renderDokuWikiToHtml($event['title']);
2313                    }
2314                    if (isset($event['description'])) {
2315                        $eventWithHtml['description_html'] = $this->renderDokuWikiToHtml($event['description']);
2316                    }
2317                    $weekEvents[$dateKey][] = $eventWithHtml;
2318                }
2319
2320                // Check if this is an important namespace
2321                $eventNs = isset($event['namespace']) ? $event['namespace'] : '';
2322                $isImportant = false;
2323                foreach ($importantNsList as $impNs) {
2324                    if ($eventNs === $impNs || strpos($eventNs, $impNs . ':') === 0) {
2325                        $isImportant = true;
2326                        break;
2327                    }
2328                }
2329
2330                // Important events: show from today through next 2 weeks
2331                if ($isImportant && $dateKey >= $todayStr) {
2332                    $importantEvents[] = array_merge($event, ['date' => $dateKey]);
2333                }
2334            }
2335        }
2336
2337        // Sort Important Events by date (earliest first)
2338        usort($importantEvents, function($a, $b) {
2339            $dateA = isset($a['date']) ? $a['date'] : '';
2340            $dateB = isset($b['date']) ? $b['date'] : '';
2341
2342            // Compare dates
2343            if ($dateA === $dateB) {
2344                // Same date - sort by time
2345                $timeA = isset($a['time']) ? $a['time'] : '';
2346                $timeB = isset($b['time']) ? $b['time'] : '';
2347
2348                if (empty($timeA) && !empty($timeB)) return 1;  // All-day events last
2349                if (!empty($timeA) && empty($timeB)) return -1;
2350                if (empty($timeA) && empty($timeB)) return 0;
2351
2352                // Both have times
2353                $aMinutes = $this->timeToMinutes($timeA);
2354                $bMinutes = $this->timeToMinutes($timeB);
2355                return $aMinutes - $bMinutes;
2356            }
2357
2358            return strcmp($dateA, $dateB);
2359        });
2360
2361        // Get theme - prefer override from syntax parameter, fall back to admin default
2362        $theme = !empty($themeOverride) ? $themeOverride : $this->getSidebarTheme();
2363        $themeStyles = $this->getSidebarThemeStyles($theme);
2364        $themeClass = 'sidebar-' . $theme;
2365
2366        // Start building HTML - Dynamic width with default font (overflow:visible for tooltips)
2367        $html = '<div class="sidebar-widget ' . $themeClass . '" id="sidebar-widget-' . $calId . '" style="width:100%; max-width:100%; box-sizing:border-box; font-family:system-ui, sans-serif; background:' . $themeStyles['bg'] . '; border:2px solid ' . $themeStyles['border'] . '; border-radius:4px; overflow:visible; box-shadow:0 0 10px ' . $themeStyles['shadow'] . '; position:relative;">';
2368
2369        // Inject CSS variables so the event dialog (shared component) picks up the theme
2370        $btnTextColor = ($theme === 'professional') ? '#fff' : $themeStyles['bg'];
2371        $html .= '<style>
2372        #sidebar-widget-' . $calId . ' {
2373            --background-site: ' . $themeStyles['bg'] . ';
2374            --background-alt: ' . $themeStyles['cell_bg'] . ';
2375            --background-header: ' . $themeStyles['header_bg'] . ';
2376            --text-primary: ' . $themeStyles['text_primary'] . ';
2377            --text-dim: ' . $themeStyles['text_dim'] . ';
2378            --text-bright: ' . $themeStyles['text_bright'] . ';
2379            --border-color: ' . $themeStyles['grid_border'] . ';
2380            --border-main: ' . $themeStyles['border'] . ';
2381            --cell-bg: ' . $themeStyles['cell_bg'] . ';
2382            --cell-today-bg: ' . $themeStyles['cell_today_bg'] . ';
2383            --shadow-color: ' . $themeStyles['shadow'] . ';
2384            --header-border: ' . $themeStyles['header_border'] . ';
2385            --header-shadow: ' . $themeStyles['header_shadow'] . ';
2386            --grid-bg: ' . $themeStyles['grid_bg'] . ';
2387            --btn-text: ' . $btnTextColor . ';
2388            --pastdue-color: ' . $themeStyles['pastdue_color'] . ';
2389            --pastdue-bg: ' . $themeStyles['pastdue_bg'] . ';
2390            --pastdue-bg-strong: ' . $themeStyles['pastdue_bg_strong'] . ';
2391            --pastdue-bg-light: ' . $themeStyles['pastdue_bg_light'] . ';
2392            --tomorrow-bg: ' . $themeStyles['tomorrow_bg'] . ';
2393            --tomorrow-bg-strong: ' . $themeStyles['tomorrow_bg_strong'] . ';
2394            --tomorrow-bg-light: ' . $themeStyles['tomorrow_bg_light'] . ';
2395        }
2396        </style>';
2397
2398        // Add sparkle effect for pink theme
2399        if ($theme === 'pink') {
2400            $html .= '<style>
2401            @keyframes sparkle-' . $calId . ' {
2402                0% {
2403                    opacity: 0;
2404                    transform: translate(0, 0) scale(0) rotate(0deg);
2405                }
2406                50% {
2407                    opacity: 1;
2408                    transform: translate(var(--tx), var(--ty)) scale(1) rotate(180deg);
2409                }
2410                100% {
2411                    opacity: 0;
2412                    transform: translate(calc(var(--tx) * 2), calc(var(--ty) * 2)) scale(0) rotate(360deg);
2413                }
2414            }
2415
2416            @keyframes pulse-glow-' . $calId . ' {
2417                0%, 100% { box-shadow: 0 0 10px rgba(255, 20, 147, 0.4); }
2418                50% { box-shadow: 0 0 25px rgba(255, 20, 147, 0.8), 0 0 40px rgba(255, 20, 147, 0.4); }
2419            }
2420
2421            @keyframes shimmer-' . $calId . ' {
2422                0% { background-position: -200% center; }
2423                100% { background-position: 200% center; }
2424            }
2425
2426            .sidebar-pink {
2427                animation: pulse-glow-' . $calId . ' 3s ease-in-out infinite;
2428            }
2429
2430            .sidebar-pink:hover {
2431                box-shadow: 0 0 30px rgba(255, 20, 147, 0.9), 0 0 50px rgba(255, 20, 147, 0.5) !important;
2432            }
2433
2434            .sparkle-' . $calId . ' {
2435                position: absolute;
2436                pointer-events: none;
2437                font-size: 20px;
2438                z-index: 1000;
2439                animation: sparkle-' . $calId . ' 1s ease-out forwards;
2440                filter: drop-shadow(0 0 3px rgba(255, 20, 147, 0.8));
2441            }
2442            </style>';
2443
2444            $html .= '<script>
2445            (function() {
2446                const container = document.getElementById("sidebar-widget-' . $calId . '");
2447                const sparkles = ["✨", "��", "��", "⭐", "��", "��", "��", "��", "��", "��"];
2448
2449                function createSparkle(x, y) {
2450                    const sparkle = document.createElement("div");
2451                    sparkle.className = "sparkle-' . $calId . '";
2452                    sparkle.textContent = sparkles[Math.floor(Math.random() * sparkles.length)];
2453                    sparkle.style.left = x + "px";
2454                    sparkle.style.top = y + "px";
2455
2456                    // Random direction
2457                    const angle = Math.random() * Math.PI * 2;
2458                    const distance = 30 + Math.random() * 40;
2459                    sparkle.style.setProperty("--tx", Math.cos(angle) * distance + "px");
2460                    sparkle.style.setProperty("--ty", Math.sin(angle) * distance + "px");
2461
2462                    container.appendChild(sparkle);
2463
2464                    setTimeout(() => sparkle.remove(), 1000);
2465                }
2466
2467                // Click sparkles
2468                container.addEventListener("click", function(e) {
2469                    const rect = container.getBoundingClientRect();
2470                    const x = e.clientX - rect.left;
2471                    const y = e.clientY - rect.top;
2472
2473                    // Create LOTS of sparkles for maximum bling!
2474                    for (let i = 0; i < 8; i++) {
2475                        setTimeout(() => {
2476                            const offsetX = x + (Math.random() - 0.5) * 30;
2477                            const offsetY = y + (Math.random() - 0.5) * 30;
2478                            createSparkle(offsetX, offsetY);
2479                        }, i * 40);
2480                    }
2481                });
2482
2483                // Random auto-sparkles for extra glamour
2484                setInterval(() => {
2485                    const x = Math.random() * container.offsetWidth;
2486                    const y = Math.random() * container.offsetHeight;
2487                    createSparkle(x, y);
2488                }, 3000);
2489            })();
2490            </script>';
2491        }
2492
2493        // Sanitize calId for use in JavaScript variable names (remove dashes)
2494        $jsCalId = str_replace('-', '_', $calId);
2495
2496        // CRITICAL: Add ALL JavaScript FIRST before any HTML that uses it
2497        $html .= '<script>
2498(function() {
2499    // Shared state for system stats and tooltips
2500    const sharedState_' . $jsCalId . ' = {
2501        latestStats: {
2502            load: {"1min": 0, "5min": 0, "15min": 0},
2503            uptime: "",
2504            memory_details: {},
2505            top_processes: []
2506        },
2507        cpuHistory: [],
2508        CPU_HISTORY_SIZE: 2
2509    };
2510
2511    // Tooltip functions - MUST be defined before HTML uses them
2512    window["showTooltip_' . $jsCalId . '"] = function(color) {
2513        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
2514        if (!tooltip) {
2515            console.log("Tooltip element not found for color:", color);
2516            return;
2517        }
2518
2519        const latestStats = sharedState_' . $jsCalId . '.latestStats;
2520        let content = "";
2521
2522        if (color === "green") {
2523            content = "<div class=\\"tooltip-title\\">CPU Load Average</div>";
2524            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
2525            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
2526            content += "<div>15 min: " + (latestStats.load["15min"] || "N/A") + "</div>";
2527            if (latestStats.uptime) {
2528                content += "<div style=\\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_bright'] . ';\\">Uptime: " + latestStats.uptime + "</div>";
2529            }
2530            tooltip.style.setProperty("border-color", "' . $themeStyles['text_bright'] . '", "important");
2531            tooltip.style.setProperty("color", "' . $themeStyles['text_bright'] . '", "important");
2532            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_bright'] . '", "important");
2533        } else if (color === "purple") {
2534            content = "<div class=\\"tooltip-title\\">CPU Load (Short-term)</div>";
2535            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
2536            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
2537            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
2538                content += "<div style=\\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['border'] . ';\\" class=\\"tooltip-title\\">Top Processes</div>";
2539                latestStats.top_processes.slice(0, 5).forEach(proc => {
2540                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
2541                });
2542            }
2543            tooltip.style.setProperty("border-color", "' . $themeStyles['border'] . '", "important");
2544            tooltip.style.setProperty("color", "' . $themeStyles['border'] . '", "important");
2545            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['border'] . '", "important");
2546        } else if (color === "orange") {
2547            content = "<div class=\\"tooltip-title\\">Memory Usage</div>";
2548            if (latestStats.memory_details && latestStats.memory_details.total) {
2549                content += "<div>Total: " + latestStats.memory_details.total + "</div>";
2550                content += "<div>Used: " + latestStats.memory_details.used + "</div>";
2551                content += "<div>Available: " + latestStats.memory_details.available + "</div>";
2552                if (latestStats.memory_details.cached) {
2553                    content += "<div>Cached: " + latestStats.memory_details.cached + "</div>";
2554                }
2555            } else {
2556                content += "<div>Loading...</div>";
2557            }
2558            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
2559                content += "<div style=\\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_primary'] . ';\\" class=\\"tooltip-title\\">Top Processes</div>";
2560                latestStats.top_processes.slice(0, 5).forEach(proc => {
2561                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
2562                });
2563            }
2564            tooltip.style.setProperty("border-color", "' . $themeStyles['text_primary'] . '", "important");
2565            tooltip.style.setProperty("color", "' . $themeStyles['text_primary'] . '", "important");
2566            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_primary'] . '", "important");
2567        }
2568
2569        tooltip.innerHTML = content;
2570        tooltip.style.setProperty("display", "block");
2571        tooltip.style.setProperty("background", "' . $themeStyles['bg'] . '", "important");
2572
2573        const bar = tooltip.parentElement;
2574        const barRect = bar.getBoundingClientRect();
2575        const tooltipRect = tooltip.getBoundingClientRect();
2576
2577        const left = barRect.left + (barRect.width / 2) - (tooltipRect.width / 2);
2578        const top = barRect.top - tooltipRect.height - 8;
2579
2580        tooltip.style.left = left + "px";
2581        tooltip.style.top = top + "px";
2582    };
2583
2584    window["hideTooltip_' . $jsCalId . '"] = function(color) {
2585        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
2586        if (tooltip) {
2587            tooltip.style.display = "none";
2588        }
2589    };
2590
2591    // Update clock every second
2592    function updateClock() {
2593        const now = new Date();
2594        let hours = now.getHours();
2595        const minutes = String(now.getMinutes()).padStart(2, "0");
2596        const seconds = String(now.getSeconds()).padStart(2, "0");
2597        const ampm = hours >= 12 ? "PM" : "AM";
2598        hours = hours % 12 || 12;
2599        const timeStr = hours + ":" + minutes + ":" + seconds + " " + ampm;
2600        const clockEl = document.getElementById("clock-' . $calId . '");
2601        if (clockEl) clockEl.textContent = timeStr;
2602    }
2603    setInterval(updateClock, 1000);
2604
2605    // Weather - uses default location, click weather to get local
2606    var userLocationGranted = false;
2607    var userLat = 38.5816;  // Sacramento default
2608    var userLon = -121.4944;
2609
2610    function fetchWeatherData(lat, lon) {
2611        fetch("https://api.open-meteo.com/v1/forecast?latitude=" + lat + "&longitude=" + lon + "&current_weather=true&temperature_unit=fahrenheit")
2612            .then(response => response.json())
2613            .then(data => {
2614                if (data.current_weather) {
2615                    const temp = Math.round(data.current_weather.temperature);
2616                    const weatherCode = data.current_weather.weathercode;
2617                    const icon = getWeatherIcon(weatherCode);
2618                    const iconEl = document.getElementById("weather-icon-' . $calId . '");
2619                    const tempEl = document.getElementById("weather-temp-' . $calId . '");
2620                    if (iconEl) iconEl.textContent = icon;
2621                    if (tempEl) tempEl.innerHTML = temp + "&deg;";
2622                }
2623            })
2624            .catch(error => console.log("Weather fetch error:", error));
2625    }
2626
2627    function updateWeather() {
2628        fetchWeatherData(userLat, userLon);
2629    }
2630
2631    // Click weather icon to request local weather (user gesture required)
2632    function requestLocalWeather() {
2633        if (userLocationGranted) return;
2634        if ("geolocation" in navigator) {
2635            navigator.geolocation.getCurrentPosition(function(position) {
2636                userLat = position.coords.latitude;
2637                userLon = position.coords.longitude;
2638                userLocationGranted = true;
2639                fetchWeatherData(userLat, userLon);
2640            }, function(error) {
2641                console.log("Geolocation denied, using default location");
2642            });
2643        }
2644    }
2645
2646    setTimeout(function() {
2647        var weatherEl = document.querySelector("#weather-icon-' . $calId . '");
2648        if (weatherEl) {
2649            weatherEl.style.cursor = "pointer";
2650            weatherEl.title = "Click for local weather";
2651            weatherEl.addEventListener("click", requestLocalWeather);
2652        }
2653    }, 100);
2654
2655    function getWeatherIcon(code) {
2656        const icons = {
2657            0: "☀️", 1: "��️", 2: "⛅", 3: "☁️",
2658            45: "��️", 48: "��️", 51: "��️", 53: "��️", 55: "��️",
2659            61: "��️", 63: "��️", 65: "⛈️", 71: "��️", 73: "��️",
2660            75: "❄️", 77: "��️", 80: "��️", 81: "��️", 82: "⛈️",
2661            85: "��️", 86: "❄️", 95: "⛈️", 96: "⛈️", 99: "⛈️"
2662        };
2663        return icons[code] || "��️";
2664    }
2665
2666    // Update weather immediately and every 10 minutes
2667    updateWeather();
2668    setInterval(updateWeather, 600000);
2669
2670    // Update system stats and tooltips data
2671    function updateSystemStats() {
2672        fetch("' . DOKU_BASE . 'lib/plugins/calendar/get_system_stats.php")
2673            .then(response => response.json())
2674            .then(data => {
2675                sharedState_' . $jsCalId . '.latestStats = {
2676                    load: data.load || {"1min": 0, "5min": 0, "15min": 0},
2677                    uptime: data.uptime || "",
2678                    memory_details: data.memory_details || {},
2679                    top_processes: data.top_processes || []
2680                };
2681
2682                const greenBar = document.getElementById("cpu-5min-' . $calId . '");
2683                if (greenBar) {
2684                    greenBar.style.width = Math.min(100, data.cpu_5min) + "%";
2685                }
2686
2687                sharedState_' . $jsCalId . '.cpuHistory.push(data.cpu);
2688                if (sharedState_' . $jsCalId . '.cpuHistory.length > sharedState_' . $jsCalId . '.CPU_HISTORY_SIZE) {
2689                    sharedState_' . $jsCalId . '.cpuHistory.shift();
2690                }
2691
2692                const cpuAverage = sharedState_' . $jsCalId . '.cpuHistory.reduce((sum, val) => sum + val, 0) / sharedState_' . $jsCalId . '.cpuHistory.length;
2693
2694                const cpuBar = document.getElementById("cpu-realtime-' . $calId . '");
2695                if (cpuBar) {
2696                    cpuBar.style.width = Math.min(100, cpuAverage) + "%";
2697                }
2698
2699                const memBar = document.getElementById("mem-realtime-' . $calId . '");
2700                if (memBar) {
2701                    memBar.style.width = Math.min(100, data.memory) + "%";
2702                }
2703            })
2704            .catch(error => {
2705                console.log("System stats error:", error);
2706            });
2707    }
2708
2709    updateSystemStats();
2710    setInterval(updateSystemStats, 2000);
2711})();
2712</script>';
2713
2714        // NOW add the header HTML (after JavaScript is defined)
2715        $todayDate = new DateTime();
2716        $displayDate = $todayDate->format('D, M j, Y');
2717        $currentTime = $todayDate->format('g:i:s A');
2718
2719        $html .= '<div class="eventlist-today-header" style="background:' . $themeStyles['header_bg'] . '; border:2px solid ' . $themeStyles['header_border'] . '; box-shadow:' . $themeStyles['header_shadow'] . ';">';
2720        $html .= '<span class="eventlist-today-clock" id="clock-' . $calId . '" style="color:' . $themeStyles['text_bright'] . ';">' . $currentTime . '</span>';
2721        $html .= '<div class="eventlist-bottom-info">';
2722        $html .= '<span class="eventlist-weather"><span id="weather-icon-' . $calId . '">��️</span> <span id="weather-temp-' . $calId . '" style="color:' . $themeStyles['text_primary'] . ';">--°</span></span>';
2723        $html .= '<span class="eventlist-today-date" style="color:' . $themeStyles['text_dim'] . ';">' . $displayDate . '</span>';
2724        $html .= '</div>';
2725
2726        // Three CPU/Memory bars (all update live)
2727        $html .= '<div class="eventlist-stats-container">';
2728
2729        // 5-minute load average (green, updates every 2 seconds)
2730        $html .= '<div class="eventlist-cpu-bar" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $jsCalId . '(\'green\')" onmouseout="hideTooltip_' . $jsCalId . '(\'green\')">';
2731        $html .= '<div class="eventlist-cpu-fill" id="cpu-5min-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_bright'] . ' !important;"></div>';
2732        $html .= '<div class="system-tooltip" id="tooltip-green-' . $calId . '" style="display:none;"></div>';
2733        $html .= '</div>';
2734
2735        // Real-time CPU (purple, updates with 5-sec average)
2736        $html .= '<div class="eventlist-cpu-bar eventlist-cpu-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $jsCalId . '(\'purple\')" onmouseout="hideTooltip_' . $jsCalId . '(\'purple\')">';
2737        $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-purple" id="cpu-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['border'] . ' !important;"></div>';
2738        $html .= '<div class="system-tooltip" id="tooltip-purple-' . $calId . '" style="display:none;"></div>';
2739        $html .= '</div>';
2740
2741        // Real-time Memory (orange, updates)
2742        $html .= '<div class="eventlist-cpu-bar eventlist-mem-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $jsCalId . '(\'orange\')" onmouseout="hideTooltip_' . $jsCalId . '(\'orange\')">';
2743        $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-orange" id="mem-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_primary'] . ' !important;"></div>';
2744        $html .= '<div class="system-tooltip" id="tooltip-orange-' . $calId . '" style="display:none;"></div>';
2745        $html .= '</div>';
2746
2747        $html .= '</div>';
2748        $html .= '</div>';
2749
2750        // Get today's date for default event date
2751        $todayStr = date('Y-m-d');
2752
2753        // Thin "Add Event" bar between header and week grid - theme-aware colors
2754        $addBtnBg = $themeStyles['cell_today_bg'];
2755        $addBtnHover = $themeStyles['grid_bg'];
2756        $addBtnTextColor = ($theme === 'professional' || $theme === 'wiki') ?
2757                          $themeStyles['text_bright'] : $themeStyles['text_bright'];
2758        $addBtnShadow = ($theme === 'professional' || $theme === 'wiki') ?
2759                       '0 2px 4px rgba(0,0,0,0.2)' : '0 0 8px ' . $themeStyles['shadow'];
2760        $addBtnHoverShadow = ($theme === 'professional' || $theme === 'wiki') ?
2761                            '0 3px 6px rgba(0,0,0,0.3)' : '0 0 12px ' . $themeStyles['shadow'];
2762
2763        $html .= '<div style="background:' . $addBtnBg . '; padding:0; margin:0; height:12px; line-height:10px; text-align:center; cursor:pointer; border-top:1px solid rgba(0, 0, 0, 0.1); border-bottom:1px solid rgba(0, 0, 0, 0.1); box-shadow:' . $addBtnShadow . '; transition:all 0.2s;" onclick="openAddEvent(\'' . $calId . '\', \'' . $namespace . '\', \'' . $todayStr . '\');" onmouseover="this.style.background=\'' . $addBtnHover . '\'; this.style.boxShadow=\'' . $addBtnHoverShadow . '\';" onmouseout="this.style.background=\'' . $addBtnBg . '\'; this.style.boxShadow=\'' . $addBtnShadow . '\';">';
2764        $addBtnTextShadow = ($theme === 'pink') ? '0 0 3px ' . $addBtnTextColor : 'none';
2765        $html .= '<span style="color:' . $addBtnTextColor . '; font-size:8px; font-weight:700; letter-spacing:0.4px; font-family:system-ui, sans-serif; text-shadow:' . $addBtnTextShadow . '; position:relative; top:-1px;">+ ADD EVENT</span>';
2766        $html .= '</div>';
2767
2768        // Week grid (7 cells)
2769        $html .= $this->renderWeekGrid($weekEvents, $weekStart, $themeStyles, $theme);
2770
2771        // Section colors - derived from theme palette
2772        // Today: brightest accent, Tomorrow: primary accent, Important: dim/secondary accent
2773        if ($theme === 'matrix') {
2774            $todayColor = '#00ff00';     // Bright green
2775            $tomorrowColor = '#00cc07';  // Standard green
2776            $importantColor = '#00aa00'; // Dim green
2777        } else if ($theme === 'purple') {
2778            $todayColor = '#d4a5ff';     // Bright purple
2779            $tomorrowColor = '#9b59b6';  // Standard purple
2780            $importantColor = '#8e7ab8'; // Dim purple
2781        } else if ($theme === 'pink') {
2782            $todayColor = '#ff1493';     // Hot pink
2783            $tomorrowColor = '#ff69b4';  // Medium pink
2784            $importantColor = '#ff85c1'; // Light pink
2785        } else if ($theme === 'professional') {
2786            $todayColor = '#4a90e2';     // Blue accent
2787            $tomorrowColor = '#5ba3e6';  // Lighter blue
2788            $importantColor = '#7fb8ec'; // Lightest blue
2789        } else {
2790            // Wiki - section header backgrounds from template colors
2791            $todayColor = $themeStyles['text_bright'];      // __link__
2792            $tomorrowColor = $themeStyles['header_bg'];     // __background_alt__
2793            $importantColor = $themeStyles['header_border'];// __border__
2794        }
2795
2796        // Check if there are any itinerary items
2797        $hasItinerary = !empty($todayEvents) || !empty($tomorrowEvents) || !empty($importantEvents);
2798
2799        // Itinerary bar (collapsible toggle) - styled like +Add bar
2800        $itineraryBg = $themeStyles['cell_today_bg'];
2801        $itineraryHover = $themeStyles['grid_bg'];
2802        $itineraryTextColor = ($theme === 'professional' || $theme === 'wiki') ?
2803                              $themeStyles['text_bright'] : $themeStyles['text_bright'];
2804        $itineraryShadow = ($theme === 'professional' || $theme === 'wiki') ?
2805                           '0 2px 4px rgba(0,0,0,0.2)' : '0 0 8px ' . $themeStyles['shadow'];
2806        $itineraryHoverShadow = ($theme === 'professional' || $theme === 'wiki') ?
2807                                '0 3px 6px rgba(0,0,0,0.3)' : '0 0 12px ' . $themeStyles['shadow'];
2808        $itineraryTextShadow = ($theme === 'pink') ? '0 0 3px ' . $itineraryTextColor : 'none';
2809
2810        // Sanitize calId for JavaScript
2811        $jsCalId = str_replace('-', '_', $calId);
2812
2813        // Get itinerary default state from settings
2814        $itineraryDefaultCollapsed = $this->getItineraryCollapsed();
2815        $arrowDefaultStyle = $itineraryDefaultCollapsed ? 'transform:rotate(-90deg);' : '';
2816        $contentDefaultStyle = $itineraryDefaultCollapsed ? 'max-height:0px; opacity:0;' : '';
2817
2818        $html .= '<div id="itinerary-bar-' . $calId . '" style="background:' . $itineraryBg . '; padding:0; margin:0; height:12px; line-height:10px; text-align:center; cursor:pointer; border-top:1px solid rgba(0, 0, 0, 0.1); border-bottom:1px solid rgba(0, 0, 0, 0.1); box-shadow:' . $itineraryShadow . '; transition:all 0.2s; display:flex; align-items:center; justify-content:center; gap:4px;" onclick="toggleItinerary_' . $jsCalId . '();" onmouseover="this.style.background=\'' . $itineraryHover . '\'; this.style.boxShadow=\'' . $itineraryHoverShadow . '\';" onmouseout="this.style.background=\'' . $itineraryBg . '\'; this.style.boxShadow=\'' . $itineraryShadow . '\';">';
2819        $html .= '<span id="itinerary-arrow-' . $calId . '" style="color:' . $itineraryTextColor . '; font-size:6px; font-weight:700; font-family:system-ui, sans-serif; text-shadow:' . $itineraryTextShadow . '; position:relative; top:-1px; transition:transform 0.2s; ' . $arrowDefaultStyle . '">▼</span>';
2820        $html .= '<span style="color:' . $itineraryTextColor . '; font-size:8px; font-weight:700; letter-spacing:0.4px; font-family:system-ui, sans-serif; text-shadow:' . $itineraryTextShadow . '; position:relative; top:-1px;">ITINERARY</span>';
2821        $html .= '</div>';
2822
2823        // Itinerary content container (collapsible)
2824        $html .= '<div id="itinerary-content-' . $calId . '" style="transition:max-height 0.3s ease-out, opacity 0.2s ease-out; overflow:hidden; ' . $contentDefaultStyle . '">';
2825
2826        // Today section
2827        if (!empty($todayEvents)) {
2828            $html .= $this->renderSidebarSection('Today', $todayEvents, $todayColor, $calId, $themeStyles, $theme, $importantNsList);
2829        }
2830
2831        // Tomorrow section
2832        if (!empty($tomorrowEvents)) {
2833            $html .= $this->renderSidebarSection('Tomorrow', $tomorrowEvents, $tomorrowColor, $calId, $themeStyles, $theme, $importantNsList);
2834        }
2835
2836        // Important events section
2837        if (!empty($importantEvents)) {
2838            $html .= $this->renderSidebarSection('Important Events', $importantEvents, $importantColor, $calId, $themeStyles, $theme, $importantNsList);
2839        }
2840
2841        // Empty state if no itinerary items
2842        if (!$hasItinerary) {
2843            $html .= '<div style="padding:8px; text-align:center; color:' . $themeStyles['text_dim'] . '; font-size:10px; font-family:system-ui, sans-serif;">No upcoming events</div>';
2844        }
2845
2846        $html .= '</div>'; // Close itinerary-content
2847
2848        // Get itinerary default state from settings
2849        $itineraryDefaultCollapsed = $this->getItineraryCollapsed();
2850        $itineraryExpandedDefault = $itineraryDefaultCollapsed ? 'false' : 'true';
2851        $itineraryArrowDefault = $itineraryDefaultCollapsed ? 'rotate(-90deg)' : 'rotate(0deg)';
2852        $itineraryContentDefault = $itineraryDefaultCollapsed ? 'max-height:0px; opacity:0;' : 'max-height:none;';
2853
2854        // JavaScript for toggling itinerary
2855        $html .= '<script>
2856        (function() {
2857            let itineraryExpanded_' . $jsCalId . ' = ' . $itineraryExpandedDefault . ';
2858
2859            window.toggleItinerary_' . $jsCalId . ' = function() {
2860                const content = document.getElementById("itinerary-content-' . $calId . '");
2861                const arrow = document.getElementById("itinerary-arrow-' . $calId . '");
2862
2863                if (itineraryExpanded_' . $jsCalId . ') {
2864                    // Collapse
2865                    content.style.maxHeight = "0px";
2866                    content.style.opacity = "0";
2867                    arrow.style.transform = "rotate(-90deg)";
2868                    itineraryExpanded_' . $jsCalId . ' = false;
2869                } else {
2870                    // Expand
2871                    content.style.maxHeight = content.scrollHeight + "px";
2872                    content.style.opacity = "1";
2873                    arrow.style.transform = "rotate(0deg)";
2874                    itineraryExpanded_' . $jsCalId . ' = true;
2875
2876                    // After transition, set to auto for dynamic content
2877                    setTimeout(function() {
2878                        if (itineraryExpanded_' . $jsCalId . ') {
2879                            content.style.maxHeight = "none";
2880                        }
2881                    }, 300);
2882                }
2883            };
2884
2885            // Initialize based on default state
2886            const content = document.getElementById("itinerary-content-' . $calId . '");
2887            const arrow = document.getElementById("itinerary-arrow-' . $calId . '");
2888            if (content && arrow) {
2889                if (' . $itineraryExpandedDefault . ') {
2890                    content.style.maxHeight = "none";
2891                    arrow.style.transform = "rotate(0deg)";
2892                } else {
2893                    content.style.maxHeight = "0px";
2894                    content.style.opacity = "0";
2895                    arrow.style.transform = "rotate(-90deg)";
2896                }
2897            }
2898        })();
2899        </script>';
2900
2901        $html .= '</div>';
2902
2903        // Add event dialog for sidebar widget
2904        $html .= $this->renderEventDialog($calId, $namespace, $theme);
2905
2906        // Add JavaScript for positioning data-tooltip elements
2907        $html .= '<script>
2908        // Position data-tooltip elements to prevent cutoff (up and to the LEFT)
2909        document.addEventListener("DOMContentLoaded", function() {
2910            const tooltipElements = document.querySelectorAll("[data-tooltip]");
2911            const isPinkTheme = document.querySelector(".sidebar-pink") !== null;
2912
2913            tooltipElements.forEach(function(element) {
2914                element.addEventListener("mouseenter", function() {
2915                    const rect = element.getBoundingClientRect();
2916                    const style = window.getComputedStyle(element, ":before");
2917
2918                    // Position above the element, aligned to LEFT (not right)
2919                    element.style.setProperty("--tooltip-left", (rect.left - 150) + "px");
2920                    element.style.setProperty("--tooltip-top", (rect.top - 30) + "px");
2921
2922                    // Pink theme: position heart to the right of tooltip
2923                    if (isPinkTheme) {
2924                        element.style.setProperty("--heart-left", (rect.left - 150 + 210) + "px");
2925                        element.style.setProperty("--heart-top", (rect.top - 30) + "px");
2926                    }
2927                });
2928            });
2929        });
2930
2931        // Apply custom properties to position tooltips
2932        const style = document.createElement("style");
2933        style.textContent = `
2934            [data-tooltip]:hover:before {
2935                left: var(--tooltip-left, 0) !important;
2936                top: var(--tooltip-top, 0) !important;
2937            }
2938            .sidebar-pink [data-tooltip]:hover:after {
2939                left: var(--heart-left, 0) !important;
2940                top: var(--heart-top, 0) !important;
2941            }
2942        `;
2943        document.head.appendChild(style);
2944        </script>';
2945
2946        return $html;
2947    }
2948
2949    /**
2950     * Render compact week grid (7 cells with event bars) - Theme-aware
2951     */
2952    private function renderWeekGrid($weekEvents, $weekStart, $themeStyles, $theme) {
2953        // Generate unique ID for this calendar instance - sanitize for JavaScript
2954        $calId = 'cal_' . substr(md5($weekStart . microtime()), 0, 8);
2955        $jsCalId = str_replace('-', '_', $calId);  // Sanitize for JS variable names
2956
2957        $html = '<div style="display:grid; grid-template-columns:repeat(7, 1fr); gap:1px; background:' . $themeStyles['grid_bg'] . '; border-bottom:2px solid ' . $themeStyles['grid_border'] . ';">';
2958
2959        // Day names depend on week start setting
2960        $weekStartDay = $this->getWeekStartDay();
2961        if ($weekStartDay === 'monday') {
2962            $dayNames = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];  // Monday to Sunday
2963        } else {
2964            $dayNames = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];  // Sunday to Saturday
2965        }
2966        $today = date('Y-m-d');
2967
2968        for ($i = 0; $i < 7; $i++) {
2969            $date = date('Y-m-d', strtotime($weekStart . ' +' . $i . ' days'));
2970            $dayNum = date('j', strtotime($date));
2971            $isToday = $date === $today;
2972
2973            $events = isset($weekEvents[$date]) ? $weekEvents[$date] : [];
2974            $eventCount = count($events);
2975
2976            $bgColor = $isToday ? $themeStyles['cell_today_bg'] : $themeStyles['cell_bg'];
2977            $textColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
2978            $fontWeight = $isToday ? '700' : '500';
2979
2980            // Theme-aware text shadow
2981            if ($theme === 'pink') {
2982                $glowColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
2983                $textShadow = $isToday ? 'text-shadow:0 0 3px ' . $glowColor . ';' : 'text-shadow:0 0 2px ' . $glowColor . ';';
2984            } else if ($theme === 'matrix') {
2985                $glowColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
2986                $textShadow = $isToday ? 'text-shadow:0 0 2px ' . $glowColor . ';' : 'text-shadow:0 0 1px ' . $glowColor . ';';
2987            } else if ($theme === 'purple') {
2988                $glowColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
2989                $textShadow = $isToday ? 'text-shadow:0 0 2px ' . $glowColor . ';' : 'text-shadow:0 0 1px ' . $glowColor . ';';
2990            } else {
2991                $textShadow = '';  // No glow for professional/wiki
2992            }
2993
2994            // Border color based on theme
2995            $borderColor = $themeStyles['grid_border'];
2996
2997            $hasEvents = $eventCount > 0;
2998            $clickableStyle = $hasEvents ? 'cursor:pointer;' : '';
2999            $clickHandler = $hasEvents ? ' onclick="showDayEvents_' . $jsCalId . '(\'' . $date . '\')"' : '';
3000
3001            $html .= '<div style="background:' . $bgColor . '; padding:4px 2px; text-align:center; min-height:45px; position:relative; border:1px solid ' . $borderColor . ' !important; ' . $clickableStyle . '" ' . $clickHandler . '>';
3002
3003            // Day letter - theme color
3004            $dayLetterColor = $theme === 'professional' ? '#7f8c8d' : $themeStyles['text_primary'];
3005            $html .= '<div style="font-size:9px; color:' . $dayLetterColor . '; font-weight:500; font-family:system-ui, sans-serif;">' . $dayNames[$i] . '</div>';
3006
3007            // Day number
3008            $html .= '<div style="font-size:12px; color:' . $textColor . '; font-weight:' . $fontWeight . '; margin:2px 0; font-family:system-ui, sans-serif; ' . $textShadow . '">' . $dayNum . '</div>';
3009
3010            // Event bars (max 4 visible) with theme-aware glow
3011            if ($eventCount > 0) {
3012                $showCount = min($eventCount, 4);
3013                for ($j = 0; $j < $showCount; $j++) {
3014                    $event = $events[$j];
3015                    $color = isset($event['color']) ? $event['color'] : $themeStyles['text_primary'];
3016                    $barShadow = $theme === 'professional' ? '0 1px 2px rgba(0,0,0,0.2)' : '0 0 3px ' . htmlspecialchars($color);
3017                    $html .= '<div style="height:2px; background:' . htmlspecialchars($color) . '; margin:1px 0; border-radius:1px; box-shadow:' . $barShadow . ';"></div>';
3018                }
3019
3020                // Show "+N more" if more than 4 - theme color
3021                if ($eventCount > 4) {
3022                    $moreTextColor = $theme === 'professional' ? '#7f8c8d' : $themeStyles['text_primary'];
3023                    $html .= '<div style="font-size:7px; color:' . $moreTextColor . '; margin-top:1px; font-family:system-ui, sans-serif;">+' . ($eventCount - 4) . '</div>';
3024                }
3025            }
3026
3027            $html .= '</div>';
3028        }
3029
3030        $html .= '</div>';
3031
3032        // Add container for selected day events display (with unique ID) - theme-aware
3033        $panelBorderColor = $themeStyles['border'];
3034        $panelHeaderBg = $themeStyles['border'];
3035        $panelShadow = ($theme === 'professional' || $theme === 'wiki') ?
3036                      '0 1px 3px rgba(0, 0, 0, 0.1)' :
3037                      '0 0 5px ' . $themeStyles['shadow'];
3038        $panelContentBg = ($theme === 'professional') ? 'rgba(255, 255, 255, 0.95)' :
3039                         ($theme === 'wiki' ? $themeStyles['cell_bg'] : 'rgba(36, 36, 36, 0.5)');
3040        $panelHeaderShadow = ($theme === 'professional' || $theme === 'wiki') ? '0 2px 4px rgba(0, 0, 0, 0.15)' : '0 0 8px ' . $panelHeaderBg;
3041
3042        // Header text color - dark bg text for dark themes, white for light theme accent headers
3043        $panelHeaderColor = ($theme === 'matrix' || $theme === 'purple' || $theme === 'pink') ? $themeStyles['bg'] :
3044                            (($theme === 'wiki') ? $themeStyles['text_primary'] : '#fff');
3045
3046        $html .= '<div id="selected-day-events-' . $calId . '" style="display:none; margin:8px 4px; border-left:3px solid ' . $panelBorderColor . ($theme === 'wiki' ? '' : ' !important') . '; box-shadow:' . $panelShadow . ';">';
3047        if ($theme === 'wiki') {
3048            $html .= '<div style="background:' . $panelHeaderBg . '; color:' . $panelHeaderColor . '; padding:4px 6px; font-size:9px; font-weight:700; letter-spacing:0.3px; font-family:system-ui, sans-serif; box-shadow:' . $panelHeaderShadow . '; display:flex; justify-content:space-between; align-items:center;">';
3049            $html .= '<span id="selected-day-title-' . $calId . '"></span>';
3050            $html .= '<span onclick="document.getElementById(\'selected-day-events-' . $calId . '\').style.display=\'none\';" style="cursor:pointer; font-size:12px; padding:0 4px; font-weight:700; color:' . $panelHeaderColor . ';">✕</span>';
3051        } else {
3052            $html .= '<div style="background:' . $panelHeaderBg . ' !important; color:' . $panelHeaderColor . ' !important; -webkit-text-fill-color:' . $panelHeaderColor . ' !important; padding:4px 6px; font-size:9px; font-weight:700; letter-spacing:0.3px; font-family:system-ui, sans-serif; box-shadow:' . $panelHeaderShadow . '; display:flex; justify-content:space-between; align-items:center;">';
3053            $html .= '<span id="selected-day-title-' . $calId . '"></span>';
3054            $html .= '<span onclick="document.getElementById(\'selected-day-events-' . $calId . '\').style.display=\'none\';" style="cursor:pointer; font-size:12px; padding:0 4px; font-weight:700; color:' . $panelHeaderColor . ' !important; -webkit-text-fill-color:' . $panelHeaderColor . ' !important;">✕</span>';
3055        }
3056        $html .= '</div>';
3057        $html .= '<div id="selected-day-content-' . $calId . '" style="padding:4px 0; background:' . $panelContentBg . ';"></div>';
3058        $html .= '</div>';
3059
3060        // Add JavaScript for day selection with event data
3061        $html .= '<script>';
3062        // Sanitize calId for JavaScript variable names
3063        $jsCalId = str_replace('-', '_', $calId);
3064        $html .= 'window.weekEventsData_' . $jsCalId . ' = ' . json_encode($weekEvents) . ';';
3065
3066        // Pass theme colors to JavaScript
3067        $jsThemeColors = json_encode([
3068            'text_primary' => $themeStyles['text_primary'],
3069            'text_bright' => $themeStyles['text_bright'],
3070            'text_dim' => $themeStyles['text_dim'],
3071            'text_shadow' => ($theme === 'pink') ? 'text-shadow:0 0 2px ' . $themeStyles['text_primary'] :
3072                             ((in_array($theme, ['matrix', 'purple'])) ? 'text-shadow:0 0 1px ' . $themeStyles['text_primary'] : ''),
3073            'event_bg' => $theme === 'professional' ? 'rgba(255, 255, 255, 0.5)' :
3074                         ($theme === 'wiki' ? $themeStyles['cell_bg'] : 'rgba(36, 36, 36, 0.3)'),
3075            'border_color' => $theme === 'professional' ? 'rgba(0, 0, 0, 0.1)' :
3076                             ($theme === 'purple' ? 'rgba(155, 89, 182, 0.2)' :
3077                             ($theme === 'pink' ? 'rgba(255, 20, 147, 0.3)' :
3078                             ($theme === 'wiki' ? $themeStyles['grid_border'] : 'rgba(0, 204, 7, 0.2)'))),
3079            'bar_shadow' => $theme === 'professional' ? '0 1px 2px rgba(0,0,0,0.2)' :
3080                           ($theme === 'wiki' ? '0 1px 2px rgba(0,0,0,0.15)' : '0 0 3px')
3081        ]);
3082        $html .= 'window.themeColors_' . $jsCalId . ' = ' . $jsThemeColors . ';';
3083        $html .= '
3084        window.showDayEvents_' . $jsCalId . ' = function(dateKey) {
3085            const eventsData = window.weekEventsData_' . $jsCalId . ';
3086            const container = document.getElementById("selected-day-events-' . $calId . '");
3087            const title = document.getElementById("selected-day-title-' . $calId . '");
3088            const content = document.getElementById("selected-day-content-' . $calId . '");
3089
3090            if (!eventsData[dateKey] || eventsData[dateKey].length === 0) return;
3091
3092            // Format date for display
3093            const dateObj = new Date(dateKey + "T00:00:00");
3094            const dayName = dateObj.toLocaleDateString("en-US", { weekday: "long" });
3095            const monthDay = dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric" });
3096            title.textContent = dayName + ", " + monthDay;
3097
3098            // Clear content
3099            content.innerHTML = "";
3100
3101            // Sort events by time (all-day events first, then timed events chronologically)
3102            const sortedEvents = [...eventsData[dateKey]].sort((a, b) => {
3103                // All-day events (no time) go to the beginning
3104                if (!a.time && !b.time) return 0;
3105                if (!a.time) return -1;  // a is all-day, comes first
3106                if (!b.time) return 1;   // b is all-day, comes first
3107
3108                // Compare times (format: "HH:MM")
3109                const timeA = a.time.split(":").map(Number);
3110                const timeB = b.time.split(":").map(Number);
3111                const minutesA = timeA[0] * 60 + timeA[1];
3112                const minutesB = timeB[0] * 60 + timeB[1];
3113
3114                return minutesA - minutesB;
3115            });
3116
3117            // Build events HTML with single color bar (event color only) - theme-aware
3118            const themeColors = window.themeColors_' . $jsCalId . ';
3119            sortedEvents.forEach(event => {
3120                const eventColor = event.color || themeColors.text_primary;
3121
3122                const eventDiv = document.createElement("div");
3123                eventDiv.style.cssText = "padding:4px 6px; border-bottom:1px solid " + themeColors.border_color + "; font-size:10px; display:flex; align-items:stretch; gap:6px; background:" + themeColors.event_bg + "; min-height:20px;";
3124
3125                let eventHTML = "";
3126
3127                // Event assigned color bar (single bar on left) - theme-aware shadow
3128                const barShadow = themeColors.bar_shadow + (themeColors.bar_shadow.includes("rgba") ? "" : " " + eventColor);
3129                eventHTML += "<div style=\\"width:3px; align-self:stretch; background:" + eventColor + "; border-radius:1px; flex-shrink:0; box-shadow:" + barShadow + ";\\"></div>";
3130
3131                // Content wrapper
3132                eventHTML += "<div style=\\"flex:1; min-width:0; display:flex; justify-content:space-between; align-items:start; gap:4px;\\">";
3133
3134                // Left side: event details
3135                eventHTML += "<div style=\\"flex:1; min-width:0;\\">";
3136                eventHTML += "<div style=\\"font-weight:600; color:" + themeColors.text_primary + "; word-wrap:break-word; font-family:system-ui, sans-serif; " + themeColors.text_shadow + ";\\">";
3137
3138                // Time
3139                if (event.time) {
3140                    const timeParts = event.time.split(":");
3141                    let hours = parseInt(timeParts[0]);
3142                    const minutes = timeParts[1];
3143                    const ampm = hours >= 12 ? "PM" : "AM";
3144                    hours = hours % 12 || 12;
3145                    eventHTML += "<span style=\\"color:" + themeColors.text_bright + "; font-weight:500; font-size:9px;\\">" + hours + ":" + minutes + " " + ampm + "</span> ";
3146                }
3147
3148                // Title - use HTML version if available
3149                const titleHTML = event.title_html || event.title || "Untitled";
3150                eventHTML += titleHTML;
3151                eventHTML += "</div>";
3152
3153                // Description if present - use HTML version - theme-aware color
3154                if (event.description_html || event.description) {
3155                    const descHTML = event.description_html || event.description;
3156                    eventHTML += "<div style=\\"font-size:9px; color:" + themeColors.text_dim + "; margin-top:2px;\\">" + descHTML + "</div>";
3157                }
3158
3159                eventHTML += "</div>"; // Close event details
3160
3161                // Right side: conflict badge with tooltip
3162                if (event.conflict) {
3163                    let conflictList = [];
3164                    if (event.conflictingWith && event.conflictingWith.length > 0) {
3165                        event.conflictingWith.forEach(conf => {
3166                            const confTime = conf.time + (conf.end_time ? " - " + conf.end_time : "");
3167                            conflictList.push(conf.title + " (" + confTime + ")");
3168                        });
3169                    }
3170                    const conflictData = btoa(unescape(encodeURIComponent(JSON.stringify(conflictList))));
3171                    eventHTML += "<span class=\\"event-conflict-badge\\" style=\\"font-size:10px;\\" data-conflicts=\\"" + conflictData + "\\" onmouseenter=\\"showConflictTooltip(this)\\" onmouseleave=\\"hideConflictTooltip()\\">⚠️ " + (event.conflictingWith ? event.conflictingWith.length : 1) + "</span>";
3172                }
3173
3174                eventHTML += "</div>"; // Close content wrapper
3175
3176                eventDiv.innerHTML = eventHTML;
3177                content.appendChild(eventDiv);
3178            });
3179
3180            container.style.display = "block";
3181        };
3182        ';
3183        $html .= '</script>';
3184
3185        return $html;
3186    }
3187
3188    /**
3189     * Render a sidebar section (Today/Tomorrow/Important) - Matrix themed with colored borders
3190     */
3191    private function renderSidebarSection($title, $events, $accentColor, $calId, $themeStyles, $theme, $importantNsList = ['important']) {
3192        // Keep the original accent colors for borders
3193        $borderColor = $accentColor;
3194
3195        // Show date for Important Events section
3196        $showDate = ($title === 'Important Events');
3197
3198        // Sort events differently based on section
3199        if ($title === 'Important Events') {
3200            // Important Events: sort by date first, then by time
3201            usort($events, function($a, $b) {
3202                $aDate = isset($a['date']) ? $a['date'] : '';
3203                $bDate = isset($b['date']) ? $b['date'] : '';
3204
3205                // Different dates - sort by date
3206                if ($aDate !== $bDate) {
3207                    return strcmp($aDate, $bDate);
3208                }
3209
3210                // Same date - sort by time
3211                $aTime = isset($a['time']) && !empty($a['time']) ? $a['time'] : '';
3212                $bTime = isset($b['time']) && !empty($b['time']) ? $b['time'] : '';
3213
3214                // All-day events last within same date
3215                if (empty($aTime) && !empty($bTime)) return 1;
3216                if (!empty($aTime) && empty($bTime)) return -1;
3217                if (empty($aTime) && empty($bTime)) return 0;
3218
3219                // Both have times
3220                $aMinutes = $this->timeToMinutes($aTime);
3221                $bMinutes = $this->timeToMinutes($bTime);
3222                return $aMinutes - $bMinutes;
3223            });
3224        } else {
3225            // Today/Tomorrow: sort by time only (all same date)
3226            usort($events, function($a, $b) {
3227                $aTime = isset($a['time']) && !empty($a['time']) ? $a['time'] : '';
3228                $bTime = isset($b['time']) && !empty($b['time']) ? $b['time'] : '';
3229
3230                // All-day events (no time) come first
3231                if (empty($aTime) && !empty($bTime)) return -1;
3232                if (!empty($aTime) && empty($bTime)) return 1;
3233                if (empty($aTime) && empty($bTime)) return 0;
3234
3235                // Both have times - convert to minutes for proper chronological sort
3236                $aMinutes = $this->timeToMinutes($aTime);
3237                $bMinutes = $this->timeToMinutes($bTime);
3238
3239                return $aMinutes - $bMinutes;
3240            });
3241        }
3242
3243        // Theme-aware section shadow
3244        $sectionShadow = ($theme === 'professional' || $theme === 'wiki') ?
3245                        '0 1px 3px rgba(0, 0, 0, 0.1)' :
3246                        '0 0 5px ' . $themeStyles['shadow'];
3247
3248        if ($theme === 'wiki') {
3249            // Wiki theme: use a background div for the left bar instead of border-left
3250            // Dark Reader maps border colors differently from background colors, causing mismatch
3251            $html = '<div style="display:flex; margin:8px 4px; box-shadow:' . $sectionShadow . '; background:' . $themeStyles['bg'] . ';">';
3252            $html .= '<div style="width:3px; flex-shrink:0; background:' . $borderColor . ';"></div>';
3253            $html .= '<div style="flex:1; min-width:0;">';
3254        } else {
3255            $html = '<div style="border-left:3px solid ' . $borderColor . ' !important; margin:8px 4px; box-shadow:' . $sectionShadow . ';">';
3256        }
3257
3258        // Section header with accent color background - theme-aware
3259        $headerShadow = ($theme === 'professional' || $theme === 'wiki') ? '0 2px 4px rgba(0, 0, 0, 0.15)' : '0 0 8px ' . $accentColor;
3260        $headerTextColor = ($theme === 'matrix' || $theme === 'purple' || $theme === 'pink') ? $themeStyles['bg'] :
3261                           (($theme === 'wiki') ? $themeStyles['text_primary'] : '#fff');
3262        if ($theme === 'wiki') {
3263            // Wiki theme: no !important — let Dark Reader adjust these
3264            $html .= '<div style="background:' . $accentColor . '; color:' . $headerTextColor . '; padding:4px 6px; font-size:9px; font-weight:700; letter-spacing:0.3px; font-family:system-ui, sans-serif; box-shadow:' . $headerShadow . ';">';
3265        } else {
3266            // Dark themes + professional: lock colors against Dark Reader
3267            $html .= '<div style="background:' . $accentColor . ' !important; color:' . $headerTextColor . ' !important; -webkit-text-fill-color:' . $headerTextColor . ' !important; padding:4px 6px; font-size:9px; font-weight:700; letter-spacing:0.3px; font-family:system-ui, sans-serif; box-shadow:' . $headerShadow . ';">';
3268        }
3269        $html .= htmlspecialchars($title);
3270        $html .= '</div>';
3271
3272        // Events - no background (transparent)
3273        $html .= '<div style="padding:4px 0;">';
3274
3275        foreach ($events as $event) {
3276            $html .= $this->renderSidebarEvent($event, $calId, $showDate, $accentColor, $themeStyles, $theme, $importantNsList);
3277        }
3278
3279        $html .= '</div>';
3280        $html .= '</div>';
3281        if ($theme === 'wiki') {
3282            $html .= '</div>'; // Close flex wrapper
3283        }
3284
3285        return $html;
3286    }
3287
3288    /**
3289     * Render individual event in sidebar - Theme-aware
3290     */
3291    private function renderSidebarEvent($event, $calId, $showDate = false, $sectionColor = '#00cc07', $themeStyles = null, $theme = 'matrix', $importantNsList = ['important']) {
3292        $title = isset($event['title']) ? htmlspecialchars($event['title']) : 'Untitled';
3293        $time = isset($event['time']) ? $event['time'] : '';
3294        $endTime = isset($event['endTime']) ? $event['endTime'] : '';
3295        $eventColor = isset($event['color']) ? htmlspecialchars($event['color']) : ($themeStyles ? $themeStyles['text_primary'] : '#00cc07');
3296        $date = isset($event['date']) ? $event['date'] : '';
3297        $isTask = isset($event['isTask']) && $event['isTask'];
3298        $completed = isset($event['completed']) && $event['completed'];
3299
3300        // Check if this is an important namespace event
3301        $eventNs = isset($event['namespace']) ? $event['namespace'] : '';
3302        $isImportantNs = false;
3303        foreach ($importantNsList as $impNs) {
3304            if ($eventNs === $impNs || strpos($eventNs, $impNs . ':') === 0) {
3305                $isImportantNs = true;
3306                break;
3307            }
3308        }
3309
3310        // Theme-aware colors
3311        $titleColor = $themeStyles ? $themeStyles['text_primary'] : '#00cc07';
3312        $timeColor = $themeStyles ? $themeStyles['text_bright'] : '#00dd00';
3313        $textShadow = ($theme === 'pink') ? 'text-shadow:0 0 2px ' . $titleColor . ';' :
3314                      ((in_array($theme, ['matrix', 'purple'])) ? 'text-shadow:0 0 1px ' . $titleColor . ';' : '');
3315
3316        // Check for conflicts (using 'conflict' field set by detectTimeConflicts)
3317        $hasConflict = isset($event['conflict']) && $event['conflict'];
3318        $conflictingWith = isset($event['conflictingWith']) ? $event['conflictingWith'] : [];
3319
3320        // Build conflict list for tooltip
3321        $conflictList = [];
3322        if ($hasConflict && !empty($conflictingWith)) {
3323            foreach ($conflictingWith as $conf) {
3324                $confTime = $this->formatTimeDisplay($conf['time'], isset($conf['end_time']) ? $conf['end_time'] : '');
3325                $conflictList[] = $conf['title'] . ' (' . $confTime . ')';
3326            }
3327        }
3328
3329        // No background on individual events (transparent) - unless important namespace
3330        // Use theme grid_border with slight opacity for subtle divider
3331        $borderColor = $themeStyles['grid_border'];
3332
3333        // Important namespace highlighting - subtle themed background
3334        $importantBg = '';
3335        $importantBorder = '';
3336        if ($isImportantNs) {
3337            // Theme-specific important highlighting
3338            switch ($theme) {
3339                case 'matrix':
3340                    $importantBg = 'background:rgba(0,204,7,0.08);';
3341                    $importantBorder = 'border-right:2px solid rgba(0,204,7,0.4);';
3342                    break;
3343                case 'purple':
3344                    $importantBg = 'background:rgba(156,39,176,0.08);';
3345                    $importantBorder = 'border-right:2px solid rgba(156,39,176,0.4);';
3346                    break;
3347                case 'pink':
3348                    $importantBg = 'background:rgba(255,105,180,0.1);';
3349                    $importantBorder = 'border-right:2px solid rgba(255,105,180,0.5);';
3350                    break;
3351                case 'professional':
3352                    $importantBg = 'background:rgba(33,150,243,0.08);';
3353                    $importantBorder = 'border-right:2px solid rgba(33,150,243,0.4);';
3354                    break;
3355                case 'wiki':
3356                    $importantBg = 'background:rgba(0,102,204,0.06);';
3357                    $importantBorder = 'border-right:2px solid rgba(0,102,204,0.3);';
3358                    break;
3359                default:
3360                    $importantBg = 'background:rgba(0,204,7,0.08);';
3361                    $importantBorder = 'border-right:2px solid rgba(0,204,7,0.4);';
3362            }
3363        }
3364
3365        $html = '<div style="padding:4px 6px; border-bottom:1px solid ' . $borderColor . ' !important; font-size:10px; display:flex; align-items:stretch; gap:6px; min-height:20px; ' . $importantBg . $importantBorder . '">';
3366
3367        // Event's assigned color bar (single bar on the left)
3368        $barShadow = ($theme === 'professional') ? '0 1px 2px rgba(0,0,0,0.2)' : '0 0 3px ' . $eventColor;
3369        $html .= '<div style="width:3px; align-self:stretch; background:' . $eventColor . '; border-radius:1px; flex-shrink:0; box-shadow:' . $barShadow . ';"></div>';
3370
3371        // Content
3372        $html .= '<div style="flex:1; min-width:0;">';
3373
3374        // Time + title
3375        $html .= '<div style="font-weight:600; color:' . $titleColor . '; word-wrap:break-word; font-family:system-ui, sans-serif; ' . $textShadow . '">';
3376
3377        if ($time) {
3378            $displayTime = $this->formatTimeDisplay($time, $endTime);
3379            $html .= '<span style="color:' . $timeColor . '; font-weight:500; font-size:9px;">' . htmlspecialchars($displayTime) . '</span> ';
3380        }
3381
3382        // Task checkbox
3383        if ($isTask) {
3384            $checkIcon = $completed ? '☑' : '☐';
3385            $checkColor = $themeStyles ? $themeStyles['text_bright'] : '#00ff00';
3386            $html .= '<span style="font-size:11px; color:' . $checkColor . ';">' . $checkIcon . '</span> ';
3387        }
3388
3389        // Important indicator icon for important namespace events
3390        if ($isImportantNs) {
3391            $html .= '<span style="font-size:9px;" title="Important">⭐</span> ';
3392        }
3393
3394        $html .= $title; // Already HTML-escaped on line 2625
3395
3396        // Conflict badge using same system as main calendar
3397        if ($hasConflict && !empty($conflictList)) {
3398            $conflictJson = base64_encode(json_encode($conflictList));
3399            $html .= ' <span class="event-conflict-badge" style="font-size:10px;" data-conflicts="' . $conflictJson . '" onmouseenter="showConflictTooltip(this)" onmouseleave="hideConflictTooltip()">⚠️ ' . count($conflictList) . '</span>';
3400        }
3401
3402        $html .= '</div>';
3403
3404        // Date display BELOW event name for Important events
3405        if ($showDate && $date) {
3406            $dateObj = new DateTime($date);
3407            $displayDate = $dateObj->format('D, M j'); // e.g., "Mon, Feb 10"
3408            $dateColor = $themeStyles ? $themeStyles['text_dim'] : '#00aa00';
3409            $dateShadow = ($theme === 'pink') ? 'text-shadow:0 0 2px ' . $dateColor . ';' :
3410                          ((in_array($theme, ['matrix', 'purple'])) ? 'text-shadow:0 0 1px ' . $dateColor . ';' : '');
3411            $html .= '<div style="font-size:8px; color:' . $dateColor . '; font-weight:500; margin-top:2px; ' . $dateShadow . '">' . htmlspecialchars($displayDate) . '</div>';
3412        }
3413
3414        $html .= '</div>';
3415        $html .= '</div>';
3416
3417        return $html;
3418    }
3419
3420    /**
3421     * Format time display (12-hour format with optional end time)
3422     */
3423    private function formatTimeDisplay($startTime, $endTime = '') {
3424        // Convert start time
3425        list($hour, $minute) = explode(':', $startTime);
3426        $hour = (int)$hour;
3427        $ampm = $hour >= 12 ? 'PM' : 'AM';
3428        $displayHour = $hour % 12;
3429        if ($displayHour === 0) $displayHour = 12;
3430
3431        $display = $displayHour . ':' . $minute . ' ' . $ampm;
3432
3433        // Add end time if provided
3434        if ($endTime && $endTime !== '') {
3435            list($endHour, $endMinute) = explode(':', $endTime);
3436            $endHour = (int)$endHour;
3437            $endAmpm = $endHour >= 12 ? 'PM' : 'AM';
3438            $endDisplayHour = $endHour % 12;
3439            if ($endDisplayHour === 0) $endDisplayHour = 12;
3440
3441            $display .= '-' . $endDisplayHour . ':' . $endMinute . ' ' . $endAmpm;
3442        }
3443
3444        return $display;
3445    }
3446
3447    /**
3448     * Detect time conflicts among events on the same day
3449     * Returns events array with 'conflict' flag and 'conflictingWith' array
3450     */
3451    private function detectTimeConflicts($dayEvents) {
3452        if (empty($dayEvents)) {
3453            return $dayEvents;
3454        }
3455
3456        // If only 1 event, no conflicts possible but still add the flag
3457        if (count($dayEvents) === 1) {
3458            return [array_merge($dayEvents[0], ['conflict' => false, 'conflictingWith' => []])];
3459        }
3460
3461        $eventsWithFlags = [];
3462
3463        foreach ($dayEvents as $i => $event) {
3464            $hasConflict = false;
3465            $conflictingWith = [];
3466
3467            // Skip all-day events (no time)
3468            if (empty($event['time'])) {
3469                $eventsWithFlags[] = array_merge($event, ['conflict' => false, 'conflictingWith' => []]);
3470                continue;
3471            }
3472
3473            // Get this event's time range
3474            $startTime = $event['time'];
3475            // Check both 'end_time' (snake_case) and 'endTime' (camelCase) for compatibility
3476            $endTime = '';
3477            if (isset($event['end_time']) && $event['end_time'] !== '') {
3478                $endTime = $event['end_time'];
3479            } elseif (isset($event['endTime']) && $event['endTime'] !== '') {
3480                $endTime = $event['endTime'];
3481            } else {
3482                // If no end time, use start time (zero duration) - matches main calendar logic
3483                $endTime = $startTime;
3484            }
3485
3486            // Check against all other events
3487            foreach ($dayEvents as $j => $otherEvent) {
3488                if ($i === $j) continue; // Skip self
3489                if (empty($otherEvent['time'])) continue; // Skip all-day events
3490
3491                $otherStart = $otherEvent['time'];
3492                // Check both field name formats
3493                $otherEnd = '';
3494                if (isset($otherEvent['end_time']) && $otherEvent['end_time'] !== '') {
3495                    $otherEnd = $otherEvent['end_time'];
3496                } elseif (isset($otherEvent['endTime']) && $otherEvent['endTime'] !== '') {
3497                    $otherEnd = $otherEvent['endTime'];
3498                } else {
3499                    $otherEnd = $otherStart;
3500                }
3501
3502                // Check for overlap: convert to minutes and compare
3503                $start1Min = $this->timeToMinutes($startTime);
3504                $end1Min = $this->timeToMinutes($endTime);
3505                $start2Min = $this->timeToMinutes($otherStart);
3506                $end2Min = $this->timeToMinutes($otherEnd);
3507
3508                // Overlap if: start1 < end2 AND start2 < end1
3509                // Note: Using < (not <=) so events that just touch at boundaries don't conflict
3510                // e.g., 1:00-2:00 and 2:00-3:00 are NOT in conflict
3511                if ($start1Min < $end2Min && $start2Min < $end1Min) {
3512                    $hasConflict = true;
3513                    $conflictingWith[] = [
3514                        'title' => isset($otherEvent['title']) ? $otherEvent['title'] : 'Untitled',
3515                        'time' => $otherStart,
3516                        'end_time' => $otherEnd
3517                    ];
3518                }
3519            }
3520
3521            $eventsWithFlags[] = array_merge($event, [
3522                'conflict' => $hasConflict,
3523                'conflictingWith' => $conflictingWith
3524            ]);
3525        }
3526
3527        return $eventsWithFlags;
3528    }
3529
3530    /**
3531     * Add hours to a time string
3532     */
3533    private function addHoursToTime($time, $hours) {
3534        $totalMinutes = $this->timeToMinutes($time) + ($hours * 60);
3535        $h = floor($totalMinutes / 60) % 24;
3536        $m = $totalMinutes % 60;
3537        return sprintf('%02d:%02d', $h, $m);
3538    }
3539
3540    /**
3541     * Render DokuWiki syntax to HTML
3542     * Converts **bold**, //italic//, [[links]], etc. to HTML
3543     */
3544    private function renderDokuWikiToHtml($text) {
3545        if (empty($text)) return '';
3546
3547        // Use DokuWiki's parser to render the text
3548        $instructions = p_get_instructions($text);
3549
3550        // Render instructions to XHTML
3551        $xhtml = p_render('xhtml', $instructions, $info);
3552
3553        // Remove surrounding <p> tags if present (we're rendering inline)
3554        $xhtml = preg_replace('/^<p>(.*)<\/p>$/s', '$1', trim($xhtml));
3555
3556        return $xhtml;
3557    }
3558
3559    // Keep old scanForNamespaces for backward compatibility (not used anymore)
3560    private function scanForNamespaces($dir, $baseNamespace, &$namespaces) {
3561        if (!is_dir($dir)) return;
3562
3563        $items = scandir($dir);
3564        foreach ($items as $item) {
3565            if ($item === '.' || $item === '..' || $item === 'calendar') continue;
3566
3567            $path = $dir . $item;
3568            if (is_dir($path)) {
3569                $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
3570                $namespaces[] = $namespace;
3571                $this->scanForNamespaces($path . '/', $namespace, $namespaces);
3572            }
3573        }
3574    }
3575
3576    /**
3577     * Get current sidebar theme
3578     */
3579    private function getSidebarTheme() {
3580        $configFile = DOKU_INC . 'data/meta/calendar_theme.txt';
3581        if (file_exists($configFile)) {
3582            $theme = trim(file_get_contents($configFile));
3583            if (in_array($theme, ['matrix', 'purple', 'professional', 'pink', 'wiki'])) {
3584                return $theme;
3585            }
3586        }
3587        return 'matrix'; // Default
3588    }
3589
3590    /**
3591     * Get colors from DokuWiki template's style.ini file
3592     */
3593    private function getWikiTemplateColors() {
3594        global $conf;
3595
3596        // Get current template name
3597        $template = $conf['template'];
3598
3599        // Try multiple possible locations for style.ini
3600        $possiblePaths = [
3601            DOKU_INC . 'conf/tpl/' . $template . '/style.ini',
3602            DOKU_INC . 'lib/tpl/' . $template . '/style.ini',
3603        ];
3604
3605        $styleIni = null;
3606        foreach ($possiblePaths as $path) {
3607            if (file_exists($path)) {
3608                $styleIni = parse_ini_file($path, true);
3609                break;
3610            }
3611        }
3612
3613        if (!$styleIni) {
3614            return null; // Fall back to CSS variables
3615        }
3616
3617        // Extract color replacements
3618        $replacements = isset($styleIni['replacements']) ? $styleIni['replacements'] : [];
3619
3620        // Map style.ini colors to our theme structure
3621        $bgSite = isset($replacements['__background_site__']) ? $replacements['__background_site__'] : '#f5f5f5';
3622        $background = isset($replacements['__background__']) ? $replacements['__background__'] : '#fff';
3623        $bgAlt = isset($replacements['__background_alt__']) ? $replacements['__background_alt__'] : '#e8e8e8';
3624        $bgNeu = isset($replacements['__background_neu__']) ? $replacements['__background_neu__'] : '#eee';
3625        $text = isset($replacements['__text__']) ? $replacements['__text__'] : '#333';
3626        $textAlt = isset($replacements['__text_alt__']) ? $replacements['__text_alt__'] : '#999';
3627        $textNeu = isset($replacements['__text_neu__']) ? $replacements['__text_neu__'] : '#666';
3628        $border = isset($replacements['__border__']) ? $replacements['__border__'] : '#ccc';
3629        $link = isset($replacements['__link__']) ? $replacements['__link__'] : '#2b73b7';
3630        $existing = isset($replacements['__existing__']) ? $replacements['__existing__'] : $link;
3631
3632        // Build theme colors from template colors
3633        // ============================================
3634        // DokuWiki style.ini → Calendar CSS Variable Mapping
3635        // ============================================
3636        //   style.ini key         → CSS variable          → Used for
3637        //   __background_site__   → --background-site     → Container, panel backgrounds
3638        //   __background__        → --cell-bg             → Cell/input backgrounds (typically white)
3639        //   __background_alt__    → --background-alt      → Hover states, header backgrounds
3640        //                         → --background-header
3641        //   __background_neu__    → --cell-today-bg       → Today cell highlight
3642        //   __text__              → --text-primary        → Primary text, labels, titles
3643        //   __text_neu__          → --text-dim            → Secondary text, dates, descriptions
3644        //   __text_alt__          → (not mapped)          → Available for future use
3645        //   __border__            → --border-color        → Grid lines, input borders
3646        //                         → --border-main         → Accent color: buttons, badges, active elements, section headers
3647        //                         → --header-border
3648        //   __link__              → --text-bright         → Links, accent text
3649        //   __existing__          → (fallback to __link__)→ Available for future use
3650        //
3651        // To customize: edit your template's conf/style.ini [replacements]
3652        return [
3653            'bg' => $bgSite,
3654            'border' => $border,         // Accent color from template border
3655            'shadow' => 'rgba(0, 0, 0, 0.1)',
3656            'header_bg' => $bgAlt,       // Headers use alt background
3657            'header_border' => $border,
3658            'header_shadow' => '0 2px 4px rgba(0, 0, 0, 0.1)',
3659            'text_primary' => $text,
3660            'text_bright' => $link,
3661            'text_dim' => $textNeu,
3662            'grid_bg' => $bgSite,
3663            'grid_border' => $border,
3664            'cell_bg' => $background,    // Cells use __background__ (white/light)
3665            'cell_today_bg' => $bgNeu,
3666            'bar_glow' => '0 1px 2px',
3667            'pastdue_color' => '#e74c3c',
3668            'pastdue_bg' => '#ffe6e6',
3669            'pastdue_bg_strong' => '#ffd9d9',
3670            'pastdue_bg_light' => '#fff2f2',
3671            'tomorrow_bg' => '#fff9e6',
3672            'tomorrow_bg_strong' => '#fff4cc',
3673            'tomorrow_bg_light' => '#fffbf0',
3674        ];
3675    }
3676
3677    /**
3678     * Get theme-specific color styles
3679     */
3680    private function getSidebarThemeStyles($theme) {
3681        // For wiki theme, try to read colors from template's style.ini
3682        if ($theme === 'wiki') {
3683            $wikiColors = $this->getWikiTemplateColors();
3684            if (!empty($wikiColors)) {
3685                return $wikiColors;
3686            }
3687            // Fall through to default wiki colors if reading fails
3688        }
3689
3690        $themes = [
3691            'matrix' => [
3692                'bg' => '#242424',
3693                'border' => '#00cc07',
3694                'shadow' => 'rgba(0, 204, 7, 0.3)',
3695                'header_bg' => 'linear-gradient(180deg, #2a2a2a 0%, #242424 100%)',
3696                'header_border' => '#00cc07',
3697                'header_shadow' => '0 2px 8px rgba(0, 204, 7, 0.3)',
3698                'text_primary' => '#00cc07',
3699                'text_bright' => '#00ff00',
3700                'text_dim' => '#00aa00',
3701                'grid_bg' => '#1a3d1a',
3702                'grid_border' => '#00cc07',
3703                'cell_bg' => '#242424',
3704                'cell_today_bg' => '#2a4d2a',
3705                'bar_glow' => '0 0 3px',
3706                'pastdue_color' => '#e74c3c',
3707                'pastdue_bg' => '#3d1a1a',
3708                'pastdue_bg_strong' => '#4d2020',
3709                'pastdue_bg_light' => '#2d1515',
3710                'tomorrow_bg' => '#3d3d1a',
3711                'tomorrow_bg_strong' => '#4d4d20',
3712                'tomorrow_bg_light' => '#2d2d15',
3713            ],
3714            'purple' => [
3715                'bg' => '#2a2030',
3716                'border' => '#9b59b6',
3717                'shadow' => 'rgba(155, 89, 182, 0.3)',
3718                'header_bg' => 'linear-gradient(180deg, #2f2438 0%, #2a2030 100%)',
3719                'header_border' => '#9b59b6',
3720                'header_shadow' => '0 2px 8px rgba(155, 89, 182, 0.3)',
3721                'text_primary' => '#b19cd9',
3722                'text_bright' => '#d4a5ff',
3723                'text_dim' => '#8e7ab8',
3724                'grid_bg' => '#3d2b4d',
3725                'grid_border' => '#9b59b6',
3726                'cell_bg' => '#2a2030',
3727                'cell_today_bg' => '#3d2b4d',
3728                'bar_glow' => '0 0 3px',
3729                'pastdue_color' => '#e74c3c',
3730                'pastdue_bg' => '#3d1a2a',
3731                'pastdue_bg_strong' => '#4d2035',
3732                'pastdue_bg_light' => '#2d1520',
3733                'tomorrow_bg' => '#3d3520',
3734                'tomorrow_bg_strong' => '#4d4028',
3735                'tomorrow_bg_light' => '#2d2a18',
3736            ],
3737            'professional' => [
3738                'bg' => '#f5f7fa',
3739                'border' => '#4a90e2',
3740                'shadow' => 'rgba(74, 144, 226, 0.2)',
3741                'header_bg' => 'linear-gradient(180deg, #ffffff 0%, #f5f7fa 100%)',
3742                'header_border' => '#4a90e2',
3743                'header_shadow' => '0 2px 4px rgba(0, 0, 0, 0.1)',
3744                'text_primary' => '#2c3e50',
3745                'text_bright' => '#4a90e2',
3746                'text_dim' => '#7f8c8d',
3747                'grid_bg' => '#e8ecf1',
3748                'grid_border' => '#d0d7de',
3749                'cell_bg' => '#ffffff',
3750                'cell_today_bg' => '#dce8f7',
3751                'bar_glow' => '0 1px 2px',
3752                'pastdue_color' => '#e74c3c',
3753                'pastdue_bg' => '#ffe6e6',
3754                'pastdue_bg_strong' => '#ffd9d9',
3755                'pastdue_bg_light' => '#fff2f2',
3756                'tomorrow_bg' => '#fff9e6',
3757                'tomorrow_bg_strong' => '#fff4cc',
3758                'tomorrow_bg_light' => '#fffbf0',
3759            ],
3760            'pink' => [
3761                'bg' => '#1a0d14',
3762                'border' => '#ff1493',
3763                'shadow' => 'rgba(255, 20, 147, 0.4)',
3764                'header_bg' => 'linear-gradient(180deg, #2d1a24 0%, #1a0d14 100%)',
3765                'header_border' => '#ff1493',
3766                'header_shadow' => '0 0 12px rgba(255, 20, 147, 0.6)',
3767                'text_primary' => '#ff69b4',
3768                'text_bright' => '#ff1493',
3769                'text_dim' => '#ff85c1',
3770                'grid_bg' => '#2d1a24',
3771                'grid_border' => '#ff1493',
3772                'cell_bg' => '#1a0d14',
3773                'cell_today_bg' => '#3d2030',
3774                'bar_glow' => '0 0 5px',
3775                'pastdue_color' => '#e74c3c',
3776                'pastdue_bg' => '#3d1520',
3777                'pastdue_bg_strong' => '#4d1a28',
3778                'pastdue_bg_light' => '#2d1018',
3779                'tomorrow_bg' => '#3d3020',
3780                'tomorrow_bg_strong' => '#4d3a28',
3781                'tomorrow_bg_light' => '#2d2518',
3782            ],
3783            'wiki' => [
3784                'bg' => '#f5f5f5',
3785                'border' => '#ccc',          // Template __border__ color
3786                'shadow' => 'rgba(0, 0, 0, 0.1)',
3787                'header_bg' => '#e8e8e8',
3788                'header_border' => '#ccc',
3789                'header_shadow' => '0 2px 4px rgba(0, 0, 0, 0.1)',
3790                'text_primary' => '#333',
3791                'text_bright' => '#2b73b7',  // Template __link__ color
3792                'text_dim' => '#666',
3793                'grid_bg' => '#f5f5f5',
3794                'grid_border' => '#ccc',
3795                'cell_bg' => '#fff',
3796                'cell_today_bg' => '#eee',
3797                'bar_glow' => '0 1px 2px',
3798                'pastdue_color' => '#e74c3c',
3799                'pastdue_bg' => '#ffe6e6',
3800                'pastdue_bg_strong' => '#ffd9d9',
3801                'pastdue_bg_light' => '#fff2f2',
3802                'tomorrow_bg' => '#fff9e6',
3803                'tomorrow_bg_strong' => '#fff4cc',
3804                'tomorrow_bg_light' => '#fffbf0',
3805            ],
3806        ];
3807
3808        return isset($themes[$theme]) ? $themes[$theme] : $themes['matrix'];
3809    }
3810
3811    /**
3812     * Get week start day preference
3813     */
3814    private function getWeekStartDay() {
3815        $configFile = DOKU_INC . 'data/meta/calendar_week_start.txt';
3816        if (file_exists($configFile)) {
3817            $start = trim(file_get_contents($configFile));
3818            if (in_array($start, ['monday', 'sunday'])) {
3819                return $start;
3820            }
3821        }
3822        return 'sunday'; // Default to Sunday (US/Canada standard)
3823    }
3824
3825    /**
3826     * Get itinerary collapsed default state
3827     */
3828    private function getItineraryCollapsed() {
3829        $configFile = DOKU_INC . 'data/meta/calendar_itinerary_collapsed.txt';
3830        if (file_exists($configFile)) {
3831            return trim(file_get_contents($configFile)) === 'yes';
3832        }
3833        return false; // Default to expanded
3834    }
3835}