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