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