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