xref: /plugin/calendar/syntax.php (revision da2061786a295965aec1e3343408c72b19fbbb6c)
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 . '">';
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)
1547            $html .= '<div class="eventlist-stats-container">';
1548
1549            // 5-minute load average (green, updates every 2 seconds)
1550            $html .= '<div class="eventlist-cpu-bar" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $calId . '(\'green\')" onmouseout="hideTooltip_' . $calId . '(\'green\')">';
1551            $html .= '<div class="eventlist-cpu-fill" id="cpu-5min-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_bright'] . ' !important;"></div>';
1552            $html .= '<div class="system-tooltip" id="tooltip-green-' . $calId . '" style="display:none;"></div>';
1553            $html .= '</div>';
1554
1555            // Real-time CPU (purple, updates with 5-sec average)
1556            $html .= '<div class="eventlist-cpu-bar eventlist-cpu-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $calId . '(\'purple\')" onmouseout="hideTooltip_' . $calId . '(\'purple\')">';
1557            $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-purple" id="cpu-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['border'] . ' !important;"></div>';
1558            $html .= '<div class="system-tooltip" id="tooltip-purple-' . $calId . '" style="display:none;"></div>';
1559            $html .= '</div>';
1560
1561            // Real-time Memory (orange, updates)
1562            $html .= '<div class="eventlist-cpu-bar eventlist-mem-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $calId . '(\'orange\')" onmouseout="hideTooltip_' . $calId . '(\'orange\')">';
1563            $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-orange" id="mem-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_primary'] . ' !important;"></div>';
1564            $html .= '<div class="system-tooltip" id="tooltip-orange-' . $calId . '" style="display:none;"></div>';
1565            $html .= '</div>';
1566
1567            $html .= '</div>';
1568            $html .= '</div>';
1569
1570            // Add JavaScript to update clock and weather
1571            $html .= '<script>
1572(function() {
1573    // Update clock every second
1574    function updateClock() {
1575        const now = new Date();
1576        let hours = now.getHours();
1577        const minutes = String(now.getMinutes()).padStart(2, "0");
1578        const seconds = String(now.getSeconds()).padStart(2, "0");
1579        const ampm = hours >= 12 ? "PM" : "AM";
1580        hours = hours % 12 || 12;
1581        const timeStr = hours + ":" + minutes + ":" + seconds + " " + ampm;
1582        const clockEl = document.getElementById("clock-' . $calId . '");
1583        if (clockEl) clockEl.textContent = timeStr;
1584    }
1585    setInterval(updateClock, 1000);
1586
1587    // Fetch weather - uses default location, click weather to get local
1588    var userLocationGranted = false;
1589    var userLat = 38.5816;  // Sacramento default
1590    var userLon = -121.4944;
1591
1592    function fetchWeatherData(lat, lon) {
1593        fetch("https://api.open-meteo.com/v1/forecast?latitude=" + lat + "&longitude=" + lon + "&current_weather=true&temperature_unit=fahrenheit")
1594            .then(response => response.json())
1595            .then(data => {
1596                if (data.current_weather) {
1597                    const temp = Math.round(data.current_weather.temperature);
1598                    const weatherCode = data.current_weather.weathercode;
1599                    const icon = getWeatherIcon(weatherCode);
1600                    const iconEl = document.getElementById("weather-icon-' . $calId . '");
1601                    const tempEl = document.getElementById("weather-temp-' . $calId . '");
1602                    if (iconEl) iconEl.textContent = icon;
1603                    if (tempEl) tempEl.innerHTML = temp + "&deg;";
1604                }
1605            })
1606            .catch(error => {
1607                console.log("Weather fetch error:", error);
1608            });
1609    }
1610
1611    function updateWeather() {
1612        fetchWeatherData(userLat, userLon);
1613    }
1614
1615    // Allow user to click weather to get local weather (requires user gesture)
1616    function requestLocalWeather() {
1617        if (userLocationGranted) return; // Already have permission
1618
1619        if ("geolocation" in navigator) {
1620            navigator.geolocation.getCurrentPosition(function(position) {
1621                userLat = position.coords.latitude;
1622                userLon = position.coords.longitude;
1623                userLocationGranted = true;
1624                fetchWeatherData(userLat, userLon);
1625            }, function(error) {
1626                console.log("Geolocation denied or unavailable, using default location");
1627            });
1628        }
1629    }
1630
1631    // Add click handler to weather widget for local weather
1632    setTimeout(function() {
1633        var weatherEl = document.querySelector("#weather-icon-' . $calId . '");
1634        if (weatherEl) {
1635            weatherEl.style.cursor = "pointer";
1636            weatherEl.title = "Click for local weather";
1637            weatherEl.addEventListener("click", requestLocalWeather);
1638        }
1639    }, 100);
1640
1641    // WMO Weather interpretation codes
1642    function getWeatherIcon(code) {
1643        const icons = {
1644            0: "☀️",   // Clear sky
1645            1: "��️",   // Mainly clear
1646            2: "⛅",   // Partly cloudy
1647            3: "☁️",   // Overcast
1648            45: "��️",  // Fog
1649            48: "��️",  // Depositing rime fog
1650            51: "��️",  // Light drizzle
1651            53: "��️",  // Moderate drizzle
1652            55: "��️",  // Dense drizzle
1653            61: "��️",  // Slight rain
1654            63: "��️",  // Moderate rain
1655            65: "⛈️",  // Heavy rain
1656            71: "��️",  // Slight snow
1657            73: "��️",  // Moderate snow
1658            75: "❄️",  // Heavy snow
1659            77: "��️",  // Snow grains
1660            80: "��️",  // Slight rain showers
1661            81: "��️",  // Moderate rain showers
1662            82: "⛈️",  // Violent rain showers
1663            85: "��️",  // Slight snow showers
1664            86: "❄️",  // Heavy snow showers
1665            95: "⛈️",  // Thunderstorm
1666            96: "⛈️",  // Thunderstorm with slight hail
1667            99: "⛈️"   // Thunderstorm with heavy hail
1668        };
1669        return icons[code] || "��️";
1670    }
1671
1672    // Update weather immediately and every 10 minutes
1673    updateWeather();
1674    setInterval(updateWeather, 600000);
1675
1676    // CPU load history for 4-second rolling average
1677    const cpuHistory = [];
1678    const CPU_HISTORY_SIZE = 2; // 2 samples × 2 seconds = 4 seconds
1679
1680    // Store latest system stats for tooltips
1681    let latestStats = {
1682        load: {"1min": 0, "5min": 0, "15min": 0},
1683        uptime: "",
1684        memory_details: {},
1685        top_processes: []
1686    };
1687
1688    // Tooltip functions
1689    window["showTooltip_' . $calId . '"] = function(color) {
1690        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
1691        if (!tooltip) {
1692            console.log("Tooltip element not found for color:", color);
1693            return;
1694        }
1695
1696
1697        let content = "";
1698
1699        if (color === "green") {
1700            // Green bar: Load averages and uptime
1701            content = "<div class=\"tooltip-title\">CPU Load Average</div>";
1702            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
1703            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
1704            content += "<div>15 min: " + (latestStats.load["15min"] || "N/A") + "</div>";
1705            if (latestStats.uptime) {
1706                content += "<div style=\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_bright'] . ';\">Uptime: " + latestStats.uptime + "</div>";
1707            }
1708            tooltip.style.setProperty("border-color", "' . $themeStyles['text_bright'] . '", "important");
1709            tooltip.style.setProperty("color", "' . $themeStyles['text_bright'] . '", "important");
1710            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_bright'] . '", "important");
1711        } else if (color === "purple") {
1712            // Purple bar: Load averages (short-term) and top processes
1713            content = "<div class=\"tooltip-title\">CPU Load (Short-term)</div>";
1714            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
1715            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
1716            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
1717                content += "<div style=\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['border'] . ';\" class=\"tooltip-title\">Top Processes</div>";
1718                latestStats.top_processes.slice(0, 5).forEach(proc => {
1719                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
1720                });
1721            }
1722            tooltip.style.setProperty("border-color", "' . $themeStyles['border'] . '", "important");
1723            tooltip.style.setProperty("color", "' . $themeStyles['border'] . '", "important");
1724            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['border'] . '", "important");
1725        } else if (color === "orange") {
1726            // Orange bar: Memory details and top processes
1727            content = "<div class=\"tooltip-title\">Memory Usage</div>";
1728            if (latestStats.memory_details && latestStats.memory_details.total) {
1729                content += "<div>Total: " + latestStats.memory_details.total + "</div>";
1730                content += "<div>Used: " + latestStats.memory_details.used + "</div>";
1731                content += "<div>Available: " + latestStats.memory_details.available + "</div>";
1732                if (latestStats.memory_details.cached) {
1733                    content += "<div>Cached: " + latestStats.memory_details.cached + "</div>";
1734                }
1735            } else {
1736                content += "<div>Loading...</div>";
1737            }
1738            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
1739                content += "<div style=\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_primary'] . ';\" class=\"tooltip-title\">Top Processes</div>";
1740                latestStats.top_processes.slice(0, 5).forEach(proc => {
1741                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
1742                });
1743            }
1744            tooltip.style.setProperty("border-color", "' . $themeStyles['text_primary'] . '", "important");
1745            tooltip.style.setProperty("color", "' . $themeStyles['text_primary'] . '", "important");
1746            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_primary'] . '", "important");
1747        }
1748
1749        tooltip.innerHTML = content;
1750        tooltip.style.setProperty("display", "block");
1751        tooltip.style.setProperty("background", "' . $themeStyles['bg'] . '", "important");
1752
1753        // Position tooltip using fixed positioning above the bar
1754        const bar = tooltip.parentElement;
1755        const barRect = bar.getBoundingClientRect();
1756        const tooltipRect = tooltip.getBoundingClientRect();
1757
1758        // Center horizontally on the bar
1759        const left = barRect.left + (barRect.width / 2) - (tooltipRect.width / 2);
1760        // Position above the bar with 8px gap
1761        const top = barRect.top - tooltipRect.height - 8;
1762
1763        tooltip.style.left = left + "px";
1764        tooltip.style.top = top + "px";
1765    };
1766
1767    window["hideTooltip_' . $calId . '"] = function(color) {
1768        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
1769        if (tooltip) {
1770            tooltip.style.display = "none";
1771        }
1772    };
1773
1774    // Update CPU and memory bars every 2 seconds
1775    function updateSystemStats() {
1776        // Fetch real system stats from server
1777        fetch("' . DOKU_BASE . 'lib/plugins/calendar/get_system_stats.php")
1778            .then(response => response.json())
1779            .then(data => {
1780
1781                // Store data for tooltips
1782                latestStats = {
1783                    load: data.load || {"1min": 0, "5min": 0, "15min": 0},
1784                    uptime: data.uptime || "",
1785                    memory_details: data.memory_details || {},
1786                    top_processes: data.top_processes || []
1787                };
1788
1789
1790                // Update green bar (5-minute average) - updates live now!
1791                const greenBar = document.getElementById("cpu-5min-' . $calId . '");
1792                if (greenBar) {
1793                    greenBar.style.width = Math.min(100, data.cpu_5min) + "%";
1794                }
1795
1796                // Add current CPU to history for purple bar
1797                cpuHistory.push(data.cpu);
1798                if (cpuHistory.length > CPU_HISTORY_SIZE) {
1799                    cpuHistory.shift(); // Remove oldest
1800                }
1801
1802                // Calculate 5-second average for CPU
1803                const cpuAverage = cpuHistory.reduce((sum, val) => sum + val, 0) / cpuHistory.length;
1804
1805                // Update CPU bar (purple) with 5-second average
1806                const cpuBar = document.getElementById("cpu-realtime-' . $calId . '");
1807                if (cpuBar) {
1808                    cpuBar.style.width = Math.min(100, cpuAverage) + "%";
1809                }
1810
1811                // Update memory bar (orange) with real data
1812                const memBar = document.getElementById("mem-realtime-' . $calId . '");
1813                if (memBar) {
1814                    memBar.style.width = Math.min(100, data.memory) + "%";
1815                }
1816            })
1817            .catch(error => {
1818                console.log("System stats error:", error);
1819                // Fallback to client-side estimates on error
1820                const cpuFallback = Math.random() * 100;
1821                cpuHistory.push(cpuFallback);
1822                if (cpuHistory.length > CPU_HISTORY_SIZE) {
1823                    cpuHistory.shift();
1824                }
1825                const cpuAverage = cpuHistory.reduce((sum, val) => sum + val, 0) / cpuHistory.length;
1826
1827                const greenBar = document.getElementById("cpu-5min-' . $calId . '");
1828                if (greenBar) greenBar.style.width = Math.min(100, cpuFallback) + "%";
1829
1830                const cpuBar = document.getElementById("cpu-realtime-' . $calId . '");
1831                if (cpuBar) cpuBar.style.width = Math.min(100, cpuAverage) + "%";
1832
1833                let memoryUsage = 0;
1834                if (performance.memory) {
1835                    memoryUsage = (performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit) * 100;
1836                } else {
1837                    memoryUsage = Math.random() * 100;
1838                }
1839                const memBar = document.getElementById("mem-realtime-' . $calId . '");
1840                if (memBar) memBar.style.width = Math.min(100, memoryUsage) + "%";
1841            });
1842    }
1843
1844    // Update immediately and then every 2 seconds
1845    updateSystemStats();
1846    setInterval(updateSystemStats, 2000);
1847})();
1848</script>';
1849        }
1850
1851        if (empty($allEvents)) {
1852            $html .= '<div class="eventlist-simple-empty">';
1853            $html .= '<div class="eventlist-simple-header">' . htmlspecialchars($headerText);
1854            if ($namespace) {
1855                $html .= ' <span class="eventlist-simple-namespace">' . htmlspecialchars($namespace) . '</span>';
1856            }
1857            $html .= '</div>';
1858            $html .= '<div class="eventlist-simple-body">No events</div>';
1859            $html .= '</div>';
1860        } else {
1861            // Calculate today and tomorrow's dates for highlighting
1862            $todayStr = date('Y-m-d');
1863            $tomorrow = date('Y-m-d', strtotime('+1 day'));
1864
1865            foreach ($allEvents as $dateKey => $dayEvents) {
1866                $dateObj = new DateTime($dateKey);
1867                $displayDate = $dateObj->format('D, M j');
1868
1869                // Check if this date is today or tomorrow or past
1870                // Enable highlighting for sidebar mode AND range modes (day, week, month)
1871                $enableHighlighting = $sidebar || !empty($range);
1872                $isToday = $enableHighlighting && ($dateKey === $todayStr);
1873                $isTomorrow = $enableHighlighting && ($dateKey === $tomorrow);
1874                $isPast = $dateKey < $todayStr;
1875
1876                foreach ($dayEvents as $event) {
1877                    // Check if this is a task and if it's completed
1878                    $isTask = !empty($event['isTask']);
1879                    $completed = !empty($event['completed']);
1880
1881                    // ALWAYS skip completed tasks UNLESS showchecked is explicitly set
1882                    if (!$showchecked && $isTask && $completed) {
1883                        continue;
1884                    }
1885
1886                    // Skip past events that are NOT tasks (only show past due tasks from the past)
1887                    if ($isPast && !$isTask) {
1888                        continue;
1889                    }
1890
1891                    // Determine if task is past due (past date, is task, not completed)
1892                    $isPastDue = $isPast && $isTask && !$completed;
1893
1894                    // Line 1: Header (Title, Time, Date, Namespace)
1895                    $todayClass = $isToday ? ' eventlist-simple-today' : '';
1896                    $tomorrowClass = $isTomorrow ? ' eventlist-simple-tomorrow' : '';
1897                    $pastDueClass = $isPastDue ? ' eventlist-simple-pastdue' : '';
1898                    $html .= '<div class="eventlist-simple-item' . $todayClass . $tomorrowClass . $pastDueClass . '">';
1899                    $html .= '<div class="eventlist-simple-header">';
1900
1901                    // Title
1902                    $html .= '<span class="eventlist-simple-title">' . htmlspecialchars($event['title']) . '</span>';
1903
1904                    // Time (12-hour format)
1905                    if (!empty($event['time'])) {
1906                        $timeParts = explode(':', $event['time']);
1907                        if (count($timeParts) === 2) {
1908                            $hour = (int)$timeParts[0];
1909                            $minute = $timeParts[1];
1910                            $ampm = $hour >= 12 ? 'PM' : 'AM';
1911                            $hour = $hour % 12 ?: 12;
1912                            $displayTime = $hour . ':' . $minute . ' ' . $ampm;
1913                            $html .= ' <span class="eventlist-simple-time">' . $displayTime . '</span>';
1914                        }
1915                    }
1916
1917                    // Date
1918                    $html .= ' <span class="eventlist-simple-date">' . $displayDate . '</span>';
1919
1920                    // Badge: PAST DUE, TODAY, or nothing
1921                    if ($isPastDue) {
1922                        $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>';
1923                    } elseif ($isToday) {
1924                        $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>';
1925                    }
1926
1927                    // Namespace badge (show individual event's namespace)
1928                    $eventNamespace = isset($event['namespace']) ? $event['namespace'] : '';
1929                    if (!$eventNamespace && isset($event['_namespace'])) {
1930                        $eventNamespace = $event['_namespace']; // Fallback to _namespace for multi-namespace loading
1931                    }
1932                    if ($eventNamespace) {
1933                        $html .= ' <span class="eventlist-simple-namespace">' . htmlspecialchars($eventNamespace) . '</span>';
1934                    }
1935
1936                    $html .= '</div>'; // header
1937
1938                    // Line 2: Body (Description only) - only show if description exists
1939                    if (!empty($event['description'])) {
1940                        $html .= '<div class="eventlist-simple-body">' . $this->renderDescription($event['description']) . '</div>';
1941                    }
1942
1943                    $html .= '</div>'; // item
1944                }
1945            }
1946        }
1947
1948        $html .= '</div>'; // eventlist-simple
1949
1950        return $html;
1951    }
1952
1953    private function renderEventDialog($calId, $namespace, $theme = null) {
1954        // Get theme for dialog
1955        if ($theme === null) {
1956            $theme = $this->getSidebarTheme();
1957        }
1958        $themeStyles = $this->getSidebarThemeStyles($theme);
1959
1960        $html = '<div class="event-dialog-compact" id="dialog-' . $calId . '" style="display:none;">';
1961        $html .= '<div class="dialog-overlay" onclick="closeEventDialog(\'' . $calId . '\')"></div>';
1962
1963        // Draggable dialog with theme
1964        $html .= '<div class="dialog-content-sleek" id="dialog-content-' . $calId . '">';
1965
1966        // Header with drag handle and close button
1967        $html .= '<div class="dialog-header-sleek dialog-drag-handle" id="drag-handle-' . $calId . '">';
1968        $html .= '<h3 id="dialog-title-' . $calId . '">Add Event</h3>';
1969        $html .= '<button type="button" class="dialog-close-btn" onclick="closeEventDialog(\'' . $calId . '\')">×</button>';
1970        $html .= '</div>';
1971
1972        // Form content
1973        $html .= '<form id="eventform-' . $calId . '" onsubmit="saveEventCompact(\'' . $calId . '\', \'' . $namespace . '\'); return false;" class="sleek-form">';
1974
1975        // Hidden ID field
1976        $html .= '<input type="hidden" id="event-id-' . $calId . '" name="eventId" value="">';
1977
1978        // 1. TITLE
1979        $html .= '<div class="form-field">';
1980        $html .= '<label class="field-label">�� Title</label>';
1981        $html .= '<input type="text" id="event-title-' . $calId . '" name="title" required class="input-sleek input-compact" placeholder="Event or task title...">';
1982        $html .= '</div>';
1983
1984        // 1.5 NAMESPACE SELECTOR (Searchable with fuzzy matching)
1985        $html .= '<div class="form-field">';
1986        $html .= '<label class="field-label">�� Namespace</label>';
1987
1988        // Hidden field to store actual selected namespace
1989        $html .= '<input type="hidden" id="event-namespace-' . $calId . '" name="namespace" value="">';
1990
1991        // Searchable input
1992        $html .= '<div class="namespace-search-wrapper">';
1993        $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">';
1994        $html .= '<div class="namespace-dropdown" id="event-namespace-dropdown-' . $calId . '" style="display:none;"></div>';
1995        $html .= '</div>';
1996
1997        // Store namespaces as JSON for JavaScript
1998        $allNamespaces = $this->getAllNamespaces();
1999        $html .= '<script type="application/json" id="namespaces-data-' . $calId . '">' . json_encode($allNamespaces) . '</script>';
2000
2001        $html .= '</div>';
2002
2003        // 2. DESCRIPTION
2004        $html .= '<div class="form-field">';
2005        $html .= '<label class="field-label">�� Description</label>';
2006        $html .= '<textarea id="event-desc-' . $calId . '" name="description" rows="2" class="input-sleek textarea-sleek textarea-compact" placeholder="Optional details..."></textarea>';
2007        $html .= '</div>';
2008
2009        // 3. START DATE - END DATE (inline)
2010        $html .= '<div class="form-row-group">';
2011
2012        $html .= '<div class="form-field form-field-half">';
2013        $html .= '<label class="field-label-compact">�� Start Date</label>';
2014        $html .= '<input type="date" id="event-date-' . $calId . '" name="date" required class="input-sleek input-date input-compact" onchange="updateEndTimeOptions(\'' . $calId . '\')">';
2015        $html .= '</div>';
2016
2017        $html .= '<div class="form-field form-field-half">';
2018        $html .= '<label class="field-label-compact">�� End Date</label>';
2019        $html .= '<input type="date" id="event-end-date-' . $calId . '" name="endDate" class="input-sleek input-date input-compact" placeholder="Optional" onchange="updateEndTimeOptions(\'' . $calId . '\')">';
2020        $html .= '</div>';
2021
2022        $html .= '</div>'; // End row
2023
2024        // 4. IS REPEATING CHECKBOX
2025        $html .= '<div class="form-field form-field-checkbox form-field-checkbox-compact">';
2026        $html .= '<label class="checkbox-label checkbox-label-compact">';
2027        $html .= '<input type="checkbox" id="event-recurring-' . $calId . '" name="isRecurring" class="recurring-toggle" onchange="toggleRecurringOptions(\'' . $calId . '\')">';
2028        $html .= '<span>�� Repeating Event</span>';
2029        $html .= '</label>';
2030        $html .= '</div>';
2031
2032        // Recurring options (shown when checkbox is checked)
2033        $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));">';
2034
2035        // Row 1: Repeat every [N] [period]
2036        $html .= '<div class="form-row-group" style="margin-bottom:6px;">';
2037
2038        $html .= '<div class="form-field" style="flex:0 0 auto; min-width:0;">';
2039        $html .= '<label class="field-label-compact">Repeat every</label>';
2040        $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;">';
2041        $html .= '</div>';
2042
2043        $html .= '<div class="form-field" style="flex:1; min-width:0;">';
2044        $html .= '<label class="field-label-compact">&nbsp;</label>';
2045        $html .= '<select id="event-recurrence-type-' . $calId . '" name="recurrenceType" class="input-sleek input-compact" onchange="updateRecurrenceOptions(\'' . $calId . '\')">';
2046        $html .= '<option value="daily">Day(s)</option>';
2047        $html .= '<option value="weekly">Week(s)</option>';
2048        $html .= '<option value="monthly">Month(s)</option>';
2049        $html .= '<option value="yearly">Year(s)</option>';
2050        $html .= '</select>';
2051        $html .= '</div>';
2052
2053        $html .= '</div>'; // End row 1
2054
2055        // Row 2: Weekly options - day of week checkboxes
2056        $html .= '<div id="weekly-options-' . $calId . '" class="weekly-options" style="display:none; margin-bottom:6px;">';
2057        $html .= '<label class="field-label-compact" style="display:block; margin-bottom:4px;">On these days:</label>';
2058        $html .= '<div style="display:flex; flex-wrap:wrap; gap:2px;">';
2059        $dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
2060        foreach ($dayNames as $idx => $day) {
2061            $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;">';
2062            $html .= '<input type="checkbox" name="weekDays[]" value="' . $idx . '" style="margin-right:3px; width:12px; height:12px;">';
2063            $html .= '<span>' . $day . '</span>';
2064            $html .= '</label>';
2065        }
2066        $html .= '</div>';
2067        $html .= '</div>'; // End weekly options
2068
2069        // Row 3: Monthly options - day of month OR ordinal weekday
2070        $html .= '<div id="monthly-options-' . $calId . '" class="monthly-options" style="display:none; margin-bottom:6px;">';
2071        $html .= '<label class="field-label-compact" style="display:block; margin-bottom:4px;">Repeat on:</label>';
2072
2073        // Radio: Day of month vs Ordinal weekday
2074        $html .= '<div style="margin-bottom:6px;">';
2075        $html .= '<label style="display:inline-flex; align-items:center; margin-right:12px; cursor:pointer; font-size:11px;">';
2076        $html .= '<input type="radio" name="monthlyType" value="dayOfMonth" checked onchange="updateMonthlyType(\'' . $calId . '\')" style="margin-right:4px;">';
2077        $html .= 'Day of month';
2078        $html .= '</label>';
2079        $html .= '<label style="display:inline-flex; align-items:center; cursor:pointer; font-size:11px;">';
2080        $html .= '<input type="radio" name="monthlyType" value="ordinalWeekday" onchange="updateMonthlyType(\'' . $calId . '\')" style="margin-right:4px;">';
2081        $html .= 'Weekday pattern';
2082        $html .= '</label>';
2083        $html .= '</div>';
2084
2085        // Day of month input (shown by default)
2086        $html .= '<div id="monthly-day-' . $calId . '" style="display:flex; align-items:center; gap:6px;">';
2087        $html .= '<span style="font-size:11px;">Day</span>';
2088        $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;">';
2089        $html .= '<span style="font-size:10px; color:var(--text-dim, #666);">of each month</span>';
2090        $html .= '</div>';
2091
2092        // Ordinal weekday (hidden by default)
2093        $html .= '<div id="monthly-ordinal-' . $calId . '" style="display:none;">';
2094        $html .= '<div style="display:flex; align-items:center; gap:4px; flex-wrap:wrap;">';
2095        $html .= '<select id="event-ordinal-' . $calId . '" name="ordinalWeek" class="input-sleek input-compact" style="width:auto;">';
2096        $html .= '<option value="1">First</option>';
2097        $html .= '<option value="2">Second</option>';
2098        $html .= '<option value="3">Third</option>';
2099        $html .= '<option value="4">Fourth</option>';
2100        $html .= '<option value="5">Fifth</option>';
2101        $html .= '<option value="-1">Last</option>';
2102        $html .= '</select>';
2103        $html .= '<select id="event-ordinal-day-' . $calId . '" name="ordinalDay" class="input-sleek input-compact" style="width:auto;">';
2104        $html .= '<option value="0">Sunday</option>';
2105        $html .= '<option value="1">Monday</option>';
2106        $html .= '<option value="2">Tuesday</option>';
2107        $html .= '<option value="3">Wednesday</option>';
2108        $html .= '<option value="4">Thursday</option>';
2109        $html .= '<option value="5">Friday</option>';
2110        $html .= '<option value="6">Saturday</option>';
2111        $html .= '</select>';
2112        $html .= '<span style="font-size:10px; color:var(--text-dim, #666);">of each month</span>';
2113        $html .= '</div>';
2114        $html .= '</div>';
2115
2116        $html .= '</div>'; // End monthly options
2117
2118        // Row 4: End date
2119        $html .= '<div class="form-row-group">';
2120        $html .= '<div class="form-field">';
2121        $html .= '<label class="field-label-compact">Repeat Until (optional)</label>';
2122        $html .= '<input type="date" id="event-recurrence-end-' . $calId . '" name="recurrenceEnd" class="input-sleek input-date input-compact" placeholder="Optional">';
2123        $html .= '<div style="font-size:9px; color:var(--text-dim, #666); margin-top:2px;">Leave empty for 1 year of events</div>';
2124        $html .= '</div>';
2125        $html .= '</div>'; // End row 4
2126
2127        $html .= '</div>'; // End recurring options
2128
2129        // 5. TIME (Start & End) - COLOR (inline)
2130        $html .= '<div class="form-row-group">';
2131
2132        $html .= '<div class="form-field form-field-half">';
2133        $html .= '<label class="field-label-compact">�� Start Time</label>';
2134        $html .= '<div class="time-picker-wrapper">';
2135        $html .= '<select id="event-time-' . $calId . '" name="time" class="input-sleek input-compact time-select" onchange="updateEndTimeOptions(\'' . $calId . '\')">';
2136        $html .= '<option value="">All day</option>';
2137
2138        // Generate time options grouped by period
2139        $periods = [
2140            'Morning' => [6, 7, 8, 9, 10, 11],
2141            'Afternoon' => [12, 13, 14, 15, 16, 17],
2142            'Evening' => [18, 19, 20, 21, 22, 23],
2143            'Night' => [0, 1, 2, 3, 4, 5]
2144        ];
2145
2146        foreach ($periods as $periodName => $hours) {
2147            $html .= '<optgroup label="── ' . $periodName . ' ──">';
2148            foreach ($hours as $hour) {
2149                for ($minute = 0; $minute < 60; $minute += 15) {
2150                    $timeValue = sprintf('%02d:%02d', $hour, $minute);
2151                    $displayHour = $hour == 0 ? 12 : ($hour > 12 ? $hour - 12 : $hour);
2152                    $ampm = $hour < 12 ? 'AM' : 'PM';
2153                    $displayTime = sprintf('%d:%02d %s', $displayHour, $minute, $ampm);
2154                    $html .= '<option value="' . $timeValue . '">' . $displayTime . '</option>';
2155                }
2156            }
2157            $html .= '</optgroup>';
2158        }
2159
2160        $html .= '</select>';
2161        $html .= '</div>';
2162        $html .= '</div>';
2163
2164        $html .= '<div class="form-field form-field-half">';
2165        $html .= '<label class="field-label-compact">�� End Time</label>';
2166        $html .= '<div class="time-picker-wrapper">';
2167        $html .= '<select id="event-end-time-' . $calId . '" name="endTime" class="input-sleek input-compact time-select">';
2168        $html .= '<option value="">Same as start</option>';
2169
2170        // Generate time options grouped by period (same as start time)
2171        foreach ($periods as $periodName => $hours) {
2172            $html .= '<optgroup label="── ' . $periodName . ' ──">';
2173            foreach ($hours as $hour) {
2174                for ($minute = 0; $minute < 60; $minute += 15) {
2175                    $timeValue = sprintf('%02d:%02d', $hour, $minute);
2176                    $displayHour = $hour == 0 ? 12 : ($hour > 12 ? $hour - 12 : $hour);
2177                    $ampm = $hour < 12 ? 'AM' : 'PM';
2178                    $displayTime = sprintf('%d:%02d %s', $displayHour, $minute, $ampm);
2179                    $html .= '<option value="' . $timeValue . '">' . $displayTime . '</option>';
2180                }
2181            }
2182            $html .= '</optgroup>';
2183        }
2184
2185        $html .= '</select>';
2186        $html .= '</div>';
2187        $html .= '</div>';
2188
2189        $html .= '</div>'; // End row
2190
2191        // Color field (new row)
2192        $html .= '<div class="form-row-group">';
2193
2194        $html .= '<div class="form-field form-field-full">';
2195        $html .= '<label class="field-label-compact">�� Color</label>';
2196        $html .= '<div class="color-picker-wrapper">';
2197        $html .= '<select id="event-color-' . $calId . '" name="color" class="input-sleek input-compact color-select" onchange="updateCustomColorPicker(\'' . $calId . '\')">';
2198        $html .= '<option value="#3498db" style="background:#3498db;color:white">�� Blue</option>';
2199        $html .= '<option value="#2ecc71" style="background:#2ecc71;color:white">�� Green</option>';
2200        $html .= '<option value="#e74c3c" style="background:#e74c3c;color:white">�� Red</option>';
2201        $html .= '<option value="#f39c12" style="background:#f39c12;color:white">�� Orange</option>';
2202        $html .= '<option value="#9b59b6" style="background:#9b59b6;color:white">�� Purple</option>';
2203        $html .= '<option value="#e91e63" style="background:#e91e63;color:white">�� Pink</option>';
2204        $html .= '<option value="#1abc9c" style="background:#1abc9c;color:white">�� Teal</option>';
2205        $html .= '<option value="custom">�� Custom...</option>';
2206        $html .= '</select>';
2207        $html .= '<input type="color" id="event-color-custom-' . $calId . '" class="color-picker-input color-picker-compact" value="#3498db" onchange="updateColorFromPicker(\'' . $calId . '\')">';
2208        $html .= '</div>';
2209        $html .= '</div>';
2210
2211        $html .= '</div>'; // End row
2212
2213        // Task checkbox
2214        $html .= '<div class="form-field form-field-checkbox form-field-checkbox-compact">';
2215        $html .= '<label class="checkbox-label checkbox-label-compact">';
2216        $html .= '<input type="checkbox" id="event-is-task-' . $calId . '" name="isTask" class="task-toggle">';
2217        $html .= '<span>�� This is a task (can be checked off)</span>';
2218        $html .= '</label>';
2219        $html .= '</div>';
2220
2221        // Action buttons
2222        $html .= '<div class="dialog-actions-sleek">';
2223        $html .= '<button type="button" class="btn-sleek btn-cancel-sleek" onclick="closeEventDialog(\'' . $calId . '\')">Cancel</button>';
2224        $html .= '<button type="submit" class="btn-sleek btn-save-sleek">�� Save</button>';
2225        $html .= '</div>';
2226
2227        $html .= '</form>';
2228        $html .= '</div>';
2229        $html .= '</div>';
2230
2231        return $html;
2232    }
2233
2234    private function renderMonthPicker($calId, $year, $month, $namespace, $theme = 'matrix', $themeStyles = null) {
2235        // Fallback to default theme if not provided
2236        if ($themeStyles === null) {
2237            $themeStyles = $this->getSidebarThemeStyles($theme);
2238        }
2239
2240        $themeClass = 'calendar-theme-' . $theme;
2241
2242        $html = '<div class="month-picker-overlay ' . $themeClass . '" id="month-picker-overlay-' . $calId . '" style="display:none;" onclick="closeMonthPicker(\'' . $calId . '\')">';
2243        $html .= '<div class="month-picker-dialog" onclick="event.stopPropagation();">';
2244        $html .= '<h4>Jump to Month</h4>';
2245
2246        $html .= '<div class="month-picker-selects">';
2247        $html .= '<select id="month-picker-month-' . $calId . '" class="month-picker-select">';
2248        $monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
2249        for ($m = 1; $m <= 12; $m++) {
2250            $selected = ($m == $month) ? ' selected' : '';
2251            $html .= '<option value="' . $m . '"' . $selected . '>' . $monthNames[$m - 1] . '</option>';
2252        }
2253        $html .= '</select>';
2254
2255        $html .= '<select id="month-picker-year-' . $calId . '" class="month-picker-select">';
2256        $currentYear = (int)date('Y');
2257        for ($y = $currentYear - 5; $y <= $currentYear + 5; $y++) {
2258            $selected = ($y == $year) ? ' selected' : '';
2259            $html .= '<option value="' . $y . '"' . $selected . '>' . $y . '</option>';
2260        }
2261        $html .= '</select>';
2262        $html .= '</div>';
2263
2264        $html .= '<div class="month-picker-actions">';
2265        $html .= '<button class="btn-sleek btn-cancel-sleek" onclick="closeMonthPicker(\'' . $calId . '\')">Cancel</button>';
2266        $html .= '<button class="btn-sleek btn-save-sleek" onclick="jumpToSelectedMonth(\'' . $calId . '\', \'' . $namespace . '\')">Go</button>';
2267        $html .= '</div>';
2268
2269        $html .= '</div>';
2270        $html .= '</div>';
2271
2272        return $html;
2273    }
2274
2275    private function renderDescription($description, $themeStyles = null) {
2276        if (empty($description)) {
2277            return '';
2278        }
2279
2280        // Get theme for link colors if not provided
2281        if ($themeStyles === null) {
2282            $theme = $this->getSidebarTheme();
2283            $themeStyles = $this->getSidebarThemeStyles($theme);
2284        }
2285
2286        $linkColor = '';
2287        $linkStyle = ' class="cal-link"';
2288
2289        // Token-based parsing to avoid escaping issues
2290        $rendered = $description;
2291        $tokens = array();
2292        $tokenIndex = 0;
2293
2294        // Convert DokuWiki image syntax {{image.jpg}} to tokens
2295        $pattern = '/\{\{([^}|]+?)(?:\|([^}]+))?\}\}/';
2296        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
2297        foreach ($matches as $match) {
2298            $imagePath = trim($match[1]);
2299            $alt = isset($match[2]) ? trim($match[2]) : '';
2300
2301            // Handle external URLs
2302            if (preg_match('/^https?:\/\//', $imagePath)) {
2303                $imageHtml = '<img src="' . htmlspecialchars($imagePath) . '" alt="' . htmlspecialchars($alt) . '" class="event-image" />';
2304            } else {
2305                // Handle internal DokuWiki images
2306                $imageUrl = DOKU_BASE . 'lib/exe/fetch.php?media=' . rawurlencode($imagePath);
2307                $imageHtml = '<img src="' . $imageUrl . '" alt="' . htmlspecialchars($alt) . '" class="event-image" />';
2308            }
2309
2310            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2311            $tokens[$tokenIndex] = $imageHtml;
2312            $tokenIndex++;
2313            $rendered = str_replace($match[0], $token, $rendered);
2314        }
2315
2316        // Convert DokuWiki link syntax [[link|text]] to tokens
2317        $pattern = '/\[\[([^|\]]+?)(?:\|([^\]]+))?\]\]/';
2318        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
2319        foreach ($matches as $match) {
2320            $link = trim($match[1]);
2321            $text = isset($match[2]) ? trim($match[2]) : $link;
2322
2323            // Handle external URLs
2324            if (preg_match('/^https?:\/\//', $link)) {
2325                $linkHtml = '<a href="' . htmlspecialchars($link) . '" target="_blank" rel="noopener noreferrer"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
2326            } else {
2327                // Handle internal DokuWiki links with section anchors
2328                $parts = explode('#', $link, 2);
2329                $pagePart = $parts[0];
2330                $sectionPart = isset($parts[1]) ? '#' . $parts[1] : '';
2331
2332                $wikiUrl = DOKU_BASE . 'doku.php?id=' . rawurlencode($pagePart) . $sectionPart;
2333                $linkHtml = '<a href="' . $wikiUrl . '"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
2334            }
2335
2336            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2337            $tokens[$tokenIndex] = $linkHtml;
2338            $tokenIndex++;
2339            $rendered = str_replace($match[0], $token, $rendered);
2340        }
2341
2342        // Convert markdown-style links [text](url) to tokens
2343        $pattern = '/\[([^\]]+)\]\(([^)]+)\)/';
2344        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
2345        foreach ($matches as $match) {
2346            $text = trim($match[1]);
2347            $url = trim($match[2]);
2348
2349            if (preg_match('/^https?:\/\//', $url)) {
2350                $linkHtml = '<a href="' . htmlspecialchars($url) . '" target="_blank" rel="noopener noreferrer"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
2351            } else {
2352                $linkHtml = '<a href="' . htmlspecialchars($url) . '"' . $linkStyle . '>' . htmlspecialchars($text) . '</a>';
2353            }
2354
2355            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2356            $tokens[$tokenIndex] = $linkHtml;
2357            $tokenIndex++;
2358            $rendered = str_replace($match[0], $token, $rendered);
2359        }
2360
2361        // Convert plain URLs to tokens
2362        $pattern = '/(https?:\/\/[^\s<]+)/';
2363        preg_match_all($pattern, $rendered, $matches, PREG_SET_ORDER);
2364        foreach ($matches as $match) {
2365            $url = $match[1];
2366            $linkHtml = '<a href="' . htmlspecialchars($url) . '" target="_blank" rel="noopener noreferrer"' . $linkStyle . '>' . htmlspecialchars($url) . '</a>';
2367
2368            $token = "\x00TOKEN" . $tokenIndex . "\x00";
2369            $tokens[$tokenIndex] = $linkHtml;
2370            $tokenIndex++;
2371            $rendered = str_replace($match[0], $token, $rendered);
2372        }
2373
2374        // NOW escape HTML (tokens are protected)
2375        $rendered = htmlspecialchars($rendered);
2376
2377        // Convert newlines to <br>
2378        $rendered = nl2br($rendered);
2379
2380        // DokuWiki text formatting
2381        // Bold: **text** or __text__
2382        $boldStyle = '';
2383        $rendered = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $rendered);
2384        $rendered = preg_replace('/__(.+?)__/', '<strong>$1</strong>', $rendered);
2385
2386        // Italic: //text//
2387        $rendered = preg_replace('/\/\/(.+?)\/\//', '<em>$1</em>', $rendered);
2388
2389        // Strikethrough: <del>text</del>
2390        $rendered = preg_replace('/&lt;del&gt;(.+?)&lt;\/del&gt;/', '<del>$1</del>', $rendered);
2391
2392        // Monospace: ''text''
2393        $rendered = preg_replace('/&#039;&#039;(.+?)&#039;&#039;/', '<code>$1</code>', $rendered);
2394
2395        // Subscript: <sub>text</sub>
2396        $rendered = preg_replace('/&lt;sub&gt;(.+?)&lt;\/sub&gt;/', '<sub>$1</sub>', $rendered);
2397
2398        // Superscript: <sup>text</sup>
2399        $rendered = preg_replace('/&lt;sup&gt;(.+?)&lt;\/sup&gt;/', '<sup>$1</sup>', $rendered);
2400
2401        // Restore tokens
2402        foreach ($tokens as $i => $html) {
2403            $rendered = str_replace("\x00TOKEN" . $i . "\x00", $html, $rendered);
2404        }
2405
2406        return $rendered;
2407    }
2408
2409    private function loadEvents($namespace, $year, $month) {
2410        $dataDir = DOKU_INC . 'data/meta/';
2411        if ($namespace) {
2412            $dataDir .= str_replace(':', '/', $namespace) . '/';
2413        }
2414        $dataDir .= 'calendar/';
2415
2416        $eventFile = $dataDir . sprintf('%04d-%02d.json', $year, $month);
2417
2418        if (file_exists($eventFile)) {
2419            $json = file_get_contents($eventFile);
2420            return json_decode($json, true);
2421        }
2422
2423        return array();
2424    }
2425
2426    private function loadEventsMultiNamespace($namespaces, $year, $month) {
2427        // Check for wildcard pattern (namespace:*)
2428        if (preg_match('/^(.+):\*$/', $namespaces, $matches)) {
2429            $baseNamespace = $matches[1];
2430            return $this->loadEventsWildcard($baseNamespace, $year, $month);
2431        }
2432
2433        // Check for root wildcard (just *)
2434        if ($namespaces === '*') {
2435            return $this->loadEventsWildcard('', $year, $month);
2436        }
2437
2438        // Parse namespace list (semicolon separated)
2439        // e.g., "team:projects;personal;work:tasks" = three namespaces
2440        $namespaceList = array_map('trim', explode(';', $namespaces));
2441
2442        // Load events from all namespaces
2443        $allEvents = array();
2444        foreach ($namespaceList as $ns) {
2445            $ns = trim($ns);
2446            if (empty($ns)) continue;
2447
2448            $events = $this->loadEvents($ns, $year, $month);
2449
2450            // Add namespace tag to each event
2451            foreach ($events as $dateKey => $dayEvents) {
2452                if (!isset($allEvents[$dateKey])) {
2453                    $allEvents[$dateKey] = array();
2454                }
2455                foreach ($dayEvents as $event) {
2456                    $event['_namespace'] = $ns;
2457                    $allEvents[$dateKey][] = $event;
2458                }
2459            }
2460        }
2461
2462        return $allEvents;
2463    }
2464
2465    private function loadEventsWildcard($baseNamespace, $year, $month) {
2466        // Find all subdirectories under the base namespace
2467        $dataDir = DOKU_INC . 'data/meta/';
2468        if ($baseNamespace) {
2469            $dataDir .= str_replace(':', '/', $baseNamespace) . '/';
2470        }
2471
2472        $allEvents = array();
2473
2474        // First, load events from the base namespace itself
2475        if (empty($baseNamespace)) {
2476            // Root wildcard - load from root calendar
2477            $events = $this->loadEvents('', $year, $month);
2478            foreach ($events as $dateKey => $dayEvents) {
2479                if (!isset($allEvents[$dateKey])) {
2480                    $allEvents[$dateKey] = array();
2481                }
2482                foreach ($dayEvents as $event) {
2483                    $event['_namespace'] = '';
2484                    $allEvents[$dateKey][] = $event;
2485                }
2486            }
2487        } else {
2488            $events = $this->loadEvents($baseNamespace, $year, $month);
2489            foreach ($events as $dateKey => $dayEvents) {
2490                if (!isset($allEvents[$dateKey])) {
2491                    $allEvents[$dateKey] = array();
2492                }
2493                foreach ($dayEvents as $event) {
2494                    $event['_namespace'] = $baseNamespace;
2495                    $allEvents[$dateKey][] = $event;
2496                }
2497            }
2498        }
2499
2500        // Recursively find all subdirectories
2501        $this->findSubNamespaces($dataDir, $baseNamespace, $year, $month, $allEvents);
2502
2503        return $allEvents;
2504    }
2505
2506    private function findSubNamespaces($dir, $baseNamespace, $year, $month, &$allEvents) {
2507        if (!is_dir($dir)) return;
2508
2509        $items = scandir($dir);
2510        foreach ($items as $item) {
2511            if ($item === '.' || $item === '..') continue;
2512
2513            $path = $dir . $item;
2514            if (is_dir($path) && $item !== 'calendar') {
2515                // This is a namespace directory
2516                $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
2517
2518                // Load events from this namespace
2519                $events = $this->loadEvents($namespace, $year, $month);
2520                foreach ($events as $dateKey => $dayEvents) {
2521                    if (!isset($allEvents[$dateKey])) {
2522                        $allEvents[$dateKey] = array();
2523                    }
2524                    foreach ($dayEvents as $event) {
2525                        $event['_namespace'] = $namespace;
2526                        $allEvents[$dateKey][] = $event;
2527                    }
2528                }
2529
2530                // Recurse into subdirectories
2531                $this->findSubNamespaces($path . '/', $namespace, $year, $month, $allEvents);
2532            }
2533        }
2534    }
2535
2536    private function getAllNamespaces() {
2537        $dataDir = DOKU_INC . 'data/meta/';
2538        $namespaces = [];
2539
2540        // Scan for namespaces that have calendar data
2541        $this->scanForCalendarNamespaces($dataDir, '', $namespaces);
2542
2543        // Sort alphabetically
2544        sort($namespaces);
2545
2546        return $namespaces;
2547    }
2548
2549    private function scanForCalendarNamespaces($dir, $baseNamespace, &$namespaces) {
2550        if (!is_dir($dir)) return;
2551
2552        $items = scandir($dir);
2553        foreach ($items as $item) {
2554            if ($item === '.' || $item === '..') continue;
2555
2556            $path = $dir . $item;
2557            if (is_dir($path)) {
2558                // Check if this directory has a calendar subdirectory with data
2559                $calendarDir = $path . '/calendar/';
2560                if (is_dir($calendarDir)) {
2561                    // Check if there are any JSON files in the calendar directory
2562                    $jsonFiles = glob($calendarDir . '*.json');
2563                    if (!empty($jsonFiles)) {
2564                        // This namespace has calendar data
2565                        $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
2566                        $namespaces[] = $namespace;
2567                    }
2568                }
2569
2570                // Recurse into subdirectories
2571                $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
2572                $this->scanForCalendarNamespaces($path . '/', $namespace, $namespaces);
2573            }
2574        }
2575    }
2576
2577    /**
2578     * Render new sidebar widget - Week at a glance itinerary (200px wide)
2579     */
2580    private function renderSidebarWidget($events, $namespace, $calId, $themeOverride = null) {
2581        if (empty($events)) {
2582            return '<div style="width:200px; padding:12px; text-align:center; color:#999; font-size:11px;">No events this week</div>';
2583        }
2584
2585        // Get important namespaces from config
2586        $configFile = DOKU_PLUGIN . 'calendar/sync_config.php';
2587        $importantNsList = ['important']; // default
2588        if (file_exists($configFile)) {
2589            $config = include $configFile;
2590            if (isset($config['important_namespaces']) && !empty($config['important_namespaces'])) {
2591                $importantNsList = array_map('trim', explode(',', $config['important_namespaces']));
2592            }
2593        }
2594
2595        // Calculate date ranges
2596        $todayStr = date('Y-m-d');
2597        $tomorrowStr = date('Y-m-d', strtotime('+1 day'));
2598
2599        // Get week start preference and calculate week range
2600        $weekStartDay = $this->getWeekStartDay();
2601
2602        if ($weekStartDay === 'monday') {
2603            // Monday start
2604            $weekStart = date('Y-m-d', strtotime('monday this week'));
2605            $weekEnd = date('Y-m-d', strtotime('sunday this week'));
2606        } else {
2607            // Sunday start (default - US/Canada standard)
2608            $today = date('w'); // 0 (Sun) to 6 (Sat)
2609            if ($today == 0) {
2610                // Today is Sunday
2611                $weekStart = date('Y-m-d');
2612            } else {
2613                // Monday-Saturday: go back to last Sunday
2614                $weekStart = date('Y-m-d', strtotime('-' . $today . ' days'));
2615            }
2616            $weekEnd = date('Y-m-d', strtotime($weekStart . ' +6 days'));
2617        }
2618
2619        // Group events by category
2620        $todayEvents = [];
2621        $tomorrowEvents = [];
2622        $importantEvents = [];
2623        $weekEvents = []; // For week grid
2624
2625        // Process all events
2626        foreach ($events as $dateKey => $dayEvents) {
2627            // Detect conflicts for events on this day
2628            $eventsWithConflicts = $this->detectTimeConflicts($dayEvents);
2629
2630            foreach ($eventsWithConflicts as $event) {
2631                // Always categorize Today and Tomorrow regardless of week boundaries
2632                if ($dateKey === $todayStr) {
2633                    $todayEvents[] = array_merge($event, ['date' => $dateKey]);
2634                }
2635                if ($dateKey === $tomorrowStr) {
2636                    $tomorrowEvents[] = array_merge($event, ['date' => $dateKey]);
2637                }
2638
2639                // Process week grid events (only for current week)
2640                if ($dateKey >= $weekStart && $dateKey <= $weekEnd) {
2641                    // Initialize week grid day if not exists
2642                    if (!isset($weekEvents[$dateKey])) {
2643                        $weekEvents[$dateKey] = [];
2644                    }
2645
2646                    // Pre-render DokuWiki syntax to HTML for JavaScript display
2647                    $eventWithHtml = $event;
2648                    if (isset($event['title'])) {
2649                        $eventWithHtml['title_html'] = $this->renderDokuWikiToHtml($event['title']);
2650                    }
2651                    if (isset($event['description'])) {
2652                        $eventWithHtml['description_html'] = $this->renderDokuWikiToHtml($event['description']);
2653                    }
2654                    $weekEvents[$dateKey][] = $eventWithHtml;
2655                }
2656
2657                // Check if this is an important namespace
2658                $eventNs = isset($event['namespace']) ? $event['namespace'] : '';
2659                $isImportant = false;
2660                foreach ($importantNsList as $impNs) {
2661                    if ($eventNs === $impNs || strpos($eventNs, $impNs . ':') === 0) {
2662                        $isImportant = true;
2663                        break;
2664                    }
2665                }
2666
2667                // Important events: show from today through next 2 weeks
2668                if ($isImportant && $dateKey >= $todayStr) {
2669                    $importantEvents[] = array_merge($event, ['date' => $dateKey]);
2670                }
2671            }
2672        }
2673
2674        // Sort Important Events by date (earliest first)
2675        usort($importantEvents, function($a, $b) {
2676            $dateA = isset($a['date']) ? $a['date'] : '';
2677            $dateB = isset($b['date']) ? $b['date'] : '';
2678
2679            // Compare dates
2680            if ($dateA === $dateB) {
2681                // Same date - sort by time
2682                $timeA = isset($a['time']) ? $a['time'] : '';
2683                $timeB = isset($b['time']) ? $b['time'] : '';
2684
2685                if (empty($timeA) && !empty($timeB)) return 1;  // All-day events last
2686                if (!empty($timeA) && empty($timeB)) return -1;
2687                if (empty($timeA) && empty($timeB)) return 0;
2688
2689                // Both have times
2690                $aMinutes = $this->timeToMinutes($timeA);
2691                $bMinutes = $this->timeToMinutes($timeB);
2692                return $aMinutes - $bMinutes;
2693            }
2694
2695            return strcmp($dateA, $dateB);
2696        });
2697
2698        // Get theme - prefer override from syntax parameter, fall back to admin default
2699        $theme = !empty($themeOverride) ? $themeOverride : $this->getSidebarTheme();
2700        $themeStyles = $this->getSidebarThemeStyles($theme);
2701        $themeClass = 'sidebar-' . $theme;
2702
2703        // Start building HTML - Dynamic width with default font (overflow:visible for tooltips)
2704        $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;">';
2705
2706        // Inject CSS variables so the event dialog (shared component) picks up the theme
2707        $btnTextColor = ($theme === 'professional') ? '#fff' : $themeStyles['bg'];
2708        $html .= '<style>
2709        #sidebar-widget-' . $calId . ' {
2710            --background-site: ' . $themeStyles['bg'] . ';
2711            --background-alt: ' . $themeStyles['cell_bg'] . ';
2712            --background-header: ' . $themeStyles['header_bg'] . ';
2713            --text-primary: ' . $themeStyles['text_primary'] . ';
2714            --text-dim: ' . $themeStyles['text_dim'] . ';
2715            --text-bright: ' . $themeStyles['text_bright'] . ';
2716            --border-color: ' . $themeStyles['grid_border'] . ';
2717            --border-main: ' . $themeStyles['border'] . ';
2718            --cell-bg: ' . $themeStyles['cell_bg'] . ';
2719            --cell-today-bg: ' . $themeStyles['cell_today_bg'] . ';
2720            --shadow-color: ' . $themeStyles['shadow'] . ';
2721            --header-border: ' . $themeStyles['header_border'] . ';
2722            --header-shadow: ' . $themeStyles['header_shadow'] . ';
2723            --grid-bg: ' . $themeStyles['grid_bg'] . ';
2724            --btn-text: ' . $btnTextColor . ';
2725            --pastdue-color: ' . $themeStyles['pastdue_color'] . ';
2726            --pastdue-bg: ' . $themeStyles['pastdue_bg'] . ';
2727            --pastdue-bg-strong: ' . $themeStyles['pastdue_bg_strong'] . ';
2728            --pastdue-bg-light: ' . $themeStyles['pastdue_bg_light'] . ';
2729            --tomorrow-bg: ' . $themeStyles['tomorrow_bg'] . ';
2730            --tomorrow-bg-strong: ' . $themeStyles['tomorrow_bg_strong'] . ';
2731            --tomorrow-bg-light: ' . $themeStyles['tomorrow_bg_light'] . ';
2732        }
2733        </style>';
2734
2735        // Add sparkle effect for pink theme
2736        if ($theme === 'pink') {
2737            $html .= '<style>
2738            @keyframes sparkle-' . $calId . ' {
2739                0% {
2740                    opacity: 0;
2741                    transform: translate(0, 0) scale(0) rotate(0deg);
2742                }
2743                50% {
2744                    opacity: 1;
2745                    transform: translate(var(--tx), var(--ty)) scale(1) rotate(180deg);
2746                }
2747                100% {
2748                    opacity: 0;
2749                    transform: translate(calc(var(--tx) * 2), calc(var(--ty) * 2)) scale(0) rotate(360deg);
2750                }
2751            }
2752
2753            @keyframes pulse-glow-' . $calId . ' {
2754                0%, 100% { box-shadow: 0 0 10px rgba(255, 20, 147, 0.4); }
2755                50% { box-shadow: 0 0 25px rgba(255, 20, 147, 0.8), 0 0 40px rgba(255, 20, 147, 0.4); }
2756            }
2757
2758            @keyframes shimmer-' . $calId . ' {
2759                0% { background-position: -200% center; }
2760                100% { background-position: 200% center; }
2761            }
2762
2763            .sidebar-pink {
2764                animation: pulse-glow-' . $calId . ' 3s ease-in-out infinite;
2765            }
2766
2767            .sidebar-pink:hover {
2768                box-shadow: 0 0 30px rgba(255, 20, 147, 0.9), 0 0 50px rgba(255, 20, 147, 0.5) !important;
2769            }
2770
2771            .sparkle-' . $calId . ' {
2772                position: absolute;
2773                pointer-events: none;
2774                font-size: 20px;
2775                z-index: 1000;
2776                animation: sparkle-' . $calId . ' 1s ease-out forwards;
2777                filter: drop-shadow(0 0 3px rgba(255, 20, 147, 0.8));
2778            }
2779            </style>';
2780
2781            $html .= '<script>
2782            (function() {
2783                const container = document.getElementById("sidebar-widget-' . $calId . '");
2784                const sparkles = ["✨", "��", "��", "⭐", "��", "��", "��", "��", "��", "��"];
2785
2786                function createSparkle(x, y) {
2787                    const sparkle = document.createElement("div");
2788                    sparkle.className = "sparkle-' . $calId . '";
2789                    sparkle.textContent = sparkles[Math.floor(Math.random() * sparkles.length)];
2790                    sparkle.style.left = x + "px";
2791                    sparkle.style.top = y + "px";
2792
2793                    // Random direction
2794                    const angle = Math.random() * Math.PI * 2;
2795                    const distance = 30 + Math.random() * 40;
2796                    sparkle.style.setProperty("--tx", Math.cos(angle) * distance + "px");
2797                    sparkle.style.setProperty("--ty", Math.sin(angle) * distance + "px");
2798
2799                    container.appendChild(sparkle);
2800
2801                    setTimeout(() => sparkle.remove(), 1000);
2802                }
2803
2804                // Click sparkles
2805                container.addEventListener("click", function(e) {
2806                    const rect = container.getBoundingClientRect();
2807                    const x = e.clientX - rect.left;
2808                    const y = e.clientY - rect.top;
2809
2810                    // Create LOTS of sparkles for maximum bling!
2811                    for (let i = 0; i < 8; i++) {
2812                        setTimeout(() => {
2813                            const offsetX = x + (Math.random() - 0.5) * 30;
2814                            const offsetY = y + (Math.random() - 0.5) * 30;
2815                            createSparkle(offsetX, offsetY);
2816                        }, i * 40);
2817                    }
2818                });
2819
2820                // Random auto-sparkles for extra glamour
2821                setInterval(() => {
2822                    const x = Math.random() * container.offsetWidth;
2823                    const y = Math.random() * container.offsetHeight;
2824                    createSparkle(x, y);
2825                }, 3000);
2826            })();
2827            </script>';
2828        }
2829
2830        // Sanitize calId for use in JavaScript variable names (remove dashes)
2831        $jsCalId = str_replace('-', '_', $calId);
2832
2833        // CRITICAL: Add ALL JavaScript FIRST before any HTML that uses it
2834        $html .= '<script>
2835(function() {
2836    // Shared state for system stats and tooltips
2837    const sharedState_' . $jsCalId . ' = {
2838        latestStats: {
2839            load: {"1min": 0, "5min": 0, "15min": 0},
2840            uptime: "",
2841            memory_details: {},
2842            top_processes: []
2843        },
2844        cpuHistory: [],
2845        CPU_HISTORY_SIZE: 2
2846    };
2847
2848    // Tooltip functions - MUST be defined before HTML uses them
2849    window["showTooltip_' . $jsCalId . '"] = function(color) {
2850        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
2851        if (!tooltip) {
2852            console.log("Tooltip element not found for color:", color);
2853            return;
2854        }
2855
2856        const latestStats = sharedState_' . $jsCalId . '.latestStats;
2857        let content = "";
2858
2859        if (color === "green") {
2860            content = "<div class=\\"tooltip-title\\">CPU Load Average</div>";
2861            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
2862            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
2863            content += "<div>15 min: " + (latestStats.load["15min"] || "N/A") + "</div>";
2864            if (latestStats.uptime) {
2865                content += "<div style=\\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_bright'] . ';\\">Uptime: " + latestStats.uptime + "</div>";
2866            }
2867            tooltip.style.setProperty("border-color", "' . $themeStyles['text_bright'] . '", "important");
2868            tooltip.style.setProperty("color", "' . $themeStyles['text_bright'] . '", "important");
2869            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_bright'] . '", "important");
2870        } else if (color === "purple") {
2871            content = "<div class=\\"tooltip-title\\">CPU Load (Short-term)</div>";
2872            content += "<div>1 min: " + (latestStats.load["1min"] || "N/A") + "</div>";
2873            content += "<div>5 min: " + (latestStats.load["5min"] || "N/A") + "</div>";
2874            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
2875                content += "<div style=\\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['border'] . ';\\" class=\\"tooltip-title\\">Top Processes</div>";
2876                latestStats.top_processes.slice(0, 5).forEach(proc => {
2877                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
2878                });
2879            }
2880            tooltip.style.setProperty("border-color", "' . $themeStyles['border'] . '", "important");
2881            tooltip.style.setProperty("color", "' . $themeStyles['border'] . '", "important");
2882            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['border'] . '", "important");
2883        } else if (color === "orange") {
2884            content = "<div class=\\"tooltip-title\\">Memory Usage</div>";
2885            if (latestStats.memory_details && latestStats.memory_details.total) {
2886                content += "<div>Total: " + latestStats.memory_details.total + "</div>";
2887                content += "<div>Used: " + latestStats.memory_details.used + "</div>";
2888                content += "<div>Available: " + latestStats.memory_details.available + "</div>";
2889                if (latestStats.memory_details.cached) {
2890                    content += "<div>Cached: " + latestStats.memory_details.cached + "</div>";
2891                }
2892            } else {
2893                content += "<div>Loading...</div>";
2894            }
2895            if (latestStats.top_processes && latestStats.top_processes.length > 0) {
2896                content += "<div style=\\"margin-top:3px; padding-top:2px; border-top:1px solid ' . $themeStyles['text_primary'] . ';\\" class=\\"tooltip-title\\">Top Processes</div>";
2897                latestStats.top_processes.slice(0, 5).forEach(proc => {
2898                    content += "<div>" + proc.cpu + " " + proc.command + "</div>";
2899                });
2900            }
2901            tooltip.style.setProperty("border-color", "' . $themeStyles['text_primary'] . '", "important");
2902            tooltip.style.setProperty("color", "' . $themeStyles['text_primary'] . '", "important");
2903            tooltip.style.setProperty("-webkit-text-fill-color", "' . $themeStyles['text_primary'] . '", "important");
2904        }
2905
2906        tooltip.innerHTML = content;
2907        tooltip.style.setProperty("display", "block");
2908        tooltip.style.setProperty("background", "' . $themeStyles['bg'] . '", "important");
2909
2910        const bar = tooltip.parentElement;
2911        const barRect = bar.getBoundingClientRect();
2912        const tooltipRect = tooltip.getBoundingClientRect();
2913
2914        const left = barRect.left + (barRect.width / 2) - (tooltipRect.width / 2);
2915        const top = barRect.top - tooltipRect.height - 8;
2916
2917        tooltip.style.left = left + "px";
2918        tooltip.style.top = top + "px";
2919    };
2920
2921    window["hideTooltip_' . $jsCalId . '"] = function(color) {
2922        const tooltip = document.getElementById("tooltip-" + color + "-' . $calId . '");
2923        if (tooltip) {
2924            tooltip.style.display = "none";
2925        }
2926    };
2927
2928    // Update clock every second
2929    function updateClock() {
2930        const now = new Date();
2931        let hours = now.getHours();
2932        const minutes = String(now.getMinutes()).padStart(2, "0");
2933        const seconds = String(now.getSeconds()).padStart(2, "0");
2934        const ampm = hours >= 12 ? "PM" : "AM";
2935        hours = hours % 12 || 12;
2936        const timeStr = hours + ":" + minutes + ":" + seconds + " " + ampm;
2937        const clockEl = document.getElementById("clock-' . $calId . '");
2938        if (clockEl) clockEl.textContent = timeStr;
2939    }
2940    setInterval(updateClock, 1000);
2941
2942    // Weather - uses default location, click weather to get local
2943    var userLocationGranted = false;
2944    var userLat = 38.5816;  // Sacramento default
2945    var userLon = -121.4944;
2946
2947    function fetchWeatherData(lat, lon) {
2948        fetch("https://api.open-meteo.com/v1/forecast?latitude=" + lat + "&longitude=" + lon + "&current_weather=true&temperature_unit=fahrenheit")
2949            .then(response => response.json())
2950            .then(data => {
2951                if (data.current_weather) {
2952                    const temp = Math.round(data.current_weather.temperature);
2953                    const weatherCode = data.current_weather.weathercode;
2954                    const icon = getWeatherIcon(weatherCode);
2955                    const iconEl = document.getElementById("weather-icon-' . $calId . '");
2956                    const tempEl = document.getElementById("weather-temp-' . $calId . '");
2957                    if (iconEl) iconEl.textContent = icon;
2958                    if (tempEl) tempEl.innerHTML = temp + "&deg;";
2959                }
2960            })
2961            .catch(error => console.log("Weather fetch error:", error));
2962    }
2963
2964    function updateWeather() {
2965        fetchWeatherData(userLat, userLon);
2966    }
2967
2968    // Click weather icon to request local weather (user gesture required)
2969    function requestLocalWeather() {
2970        if (userLocationGranted) return;
2971        if ("geolocation" in navigator) {
2972            navigator.geolocation.getCurrentPosition(function(position) {
2973                userLat = position.coords.latitude;
2974                userLon = position.coords.longitude;
2975                userLocationGranted = true;
2976                fetchWeatherData(userLat, userLon);
2977            }, function(error) {
2978                console.log("Geolocation denied, using default location");
2979            });
2980        }
2981    }
2982
2983    setTimeout(function() {
2984        var weatherEl = document.querySelector("#weather-icon-' . $calId . '");
2985        if (weatherEl) {
2986            weatherEl.style.cursor = "pointer";
2987            weatherEl.title = "Click for local weather";
2988            weatherEl.addEventListener("click", requestLocalWeather);
2989        }
2990    }, 100);
2991
2992    function getWeatherIcon(code) {
2993        const icons = {
2994            0: "☀️", 1: "��️", 2: "⛅", 3: "☁️",
2995            45: "��️", 48: "��️", 51: "��️", 53: "��️", 55: "��️",
2996            61: "��️", 63: "��️", 65: "⛈️", 71: "��️", 73: "��️",
2997            75: "❄️", 77: "��️", 80: "��️", 81: "��️", 82: "⛈️",
2998            85: "��️", 86: "❄️", 95: "⛈️", 96: "⛈️", 99: "⛈️"
2999        };
3000        return icons[code] || "��️";
3001    }
3002
3003    // Update weather immediately and every 10 minutes
3004    updateWeather();
3005    setInterval(updateWeather, 600000);
3006
3007    // Update system stats and tooltips data
3008    function updateSystemStats() {
3009        fetch("' . DOKU_BASE . 'lib/plugins/calendar/get_system_stats.php")
3010            .then(response => response.json())
3011            .then(data => {
3012                sharedState_' . $jsCalId . '.latestStats = {
3013                    load: data.load || {"1min": 0, "5min": 0, "15min": 0},
3014                    uptime: data.uptime || "",
3015                    memory_details: data.memory_details || {},
3016                    top_processes: data.top_processes || []
3017                };
3018
3019                const greenBar = document.getElementById("cpu-5min-' . $calId . '");
3020                if (greenBar) {
3021                    greenBar.style.width = Math.min(100, data.cpu_5min) + "%";
3022                }
3023
3024                sharedState_' . $jsCalId . '.cpuHistory.push(data.cpu);
3025                if (sharedState_' . $jsCalId . '.cpuHistory.length > sharedState_' . $jsCalId . '.CPU_HISTORY_SIZE) {
3026                    sharedState_' . $jsCalId . '.cpuHistory.shift();
3027                }
3028
3029                const cpuAverage = sharedState_' . $jsCalId . '.cpuHistory.reduce((sum, val) => sum + val, 0) / sharedState_' . $jsCalId . '.cpuHistory.length;
3030
3031                const cpuBar = document.getElementById("cpu-realtime-' . $calId . '");
3032                if (cpuBar) {
3033                    cpuBar.style.width = Math.min(100, cpuAverage) + "%";
3034                }
3035
3036                const memBar = document.getElementById("mem-realtime-' . $calId . '");
3037                if (memBar) {
3038                    memBar.style.width = Math.min(100, data.memory) + "%";
3039                }
3040            })
3041            .catch(error => {
3042                console.log("System stats error:", error);
3043            });
3044    }
3045
3046    updateSystemStats();
3047    setInterval(updateSystemStats, 2000);
3048})();
3049</script>';
3050
3051        // NOW add the header HTML (after JavaScript is defined)
3052        $todayDate = new DateTime();
3053        $displayDate = $todayDate->format('D, M j, Y');
3054        $currentTime = $todayDate->format('g:i:s A');
3055
3056        $html .= '<div class="eventlist-today-header" style="background:' . $themeStyles['header_bg'] . '; border:2px solid ' . $themeStyles['header_border'] . '; box-shadow:' . $themeStyles['header_shadow'] . ';">';
3057        $html .= '<span class="eventlist-today-clock" id="clock-' . $calId . '" style="color:' . $themeStyles['text_bright'] . ';">' . $currentTime . '</span>';
3058        $html .= '<div class="eventlist-bottom-info">';
3059        $html .= '<span class="eventlist-weather"><span id="weather-icon-' . $calId . '">��️</span> <span id="weather-temp-' . $calId . '" style="color:' . $themeStyles['text_primary'] . ';">--°</span></span>';
3060        $html .= '<span class="eventlist-today-date" style="color:' . $themeStyles['text_dim'] . ';">' . $displayDate . '</span>';
3061        $html .= '</div>';
3062
3063        // Three CPU/Memory bars (all update live)
3064        $html .= '<div class="eventlist-stats-container">';
3065
3066        // 5-minute load average (green, updates every 2 seconds)
3067        $html .= '<div class="eventlist-cpu-bar" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $jsCalId . '(\'green\')" onmouseout="hideTooltip_' . $jsCalId . '(\'green\')">';
3068        $html .= '<div class="eventlist-cpu-fill" id="cpu-5min-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_bright'] . ' !important;"></div>';
3069        $html .= '<div class="system-tooltip" id="tooltip-green-' . $calId . '" style="display:none;"></div>';
3070        $html .= '</div>';
3071
3072        // Real-time CPU (purple, updates with 5-sec average)
3073        $html .= '<div class="eventlist-cpu-bar eventlist-cpu-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $jsCalId . '(\'purple\')" onmouseout="hideTooltip_' . $jsCalId . '(\'purple\')">';
3074        $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-purple" id="cpu-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['border'] . ' !important;"></div>';
3075        $html .= '<div class="system-tooltip" id="tooltip-purple-' . $calId . '" style="display:none;"></div>';
3076        $html .= '</div>';
3077
3078        // Real-time Memory (orange, updates)
3079        $html .= '<div class="eventlist-cpu-bar eventlist-mem-realtime" style="background:' . $themeStyles['cell_today_bg'] . ' !important;" onmouseover="showTooltip_' . $jsCalId . '(\'orange\')" onmouseout="hideTooltip_' . $jsCalId . '(\'orange\')">';
3080        $html .= '<div class="eventlist-cpu-fill eventlist-cpu-fill-orange" id="mem-realtime-' . $calId . '" style="width: 0%; background:' . $themeStyles['text_primary'] . ' !important;"></div>';
3081        $html .= '<div class="system-tooltip" id="tooltip-orange-' . $calId . '" style="display:none;"></div>';
3082        $html .= '</div>';
3083
3084        $html .= '</div>';
3085        $html .= '</div>';
3086
3087        // Get today's date for default event date
3088        $todayStr = date('Y-m-d');
3089
3090        // Thin "Add Event" bar between header and week grid - theme-aware colors
3091        $addBtnBg = $themeStyles['cell_today_bg'];
3092        $addBtnHover = $themeStyles['grid_bg'];
3093        $addBtnTextColor = ($theme === 'professional' || $theme === 'wiki') ?
3094                          $themeStyles['text_bright'] : $themeStyles['text_bright'];
3095        $addBtnShadow = ($theme === 'professional' || $theme === 'wiki') ?
3096                       '0 2px 4px rgba(0,0,0,0.2)' : '0 0 8px ' . $themeStyles['shadow'];
3097        $addBtnHoverShadow = ($theme === 'professional' || $theme === 'wiki') ?
3098                            '0 3px 6px rgba(0,0,0,0.3)' : '0 0 12px ' . $themeStyles['shadow'];
3099
3100        $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 . '\';">';
3101        $addBtnTextShadow = ($theme === 'pink') ? '0 0 3px ' . $addBtnTextColor : 'none';
3102        $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>';
3103        $html .= '</div>';
3104
3105        // Week grid (7 cells)
3106        $html .= $this->renderWeekGrid($weekEvents, $weekStart, $themeStyles, $theme);
3107
3108        // Section colors - derived from theme palette
3109        // Today: brightest accent, Tomorrow: primary accent, Important: dim/secondary accent
3110        if ($theme === 'matrix') {
3111            $todayColor = '#00ff00';     // Bright green
3112            $tomorrowColor = '#00cc07';  // Standard green
3113            $importantColor = '#00aa00'; // Dim green
3114        } else if ($theme === 'purple') {
3115            $todayColor = '#d4a5ff';     // Bright purple
3116            $tomorrowColor = '#9b59b6';  // Standard purple
3117            $importantColor = '#8e7ab8'; // Dim purple
3118        } else if ($theme === 'pink') {
3119            $todayColor = '#ff1493';     // Hot pink
3120            $tomorrowColor = '#ff69b4';  // Medium pink
3121            $importantColor = '#ff85c1'; // Light pink
3122        } else if ($theme === 'professional') {
3123            $todayColor = '#4a90e2';     // Blue accent
3124            $tomorrowColor = '#5ba3e6';  // Lighter blue
3125            $importantColor = '#7fb8ec'; // Lightest blue
3126        } else {
3127            // Wiki - section header backgrounds from template colors
3128            $todayColor = $themeStyles['text_bright'];      // __link__
3129            $tomorrowColor = $themeStyles['header_bg'];     // __background_alt__
3130            $importantColor = $themeStyles['header_border'];// __border__
3131        }
3132
3133        // Check if there are any itinerary items
3134        $hasItinerary = !empty($todayEvents) || !empty($tomorrowEvents) || !empty($importantEvents);
3135
3136        // Itinerary bar (collapsible toggle) - styled like +Add bar
3137        $itineraryBg = $themeStyles['cell_today_bg'];
3138        $itineraryHover = $themeStyles['grid_bg'];
3139        $itineraryTextColor = ($theme === 'professional' || $theme === 'wiki') ?
3140                              $themeStyles['text_bright'] : $themeStyles['text_bright'];
3141        $itineraryShadow = ($theme === 'professional' || $theme === 'wiki') ?
3142                           '0 2px 4px rgba(0,0,0,0.2)' : '0 0 8px ' . $themeStyles['shadow'];
3143        $itineraryHoverShadow = ($theme === 'professional' || $theme === 'wiki') ?
3144                                '0 3px 6px rgba(0,0,0,0.3)' : '0 0 12px ' . $themeStyles['shadow'];
3145        $itineraryTextShadow = ($theme === 'pink') ? '0 0 3px ' . $itineraryTextColor : 'none';
3146
3147        // Sanitize calId for JavaScript
3148        $jsCalId = str_replace('-', '_', $calId);
3149
3150        // Get itinerary default state from settings
3151        $itineraryDefaultCollapsed = $this->getItineraryCollapsed();
3152        $arrowDefaultStyle = $itineraryDefaultCollapsed ? 'transform:rotate(-90deg);' : '';
3153        $contentDefaultStyle = $itineraryDefaultCollapsed ? 'max-height:0px; opacity:0;' : '';
3154
3155        $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 . '\';">';
3156        $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>';
3157        $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>';
3158        $html .= '</div>';
3159
3160        // Itinerary content container (collapsible)
3161        $html .= '<div id="itinerary-content-' . $calId . '" style="transition:max-height 0.3s ease-out, opacity 0.2s ease-out; overflow:hidden; ' . $contentDefaultStyle . '">';
3162
3163        // Today section
3164        if (!empty($todayEvents)) {
3165            $html .= $this->renderSidebarSection('Today', $todayEvents, $todayColor, $calId, $themeStyles, $theme, $importantNsList);
3166        }
3167
3168        // Tomorrow section
3169        if (!empty($tomorrowEvents)) {
3170            $html .= $this->renderSidebarSection('Tomorrow', $tomorrowEvents, $tomorrowColor, $calId, $themeStyles, $theme, $importantNsList);
3171        }
3172
3173        // Important events section
3174        if (!empty($importantEvents)) {
3175            $html .= $this->renderSidebarSection('Important Events', $importantEvents, $importantColor, $calId, $themeStyles, $theme, $importantNsList);
3176        }
3177
3178        // Empty state if no itinerary items
3179        if (!$hasItinerary) {
3180            $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>';
3181        }
3182
3183        $html .= '</div>'; // Close itinerary-content
3184
3185        // Get itinerary default state from settings
3186        $itineraryDefaultCollapsed = $this->getItineraryCollapsed();
3187        $itineraryExpandedDefault = $itineraryDefaultCollapsed ? 'false' : 'true';
3188        $itineraryArrowDefault = $itineraryDefaultCollapsed ? 'rotate(-90deg)' : 'rotate(0deg)';
3189        $itineraryContentDefault = $itineraryDefaultCollapsed ? 'max-height:0px; opacity:0;' : 'max-height:none;';
3190
3191        // JavaScript for toggling itinerary
3192        $html .= '<script>
3193        (function() {
3194            let itineraryExpanded_' . $jsCalId . ' = ' . $itineraryExpandedDefault . ';
3195
3196            window.toggleItinerary_' . $jsCalId . ' = function() {
3197                const content = document.getElementById("itinerary-content-' . $calId . '");
3198                const arrow = document.getElementById("itinerary-arrow-' . $calId . '");
3199
3200                if (itineraryExpanded_' . $jsCalId . ') {
3201                    // Collapse
3202                    content.style.maxHeight = "0px";
3203                    content.style.opacity = "0";
3204                    arrow.style.transform = "rotate(-90deg)";
3205                    itineraryExpanded_' . $jsCalId . ' = false;
3206                } else {
3207                    // Expand
3208                    content.style.maxHeight = content.scrollHeight + "px";
3209                    content.style.opacity = "1";
3210                    arrow.style.transform = "rotate(0deg)";
3211                    itineraryExpanded_' . $jsCalId . ' = true;
3212
3213                    // After transition, set to auto for dynamic content
3214                    setTimeout(function() {
3215                        if (itineraryExpanded_' . $jsCalId . ') {
3216                            content.style.maxHeight = "none";
3217                        }
3218                    }, 300);
3219                }
3220            };
3221
3222            // Initialize based on default state
3223            const content = document.getElementById("itinerary-content-' . $calId . '");
3224            const arrow = document.getElementById("itinerary-arrow-' . $calId . '");
3225            if (content && arrow) {
3226                if (' . $itineraryExpandedDefault . ') {
3227                    content.style.maxHeight = "none";
3228                    arrow.style.transform = "rotate(0deg)";
3229                } else {
3230                    content.style.maxHeight = "0px";
3231                    content.style.opacity = "0";
3232                    arrow.style.transform = "rotate(-90deg)";
3233                }
3234            }
3235        })();
3236        </script>';
3237
3238        $html .= '</div>';
3239
3240        // Add event dialog for sidebar widget
3241        $html .= $this->renderEventDialog($calId, $namespace, $theme);
3242
3243        // Add JavaScript for positioning data-tooltip elements
3244        $html .= '<script>
3245        // Position data-tooltip elements to prevent cutoff (up and to the LEFT)
3246        document.addEventListener("DOMContentLoaded", function() {
3247            const tooltipElements = document.querySelectorAll("[data-tooltip]");
3248            const isPinkTheme = document.querySelector(".sidebar-pink") !== null;
3249
3250            tooltipElements.forEach(function(element) {
3251                element.addEventListener("mouseenter", function() {
3252                    const rect = element.getBoundingClientRect();
3253                    const style = window.getComputedStyle(element, ":before");
3254
3255                    // Position above the element, aligned to LEFT (not right)
3256                    element.style.setProperty("--tooltip-left", (rect.left - 150) + "px");
3257                    element.style.setProperty("--tooltip-top", (rect.top - 30) + "px");
3258
3259                    // Pink theme: position heart to the right of tooltip
3260                    if (isPinkTheme) {
3261                        element.style.setProperty("--heart-left", (rect.left - 150 + 210) + "px");
3262                        element.style.setProperty("--heart-top", (rect.top - 30) + "px");
3263                    }
3264                });
3265            });
3266        });
3267
3268        // Apply custom properties to position tooltips
3269        const style = document.createElement("style");
3270        style.textContent = `
3271            [data-tooltip]:hover:before {
3272                left: var(--tooltip-left, 0) !important;
3273                top: var(--tooltip-top, 0) !important;
3274            }
3275            .sidebar-pink [data-tooltip]:hover:after {
3276                left: var(--heart-left, 0) !important;
3277                top: var(--heart-top, 0) !important;
3278            }
3279        `;
3280        document.head.appendChild(style);
3281        </script>';
3282
3283        return $html;
3284    }
3285
3286    /**
3287     * Render compact week grid (7 cells with event bars) - Theme-aware
3288     */
3289    private function renderWeekGrid($weekEvents, $weekStart, $themeStyles, $theme) {
3290        // Generate unique ID for this calendar instance - sanitize for JavaScript
3291        $calId = 'cal_' . substr(md5($weekStart . microtime()), 0, 8);
3292        $jsCalId = str_replace('-', '_', $calId);  // Sanitize for JS variable names
3293
3294        $html = '<div style="display:grid; grid-template-columns:repeat(7, 1fr); gap:1px; background:' . $themeStyles['grid_bg'] . '; border-bottom:2px solid ' . $themeStyles['grid_border'] . ';">';
3295
3296        // Day names depend on week start setting
3297        $weekStartDay = $this->getWeekStartDay();
3298        if ($weekStartDay === 'monday') {
3299            $dayNames = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];  // Monday to Sunday
3300        } else {
3301            $dayNames = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];  // Sunday to Saturday
3302        }
3303        $today = date('Y-m-d');
3304
3305        for ($i = 0; $i < 7; $i++) {
3306            $date = date('Y-m-d', strtotime($weekStart . ' +' . $i . ' days'));
3307            $dayNum = date('j', strtotime($date));
3308            $isToday = $date === $today;
3309
3310            $events = isset($weekEvents[$date]) ? $weekEvents[$date] : [];
3311            $eventCount = count($events);
3312
3313            $bgColor = $isToday ? $themeStyles['cell_today_bg'] : $themeStyles['cell_bg'];
3314            $textColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
3315            $fontWeight = $isToday ? '700' : '500';
3316
3317            // Theme-aware text shadow
3318            if ($theme === 'pink') {
3319                $glowColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
3320                $textShadow = $isToday ? 'text-shadow:0 0 3px ' . $glowColor . ';' : 'text-shadow:0 0 2px ' . $glowColor . ';';
3321            } else if ($theme === 'matrix') {
3322                $glowColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
3323                $textShadow = $isToday ? 'text-shadow:0 0 2px ' . $glowColor . ';' : 'text-shadow:0 0 1px ' . $glowColor . ';';
3324            } else if ($theme === 'purple') {
3325                $glowColor = $isToday ? $themeStyles['text_bright'] : $themeStyles['text_primary'];
3326                $textShadow = $isToday ? 'text-shadow:0 0 2px ' . $glowColor . ';' : 'text-shadow:0 0 1px ' . $glowColor . ';';
3327            } else {
3328                $textShadow = '';  // No glow for professional/wiki
3329            }
3330
3331            // Border color based on theme
3332            $borderColor = $themeStyles['grid_border'];
3333
3334            $hasEvents = $eventCount > 0;
3335            $clickableStyle = $hasEvents ? 'cursor:pointer;' : '';
3336            $clickHandler = $hasEvents ? ' onclick="showDayEvents_' . $jsCalId . '(\'' . $date . '\')"' : '';
3337
3338            $html .= '<div style="background:' . $bgColor . '; padding:4px 2px; text-align:center; min-height:45px; position:relative; border:1px solid ' . $borderColor . ' !important; ' . $clickableStyle . '" ' . $clickHandler . '>';
3339
3340            // Day letter - theme color
3341            $dayLetterColor = $theme === 'professional' ? '#7f8c8d' : $themeStyles['text_primary'];
3342            $html .= '<div style="font-size:9px; color:' . $dayLetterColor . '; font-weight:500; font-family:system-ui, sans-serif;">' . $dayNames[$i] . '</div>';
3343
3344            // Day number
3345            $html .= '<div style="font-size:12px; color:' . $textColor . '; font-weight:' . $fontWeight . '; margin:2px 0; font-family:system-ui, sans-serif; ' . $textShadow . '">' . $dayNum . '</div>';
3346
3347            // Event bars (max 4 visible) with theme-aware glow
3348            if ($eventCount > 0) {
3349                $showCount = min($eventCount, 4);
3350                for ($j = 0; $j < $showCount; $j++) {
3351                    $event = $events[$j];
3352                    $color = isset($event['color']) ? $event['color'] : $themeStyles['text_primary'];
3353                    $barShadow = $theme === 'professional' ? '0 1px 2px rgba(0,0,0,0.2)' : '0 0 3px ' . htmlspecialchars($color);
3354                    $html .= '<div style="height:2px; background:' . htmlspecialchars($color) . '; margin:1px 0; border-radius:1px; box-shadow:' . $barShadow . ';"></div>';
3355                }
3356
3357                // Show "+N more" if more than 4 - theme color
3358                if ($eventCount > 4) {
3359                    $moreTextColor = $theme === 'professional' ? '#7f8c8d' : $themeStyles['text_primary'];
3360                    $html .= '<div style="font-size:7px; color:' . $moreTextColor . '; margin-top:1px; font-family:system-ui, sans-serif;">+' . ($eventCount - 4) . '</div>';
3361                }
3362            }
3363
3364            $html .= '</div>';
3365        }
3366
3367        $html .= '</div>';
3368
3369        // Add container for selected day events display (with unique ID) - theme-aware
3370        $panelBorderColor = $themeStyles['border'];
3371        $panelHeaderBg = $themeStyles['border'];
3372        $panelShadow = ($theme === 'professional' || $theme === 'wiki') ?
3373                      '0 1px 3px rgba(0, 0, 0, 0.1)' :
3374                      '0 0 5px ' . $themeStyles['shadow'];
3375        $panelContentBg = ($theme === 'professional') ? 'rgba(255, 255, 255, 0.95)' :
3376                         ($theme === 'wiki' ? $themeStyles['cell_bg'] : 'rgba(36, 36, 36, 0.5)');
3377        $panelHeaderShadow = ($theme === 'professional' || $theme === 'wiki') ? '0 2px 4px rgba(0, 0, 0, 0.15)' : '0 0 8px ' . $panelHeaderBg;
3378
3379        // Header text color - dark bg text for dark themes, white for light theme accent headers
3380        $panelHeaderColor = ($theme === 'matrix' || $theme === 'purple' || $theme === 'pink') ? $themeStyles['bg'] :
3381                            (($theme === 'wiki') ? $themeStyles['text_primary'] : '#fff');
3382
3383        $html .= '<div id="selected-day-events-' . $calId . '" style="display:none; margin:8px 4px; border-left:3px solid ' . $panelBorderColor . ($theme === 'wiki' ? '' : ' !important') . '; box-shadow:' . $panelShadow . ';">';
3384        if ($theme === 'wiki') {
3385            $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;">';
3386            $html .= '<span id="selected-day-title-' . $calId . '"></span>';
3387            $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>';
3388        } else {
3389            $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;">';
3390            $html .= '<span id="selected-day-title-' . $calId . '"></span>';
3391            $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>';
3392        }
3393        $html .= '</div>';
3394        $html .= '<div id="selected-day-content-' . $calId . '" style="padding:4px 0; background:' . $panelContentBg . ';"></div>';
3395        $html .= '</div>';
3396
3397        // Add JavaScript for day selection with event data
3398        $html .= '<script>';
3399        // Sanitize calId for JavaScript variable names
3400        $jsCalId = str_replace('-', '_', $calId);
3401        $html .= 'window.weekEventsData_' . $jsCalId . ' = ' . json_encode($weekEvents) . ';';
3402
3403        // Pass theme colors to JavaScript
3404        $jsThemeColors = json_encode([
3405            'text_primary' => $themeStyles['text_primary'],
3406            'text_bright' => $themeStyles['text_bright'],
3407            'text_dim' => $themeStyles['text_dim'],
3408            'text_shadow' => ($theme === 'pink') ? 'text-shadow:0 0 2px ' . $themeStyles['text_primary'] :
3409                             ((in_array($theme, ['matrix', 'purple'])) ? 'text-shadow:0 0 1px ' . $themeStyles['text_primary'] : ''),
3410            'event_bg' => $theme === 'professional' ? 'rgba(255, 255, 255, 0.5)' :
3411                         ($theme === 'wiki' ? $themeStyles['cell_bg'] : 'rgba(36, 36, 36, 0.3)'),
3412            'border_color' => $theme === 'professional' ? 'rgba(0, 0, 0, 0.1)' :
3413                             ($theme === 'purple' ? 'rgba(155, 89, 182, 0.2)' :
3414                             ($theme === 'pink' ? 'rgba(255, 20, 147, 0.3)' :
3415                             ($theme === 'wiki' ? $themeStyles['grid_border'] : 'rgba(0, 204, 7, 0.2)'))),
3416            'bar_shadow' => $theme === 'professional' ? '0 1px 2px rgba(0,0,0,0.2)' :
3417                           ($theme === 'wiki' ? '0 1px 2px rgba(0,0,0,0.15)' : '0 0 3px')
3418        ]);
3419        $html .= 'window.themeColors_' . $jsCalId . ' = ' . $jsThemeColors . ';';
3420        $html .= '
3421        window.showDayEvents_' . $jsCalId . ' = function(dateKey) {
3422            const eventsData = window.weekEventsData_' . $jsCalId . ';
3423            const container = document.getElementById("selected-day-events-' . $calId . '");
3424            const title = document.getElementById("selected-day-title-' . $calId . '");
3425            const content = document.getElementById("selected-day-content-' . $calId . '");
3426
3427            if (!eventsData[dateKey] || eventsData[dateKey].length === 0) return;
3428
3429            // Format date for display
3430            const dateObj = new Date(dateKey + "T00:00:00");
3431            const dayName = dateObj.toLocaleDateString("en-US", { weekday: "long" });
3432            const monthDay = dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric" });
3433            title.textContent = dayName + ", " + monthDay;
3434
3435            // Clear content
3436            content.innerHTML = "";
3437
3438            // Sort events by time (all-day events first, then timed events chronologically)
3439            const sortedEvents = [...eventsData[dateKey]].sort((a, b) => {
3440                // All-day events (no time) go to the beginning
3441                if (!a.time && !b.time) return 0;
3442                if (!a.time) return -1;  // a is all-day, comes first
3443                if (!b.time) return 1;   // b is all-day, comes first
3444
3445                // Compare times (format: "HH:MM")
3446                const timeA = a.time.split(":").map(Number);
3447                const timeB = b.time.split(":").map(Number);
3448                const minutesA = timeA[0] * 60 + timeA[1];
3449                const minutesB = timeB[0] * 60 + timeB[1];
3450
3451                return minutesA - minutesB;
3452            });
3453
3454            // Build events HTML with single color bar (event color only) - theme-aware
3455            const themeColors = window.themeColors_' . $jsCalId . ';
3456            sortedEvents.forEach(event => {
3457                const eventColor = event.color || themeColors.text_primary;
3458
3459                const eventDiv = document.createElement("div");
3460                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;";
3461
3462                let eventHTML = "";
3463
3464                // Event assigned color bar (single bar on left) - theme-aware shadow
3465                const barShadow = themeColors.bar_shadow + (themeColors.bar_shadow.includes("rgba") ? "" : " " + eventColor);
3466                eventHTML += "<div style=\\"width:3px; align-self:stretch; background:" + eventColor + "; border-radius:1px; flex-shrink:0; box-shadow:" + barShadow + ";\\"></div>";
3467
3468                // Content wrapper
3469                eventHTML += "<div style=\\"flex:1; min-width:0; display:flex; justify-content:space-between; align-items:start; gap:4px;\\">";
3470
3471                // Left side: event details
3472                eventHTML += "<div style=\\"flex:1; min-width:0;\\">";
3473                eventHTML += "<div style=\\"font-weight:600; color:" + themeColors.text_primary + "; word-wrap:break-word; font-family:system-ui, sans-serif; " + themeColors.text_shadow + ";\\">";
3474
3475                // Time
3476                if (event.time) {
3477                    const timeParts = event.time.split(":");
3478                    let hours = parseInt(timeParts[0]);
3479                    const minutes = timeParts[1];
3480                    const ampm = hours >= 12 ? "PM" : "AM";
3481                    hours = hours % 12 || 12;
3482                    eventHTML += "<span style=\\"color:" + themeColors.text_bright + "; font-weight:500; font-size:9px;\\">" + hours + ":" + minutes + " " + ampm + "</span> ";
3483                }
3484
3485                // Title - use HTML version if available
3486                const titleHTML = event.title_html || event.title || "Untitled";
3487                eventHTML += titleHTML;
3488                eventHTML += "</div>";
3489
3490                // Description if present - use HTML version - theme-aware color
3491                if (event.description_html || event.description) {
3492                    const descHTML = event.description_html || event.description;
3493                    eventHTML += "<div style=\\"font-size:9px; color:" + themeColors.text_dim + "; margin-top:2px;\\">" + descHTML + "</div>";
3494                }
3495
3496                eventHTML += "</div>"; // Close event details
3497
3498                // Right side: conflict badge with tooltip
3499                if (event.conflict) {
3500                    let conflictList = [];
3501                    if (event.conflictingWith && event.conflictingWith.length > 0) {
3502                        event.conflictingWith.forEach(conf => {
3503                            const confTime = conf.time + (conf.end_time ? " - " + conf.end_time : "");
3504                            conflictList.push(conf.title + " (" + confTime + ")");
3505                        });
3506                    }
3507                    const conflictData = btoa(unescape(encodeURIComponent(JSON.stringify(conflictList))));
3508                    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>";
3509                }
3510
3511                eventHTML += "</div>"; // Close content wrapper
3512
3513                eventDiv.innerHTML = eventHTML;
3514                content.appendChild(eventDiv);
3515            });
3516
3517            container.style.display = "block";
3518        };
3519        ';
3520        $html .= '</script>';
3521
3522        return $html;
3523    }
3524
3525    /**
3526     * Render a sidebar section (Today/Tomorrow/Important) - Matrix themed with colored borders
3527     */
3528    private function renderSidebarSection($title, $events, $accentColor, $calId, $themeStyles, $theme, $importantNsList = ['important']) {
3529        // Keep the original accent colors for borders
3530        $borderColor = $accentColor;
3531
3532        // Show date for Important Events section
3533        $showDate = ($title === 'Important Events');
3534
3535        // Sort events differently based on section
3536        if ($title === 'Important Events') {
3537            // Important Events: sort by date first, then by time
3538            usort($events, function($a, $b) {
3539                $aDate = isset($a['date']) ? $a['date'] : '';
3540                $bDate = isset($b['date']) ? $b['date'] : '';
3541
3542                // Different dates - sort by date
3543                if ($aDate !== $bDate) {
3544                    return strcmp($aDate, $bDate);
3545                }
3546
3547                // Same date - sort by time
3548                $aTime = isset($a['time']) && !empty($a['time']) ? $a['time'] : '';
3549                $bTime = isset($b['time']) && !empty($b['time']) ? $b['time'] : '';
3550
3551                // All-day events last within same date
3552                if (empty($aTime) && !empty($bTime)) return 1;
3553                if (!empty($aTime) && empty($bTime)) return -1;
3554                if (empty($aTime) && empty($bTime)) return 0;
3555
3556                // Both have times
3557                $aMinutes = $this->timeToMinutes($aTime);
3558                $bMinutes = $this->timeToMinutes($bTime);
3559                return $aMinutes - $bMinutes;
3560            });
3561        } else {
3562            // Today/Tomorrow: sort by time only (all same date)
3563            usort($events, function($a, $b) {
3564                $aTime = isset($a['time']) && !empty($a['time']) ? $a['time'] : '';
3565                $bTime = isset($b['time']) && !empty($b['time']) ? $b['time'] : '';
3566
3567                // All-day events (no time) come first
3568                if (empty($aTime) && !empty($bTime)) return -1;
3569                if (!empty($aTime) && empty($bTime)) return 1;
3570                if (empty($aTime) && empty($bTime)) return 0;
3571
3572                // Both have times - convert to minutes for proper chronological sort
3573                $aMinutes = $this->timeToMinutes($aTime);
3574                $bMinutes = $this->timeToMinutes($bTime);
3575
3576                return $aMinutes - $bMinutes;
3577            });
3578        }
3579
3580        // Theme-aware section shadow
3581        $sectionShadow = ($theme === 'professional' || $theme === 'wiki') ?
3582                        '0 1px 3px rgba(0, 0, 0, 0.1)' :
3583                        '0 0 5px ' . $themeStyles['shadow'];
3584
3585        if ($theme === 'wiki') {
3586            // Wiki theme: use a background div for the left bar instead of border-left
3587            // Dark Reader maps border colors differently from background colors, causing mismatch
3588            $html = '<div style="display:flex; margin:8px 4px; box-shadow:' . $sectionShadow . '; background:' . $themeStyles['bg'] . ';">';
3589            $html .= '<div style="width:3px; flex-shrink:0; background:' . $borderColor . ';"></div>';
3590            $html .= '<div style="flex:1; min-width:0;">';
3591        } else {
3592            $html = '<div style="border-left:3px solid ' . $borderColor . ' !important; margin:8px 4px; box-shadow:' . $sectionShadow . ';">';
3593        }
3594
3595        // Section header with accent color background - theme-aware
3596        $headerShadow = ($theme === 'professional' || $theme === 'wiki') ? '0 2px 4px rgba(0, 0, 0, 0.15)' : '0 0 8px ' . $accentColor;
3597        $headerTextColor = ($theme === 'matrix' || $theme === 'purple' || $theme === 'pink') ? $themeStyles['bg'] :
3598                           (($theme === 'wiki') ? $themeStyles['text_primary'] : '#fff');
3599        if ($theme === 'wiki') {
3600            // Wiki theme: no !important — let Dark Reader adjust these
3601            $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 . ';">';
3602        } else {
3603            // Dark themes + professional: lock colors against Dark Reader
3604            $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 . ';">';
3605        }
3606        $html .= htmlspecialchars($title);
3607        $html .= '</div>';
3608
3609        // Events - no background (transparent)
3610        $html .= '<div style="padding:4px 0;">';
3611
3612        foreach ($events as $event) {
3613            $html .= $this->renderSidebarEvent($event, $calId, $showDate, $accentColor, $themeStyles, $theme, $importantNsList);
3614        }
3615
3616        $html .= '</div>';
3617        $html .= '</div>';
3618        if ($theme === 'wiki') {
3619            $html .= '</div>'; // Close flex wrapper
3620        }
3621
3622        return $html;
3623    }
3624
3625    /**
3626     * Render individual event in sidebar - Theme-aware
3627     */
3628    private function renderSidebarEvent($event, $calId, $showDate = false, $sectionColor = '#00cc07', $themeStyles = null, $theme = 'matrix', $importantNsList = ['important']) {
3629        $title = isset($event['title']) ? htmlspecialchars($event['title']) : 'Untitled';
3630        $time = isset($event['time']) ? $event['time'] : '';
3631        $endTime = isset($event['endTime']) ? $event['endTime'] : '';
3632        $eventColor = isset($event['color']) ? htmlspecialchars($event['color']) : ($themeStyles ? $themeStyles['text_primary'] : '#00cc07');
3633        $date = isset($event['date']) ? $event['date'] : '';
3634        $isTask = isset($event['isTask']) && $event['isTask'];
3635        $completed = isset($event['completed']) && $event['completed'];
3636
3637        // Check if this is an important namespace event
3638        $eventNs = isset($event['namespace']) ? $event['namespace'] : '';
3639        $isImportantNs = false;
3640        foreach ($importantNsList as $impNs) {
3641            if ($eventNs === $impNs || strpos($eventNs, $impNs . ':') === 0) {
3642                $isImportantNs = true;
3643                break;
3644            }
3645        }
3646
3647        // Theme-aware colors
3648        $titleColor = $themeStyles ? $themeStyles['text_primary'] : '#00cc07';
3649        $timeColor = $themeStyles ? $themeStyles['text_bright'] : '#00dd00';
3650        $textShadow = ($theme === 'pink') ? 'text-shadow:0 0 2px ' . $titleColor . ';' :
3651                      ((in_array($theme, ['matrix', 'purple'])) ? 'text-shadow:0 0 1px ' . $titleColor . ';' : '');
3652
3653        // Check for conflicts (using 'conflict' field set by detectTimeConflicts)
3654        $hasConflict = isset($event['conflict']) && $event['conflict'];
3655        $conflictingWith = isset($event['conflictingWith']) ? $event['conflictingWith'] : [];
3656
3657        // Build conflict list for tooltip
3658        $conflictList = [];
3659        if ($hasConflict && !empty($conflictingWith)) {
3660            foreach ($conflictingWith as $conf) {
3661                $confTime = $this->formatTimeDisplay($conf['time'], isset($conf['end_time']) ? $conf['end_time'] : '');
3662                $conflictList[] = $conf['title'] . ' (' . $confTime . ')';
3663            }
3664        }
3665
3666        // No background on individual events (transparent) - unless important namespace
3667        // Use theme grid_border with slight opacity for subtle divider
3668        $borderColor = $themeStyles['grid_border'];
3669
3670        // Important namespace highlighting - subtle themed background
3671        $importantBg = '';
3672        $importantBorder = '';
3673        if ($isImportantNs) {
3674            // Theme-specific important highlighting
3675            switch ($theme) {
3676                case 'matrix':
3677                    $importantBg = 'background:rgba(0,204,7,0.08);';
3678                    $importantBorder = 'border-right:2px solid rgba(0,204,7,0.4);';
3679                    break;
3680                case 'purple':
3681                    $importantBg = 'background:rgba(156,39,176,0.08);';
3682                    $importantBorder = 'border-right:2px solid rgba(156,39,176,0.4);';
3683                    break;
3684                case 'pink':
3685                    $importantBg = 'background:rgba(255,105,180,0.1);';
3686                    $importantBorder = 'border-right:2px solid rgba(255,105,180,0.5);';
3687                    break;
3688                case 'professional':
3689                    $importantBg = 'background:rgba(33,150,243,0.08);';
3690                    $importantBorder = 'border-right:2px solid rgba(33,150,243,0.4);';
3691                    break;
3692                case 'wiki':
3693                    $importantBg = 'background:rgba(0,102,204,0.06);';
3694                    $importantBorder = 'border-right:2px solid rgba(0,102,204,0.3);';
3695                    break;
3696                default:
3697                    $importantBg = 'background:rgba(0,204,7,0.08);';
3698                    $importantBorder = 'border-right:2px solid rgba(0,204,7,0.4);';
3699            }
3700        }
3701
3702        $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 . '">';
3703
3704        // Event's assigned color bar (single bar on the left)
3705        $barShadow = ($theme === 'professional') ? '0 1px 2px rgba(0,0,0,0.2)' : '0 0 3px ' . $eventColor;
3706        $html .= '<div style="width:3px; align-self:stretch; background:' . $eventColor . '; border-radius:1px; flex-shrink:0; box-shadow:' . $barShadow . ';"></div>';
3707
3708        // Content
3709        $html .= '<div style="flex:1; min-width:0;">';
3710
3711        // Time + title
3712        $html .= '<div style="font-weight:600; color:' . $titleColor . '; word-wrap:break-word; font-family:system-ui, sans-serif; ' . $textShadow . '">';
3713
3714        if ($time) {
3715            $displayTime = $this->formatTimeDisplay($time, $endTime);
3716            $html .= '<span style="color:' . $timeColor . '; font-weight:500; font-size:9px;">' . htmlspecialchars($displayTime) . '</span> ';
3717        }
3718
3719        // Task checkbox
3720        if ($isTask) {
3721            $checkIcon = $completed ? '☑' : '☐';
3722            $checkColor = $themeStyles ? $themeStyles['text_bright'] : '#00ff00';
3723            $html .= '<span style="font-size:11px; color:' . $checkColor . ';">' . $checkIcon . '</span> ';
3724        }
3725
3726        // Important indicator icon for important namespace events
3727        if ($isImportantNs) {
3728            $html .= '<span style="font-size:9px;" title="Important">⭐</span> ';
3729        }
3730
3731        $html .= $title; // Already HTML-escaped on line 2625
3732
3733        // Conflict badge using same system as main calendar
3734        if ($hasConflict && !empty($conflictList)) {
3735            $conflictJson = base64_encode(json_encode($conflictList));
3736            $html .= ' <span class="event-conflict-badge" style="font-size:10px;" data-conflicts="' . $conflictJson . '" onmouseenter="showConflictTooltip(this)" onmouseleave="hideConflictTooltip()">⚠️ ' . count($conflictList) . '</span>';
3737        }
3738
3739        $html .= '</div>';
3740
3741        // Date display BELOW event name for Important events
3742        if ($showDate && $date) {
3743            $dateObj = new DateTime($date);
3744            $displayDate = $dateObj->format('D, M j'); // e.g., "Mon, Feb 10"
3745            $dateColor = $themeStyles ? $themeStyles['text_dim'] : '#00aa00';
3746            $dateShadow = ($theme === 'pink') ? 'text-shadow:0 0 2px ' . $dateColor . ';' :
3747                          ((in_array($theme, ['matrix', 'purple'])) ? 'text-shadow:0 0 1px ' . $dateColor . ';' : '');
3748            $html .= '<div style="font-size:8px; color:' . $dateColor . '; font-weight:500; margin-top:2px; ' . $dateShadow . '">' . htmlspecialchars($displayDate) . '</div>';
3749        }
3750
3751        $html .= '</div>';
3752        $html .= '</div>';
3753
3754        return $html;
3755    }
3756
3757    /**
3758     * Format time display (12-hour format with optional end time)
3759     */
3760    private function formatTimeDisplay($startTime, $endTime = '') {
3761        // Convert start time
3762        list($hour, $minute) = explode(':', $startTime);
3763        $hour = (int)$hour;
3764        $ampm = $hour >= 12 ? 'PM' : 'AM';
3765        $displayHour = $hour % 12;
3766        if ($displayHour === 0) $displayHour = 12;
3767
3768        $display = $displayHour . ':' . $minute . ' ' . $ampm;
3769
3770        // Add end time if provided
3771        if ($endTime && $endTime !== '') {
3772            list($endHour, $endMinute) = explode(':', $endTime);
3773            $endHour = (int)$endHour;
3774            $endAmpm = $endHour >= 12 ? 'PM' : 'AM';
3775            $endDisplayHour = $endHour % 12;
3776            if ($endDisplayHour === 0) $endDisplayHour = 12;
3777
3778            $display .= '-' . $endDisplayHour . ':' . $endMinute . ' ' . $endAmpm;
3779        }
3780
3781        return $display;
3782    }
3783
3784    /**
3785     * Detect time conflicts among events on the same day
3786     * Returns events array with 'conflict' flag and 'conflictingWith' array
3787     */
3788    private function detectTimeConflicts($dayEvents) {
3789        if (empty($dayEvents)) {
3790            return $dayEvents;
3791        }
3792
3793        // If only 1 event, no conflicts possible but still add the flag
3794        if (count($dayEvents) === 1) {
3795            return [array_merge($dayEvents[0], ['conflict' => false, 'conflictingWith' => []])];
3796        }
3797
3798        $eventsWithFlags = [];
3799
3800        foreach ($dayEvents as $i => $event) {
3801            $hasConflict = false;
3802            $conflictingWith = [];
3803
3804            // Skip all-day events (no time)
3805            if (empty($event['time'])) {
3806                $eventsWithFlags[] = array_merge($event, ['conflict' => false, 'conflictingWith' => []]);
3807                continue;
3808            }
3809
3810            // Get this event's time range
3811            $startTime = $event['time'];
3812            // Check both 'end_time' (snake_case) and 'endTime' (camelCase) for compatibility
3813            $endTime = '';
3814            if (isset($event['end_time']) && $event['end_time'] !== '') {
3815                $endTime = $event['end_time'];
3816            } elseif (isset($event['endTime']) && $event['endTime'] !== '') {
3817                $endTime = $event['endTime'];
3818            } else {
3819                // If no end time, use start time (zero duration) - matches main calendar logic
3820                $endTime = $startTime;
3821            }
3822
3823            // Check against all other events
3824            foreach ($dayEvents as $j => $otherEvent) {
3825                if ($i === $j) continue; // Skip self
3826                if (empty($otherEvent['time'])) continue; // Skip all-day events
3827
3828                $otherStart = $otherEvent['time'];
3829                // Check both field name formats
3830                $otherEnd = '';
3831                if (isset($otherEvent['end_time']) && $otherEvent['end_time'] !== '') {
3832                    $otherEnd = $otherEvent['end_time'];
3833                } elseif (isset($otherEvent['endTime']) && $otherEvent['endTime'] !== '') {
3834                    $otherEnd = $otherEvent['endTime'];
3835                } else {
3836                    $otherEnd = $otherStart;
3837                }
3838
3839                // Check for overlap: convert to minutes and compare
3840                $start1Min = $this->timeToMinutes($startTime);
3841                $end1Min = $this->timeToMinutes($endTime);
3842                $start2Min = $this->timeToMinutes($otherStart);
3843                $end2Min = $this->timeToMinutes($otherEnd);
3844
3845                // Overlap if: start1 < end2 AND start2 < end1
3846                // Note: Using < (not <=) so events that just touch at boundaries don't conflict
3847                // e.g., 1:00-2:00 and 2:00-3:00 are NOT in conflict
3848                if ($start1Min < $end2Min && $start2Min < $end1Min) {
3849                    $hasConflict = true;
3850                    $conflictingWith[] = [
3851                        'title' => isset($otherEvent['title']) ? $otherEvent['title'] : 'Untitled',
3852                        'time' => $otherStart,
3853                        'end_time' => $otherEnd
3854                    ];
3855                }
3856            }
3857
3858            $eventsWithFlags[] = array_merge($event, [
3859                'conflict' => $hasConflict,
3860                'conflictingWith' => $conflictingWith
3861            ]);
3862        }
3863
3864        return $eventsWithFlags;
3865    }
3866
3867    /**
3868     * Add hours to a time string
3869     */
3870    private function addHoursToTime($time, $hours) {
3871        $totalMinutes = $this->timeToMinutes($time) + ($hours * 60);
3872        $h = floor($totalMinutes / 60) % 24;
3873        $m = $totalMinutes % 60;
3874        return sprintf('%02d:%02d', $h, $m);
3875    }
3876
3877    /**
3878     * Render DokuWiki syntax to HTML
3879     * Converts **bold**, //italic//, [[links]], etc. to HTML
3880     */
3881    private function renderDokuWikiToHtml($text) {
3882        if (empty($text)) return '';
3883
3884        // Use DokuWiki's parser to render the text
3885        $instructions = p_get_instructions($text);
3886
3887        // Render instructions to XHTML
3888        $xhtml = p_render('xhtml', $instructions, $info);
3889
3890        // Remove surrounding <p> tags if present (we're rendering inline)
3891        $xhtml = preg_replace('/^<p>(.*)<\/p>$/s', '$1', trim($xhtml));
3892
3893        return $xhtml;
3894    }
3895
3896    // Keep old scanForNamespaces for backward compatibility (not used anymore)
3897    private function scanForNamespaces($dir, $baseNamespace, &$namespaces) {
3898        if (!is_dir($dir)) return;
3899
3900        $items = scandir($dir);
3901        foreach ($items as $item) {
3902            if ($item === '.' || $item === '..' || $item === 'calendar') continue;
3903
3904            $path = $dir . $item;
3905            if (is_dir($path)) {
3906                $namespace = $baseNamespace ? $baseNamespace . ':' . $item : $item;
3907                $namespaces[] = $namespace;
3908                $this->scanForNamespaces($path . '/', $namespace, $namespaces);
3909            }
3910        }
3911    }
3912
3913    /**
3914     * Get current sidebar theme
3915     */
3916    private function getSidebarTheme() {
3917        $configFile = DOKU_INC . 'data/meta/calendar_theme.txt';
3918        if (file_exists($configFile)) {
3919            $theme = trim(file_get_contents($configFile));
3920            if (in_array($theme, ['matrix', 'purple', 'professional', 'pink', 'wiki'])) {
3921                return $theme;
3922            }
3923        }
3924        return 'matrix'; // Default
3925    }
3926
3927    /**
3928     * Get colors from DokuWiki template's style.ini file
3929     */
3930    private function getWikiTemplateColors() {
3931        global $conf;
3932
3933        // Get current template name
3934        $template = $conf['template'];
3935
3936        // Try multiple possible locations for style.ini
3937        $possiblePaths = [
3938            DOKU_INC . 'conf/tpl/' . $template . '/style.ini',
3939            DOKU_INC . 'lib/tpl/' . $template . '/style.ini',
3940        ];
3941
3942        $styleIni = null;
3943        foreach ($possiblePaths as $path) {
3944            if (file_exists($path)) {
3945                $styleIni = parse_ini_file($path, true);
3946                break;
3947            }
3948        }
3949
3950        if (!$styleIni) {
3951            return null; // Fall back to CSS variables
3952        }
3953
3954        // Extract color replacements
3955        $replacements = isset($styleIni['replacements']) ? $styleIni['replacements'] : [];
3956
3957        // Map style.ini colors to our theme structure
3958        $bgSite = isset($replacements['__background_site__']) ? $replacements['__background_site__'] : '#f5f5f5';
3959        $background = isset($replacements['__background__']) ? $replacements['__background__'] : '#fff';
3960        $bgAlt = isset($replacements['__background_alt__']) ? $replacements['__background_alt__'] : '#e8e8e8';
3961        $bgNeu = isset($replacements['__background_neu__']) ? $replacements['__background_neu__'] : '#eee';
3962        $text = isset($replacements['__text__']) ? $replacements['__text__'] : '#333';
3963        $textAlt = isset($replacements['__text_alt__']) ? $replacements['__text_alt__'] : '#999';
3964        $textNeu = isset($replacements['__text_neu__']) ? $replacements['__text_neu__'] : '#666';
3965        $border = isset($replacements['__border__']) ? $replacements['__border__'] : '#ccc';
3966        $link = isset($replacements['__link__']) ? $replacements['__link__'] : '#2b73b7';
3967        $existing = isset($replacements['__existing__']) ? $replacements['__existing__'] : $link;
3968
3969        // Build theme colors from template colors
3970        // ============================================
3971        // DokuWiki style.ini → Calendar CSS Variable Mapping
3972        // ============================================
3973        //   style.ini key         → CSS variable          → Used for
3974        //   __background_site__   → --background-site     → Container, panel backgrounds
3975        //   __background__        → --cell-bg             → Cell/input backgrounds (typically white)
3976        //   __background_alt__    → --background-alt      → Hover states, header backgrounds
3977        //                         → --background-header
3978        //   __background_neu__    → --cell-today-bg       → Today cell highlight
3979        //   __text__              → --text-primary        → Primary text, labels, titles
3980        //   __text_neu__          → --text-dim            → Secondary text, dates, descriptions
3981        //   __text_alt__          → (not mapped)          → Available for future use
3982        //   __border__            → --border-color        → Grid lines, input borders
3983        //                         → --border-main         → Accent color: buttons, badges, active elements, section headers
3984        //                         → --header-border
3985        //   __link__              → --text-bright         → Links, accent text
3986        //   __existing__          → (fallback to __link__)→ Available for future use
3987        //
3988        // To customize: edit your template's conf/style.ini [replacements]
3989        return [
3990            'bg' => $bgSite,
3991            'border' => $border,         // Accent color from template border
3992            'shadow' => 'rgba(0, 0, 0, 0.1)',
3993            'header_bg' => $bgAlt,       // Headers use alt background
3994            'header_border' => $border,
3995            'header_shadow' => '0 2px 4px rgba(0, 0, 0, 0.1)',
3996            'text_primary' => $text,
3997            'text_bright' => $link,
3998            'text_dim' => $textNeu,
3999            'grid_bg' => $bgSite,
4000            'grid_border' => $border,
4001            'cell_bg' => $background,    // Cells use __background__ (white/light)
4002            'cell_today_bg' => $bgNeu,
4003            'bar_glow' => '0 1px 2px',
4004            'pastdue_color' => '#e74c3c',
4005            'pastdue_bg' => '#ffe6e6',
4006            'pastdue_bg_strong' => '#ffd9d9',
4007            'pastdue_bg_light' => '#fff2f2',
4008            'tomorrow_bg' => '#fff9e6',
4009            'tomorrow_bg_strong' => '#fff4cc',
4010            'tomorrow_bg_light' => '#fffbf0',
4011        ];
4012    }
4013
4014    /**
4015     * Get theme-specific color styles
4016     */
4017    private function getSidebarThemeStyles($theme) {
4018        // For wiki theme, try to read colors from template's style.ini
4019        if ($theme === 'wiki') {
4020            $wikiColors = $this->getWikiTemplateColors();
4021            if (!empty($wikiColors)) {
4022                return $wikiColors;
4023            }
4024            // Fall through to default wiki colors if reading fails
4025        }
4026
4027        $themes = [
4028            'matrix' => [
4029                'bg' => '#242424',
4030                'border' => '#00cc07',
4031                'shadow' => 'rgba(0, 204, 7, 0.3)',
4032                'header_bg' => 'linear-gradient(180deg, #2a2a2a 0%, #242424 100%)',
4033                'header_border' => '#00cc07',
4034                'header_shadow' => '0 2px 8px rgba(0, 204, 7, 0.3)',
4035                'text_primary' => '#00cc07',
4036                'text_bright' => '#00ff00',
4037                'text_dim' => '#00aa00',
4038                'grid_bg' => '#1a3d1a',
4039                'grid_border' => '#00cc07',
4040                'cell_bg' => '#242424',
4041                'cell_today_bg' => '#2a4d2a',
4042                'bar_glow' => '0 0 3px',
4043                'pastdue_color' => '#e74c3c',
4044                'pastdue_bg' => '#3d1a1a',
4045                'pastdue_bg_strong' => '#4d2020',
4046                'pastdue_bg_light' => '#2d1515',
4047                'tomorrow_bg' => '#3d3d1a',
4048                'tomorrow_bg_strong' => '#4d4d20',
4049                'tomorrow_bg_light' => '#2d2d15',
4050            ],
4051            'purple' => [
4052                'bg' => '#2a2030',
4053                'border' => '#9b59b6',
4054                'shadow' => 'rgba(155, 89, 182, 0.3)',
4055                'header_bg' => 'linear-gradient(180deg, #2f2438 0%, #2a2030 100%)',
4056                'header_border' => '#9b59b6',
4057                'header_shadow' => '0 2px 8px rgba(155, 89, 182, 0.3)',
4058                'text_primary' => '#b19cd9',
4059                'text_bright' => '#d4a5ff',
4060                'text_dim' => '#8e7ab8',
4061                'grid_bg' => '#3d2b4d',
4062                'grid_border' => '#9b59b6',
4063                'cell_bg' => '#2a2030',
4064                'cell_today_bg' => '#3d2b4d',
4065                'bar_glow' => '0 0 3px',
4066                'pastdue_color' => '#e74c3c',
4067                'pastdue_bg' => '#3d1a2a',
4068                'pastdue_bg_strong' => '#4d2035',
4069                'pastdue_bg_light' => '#2d1520',
4070                'tomorrow_bg' => '#3d3520',
4071                'tomorrow_bg_strong' => '#4d4028',
4072                'tomorrow_bg_light' => '#2d2a18',
4073            ],
4074            'professional' => [
4075                'bg' => '#f5f7fa',
4076                'border' => '#4a90e2',
4077                'shadow' => 'rgba(74, 144, 226, 0.2)',
4078                'header_bg' => 'linear-gradient(180deg, #ffffff 0%, #f5f7fa 100%)',
4079                'header_border' => '#4a90e2',
4080                'header_shadow' => '0 2px 4px rgba(0, 0, 0, 0.1)',
4081                'text_primary' => '#2c3e50',
4082                'text_bright' => '#4a90e2',
4083                'text_dim' => '#7f8c8d',
4084                'grid_bg' => '#e8ecf1',
4085                'grid_border' => '#d0d7de',
4086                'cell_bg' => '#ffffff',
4087                'cell_today_bg' => '#dce8f7',
4088                'bar_glow' => '0 1px 2px',
4089                'pastdue_color' => '#e74c3c',
4090                'pastdue_bg' => '#ffe6e6',
4091                'pastdue_bg_strong' => '#ffd9d9',
4092                'pastdue_bg_light' => '#fff2f2',
4093                'tomorrow_bg' => '#fff9e6',
4094                'tomorrow_bg_strong' => '#fff4cc',
4095                'tomorrow_bg_light' => '#fffbf0',
4096            ],
4097            'pink' => [
4098                'bg' => '#1a0d14',
4099                'border' => '#ff1493',
4100                'shadow' => 'rgba(255, 20, 147, 0.4)',
4101                'header_bg' => 'linear-gradient(180deg, #2d1a24 0%, #1a0d14 100%)',
4102                'header_border' => '#ff1493',
4103                'header_shadow' => '0 0 12px rgba(255, 20, 147, 0.6)',
4104                'text_primary' => '#ff69b4',
4105                'text_bright' => '#ff1493',
4106                'text_dim' => '#ff85c1',
4107                'grid_bg' => '#2d1a24',
4108                'grid_border' => '#ff1493',
4109                'cell_bg' => '#1a0d14',
4110                'cell_today_bg' => '#3d2030',
4111                'bar_glow' => '0 0 5px',
4112                'pastdue_color' => '#e74c3c',
4113                'pastdue_bg' => '#3d1520',
4114                'pastdue_bg_strong' => '#4d1a28',
4115                'pastdue_bg_light' => '#2d1018',
4116                'tomorrow_bg' => '#3d3020',
4117                'tomorrow_bg_strong' => '#4d3a28',
4118                'tomorrow_bg_light' => '#2d2518',
4119            ],
4120            'wiki' => [
4121                'bg' => '#f5f5f5',
4122                'border' => '#ccc',          // Template __border__ color
4123                'shadow' => 'rgba(0, 0, 0, 0.1)',
4124                'header_bg' => '#e8e8e8',
4125                'header_border' => '#ccc',
4126                'header_shadow' => '0 2px 4px rgba(0, 0, 0, 0.1)',
4127                'text_primary' => '#333',
4128                'text_bright' => '#2b73b7',  // Template __link__ color
4129                'text_dim' => '#666',
4130                'grid_bg' => '#f5f5f5',
4131                'grid_border' => '#ccc',
4132                'cell_bg' => '#fff',
4133                'cell_today_bg' => '#eee',
4134                'bar_glow' => '0 1px 2px',
4135                'pastdue_color' => '#e74c3c',
4136                'pastdue_bg' => '#ffe6e6',
4137                'pastdue_bg_strong' => '#ffd9d9',
4138                'pastdue_bg_light' => '#fff2f2',
4139                'tomorrow_bg' => '#fff9e6',
4140                'tomorrow_bg_strong' => '#fff4cc',
4141                'tomorrow_bg_light' => '#fffbf0',
4142            ],
4143        ];
4144
4145        return isset($themes[$theme]) ? $themes[$theme] : $themes['matrix'];
4146    }
4147
4148    /**
4149     * Get week start day preference
4150     */
4151    private function getWeekStartDay() {
4152        $configFile = DOKU_INC . 'data/meta/calendar_week_start.txt';
4153        if (file_exists($configFile)) {
4154            $start = trim(file_get_contents($configFile));
4155            if (in_array($start, ['monday', 'sunday'])) {
4156                return $start;
4157            }
4158        }
4159        return 'sunday'; // Default to Sunday (US/Canada standard)
4160    }
4161
4162    /**
4163     * Get itinerary collapsed default state
4164     */
4165    private function getItineraryCollapsed() {
4166        $configFile = DOKU_INC . 'data/meta/calendar_itinerary_collapsed.txt';
4167        if (file_exists($configFile)) {
4168            return trim(file_get_contents($configFile)) === 'yes';
4169        }
4170        return false; // Default to expanded
4171    }
4172}