<?php
require_once __DIR__ . '/includes/app.php';
handle_get_actions();
handle_post();
$page = $_GET['page'] ?? 'dashboard';
$user = current_user();
if (!$user && $page !== 'login') redirect_to('login');
if ($user && $page === 'login') redirect_to('dashboard');
$hubId = $user ? hub_id_for_user($user) : '';
$settings = $user ? settings_for($hubId) : default_settings();
$items = $user ? items_for($hubId) : [];
$listItems = $user ? list_items_for($hubId) : [];
$stats = $user ? stats_for($hubId) : [];
$activity = $user ? activity_for($hubId) : [];
$connections = $user ? connections_for($hubId) : [];
$shares = $user ? shares_for($hubId) : [];
$photos = $user ? photos_for($hubId) : [];

function nav_active(string $pageName, string $current): string { return $pageName === $current ? 'active' : ''; }
function page_title(string $page): string { return match($page){ 'calendar'=>'Family Calendar','todo'=>'Todo List','chores'=>'Chore Chart','meals'=>'Meal Planner','lists'=>'Lists Dashboard','rewards'=>'Rewards','history'=>'History','settings'=>'Settings','sync'=>'Calendar Sync','magic'=>'Magic Import + Sidekick','display'=>'Screensaver','workspaces'=>'Family Hubs','guardian'=>'Guardian Mode','profile'=>'Profile','admin'=>'Super Admin', default=>'Dashboard'}; }

function user_initials(string $name): string {
    $name = trim(preg_replace('/\s+/', ' ', $name));
    if ($name === '') return 'U';
    $parts = explode(' ', $name);
    $first = substr((string)($parts[0] ?? 'U'), 0, 1);
    $last = count($parts) > 1 ? substr((string)$parts[count($parts)-1], 0, 1) : '';
    return strtoupper($first . $last);
}
function family_status_label(array $user, array $activeWorkspace, ?array $membership): string {
    if (is_super_admin($user)) return 'Platform Super Admin';
    $status = ucfirst((string)($membership['status'] ?? 'active'));
    $workspaceStatus = ucfirst((string)($activeWorkspace['status'] ?? 'active'));
    return $status === 'Active' && $workspaceStatus === 'Active' ? 'Active family member' : $status . ' / ' . $workspaceStatus;
}

function render_item_card(array $item, string $returnPage, array $settings, bool $compact=false): void {
    $viewer = current_user() ?: [];
    $canComplete = can_complete_items($viewer);
    $canDelete = can_edit_items($viewer);
    $done = ($item['status'] ?? 'pending') === 'done';
    $member = $item['member'] ?? 'Family';
    $profile = profile_for_member($settings, $member); ?>
    <article class="item-card <?= $done ? 'is-done' : '' ?> <?= $compact ? 'compact' : '' ?>" data-type="<?= e($item['type'] ?? 'task') ?>" data-member="<?= e($member) ?>" data-status="<?= e($item['status'] ?? 'pending') ?>">
        <div class="item-main">
            <div class="item-badge" style="--member-color: <?= e($profile['color']) ?>"><span><?= e($profile['avatar']) ?></span><b><?= type_icon($item['type'] ?? 'task') ?></b></div>
            <div class="item-copy">
                <div class="item-title-row"><h3><?= e($item['title'] ?? '') ?></h3><span class="pill <?= $done ? 'pill-done' : '' ?>"><?= $done ? 'Done' : type_label($item['type'] ?? 'task') ?></span></div>
                <p class="muted small"><?= e(format_dt($item['start'] ?? '', 'Anytime')) ?><?= !empty($item['location']) ? ' • ' . e($item['location']) : '' ?> • <?= e($member) ?><?= !empty($item['meal_slot']) ? ' • ' . e($item['meal_slot']) : '' ?><?= !empty($item['repeat']) && ($item['repeat'] ?? 'none') !== 'none' ? ' • repeats ' . e($item['repeat']) : '' ?></p>
                <?php if(!$compact && !empty($item['notes'])): ?><p class="item-notes"><?= nl2br(e($item['notes'])) ?></p><?php endif; ?>
                <?php if(!$compact): ?><div class="mini-meta"><span>Reminder <?= (int)($item['reminder_minutes'] ?? 0) ?>m</span><span><?= e($item['sync_provider'] ?? 'HomeSync') ?> · <?= e($item['sync_mode'] ?? 'local') ?></span><?php if(!empty($item['invitees'])):?><span>Invitees: <?= e($item['invitees']) ?></span><?php endif; ?></div><?php endif; ?>
            </div>
        </div>
        <div class="item-actions">
            <?php if(!$done && ($item['type'] ?? '') !== 'event' && $canComplete): ?>
                <form method="post"><input type="hidden" name="action" value="complete_item"><input type="hidden" name="item_id" value="<?= e($item['id'] ?? '') ?>"><input type="hidden" name="return" value="<?= e($returnPage) ?>"><button class="btn success" type="submit">Done</button></form>
            <?php elseif(!$done && ($item['type'] ?? '') !== 'event'): ?>
                <span class="points-chip">Read only</span>
            <?php elseif(!$done): ?>
                <span class="points-chip">Event</span>
            <?php else: ?>
                <span class="points-chip">+<?= (int)($item['points'] ?? 0) ?> pts · <?= (int)($item['stars'] ?? 0) ?>★</span>
            <?php endif; ?>
            <?php if($canDelete): ?><form method="post" onsubmit="return confirm('Delete this item?')"><input type="hidden" name="action" value="delete_item"><input type="hidden" name="item_id" value="<?= e($item['id'] ?? '') ?>"><input type="hidden" name="return" value="<?= e($returnPage) ?>"><button class="icon-btn danger" type="submit" aria-label="Delete">×</button></form><?php endif; ?>
        </div>
    </article><?php
}
function render_list_item(array $item, string $returnPage): void { $done=($item['status'] ?? 'open')==='done'; $canEdit=can_edit_items(current_user()); ?>
    <article class="list-row <?= $done ? 'checked' : '' ?>" data-list-type="<?= e($item['list_type'] ?? 'todo') ?>"><?php if($canEdit): ?><form method="post" class="check-form"><input type="hidden" name="action" value="toggle_list_item"><input type="hidden" name="list_id" value="<?= e($item['id'] ?? '') ?>"><input type="hidden" name="return" value="<?= e($returnPage) ?>"><button type="submit" class="check-btn" aria-label="Toggle item"><?= $done?'✓':'' ?></button></form><?php else: ?><span class="check-btn readonly" aria-hidden="true"><?= $done?'✓':'' ?></span><?php endif; ?><div><strong><?= e($item['title'] ?? '') ?></strong><?php if(!empty($item['notes'])):?><p><?= e($item['notes']) ?></p><?php endif; ?></div><span class="pill"><?= e(ucfirst($item['list_type'] ?? 'todo')) ?></span><?php if($canEdit): ?><form method="post" onsubmit="return confirm('Delete this list item?')"><input type="hidden" name="action" value="delete_list_item"><input type="hidden" name="list_id" value="<?= e($item['id'] ?? '') ?>"><input type="hidden" name="return" value="<?= e($returnPage) ?>"><button class="icon-btn danger" type="submit" aria-label="Delete">×</button></form><?php endif; ?></article><?php }
function render_week_strip(array $items, string $selectedDate, string $page): void { ?><div class="week-strip" aria-label="Week selector"><?php foreach(week_dates($selectedDate) as $day): $date=$day->format('Y-m-d'); $count=count(items_on_date($items,$date)); ?><a class="day-pill <?= $date===$selectedDate?'active':'' ?>" href="index.php?page=<?= e($page) ?>&date=<?= e($date) ?>"><span><?= e($day->format('D')) ?></span><strong><?= e($day->format('d')) ?></strong><em><?= (int)$count ?></em></a><?php endforeach; ?></div><?php }
function render_meal_tabs(string $view): void { ?><div class="meal-tabs" role="navigation" aria-label="Meal Planner tabs"><a class="<?= $view==='lists'?'active':'' ?>" href="index.php?page=meals&meal_view=lists">Lists Dashboard</a><a class="<?= $view==='weekly'?'active':'' ?>" href="index.php?page=meals&meal_view=weekly">Weekly Meal Plan</a><a class="<?= $view==='library'?'active':'' ?>" href="index.php?page=meals&meal_view=library">Filipino Menu Library</a><a class="<?= $view==='add'?'active':'' ?>" href="index.php?page=meals&meal_view=add">Add New Menu</a><a class="<?= $view==='grocery'?'active':'' ?>" href="index.php?page=meals&meal_view=grocery">Grocery List</a><a class="<?= $view==='favorites'?'active':'' ?>" href="index.php?page=meals&meal_view=favorites">Favorite Meals</a></div><?php }
function render_menu_card(array $meal, string $view='library'): void { ?>
    <article class="menu-card">
        <img src="<?= e($meal['image'] ?? 'assets/meals/custom_meal.png') ?>" alt="<?= e($meal['title'] ?? 'Menu item') ?>" loading="lazy" width="220" height="120">
        <div class="menu-card-copy"><span class="pill"><?= e($meal['slot'] ?? 'Meal') ?></span><h3><?= e($meal['title'] ?? '') ?></h3><p><?= e($meal['category'] ?? 'Filipino Menu') ?></p><?php if(!empty($meal['ingredients'])): ?><small><?= e(implode(', ', array_slice($meal['ingredients'],0,5))) ?></small><?php endif; ?></div>
        <div class="menu-card-actions">
            <form method="post"><input type="hidden" name="action" value="toggle_menu_favorite"><input type="hidden" name="menu_id" value="<?= e($meal['id'] ?? '') ?>"><input type="hidden" name="meal_view" value="<?= e($view) ?>"><button class="chip-btn" type="submit"><?= !empty($meal['favorite']) ? '★ Favorite' : '☆ Add Favorite' ?></button></form>
            <?php if(!empty($meal['custom'])): ?><form method="post" onsubmit="return confirm('Delete this custom menu item?')"><input type="hidden" name="action" value="delete_menu_item"><input type="hidden" name="menu_id" value="<?= e($meal['id'] ?? '') ?>"><button class="icon-btn danger" type="submit" aria-label="Delete custom menu">×</button></form><?php endif; ?>
        </div>
    </article>
<?php }
function render_add_modal(array $settings,string $returnPage): void {
    if(!can_edit_items(current_user())): ?>
        <dialog id="addModal" class="modal small-modal">
            <div class="modal-card">
                <div class="modal-head">
                    <div><p class="eyebrow">Read-only role</p><h2>Add New is locked</h2></div>
                    <button type="button" class="icon-btn" onclick="window.addModal.close()">×</button>
                </div>
                <p class="muted">Your current role can view this family hub, but your Family Hub role controls whether you can add events, tasks, chores, meals, and list items.</p>
                <div class="modal-actions"><button type="button" class="btn primary" onclick="window.addModal.close()">Close</button></div>
            </div>
        </dialog>
    <?php return; endif; ?>
    <dialog id="addModal" class="modal add-item-modal">
        <form method="post" class="modal-card add-new-modal" data-add-new-form data-item-type="task">
            <input type="hidden" name="action" value="create_item">
            <input type="hidden" name="return" value="<?= e($returnPage) ?>">
            <div class="modal-head add-new-head">
                <div>
                    <p class="eyebrow">Add New</p>
                    <h2>Create family item</h2>
                    <p class="muted">Choose the item type first, then complete the grouped details below.</p>
                </div>
                <button type="button" class="icon-btn" onclick="window.addModal.close()" aria-label="Close add new modal">×</button>
            </div>

            <section class="add-type-grid type-grid" role="radiogroup" aria-label="Item type">
                <label class="add-type-card"><input type="radio" name="type" value="task" checked><span><i>✅</i><b>Task</b><small>Personal or shared</small></span></label>
                <label class="add-type-card"><input type="radio" name="type" value="chore"><span><i>🧹</i><b>Chore</b><small>Stars + rewards</small></span></label>
                <label class="add-type-card"><input type="radio" name="type" value="event"><span><i>📅</i><b>Event</b><small>Calendar schedule</small></span></label>
                <label class="add-type-card"><input type="radio" name="type" value="meal"><span><i>🍽️</i><b>Meal</b><small>Breakfast to snacks</small></span></label>
            </section>

            <div class="add-new-sections">
                <section class="add-section add-main-section">
                    <div class="add-section-title"><span>✨</span><div><h3>Main details</h3><p>Title, schedule, profile, category, and location.</p></div></div>
                    <label class="add-field add-field-wide">Title<input name="title" data-title-input placeholder="Example: Clean kitchen, Family dinner, Soccer practice" required></label>
                    <div class="form-grid two add-row">
                        <label class="add-field">Start<input name="start" type="datetime-local"></label>
                        <label class="add-field">End<input name="end" type="datetime-local"></label>
                    </div>
                    <div class="quick-time-row add-quick-row">
                        <button type="button" class="chip-btn" onclick="setQuickTime(15)">In 15 min</button>
                        <button type="button" class="chip-btn" onclick="setTodayEvening()">Today 7 PM</button>
                        <button type="button" class="chip-btn" onclick="setTomorrowMorning()">Tomorrow 9 AM</button>
                    </div>
                    <div class="form-grid three add-row">
                        <label class="add-field">Family profile<select name="member"><?php foreach(member_names($settings) as $member): ?><option value="<?= e($member) ?>"><?= e($member) ?></option><?php endforeach; ?></select></label>
                        <label class="add-field">Category<input name="category" data-category-input placeholder="Home, School, Meal, Fitness"></label>
                        <label class="add-field">Location<input name="location" placeholder="Home, school, address, kitchen, online"></label>
                    </div>
                </section>

                <section class="add-section add-schedule-section">
                    <div class="add-section-title"><span>🔔</span><div><h3>Schedule & rewards</h3><p>Reminder, repeat rule, points, stars, meal slot, and sync mode.</p></div></div>
                    <div class="form-grid two add-row">
                        <label class="add-field">Reminder<select name="reminder_minutes"><option value="0">No reminder</option><option value="5">5 minutes before</option><option value="15">15 minutes before</option><option value="30" <?= (int)($settings['reminder_minutes'] ?? 30) === 30 ? 'selected' : '' ?>>30 minutes before</option><option value="60">1 hour before</option><option value="1440">1 day before</option></select></label>
                        <label class="add-field">Repeats<select name="repeat"><option value="none">Does not repeat</option><option value="daily">Daily</option><option value="weekly">Weekly</option><option value="monthly">Monthly</option></select></label>
                    </div>
                    <div class="form-grid two add-row">
                        <label class="add-field" data-show-for="task chore meal">Points<input name="points" type="number" min="0" max="100" value="10"></label>
                        <label class="add-field" data-show-for="task chore meal">Stars<input name="stars" type="number" min="0" max="10" value="1"></label>
                    </div>
                    <div class="form-grid two add-row">
                        <label class="add-field" data-show-for="meal">Meal slot<select name="meal_slot"><option value="">Not a meal</option><option>Breakfast</option><option>Lunch</option><option>Dinner</option><option>Snacks</option></select></label>
                        <label class="add-field">Sync provider<select name="sync_provider"><option>HomeSync</option><option>Google-ready</option><option>iCloud-ready</option><option>Outlook one-way</option><option>Cozi one-way</option><option>Yahoo one-way</option></select></label>
                    </div>
                    <label class="add-field add-field-wide homework-proof-toggle" data-show-for="task"><input type="checkbox" name="proof_required" value="1"> Require proof upload before completion <small>Best for homework, worksheets, assignments, and school tasks.</small></label>
                    <label class="add-field add-field-wide">Sync mode<select name="sync_mode"><option value="local">Local only</option><option value="one-way">One-way</option><option value="two-way-ready">Two-way ready</option></select></label>
                </section>
            </div>

            <section class="add-section add-sharing-section">
                <div class="add-section-title"><span>👥</span><div><h3>Sharing & notes</h3><p>Invitees, visibility, notes, ingredients, and details.</p></div></div>
                <div class="form-grid two add-row">
                    <label class="add-field">Invitees / shared emails<input name="invitees" placeholder="Optional comma-separated emails"></label>
                    <label class="add-field">Visibility<select name="visibility"><option value="family">Shared with Family Hub</option><option value="private">Private to me</option><option value="parents">Parents/Admins only</option></select></label>
                </div>
                <label class="add-field add-field-wide">Notes, ingredients, or details<textarea name="notes" data-notes-input rows="4" placeholder="For meals, add ingredients line by line to build grocery ideas."></textarea></label>
            </section>

            <div class="modal-actions add-new-actions">
                <button type="button" class="btn ghost" onclick="window.addModal.close()">Cancel</button>
                <button class="btn primary" type="submit">Save family item</button>
            </div>
        </form>
    </dialog>
<?php }
function render_list_modal(string $returnPage): void { if(!can_edit_items(current_user())): ?><dialog id="listModal" class="modal small-modal"><div class="modal-card"><div class="modal-head"><div><p class="eyebrow">Read-only role</p><h2>Lists are locked</h2></div><button type="button" class="icon-btn" onclick="window.listModal.close()">×</button></div><p class="muted">Only Editor and above can add or update shared lists.</p></div></dialog><?php return; endif; ?><dialog id="listModal" class="modal small-modal"><form method="post" class="modal-card"><input type="hidden" name="action" value="create_list_item"><input type="hidden" name="return" value="<?= e($returnPage) ?>"><div class="modal-head"><div><p class="eyebrow">Quick List</p><h2>Add list item</h2></div><button type="button" class="icon-btn" onclick="window.listModal.close()">×</button></div><label>List<select name="list_type"><option value="grocery">Grocery</option><option value="todo">To-do</option><option value="errand">Errand</option><option value="reminder">Reminder</option></select></label><label>Item<input name="title" placeholder="Example: Eggs" required></label><label>Notes<input name="notes" placeholder="Optional"></label><button class="btn primary full" type="submit">Add item</button></form></dialog><?php }
function render_shell_start(string $page,array $settings,array $user): void {
    $activeWorkspaceId = hub_id_for_user($user);
    $activeWorkspace = workspace_by_id(read_store(), $activeWorkspaceId) ?: ['name'=>'Workspace','join_code'=>''];
    $workspaceOptions = accessible_workspaces_for_user($user);
    $currentMembership = current_membership_for_user($user, $activeWorkspaceId);
    $currentFamilyStatus = family_status_label($user, $activeWorkspace, $currentMembership);
    $currentRoleLevel = role_badge($user);
    $userInitials = user_initials((string)($user['name'] ?? 'User'));
    $canSwitchFamilyHub = count($workspaceOptions) > 1;
    $profilePhoto = user_profile_photo($user);
    $profileBgStyle = '';
    $profileBgClass = '';
    $notifyItems = notification_items_for($activeWorkspaceId, 8);
    $notifyCount = imminent_notification_count($notifyItems, (int)($settings['reminder_minutes'] ?? 30));
    $themeMode = in_array((string)($settings['theme'] ?? 'dark'), ['dark','light','auto'], true) ? (string)($settings['theme'] ?? 'dark') : 'dark';
    $initialTheme = $themeMode === 'light' ? 'light' : 'dark';
    ?><!doctype html>
<html lang="en" data-theme="<?= e($initialTheme) ?>" data-theme-mode="<?= e($themeMode) ?>" data-accent="<?= e($settings['accent'] ?? 'ocean') ?>" data-view="<?= e($settings['view_mode'] ?? 'auto') ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="theme-color" content="#0b1220" media="(prefers-color-scheme: dark)">
    <meta name="theme-color" content="#eef6fb" media="(prefers-color-scheme: light)">
    <meta name="color-scheme" content="dark light">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="HomeSyncHub">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="format-detection" content="telephone=no,date=no,address=no,email=no,url=no">
    <title><?= e(page_title($page)) ?> · <?= e(APP_NAME) ?></title>
    <link rel="manifest" href="manifest.json">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/icons/icon-180.png">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/icons/icon-32.png">
    <link rel="stylesheet" href="assets/css/app.css?v=9.8.0">
</head>
<body class="page-<?= e($page) ?>">
<div class="app-frame">
    <aside class="sidebar dashboard-ref-sidebar" aria-label="HomeSyncHub main navigation">
        <a class="brand brand-premium sidebar-ref-brand" href="index.php?page=dashboard">
            <img class="brand-mark-img" src="assets/brand/app-brand-mark.svg" width="160" height="160" alt="">
            <span><strong>HomeSyncHub</strong><em>Family Hub</em></span>
        </a>
        <nav class="nav sidebar-ref-nav">
            <a class="<?= nav_active('dashboard',$page) ?>" href="index.php?page=dashboard"><span>🏠</span> Dashboard</a>
            <a class="<?= nav_active('todo',$page) ?>" href="index.php?page=todo"><span>✅</span> Todo List</a>
            <a class="<?= nav_active('guardian',$page) ?>" href="index.php?page=guardian"><span>🛡️</span> Guardian Mode</a>
            <a class="<?= nav_active('calendar',$page) ?>" href="index.php?page=calendar"><span>🗓️</span> Calendar</a>
            <a class="<?= nav_active('meals',$page) ?>" href="index.php?page=meals"><span>🍽️</span> Meals</a>
            <?php if($page==='meals'): ?>
                <div class="nav-submenu" aria-label="Meal Planner navigation">
                    <a class="<?= ($_GET['meal_view'] ?? 'weekly')==='lists'?'active':'' ?>" href="index.php?page=meals&meal_view=lists">Lists Dashboard</a>
                    <a class="<?= ($_GET['meal_view'] ?? 'weekly')==='weekly'?'active':'' ?>" href="index.php?page=meals&meal_view=weekly">Weekly Meal Plan</a>
                    <a class="<?= ($_GET['meal_view'] ?? '')==='library'?'active':'' ?>" href="index.php?page=meals&meal_view=library">Filipino Menu Library</a>
                    <a class="<?= ($_GET['meal_view'] ?? '')==='add'?'active':'' ?>" href="index.php?page=meals&meal_view=add">Add New Menu</a>
                    <a class="<?= ($_GET['meal_view'] ?? '')==='grocery'?'active':'' ?>" href="index.php?page=meals&meal_view=grocery">Grocery List</a>
                    <a class="<?= ($_GET['meal_view'] ?? '')==='favorites'?'active':'' ?>" href="index.php?page=meals&meal_view=favorites">Favorite Meals</a>
                </div>
            <?php endif; ?>
            <?php if(can_manage_system($user)): ?><a class="<?= nav_active('admin',$page) ?>" href="index.php?page=admin"><span>🛡️</span> Super Admin</a><?php endif; ?>
            <a class="<?= nav_active('settings',$page) ?>" href="index.php?page=settings"><span>⚙️</span> Settings</a>
        </nav>
        <div class="sidebar-user-card">
            <div class="sidebar-user-avatar"><?php if($profilePhoto !== ''): ?><img src="<?= e($profilePhoto) ?>" alt=""><?php else: ?><?= e($userInitials) ?><?php endif; ?></div>
            <div><strong><?= e($user['name'] ?? 'User') ?></strong><span><?= e(role_badge($user)) ?></span></div>
        </div>
    </aside>
    <main class="main">
        <header class="topbar">
            <div class="top-title top-title-ref">
                <button class="sidebar-toggle-ref" type="button" aria-label="Toggle navigation">☰</button>
                <div><p class="eyebrow"><?= e($activeWorkspace['name'] ?? 'Workspace') ?></p><h1><?= e(page_title($page)) ?></h1></div>
            </div>
            <form method="get" action="index.php" class="global-search" role="search" aria-label="Search HomeSyncHub">
                <input type="hidden" name="page" value="todo">
                <span aria-hidden="true">🔎</span>
                <input name="q" type="search" placeholder="Search everything..." aria-label="Search everything">
                <kbd>Ctrl + K</kbd>
            </form>
            <div class="top-actions">
                <div class="notification-wrap">
                    <button class="notification-bell" id="notificationBell" type="button" aria-haspopup="true" aria-expanded="false" aria-controls="notificationPanel" data-due="<?= $notifyCount > 0 ? 'true' : 'false' ?>">
                        <span>🔔</span>
                        <?php if($notifyCount > 0): ?><b><?= (int)$notifyCount ?></b><?php endif; ?>
                    </button>
                    <div class="notification-panel" id="notificationPanel" hidden>
                        <div class="notification-head"><strong>Upcoming alerts</strong><small>30-minute reminder window</small></div>
                        <div class="notification-list">
                            <?php foreach($notifyItems as $item): ?>
                                <a class="notification-item" href="index.php?page=calendar&view=day&date=<?= e(item_date($item['start'] ?? '')) ?>">
                                    <span><?= type_icon($item['type'] ?? 'task') ?></span>
                                    <div><strong><?= e($item['title'] ?? 'Upcoming item') ?></strong><small><?= e(format_dt($item['start'] ?? '', 'Anytime')) ?> · alerts <?= (int)($item['reminder_minutes'] ?? ($settings['reminder_minutes'] ?? 30)) ?>m before · <?= e($item['member'] ?? 'Family') ?></small></div>
                                </a>
                            <?php endforeach; ?>
                            <?php if(!$notifyItems): ?><p class="empty small-empty">No upcoming timed items for the next 14 days.</p><?php endif; ?>
                        </div>
                    </div>
                </div>
                <form method="post" class="theme-toggle-form" data-theme-toggle-form>
                    <input type="hidden" name="action" value="toggle_theme">
                    <input type="hidden" name="return" value="<?= e($page) ?>">
                    <input type="hidden" name="theme_target" value="" data-theme-target>
                    <button class="theme-toggle-btn" type="submit" aria-label="Toggle light and dark mode" data-theme-toggle-button><?= $initialTheme === 'light' ? '🌙 Dark' : '☀️ Light' ?></button>
                </form>
                <form method="post" class="view-toggle-form">
                    <input type="hidden" name="action" value="toggle_view_mode">
                    <input type="hidden" name="return" value="<?= e($page) ?>">
                    <button class="view-toggle-btn" type="submit" aria-label="Switch mobile or desktop view">
                        <?= ($settings['view_mode'] ?? 'auto') === 'mobile' ? '🖥️ Desktop' : (($settings['view_mode'] ?? 'auto') === 'desktop' ? '📱 Auto' : '📱 Mobile') ?>
                    </button>
                </form>
                <button class="btn install-btn" id="installBtn" type="button" hidden>Install App</button>
                <div class="top-profile-wrap">
                    <button class="profile-top-btn profile-tab-btn" id="profileTopButton" type="button" aria-haspopup="true" aria-expanded="false" aria-controls="profileDropdownPanel">
                        <span class="profile-tab-avatar" aria-hidden="true"><?php if($profilePhoto !== ''): ?><img src="<?= e($profilePhoto) ?>" alt=""><?php else: ?><?= e($userInitials) ?><?php endif; ?></span>
                        <span class="profile-tab-label">Profile</span>
                        <span class="profile-tab-arrow" aria-hidden="true">▾</span>
                    </button>
                    <div class="profile-dropdown-panel compact-profile-menu" id="profileDropdownPanel" hidden>
                        <div class="profile-dropdown-card" aria-label="Active Family Hub profile summary">
                            <div class="family-profile-avatar compact-profile-avatar" aria-hidden="true"><?php if($profilePhoto !== ''): ?><img class="profile-avatar-img" src="<?= e($profilePhoto) ?>" alt=""><?php else: ?><?= e($userInitials) ?><?php endif; ?></div>
                            <div class="profile-dropdown-info">
                                <strong><?= e($user['name'] ?? 'User') ?></strong>
                                <span class="hub-status mini"><i></i><?= e($currentFamilyStatus) ?></span>
                            </div>
                        </div>
                        <form method="post" class="profile-dropdown-switch">
                            <input type="hidden" name="action" value="switch_workspace">
                            <input type="hidden" name="return" value="<?= e($page) ?>">
                            <select name="workspace_id" aria-label="Switch active family hub"><?php foreach($workspaceOptions as $ws): ?><option value="<?= e($ws['id']) ?>" <?= ($ws['id']??'')===$activeWorkspaceId?'selected':'' ?>><?= e($ws['name'] ?? 'Family Hub') ?></option><?php endforeach; ?></select>
                            <button class="hub-switch-btn" type="submit" <?= $canSwitchFamilyHub ? '' : 'disabled' ?>>Switch</button>
                        </form>
                        <div class="profile-dropdown-menu" role="menu" aria-label="Profile options">
                            <a class="profile-menu-item" role="menuitem" href="index.php?page=rewards">🏆 Rewards</a>
                            <a class="profile-menu-item" role="menuitem" href="index.php?page=guardian">🛡️ Guardian Mode</a>
                            <a class="profile-menu-item" role="menuitem" href="index.php?page=workspaces">👥 Family Hubs</a>
                            <a class="profile-menu-item" role="menuitem" href="index.php?page=sync">🔄 Sync</a>
                            <a class="profile-menu-item" role="menuitem" href="index.php?page=settings">⚙️ Account Settings</a>
                            <form method="post" class="profile-menu-form"><input type="hidden" name="action" value="logout"><button class="profile-menu-item danger" role="menuitem" type="submit">Logout</button></form>
                        </div>
                    </div>
                </div>
                <a class="score-card" href="index.php?page=rewards"><span><?= (int)($user['points'] ?? 0) ?></span><small>points</small></a>
                <?php if(can_edit_items($user)): ?><button class="btn primary add-button" onclick="window.addModal.showModal()">+ Add New</button><?php endif; ?>
            </div>
        </header>
        <?php foreach(flashes() as $flash): ?><div class="flash <?= e($flash['type'] ?? 'info') ?>"><?= e($flash['message'] ?? '') ?></div><?php endforeach; ?>
<?php }

function render_shell_end(array $settings,string $page): void {
    $user = current_user() ?: [];
    $displayName = (string)($user['name'] ?? 'there');
    ?><footer class="app-footer-brand standard-brand-frame" aria-label="HomeSyncHub footer branding"><picture><source media="(max-width: 760px)" srcset="assets/brand/home-sync-hub-footer-banner-default.png"><img src="assets/brand/home-sync-hub-footer-banner-default.png" width="1400" height="170" decoding="async" alt="HomeSyncHub powered and future-ready by JoshleenTech 2026"></picture></footer><?php render_add_modal($settings,$page); render_list_modal($page); ?></main></div><nav class="bottom-nav" aria-label="Mobile navigation"><a class="<?= nav_active('dashboard',$page) ?>" href="index.php?page=dashboard"><b>🏠</b><span>Home</span></a><a class="<?= nav_active('todo',$page) ?>" href="index.php?page=todo"><b>✅</b><span>Todo</span></a><a class="<?= nav_active('calendar',$page) ?>" href="index.php?page=calendar"><b>🗓️</b><span>Calendar</span></a><?php if(can_edit_items(current_user())): ?><button onclick="window.addModal.showModal()" aria-label="Add new"><b>＋</b><span>Add</span></button><?php else: ?><a href="index.php?page=dashboard" class="locked-add" aria-label="Read only"><b>🔒</b><span>View</span></a><?php endif; ?><a class="<?= nav_active('meals',$page) ?>" href="index.php?page=meals"><b>🍽️</b><span>Meals</span></a><a class="<?= nav_active('settings',$page)||nav_active('profile',$page)||nav_active('rewards',$page)||nav_active('workspaces',$page)||nav_active('sync',$page)||nav_active('guardian',$page)?'active':'' ?>" href="index.php?page=settings"><b>👤</b><span>Profile</span></a></nav>
<div class="joshleen-ai-float-wrap" id="joshleenAiWidget" aria-live="polite">
    <button class="joshleen-ai-launcher" id="joshleenAiLauncher" type="button" data-ai-toggle aria-controls="joshleenAiPanel" aria-expanded="false" aria-label="Open Joshleen AI assistant">
        <span class="launcher-robot" aria-hidden="true"><i></i><b></b></span>
        <strong>Joshleen AI</strong>
    </button>
    <section class="joshleen-ai-chatbox" id="joshleenAiPanel" role="dialog" aria-modal="false" aria-label="Joshleen AI chatbox" hidden>
        <header class="joshleen-chat-head">
            <div class="chat-robot-avatar" aria-hidden="true"><span></span></div>
            <div><h2>Joshleen AI</h2><p>AI Assistant · Online</p></div>
            <button class="chat-minimize-btn" type="button" data-ai-minimize aria-label="Minimize Joshleen AI">—</button>
            <button class="chat-close-btn" type="button" data-ai-close aria-label="Close Joshleen AI">×</button>
        </header>
        <div class="joshleen-chat-body" data-ai-messages>
            <article class="ai-msg bot"><span>🤖</span><p>Hi <?= e($displayName) ?>! I’m Joshleen AI. Ask me to create tasks, chores, calendar events, meal reminders, or to answer questions about your Family Hub.</p></article>
            <article class="ai-msg bot"><span>🛡️</span><p>I interpret your request, prepare a draft, and save only after you confirm. Missing details are clarified inside this chatbox.</p></article>
        </div>
        <div class="joshleen-chat-suggestions" aria-label="Suggested questions">
            <button type="button" data-ai-prompt="What is due in the next 30 minutes?">Due soon</button>
            <button type="button" data-ai-prompt="Create a task to call John tomorrow at 10 AM">Create Todo</button>
            <button type="button" data-ai-prompt="Plan dinner ideas for this week.">Meal ideas</button>
        </div>
        <form class="joshleen-chat-input" data-ai-form enctype="multipart/form-data">
            <input type="file" name="chat_files[]" accept="image/*,.pdf,.doc,.docx,.txt" multiple hidden data-ai-file-input>
            <button type="button" aria-label="Attach file or photo" data-ai-attach>📎</button>
            <input type="text" name="message" placeholder="Ask Joshleen AI..." autocomplete="off" aria-label="Ask Joshleen AI">
            <button type="button" aria-label="Use voice command" data-ai-voice>🎙️</button>
            <button class="ai-send-btn" type="submit" aria-label="Send message">➤</button>
            <div class="ai-attachment-preview" data-ai-attachment-preview hidden></div>
        </form>
        <p class="joshleen-chat-powered">Powered by Joshleen AI ✨</p>
    </section>
</div>
<script src="assets/js/app.js?v=9.8.0"></script></body></html><?php }


if ($page === 'login'):
    $registrationFamilyHubs = available_family_hubs_for_join(read_store(), null);
    $resetToken = (string)($_GET['reset_token'] ?? '');
    $showReset = $resetToken !== '';
    $show2fa = !empty($_SESSION['pending_2fa_user_id']);
    $recoveryOptions = $_SESSION['recovery_options'] ?? null;
    if (is_array($recoveryOptions)) {
        $recoveryExpires = parse_dt((string)($recoveryOptions['expires_at'] ?? ''));
        if (!$recoveryExpires || $recoveryExpires < app_now()) { unset($_SESSION['recovery_options']); $recoveryOptions = null; }
    } else { $recoveryOptions = null; }
?><!doctype html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
    <meta name="theme-color" content="#0b1220" media="(prefers-color-scheme: dark)">
    <meta name="theme-color" content="#eef6fb" media="(prefers-color-scheme: light)">
    <meta name="color-scheme" content="dark light">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="HomeSyncHub">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="format-detection" content="telephone=no,date=no,address=no,email=no,url=no">
    <title>HomeSyncHub Login</title>
    <link rel="manifest" href="manifest.json">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/icons/icon-180.png">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/icons/icon-32.png">
    <link rel="stylesheet" href="assets/css/app.css?v=9.8.0">
</head>
<body class="auth-body">
<section class="auth-shell">
    <div class="auth-hero family-schedule-hero">
        <div class="auth-photo-frame">
            <img src="assets/brand/family-schedule-commandcenter-integrated.png" width="1024" height="1536" decoding="async" alt="Your Family Schedule HomeSyncHub preview">
        </div>
    </div>
    <div class="auth-card">
        <button class="theme-toggle-btn auth-theme-toggle" type="button" data-local-theme-toggle aria-label="Toggle light and dark mode">☀️ Light</button>
        <?php foreach(flashes() as $flash): ?><div class="flash <?= e($flash['type'] ?? 'info') ?>"><?= e($flash['message'] ?? '') ?></div><?php endforeach; ?>
        <?php if($show2fa): ?>
            <p class="eyebrow">Two-factor authentication</p>
            <h1>Enter your authenticator code</h1>
            <p class="muted">Open Google Authenticator, Microsoft Authenticator, or a compatible TOTP app and enter the current 6-digit code.</p>
            <form method="post" class="auth-form active">
                <input type="hidden" name="action" value="verify_2fa">
                <label>Authenticator code<input name="totp_code" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" autocomplete="one-time-code" required></label>
                <button class="btn primary full" type="submit">Verify and Login</button>
            </form>
            <form method="post" class="auth-form"><input type="hidden" name="action" value="cancel_2fa"><button class="btn ghost full" type="submit">Cancel Login</button></form>
        <?php elseif($showReset): ?>
            <p class="eyebrow">Password recovery</p>
            <h1>Create a new password</h1>
            <form method="post" class="auth-form active">
                <input type="hidden" name="action" value="reset_password">
                <input type="hidden" name="reset_token" value="<?= e($resetToken) ?>">
                <label>New password<span class="auth-input-shell"><input name="password" type="password" minlength="8" autocomplete="new-password" required data-visibility-input data-visibility-kind="password"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                <label>Confirm password<span class="auth-input-shell"><input name="password_confirm" type="password" minlength="8" autocomplete="new-password" required data-visibility-input data-visibility-kind="password"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                <button class="btn primary full" type="submit">Reset Password</button>
            </form>
            <a class="btn ghost full" href="index.php?page=login">Back to login</a>
        <?php else: ?>
            <div class="tabbar"><button class="tab active" data-tab="login">Login</button><button class="tab" data-tab="register">Create Account</button><button class="tab" data-tab="recover">Recover</button></div>
            <form method="post" class="auth-form tab-panel active" data-panel="login" data-login-form>
                <input type="hidden" name="action" value="login">
                <label>Email / username<span class="auth-input-shell"><input name="email" type="email" autocomplete="username" required data-login-username data-visibility-input data-visibility-kind="mask"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                <label>Password<span class="auth-input-shell"><input name="password" type="password" autocomplete="current-password" required data-visibility-input data-visibility-kind="password"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                <label class="remember-credentials"><input type="checkbox" name="remember_credentials" value="1" data-remember-credentials> <span><b>Remember Credentials</b><small>Keep this device signed in automatically after the first successful login.</small></span></label>
                <button class="btn primary full" type="submit">Login</button>
                <button class="btn ghost full" type="button" data-tab="recover">Forgot password?</button>
            </form>
            <form method="post" class="auth-form tab-panel" data-panel="register" data-register-form>
                <input type="hidden" name="action" value="register">
                <input type="hidden" name="account_type" value="" data-account-type-input>
                <div class="register-role-choice register-role-modal" data-register-role-choice hidden role="dialog" aria-modal="true" aria-labelledby="accountTypePromptTitle">
                    <div class="register-role-backdrop" data-account-type-cancel></div>
                    <div class="register-role-dialog" role="document">
                        <p class="eyebrow">Account creation</p>
                        <h2 id="accountTypePromptTitle">Choose account type</h2>
                        <p class="muted small">Select whether this new account is for a parent/guardian or a child. After choosing, the correct Create Account form will open automatically.</p>
                        <div class="register-role-grid">
                            <button type="button" class="register-role-card" data-select-account-type="parent"><strong>Parent / Guardian</strong><span>Can create a Family Hub, manage family settings, and approve homework.</span></button>
                            <button type="button" class="register-role-card" data-select-account-type="child"><strong>Child</strong><span>Can join an existing Family Hub and submit homework for parent review.</span></button>
                        </div>
                        <button class="btn ghost full" type="button" data-account-type-cancel>Back to Login</button>
                    </div>
                </div>
                <div class="register-fields" data-register-fields hidden>
                    <div class="register-fields-head"><div><p class="eyebrow" data-account-type-eyebrow>Create account</p><h2 data-account-type-title>Create account</h2></div><button class="btn ghost compact" type="button" data-account-type-back>Change type</button></div>
                    <label>Name<input name="name" autocomplete="name" required></label>
                    <label>Email / username<span class="auth-input-shell"><input name="email" type="email" autocomplete="username" required data-visibility-input data-visibility-kind="mask"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                    <label>Password<span class="auth-input-shell"><input name="password" type="password" minlength="8" autocomplete="new-password" required data-visibility-input data-visibility-kind="password"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                    <div class="family-hub-choice-group" role="radiogroup" aria-label="Family Hub registration choice">
                        <label class="family-hub-choice" data-parent-account-option><input type="radio" name="family_hub_mode" value="create" checked data-family-hub-mode><span><b>Create Family Hub</b><small>Start a private family hub for your household.</small></span></label>
                        <label class="family-hub-choice"><input type="radio" name="family_hub_mode" value="join" data-family-hub-mode><span><b>Join Family Hub</b><small>Connect to an existing family hub.</small></span></label>
                    </div>
                    <div class="family-hub-register-panel" data-family-hub-panel="create"><label>Family Hub name<input name="family_hub_name" placeholder="Example: Dela Cruz Family Hub"></label></div>
                    <div class="family-hub-register-panel" data-family-hub-panel="join" hidden><label>Choose Family Hub<select name="family_hub_id" data-family-hub-select><option value="">Select Family Hub</option><?php foreach($registrationFamilyHubs as $familyHub): ?><option value="<?= e($familyHub['id'] ?? '') ?>"><?= e($familyHub['name'] ?? 'Family Hub') ?></option><?php endforeach; ?></select><small class="field-help">Choose from available Family Hubs.</small></label><?php if(!$registrationFamilyHubs): ?><p class="access-note">No Family Hub is available yet. A parent should create one first.</p><?php endif; ?></div>
                    <details class="terms-box"><summary>Terms and Agreement</summary><div><strong>HomeSyncHub Terms and Agreement</strong><p>Use this family hub only for schedules, chores, meals, lists, rewards, and household coordination. Keep account details private, respect other family members, and do not upload content you do not have permission to use. Super Admins and Admins are responsible for managing access, archived users, and family hub data.</p><p>Password reset uses the registered email. For local XAMPP builds, reset messages may be stored internally for testing without showing technical storage wording on this screen.</p></div></details>
                    <label class="terms-accept"><input type="checkbox" name="accept_terms" value="1" required> <span>I agree to the HomeSyncHub Terms and Agreement.</span></label>
                    <button class="btn primary full" type="submit" data-register-submit>Create Account</button>
                    <p class="muted small" data-register-help>Choose parent or child to continue.</p>
                </div>
            </form>
            <form method="post" class="auth-form tab-panel" data-panel="recover">
                <input type="hidden" name="action" value="forgot_password">
                <label>Registered email<span class="auth-input-shell"><input name="email" type="email" autocomplete="email" required data-visibility-input data-visibility-kind="mask"><button class="field-visibility-btn" type="button" data-visibility-toggle><span class="visibility-icon" aria-hidden="true"></span><span class="sr-only">Show or hide field</span></button></span></label>
                <button class="btn primary full" type="submit">View Recovery Options</button>
                <p class="muted small">Enter the registered email to view the available recovery option. For local testing, the reset link is also shown on-screen.</p>
                <?php if(is_array($recoveryOptions)): ?>
                    <div class="recovery-options-card">
                        <strong>Recovery option found</strong>
                        <span>Registered email: <?= e((string)($recoveryOptions['masked_email'] ?? '')) ?></span>
                        <span>Expires: <?= e(format_dt((string)($recoveryOptions['expires_at'] ?? ''), 'Within 1 hour')) ?></span>
                        <a class="btn success full" href="<?= e((string)($recoveryOptions['reset_link'] ?? 'index.php?page=login')) ?>">Open Password Reset</a>
                    </div>
                <?php endif; ?>
            </form>
        <?php endif; ?>
    </div>
</section>
<script src="assets/js/app.js?v=9.8.0"></script>
</body>
</html><?php exit; endif;
render_shell_start($page,$settings,$user);
$selectedDate = $_GET['date'] ?? app_now()->format('Y-m-d');
$view = $_GET['view'] ?? 'week';
?>
<?php if ($page === 'dashboard'):
    $upcoming = upcoming_items($items, 4);
    $today = app_now();
    $weatherSummary = (string)($settings['weather_summary'] ?? 'Partly cloudy • 31°C • light breeze');
    $temperature = '31°C';
    if (preg_match('/(\d+\s*°C)/u', $weatherSummary, $temperatureMatch)) $temperature = trim($temperatureMatch[1]);
    $activityFeed = array_slice($activity, 0, 4);
    $familyProfiles = profiles_for($settings);
    $familyProfilesPreview = array_slice($familyProfiles, 0, 4);
?>
<?php
    $pendingItems = array_values(array_filter($items, fn($i)=>($i['status'] ?? 'pending') !== 'done'));
    $completedItems = array_values(array_filter($items, fn($i)=>($i['status'] ?? 'pending') === 'done'));
    $pendingPoints = array_sum(array_map(fn($i)=>(int)($i['points'] ?? 0), $pendingItems));
    $releasedPoints = array_sum(array_map(fn($i)=>(int)($i['points'] ?? 0), $completedItems));
    $releasedStars = array_sum(array_map(fn($i)=>(int)($i['stars'] ?? 0), $completedItems));
    $todayDate = $today->format('Y-m-d');
    $todaySchedule = array_values(array_filter($items, fn($i)=>item_date($i['start'] ?? '') === $todayDate));
    if(!$todaySchedule) $todaySchedule = $upcoming;
    usort($todaySchedule, fn($a,$b)=>strcmp((string)($a['start'] ?? ''),(string)($b['start'] ?? '')));
    $priorityItems = array_slice(array_values(array_filter($items, fn($i)=>($i['status'] ?? 'pending') !== 'done' && in_array(($i['type'] ?? ''), ['task','chore','meal','event'], true))),0,4);
    $mealsTodayItems = array_slice(array_values(array_filter($items, fn($i)=>($i['type'] ?? '') === 'meal' && (item_date($i['start'] ?? '') === $todayDate || empty($i['start'])))),0,3);
    $familyCount = count($familyProfiles);
?>
<section class="ai-dashboard" aria-label="HomeSyncHub AI assistant dashboard">
    <section class="ai-main-column">
        <article class="ai-welcome-card">
            <div class="ai-welcome-visual">
                <img src="assets/brand/home-sync-hub-dashboard-banner-default.png" alt="HomeSyncHub Family Dashboard Overview" loading="eager" width="1400" height="170">
            </div>
            <div class="ai-welcome-copy">
                <h2>Welcome back, <?= e($user['name'] ?? 'HomeSyncHub Admin') ?>! 👋</h2>
                <p>Here’s what’s happening in your Family Hub today.</p>
            </div>
            <div class="ai-date-card">
                <span><?= e($today->format('l')) ?></span>
                <strong><?= e($today->format('M d, Y')) ?></strong>
                <em><?= e($today->format('g:i A')) ?></em>
            </div>
        </article>

        <section class="ai-stat-grid" aria-label="Family Hub summary">
            <a class="ai-stat-card amber" href="index.php?page=todo"><span>⭐</span><strong><?= (int)$pendingPoints ?></strong><small>Pending Points</small><em>From <?= count($pendingItems) ?> active items</em></a>
            <a class="ai-stat-card green" href="index.php?page=rewards"><span>✅</span><strong><?= (int)$releasedPoints ?></strong><small>Released Points</small><em>This Family Hub</em></a>
            <a class="ai-stat-card purple" href="index.php?page=rewards"><span>☆</span><strong><?= (int)$releasedStars ?></strong><small>Stars Earned</small><em>Keep it up!</em></a>
            <a class="ai-stat-card blue" href="index.php?page=workspaces"><span>👥</span><strong><?= (int)$familyCount ?></strong><small>Family Members</small><em>Active profiles</em></a>
            <a class="ai-stat-card purple" href="index.php?page=guardian"><span>🛡️</span><strong><?= count(guardian_devices_for($hubId)) ?></strong><small>Guardian Devices</small><em>Task-gated access</em></a>
        </section>

        <section class="ai-content-grid">
            <article class="ai-panel schedule-panel">
                <div class="ai-panel-head"><div><span>🗓️</span><strong>Today’s Schedule</strong></div><a href="index.php?page=calendar&view=day&date=<?= e($todayDate) ?>">View calendar →</a></div>
                <div class="ai-schedule-list">
                    <?php if($todaySchedule): foreach(array_slice($todaySchedule,0,5) as $item):
                        $member = (string)($item['member'] ?? 'Family');
                        $profile = profile_for_member($settings,$member);
                        $timeText = format_dt($item['start'] ?? '', 'Anytime');
                    ?>
                    <a class="ai-schedule-item" href="index.php?page=calendar&view=day&date=<?= e(item_date($item['start'] ?? $todayDate)) ?>" style="--dot: <?= e($profile['color'] ?? '#3b82f6') ?>">
                        <time><?= e($timeText) ?></time>
                        <i></i>
                        <div><strong><?= e($item['title'] ?? 'Untitled item') ?></strong><small><?= e($member) ?> · <?= e(type_label($item['type'] ?? 'task')) ?></small></div>
                    </a>
                    <?php endforeach; else: ?>
                    <p class="ai-empty">No scheduled items today. Use + Add New to create one.</p>
                    <?php endif; ?>
                    <?php if(can_edit_items($user)): ?><button class="ai-inline-add" type="button" onclick="window.addModal.showModal()">＋ Add new event</button><?php endif; ?>
                </div>
            </article>

            <article class="ai-panel priority-panel">
                <div class="ai-panel-head"><div><span>☷</span><strong>Top Priorities</strong></div><a href="index.php?page=todo">View all tasks →</a></div>
                <div class="ai-priority-list">
                    <?php if($priorityItems): foreach($priorityItems as $item):
                        $type = (string)($item['type'] ?? 'task');
                        $points = (int)($item['points'] ?? 0);
                    ?>
                    <article class="ai-priority-item">
                        <span class="ai-checkbox"></span>
                        <div><strong><?= e($item['title'] ?? 'Untitled item') ?></strong><small><?= e(type_label($type)) ?> · <?= e($item['member'] ?? 'Family') ?></small></div>
                        <em>⭐ <?= $points ?></em>
                    </article>
                    <?php endforeach; else: ?>
                    <p class="ai-empty">No pending priorities. Completed items will show in activity.</p>
                    <?php endif; ?>
                </div>
            </article>

            <article class="ai-panel meals-panel">
                <div class="ai-panel-head"><div><span>🍽️</span><strong>Meals Today</strong></div><a href="index.php?page=meals">View all →</a></div>
                <div class="ai-meal-list">
                    <?php if($mealsTodayItems): foreach($mealsTodayItems as $meal): ?>
                    <div class="ai-meal-item"><span><?= e(type_icon($meal['type'] ?? 'meal')) ?></span><div><strong><?= e($meal['meal_slot'] ?: 'Meal') ?></strong><small><?= e($meal['title'] ?? 'Planned meal') ?></small></div><em><?= ($meal['status'] ?? '')==='done' ? 'Done' : 'Planned' ?></em></div>
                    <?php endforeach; else: ?>
                    <div class="ai-meal-item"><span>🍳</span><div><strong>Breakfast</strong><small>Plan from Meal Planner</small></div><em>Pending</em></div>
                    <div class="ai-meal-item"><span>🍱</span><div><strong>Lunch</strong><small>Add a meal to today</small></div><em>Pending</em></div>
                    <div class="ai-meal-item"><span>🍝</span><div><strong>Dinner</strong><small>Choose from Filipino menu</small></div><em>Planned</em></div>
                    <?php endif; ?>
                </div>
            </article>

            <article class="ai-panel activity-panel">
                <div class="ai-panel-head"><div><span>↗</span><strong>Recent Activity</strong></div><a href="index.php?page=history">View all →</a></div>
                <div class="ai-activity-list">
                    <?php if($activityFeed): foreach($activityFeed as $event): ?>
                    <a class="ai-activity-item" href="index.php?page=history"><span><?= e(type_icon($event['type'] ?? 'task')) ?></span><div><strong><?= e($event['title'] ?? 'Activity') ?></strong><small><?= e(format_dt($event['created_at'] ?? '', 'Recently')) ?></small></div><em><?= !empty($event['points']) ? '+' . (int)$event['points'] . ' pts' : '' ?></em></a>
                    <?php endforeach; else: ?>
                    <p class="ai-empty">No recent activity yet.</p>
                    <?php endif; ?>
                </div>
            </article>
        </section>
    </section>

</section>
<?php elseif ($page === 'todo'):
    $todoFilter = in_array(($_GET['filter'] ?? 'all'), ['all','task','chore','event','meal','completed'], true) ? (string)($_GET['filter'] ?? 'all') : 'all';
    $todoQuery = trim((string)($_GET['q'] ?? ''));
    $todoItems = $items;
    usort($todoItems, function($a,$b){
        $adone = (($a['status'] ?? 'pending') === 'done') ? 1 : 0;
        $bdone = (($b['status'] ?? 'pending') === 'done') ? 1 : 0;
        if($adone !== $bdone) return $adone <=> $bdone;
        return strcmp((string)($a['start'] ?? '9999'), (string)($b['start'] ?? '9999')) ?: strcmp((string)($a['title'] ?? ''), (string)($b['title'] ?? ''));
    });
    if($todoFilter === 'completed') $todoItems = array_values(array_filter($todoItems, fn($i)=>($i['status'] ?? 'pending') === 'done'));
    elseif($todoFilter !== 'all') $todoItems = array_values(array_filter($todoItems, fn($i)=>($i['type'] ?? '') === $todoFilter));
    if($todoQuery !== '') {
        $q = strtolower($todoQuery);
        $todoItems = array_values(array_filter($todoItems, function($i) use ($q){
            $hay = strtolower(implode(' ', [($i['title'] ?? ''),($i['member'] ?? ''),($i['category'] ?? ''),($i['location'] ?? ''),($i['notes'] ?? ''),($i['type'] ?? '')]));
            return str_contains($hay, $q);
        }));
    }
    $allTodo = $items;
    $pendingItems = array_values(array_filter($allTodo, fn($i)=>($i['status'] ?? 'pending') !== 'done'));
    $completedItems = array_values(array_filter($allTodo, fn($i)=>($i['status'] ?? 'pending') === 'done'));
    $pendingPoints = array_sum(array_map(fn($i)=>(int)($i['points'] ?? 0), $pendingItems));
    $releasedPoints = array_sum(array_map(fn($i)=>(int)($i['points'] ?? 0), $completedItems));
    $releasedStars = array_sum(array_map(fn($i)=>(int)($i['stars'] ?? 0), $completedItems));
    $typeCounts = [];
    foreach(['task','chore','event','meal'] as $t) $typeCounts[$t] = count(array_filter($allTodo, fn($i)=>($i['type'] ?? '') === $t && ($i['status'] ?? 'pending') !== 'done'));
    $recentUnlocks = device_unlocks_for($hubId, 5);
    $typeAccent = ['task'=>'cyan','chore'=>'orange','event'=>'blue','meal'=>'purple'];
?>
<section class="todo-page todo-list-dashboard" aria-label="Todo List Dashboard">
    <div class="todo-hero panel">
        <div>
            <p class="eyebrow">Todo List Dashboard</p>
            <h2>Tasks, chores, parent homework review, and device access</h2>
            <p class="muted">Chores can be marked done immediately. Homework tasks require a photo/file upload and parent approval before rewards and device access are released.</p>
        </div>
        <div class="todo-summary-grid" aria-label="Todo reward summary">
            <article><b><?= (int)$pendingPoints ?></b><span>pending pts</span></article>
            <article><b><?= (int)$releasedPoints ?></b><span>released pts</span></article>
            <article><b><?= (int)$releasedStars ?></b><span>stars earned</span></article>
        </div>
    </div>

    <div class="todo-filter-panel panel">
        <form method="get" class="todo-search-form">
            <input type="hidden" name="page" value="todo">
            <input type="hidden" name="filter" value="<?= e($todoFilter) ?>">
            <span aria-hidden="true">🔎</span>
            <input name="q" value="<?= e($todoQuery) ?>" placeholder="Search todo items, family member, category, notes...">
            <button class="btn ghost" type="submit">Search</button>
            <?php if($todoQuery !== ''): ?><a class="btn ghost" href="index.php?page=todo&filter=<?= e($todoFilter) ?>">Clear</a><?php endif; ?>
        </form>
        <nav class="todo-filter-tabs" aria-label="Todo filters">
            <?php foreach(['all'=>'All','task'=>'Task','chore'=>'Chore','event'=>'Event','meal'=>'Meal','completed'=>'Completed'] as $key=>$label): ?>
                <a class="<?= $todoFilter===$key?'active':'' ?>" href="index.php?page=todo&filter=<?= e($key) ?><?= $todoQuery!==''?'&q='.e(rawurlencode($todoQuery)):'' ?>">
                    <span><?= e($label) ?></span>
                    <b><?= $key==='all' ? count($pendingItems) : ($key==='completed' ? count($completedItems) : (int)($typeCounts[$key] ?? 0)) ?></b>
                </a>
            <?php endforeach; ?>
        </nav>
    </div>

    <div class="todo-layout-grid">
        <section class="todo-item-stack" aria-label="Todo items">
            <?php if($todoItems): foreach($todoItems as $item):
                $type = (string)($item['type'] ?? 'task');
                $done = ($item['status'] ?? 'pending') === 'done';
                $member = (string)($item['member'] ?? 'Family');
                $profile = profile_for_member($settings, $member);
                $startText = format_dt($item['start'] ?? '', 'Anytime');
                $category = trim((string)($item['category'] ?? ucfirst($type))) ?: ucfirst($type);
                $accent = $typeAccent[$type] ?? 'cyan';
                $requiresProof = item_requires_proof($item);
                $proofStatus = (string)($item['proof_status'] ?? ($requiresProof ? 'required' : 'not_required'));
                $proofUpload = !empty($item['proof_upload_id']) ? proof_upload_by_id((string)$item['proof_upload_id']) : null;
                $verificationMessage = trim((string)($item['verification_message'] ?? ''));
                $canDone = can_complete_items($user) && !$done && !$requiresProof;
                $canSubmitProof = can_complete_items($user) && !$done && $requiresProof;
            ?>
                <article class="todo-item-card <?= $done ? 'is-completed' : '' ?> <?= $requiresProof ? 'requires-proof' : '' ?> type-<?= e($type) ?> accent-<?= e($accent) ?>" style="--member-color: <?= e($profile['color'] ?? '#49d9ff') ?>">
                    <div class="todo-type-icon" aria-hidden="true"><?= $done ? '✓' : e(type_icon($type)) ?></div>
                    <div class="todo-item-copy">
                        <div class="todo-tags"><span><?= e(type_label($type)) ?></span><span><?= e($category) ?></span><span class="<?= $done ? 'done' : '' ?>"><?= $done ? 'Completed' : 'Pending' ?></span><?php if($requiresProof): ?><span class="proof-tag">Proof required</span><?php endif; ?></div>
                        <h3><?= e($item['title'] ?? 'Untitled item') ?></h3>
                        <p><strong>Assigned to <?= e($member) ?></strong> · <?= e($startText) ?><?= !empty($item['location']) ? ' · ' . e($item['location']) : '' ?><?= !empty($item['meal_slot']) ? ' · ' . e($item['meal_slot']) : '' ?></p>
                        <?php if(!empty($item['notes'])): ?><p class="todo-note"><?= nl2br(e($item['notes'])) ?></p><?php endif; ?>
                        <?php if($requiresProof): ?>
                            <div class="proof-status-card status-<?= e($proofStatus) ?>">
                                <strong>Homework proof: <?= e(str_replace('_',' ', ucfirst($proofStatus))) ?></strong>
                                <span><?= e($verificationMessage ?: 'Upload a clear homework photo/file. A parent will review it before completion.') ?></span>
                                <?php if($proofUpload): ?><a href="<?= e($proofUpload['path'] ?? '#') ?>" target="_blank" rel="noopener">View uploaded proof</a><?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="todo-reward-block" aria-label="Assigned reward">
                        <div><b><?= (int)($item['points'] ?? 0) ?></b><span>points</span></div>
                        <div><b>★ <?= (int)($item['stars'] ?? 0) ?></b><span>stars</span></div>
                    </div>
                    <div class="todo-actions <?= $requiresProof ? 'proof-actions' : '' ?>">
                        <?php if($canSubmitProof): ?>
                            <form method="post" enctype="multipart/form-data" class="proof-upload-form" onsubmit="return confirm('Upload this homework for parent review?')">
                                <input type="hidden" name="action" value="complete_item_with_proof">
                                <input type="hidden" name="item_id" value="<?= e($item['id'] ?? '') ?>">
                                <input type="hidden" name="return" value="todo">
                                <label>Photo/file proof<input name="proof_file" type="file" accept="image/*,.pdf" capture="environment" required></label>
                                <button class="btn primary todo-done-btn" type="submit">Upload homework for parent review</button>
                            </form>
                            <?php if(can_manage_rewards($user) && $proofUpload && in_array($proofStatus, ['uploaded','pending_parent_review','needs_review','incorrect','needs_correction'], true)): ?>
                                <form method="post" class="proof-approve-form" onsubmit="return confirm('Approve this homework and release rewards?')">
                                    <input type="hidden" name="action" value="approve_homework_proof">
                                    <input type="hidden" name="item_id" value="<?= e($item['id'] ?? '') ?>">
                                    <input type="hidden" name="return" value="todo">
                                    <button class="btn ghost" type="submit">Parent approve</button>
                                </form>
                                <form method="post" class="proof-correction-form" onsubmit="return confirm('Send this homework back for correction?')">
                                    <input type="hidden" name="action" value="request_homework_correction">
                                    <input type="hidden" name="item_id" value="<?= e($item['id'] ?? '') ?>">
                                    <input type="hidden" name="return" value="todo">
                                    <input name="parent_comment" placeholder="Correction note for child (optional)">
                                    <button class="btn danger" type="submit">Needs correction</button>
                                </form>
                            <?php endif; ?>
                        <?php elseif($canDone): ?>
                            <form method="post" onsubmit="return confirm('Mark this item as done and release assigned points/stars?')">
                                <input type="hidden" name="action" value="complete_item">
                                <input type="hidden" name="item_id" value="<?= e($item['id'] ?? '') ?>">
                                <input type="hidden" name="return" value="todo">
                                <button class="btn primary todo-done-btn" type="submit">Done</button>
                            </form>
                        <?php elseif($done): ?>
                            <span class="todo-released-chip">Reward released<?= !empty($item['device_unlock_id']) ? ' + device unlock' : '' ?></span>
                        <?php else: ?>
                            <span class="todo-released-chip readonly"><?= $requiresProof ? 'Waiting for parent review' : 'Read only' ?></span>
                        <?php endif; ?>
                    </div>
                </article>
            <?php endforeach; else: ?>
                <div class="panel todo-empty-state"><h3>No todo items found</h3><p class="muted">Create a task, chore, event, or meal using + Add New. Matching items will appear here.</p><?php if(can_edit_items($user)): ?><button class="btn primary" onclick="window.addModal.showModal()">+ Add New</button><?php endif; ?></div>
            <?php endif; ?>
        </section>

        <aside class="todo-side-panel">
            <article class="panel todo-rule-card">
                <div class="todo-side-title"><span>🏆</span><div><h3>Reward Release Rule</h3><p>How Done works</p></div></div>
                <ol>
                    <li>Chores complete immediately when marked <strong>Done</strong>.</li>
                    <li>Homework requires a photo/file upload.</li>
                    <li>A parent or Family Hub Admin must approve homework before rewards are released.</li>
                    <li>Successful completion records a device-unlock grant for the family device adapter.</li>
                </ol>
            </article>
            <article class="panel todo-completion-card">
                <div class="todo-side-title"><span>🎁</span><div><h3>Completion Summary</h3><p>Active Family Hub</p></div></div>
                <div class="todo-completion-grid"><div><b><?= count($completedItems) ?></b><span>done</span></div><div><b><?= count($pendingItems) ?></b><span>left</span></div></div>
                <?php if(can_edit_items($user)): ?><button class="btn primary full" onclick="window.addModal.showModal()">+ Add Todo Item</button><?php endif; ?>
            </article>
            <article class="panel device-unlock-card">
                <div class="todo-side-title"><span>🔓</span><div><h3>Device Unlock Grants</h3><p><?= !empty($settings['device_unlock_enabled']) ? 'Enabled' : 'Disabled' ?> · <?= (int)($settings['device_unlock_minutes'] ?? 120) ?> min</p></div></div>
                <?php if($recentUnlocks): ?>
                    <div class="unlock-list">
                    <?php foreach($recentUnlocks as $unlock): ?>
                        <div class="unlock-row"><strong><?= e($unlock['member'] ?? 'Family') ?></strong><span><?= e($unlock['device'] ?? 'Family device') ?> until <?= e(format_dt($unlock['expires_at'] ?? '', 'recently')) ?></span><small><?= e($unlock['webhook_status'] ?? 'Recorded locally') ?></small></div>
                    <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="muted small">No device access grants yet. Completing a valid task creates a local grant and can call your HTTPS webhook adapter.</p>
                <?php endif; ?>
            </article>
        </aside>
    </div>
</section>

<?php elseif ($page === 'calendar'):
    $view = in_array($view, ['day','week','month','agenda'], true) ? $view : 'week';
    try { $selectedDateObj = new DateTimeImmutable($selectedDate, new DateTimeZone(APP_TZ)); } catch (Throwable $e) { $selectedDateObj = app_now(); $selectedDate = $selectedDateObj->format('Y-m-d'); }
    $calendarToday = app_now();
    $weekDays = week_dates($selectedDate);
    $monthDays = month_dates($selectedDate);
    $selectedItems = items_on_date($items,$selectedDate);
    usort($selectedItems, fn($a,$b)=>strcmp((string)($a['start'] ?? ''),(string)($b['start'] ?? '')));
    $calendarColors = ['event'=>'#38bdf8','task'=>'#22c55e','chore'=>'#f59e0b','meal'=>'#a855f7','list'=>'#ec4899'];
    $itemColor = function(array $item) use ($settings,$calendarColors): string {
        $member = (string)($item['member'] ?? 'Family');
        $profile = profile_for_member($settings, $member);
        $color = (string)($profile['color'] ?? '');
        return preg_match('/^#[0-9a-fA-F]{6}$/', $color) ? $color : ($calendarColors[$item['type'] ?? 'event'] ?? '#49d9ff');
    };
    $timeLabel = function(?string $value): string { $dt = parse_dt($value); return $dt ? $dt->format('g:i A') : 'Anytime'; };
    $dateLabelShort = function(DateTimeImmutable $date): string { return $date->format('D, d M'); };
    $minutesOfDay = function(?string $value): int { $dt = parse_dt($value); return $dt ? (((int)$dt->format('G') * 60) + (int)$dt->format('i')) : 540; };
    $eventTop = function(array $item) use ($minutesOfDay): int { return max(0, min(960, $minutesOfDay($item['start'] ?? '') - 360)); };
    $eventHeight = function(array $item) use ($minutesOfDay): int { $start=$minutesOfDay($item['start'] ?? ''); $end=$minutesOfDay($item['end'] ?? ''); if($end <= $start) $end=$start+60; return max(46, min(180, $end-$start)); };
    $prevDate = match($view) { 'day' => $selectedDateObj->modify('-1 day'), 'month' => $selectedDateObj->modify('-1 month'), 'agenda' => $selectedDateObj->modify('-1 month'), default => $selectedDateObj->modify('-1 week') };
    $nextDate = match($view) { 'day' => $selectedDateObj->modify('+1 day'), 'month' => $selectedDateObj->modify('+1 month'), 'agenda' => $selectedDateObj->modify('+1 month'), default => $selectedDateObj->modify('+1 week') };
    $rangeLabel = match($view) {
        'day' => $selectedDateObj->format('l, d F Y'),
        'month' => $selectedDateObj->format('F Y'),
        'agenda' => 'Agenda',
        default => $weekDays[0]->format('d M') . ' – ' . $weekDays[6]->format('d M Y'),
    };
    $upcomingCalendarItems = upcoming_items($items, 8);
    $calendarProfiles = profiles_for($settings);
    $weatherSummary = (string)($settings['weather_summary'] ?? 'Partly cloudy • 31°C • light breeze');
    $temperature = '31°C'; if (preg_match('/(\d+\s*°C)/u', $weatherSummary, $temperatureMatch)) $temperature = trim($temperatureMatch[1]);
?>
<section class="calendar-redesign" aria-label="HomeSyncHub calendar redesign">
    <div class="calendar-hero-row">
        <div>
            <p class="eyebrow">Calendar Layouts</p>
            <h2><?= e($rangeLabel) ?></h2>
            <p class="muted">Daily, weekly, monthly, and agenda views for the active Family Hub.</p>
        </div>
        <div class="calendar-toolbar">
            <a class="cal-circle-btn" href="index.php?page=calendar&view=<?= e($view) ?>&date=<?= e($prevDate->format('Y-m-d')) ?>" aria-label="Previous period">‹</a>
            <a class="cal-circle-btn" href="index.php?page=calendar&view=<?= e($view) ?>&date=<?= e($nextDate->format('Y-m-d')) ?>" aria-label="Next period">›</a>
            <a class="cal-mini-btn" href="index.php?page=calendar&view=<?= e($view) ?>&date=<?= e($calendarToday->format('Y-m-d')) ?>">Today</a>
            <nav class="calendar-tabs" aria-label="Calendar views">
                <a class="<?= $view==='day'?'active':'' ?>" href="index.php?page=calendar&view=day&date=<?= e($selectedDate) ?>">Day</a>
                <a class="<?= $view==='week'?'active':'' ?>" href="index.php?page=calendar&view=week&date=<?= e($selectedDate) ?>">Week</a>
                <a class="<?= $view==='month'?'active':'' ?>" href="index.php?page=calendar&view=month&date=<?= e($selectedDate) ?>">Month</a>
                <a class="<?= $view==='agenda'?'active':'' ?>" href="index.php?page=calendar&view=agenda&date=<?= e($selectedDate) ?>">Agenda</a>
            </nav>
            <?php if(can_edit_items($user)): ?><button class="cal-add-btn" type="button" onclick="window.addModal.showModal()">+ Add Event</button><?php endif; ?>
        </div>
    </div>

    <?php if($view === 'day'): ?>
        <div class="calendar-day-layout">
            <section class="calendar-board calendar-day-board">
                <div class="calendar-time-title"><span>All-day</span><strong><?= e($selectedDateObj->format('l, d M')) ?></strong></div>
                <div class="day-timeline-wrap">
                    <div class="time-rail"><?php for($h=6;$h<=22;$h++): ?><span style="top: <?= ($h-6)*64 ?>px"><?= e(date('g:i A', mktime($h,0))) ?></span><?php endfor; ?></div>
                    <div class="day-timeline" style="height: <?= 17*64 ?>px">
                        <?php for($h=6;$h<=22;$h++): ?><div class="time-line" style="top: <?= ($h-6)*64 ?>px"></div><?php endfor; ?>
                        <?php foreach($selectedItems as $item): $color=$itemColor($item); $top=$eventTop($item)*64/60; $height=$eventHeight($item)*64/60; ?>
                            <article class="cal-event-block" style="--event-color: <?= e($color) ?>; top: <?= (int)$top ?>px; min-height: <?= (int)$height ?>px">
                                <strong><?= e($item['title'] ?? 'Untitled item') ?></strong>
                                <small><?= e($timeLabel($item['start'] ?? '')) ?> – <?= e($timeLabel($item['end'] ?? '')) ?> • <?= e($item['member'] ?? 'Family') ?></small>
                                <?php if(!empty($item['location'])): ?><em><?= e($item['location']) ?></em><?php endif; ?>
                            </article>
                        <?php endforeach; ?>
                        <?php if(!$selectedItems): ?><p class="cal-empty-state">No scheduled items for this day.</p><?php endif; ?>
                    </div>
                </div>
            </section>
            <aside class="calendar-side-rail">
                <div class="calendar-side-card weather-card-cal"><p class="eyebrow">Day Focus</p><h3><?= e($selectedDateObj->format('l, d F Y')) ?></h3><div class="weather-chip-cal"><span>🌤️</span><strong><?= e($temperature) ?></strong><small>Partly cloudy<br><?= e($settings['weather_location'] ?? 'Singapore') ?></small></div></div>
                <div class="calendar-side-card"><p class="eyebrow">Upcoming</p><?php foreach(array_slice($upcomingCalendarItems,0,4) as $item): ?><a class="agenda-mini-row" href="index.php?page=calendar&view=day&date=<?= e(item_date($item['start'] ?? '')) ?>" style="--event-color: <?= e($itemColor($item)) ?>"><strong><?= e($item['title'] ?? 'Item') ?></strong><small><?= e($timeLabel($item['start'] ?? '')) ?></small></a><?php endforeach; if(!$upcomingCalendarItems): ?><p class="empty">No upcoming items.</p><?php endif; ?></div>
                <div class="calendar-side-card"><p class="eyebrow">Quick Add</p><div class="cal-quick-add"><?php if(can_edit_items($user)): ?><button onclick="window.addModal.showModal()">🗓️<span>Event</span></button><button onclick="window.addModal.showModal()">✅<span>Task</span></button><button onclick="window.addModal.showModal()">🔔<span>Reminder</span></button><button onclick="window.listModal.showModal()">📝<span>Note</span></button><?php else: ?><span class="access-note">Read-only calendar.</span><?php endif; ?></div></div>
            </aside>
        </div>
    <?php elseif($view === 'week'): ?>
        <div class="calendar-week-layout">
            <section class="calendar-board calendar-week-board">
                <div class="week-header-grid"><span></span><?php foreach($weekDays as $day): $date=$day->format('Y-m-d'); ?><a class="week-day-head <?= $date===$selectedDate?'active':'' ?>" href="index.php?page=calendar&view=day&date=<?= e($date) ?>"><small><?= e($day->format('D')) ?></small><strong><?= e($day->format('d')) ?></strong></a><?php endforeach; ?></div>
                <div class="week-grid-wrap">
                    <div class="week-time-axis"><?php for($h=6;$h<=22;$h++): ?><span style="top: <?= ($h-6)*58 ?>px"><?= e(date('g:i A', mktime($h,0))) ?></span><?php endfor; ?></div>
                    <div class="week-days-grid" style="height: <?= 17*58 ?>px">
                        <?php for($h=6;$h<=22;$h++): ?><div class="week-time-line" style="top: <?= ($h-6)*58 ?>px"></div><?php endfor; ?>
                        <?php foreach($weekDays as $day): $date=$day->format('Y-m-d'); $dayItems=items_on_date($items,$date); usort($dayItems, fn($a,$b)=>strcmp((string)($a['start'] ?? ''),(string)($b['start'] ?? ''))); ?>
                            <div class="week-day-column <?= $date===$selectedDate?'active':'' ?>">
                                <?php foreach($dayItems as $item): $color=$itemColor($item); $top=$eventTop($item)*58/60; $height=max(38,$eventHeight($item)*58/60); ?>
                                    <a class="week-event-chip" href="index.php?page=calendar&view=day&date=<?= e($date) ?>" style="--event-color: <?= e($color) ?>; top: <?= (int)$top ?>px; min-height: <?= (int)$height ?>px"><strong><?= e($timeLabel($item['start'] ?? '')) ?></strong><span><?= e($item['title'] ?? 'Item') ?></span></a>
                                <?php endforeach; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
            <aside class="calendar-side-rail week-side-rail">
                <div class="mini-month-card"><div class="mini-month-head"><a href="index.php?page=calendar&view=week&date=<?= e($selectedDateObj->modify('-1 month')->format('Y-m-d')) ?>">‹</a><strong><?= e($selectedDateObj->format('M Y')) ?></strong><a href="index.php?page=calendar&view=week&date=<?= e($selectedDateObj->modify('+1 month')->format('Y-m-d')) ?>">›</a></div><div class="mini-month-grid"><?php foreach(['M','T','W','T','F','S','S'] as $d): ?><b><?= e($d) ?></b><?php endforeach; ?><?php foreach(month_dates($selectedDate) as $d): $date=$d->format('Y-m-d'); ?><a class="<?= $date===$selectedDate?'active':'' ?> <?= $d->format('m')!==$selectedDateObj->format('m')?'muted-date':'' ?>" href="index.php?page=calendar&view=week&date=<?= e($date) ?>"><?= e($d->format('j')) ?></a><?php endforeach; ?></div></div>
                <div class="calendar-side-card"><p class="eyebrow">Calendars</p><div class="calendar-filter-list"><?php foreach($calendarProfiles as $profile): ?><label style="--event-color: <?= e($profile['color'] ?? '#49d9ff') ?>"><input type="checkbox" checked> <?= e($profile['name'] ?? 'Family') ?></label><?php endforeach; ?></div></div>
            </aside>
        </div>
    <?php elseif($view === 'month'): ?>
        <section class="calendar-board calendar-month-board">
            <div class="month-title-row"><h3><?= e($selectedDateObj->format('F Y')) ?></h3><a class="cal-mini-btn" href="index.php?page=calendar&action=export_ics">Export .ics</a></div>
            <div class="month-weekdays"><?php foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $d): ?><span><?= e($d) ?></span><?php endforeach; ?></div>
            <div class="calendar-month-grid">
                <?php foreach($monthDays as $d): $date=$d->format('Y-m-d'); $dayItems=items_on_date($items,$date); $outside=$d->format('m')!==$selectedDateObj->format('m'); ?>
                    <a class="calendar-month-cell <?= $date===$selectedDate?'active':'' ?> <?= $outside?'outside':'' ?>" href="index.php?page=calendar&view=day&date=<?= e($date) ?>">
                        <strong><?= e($d->format('j')) ?></strong><small><?= e($d->format('D')) ?></small>
                        <?php foreach(array_slice($dayItems,0,3) as $item): ?><em style="--event-color: <?= e($itemColor($item)) ?>"><?= e($item['title'] ?? 'Item') ?></em><?php endforeach; ?>
                        <?php if(count($dayItems)>3): ?><b>+<?= count($dayItems)-3 ?> more</b><?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </section>
    <?php else: ?>
        <div class="calendar-agenda-layout">
            <section class="calendar-board agenda-board">
                <div class="month-title-row"><h3>Agenda</h3><a class="cal-mini-btn" href="index.php?page=calendar&action=export_ics">Export .ics</a></div>
                <?php $hasAgenda=false; foreach(grouped_by_date($items) as $date=>$group): $hasAgenda=true; ?>
                    <div class="agenda-date-block"><h3><?= e(date_label($date)) ?></h3><div class="agenda-list-redesign"><?php foreach($group as $item): ?><a class="agenda-event-row" href="index.php?page=calendar&view=day&date=<?= e(item_date($item['start'] ?? '')) ?>" style="--event-color: <?= e($itemColor($item)) ?>"><time><?= e($timeLabel($item['start'] ?? '')) ?></time><span></span><div><strong><?= e($item['title'] ?? 'Untitled item') ?></strong><small><?= e(type_label($item['type'] ?? 'task')) ?> · <?= e($item['member'] ?? 'Family') ?><?= !empty($item['location']) ? ' · ' . e($item['location']) : '' ?></small></div><em><?= e(type_icon($item['type'] ?? 'task')) ?></em></a><?php endforeach; ?></div></div>
                <?php endforeach; if(!$hasAgenda): ?><p class="cal-empty-state static">No agenda items yet. Use + Add Event.</p><?php endif; ?>
            </section>
            <aside class="calendar-side-rail agenda-side-rail">
                <div class="mini-month-card"><div class="mini-month-head"><strong><?= e($selectedDateObj->format('M Y')) ?></strong></div><div class="mini-month-grid"><?php foreach(['M','T','W','T','F','S','S'] as $d): ?><b><?= e($d) ?></b><?php endforeach; ?><?php foreach(month_dates($selectedDate) as $d): $date=$d->format('Y-m-d'); ?><a class="<?= $date===$selectedDate?'active':'' ?> <?= $d->format('m')!==$selectedDateObj->format('m')?'muted-date':'' ?>" href="index.php?page=calendar&view=agenda&date=<?= e($date) ?>"><?= e($d->format('j')) ?></a><?php endforeach; ?></div></div>
                <div class="calendar-side-card"><p class="eyebrow">Filters</p><select class="cal-select"><option>All Calendars</option><option>Family</option><option>Personal</option><option>Chores</option><option>Meals</option></select><div class="calendar-filter-list stacked"><?php foreach($calendarProfiles as $profile): ?><label style="--event-color: <?= e($profile['color'] ?? '#49d9ff') ?>"><input type="checkbox" checked> <?= e($profile['name'] ?? 'Family') ?></label><?php endforeach; ?><label><input type="checkbox"> Show completed</label></div></div>
            </aside>
        </div>
    <?php endif; ?>
</section>
<?php elseif ($page === 'chores'): $chores=items_for($hubId,'chore'); ?>
<section class="panel"><div class="panel-head"><div><p class="eyebrow">Chore Chart</p><h2>Assign, repeat, complete, reward</h2></div><button class="btn primary" onclick="window.addModal.showModal()">Add chore</button></div><div class="member-filters"><button class="member-filter active" data-member-filter="all">All</button><?php foreach(member_names($settings) as $m): ?><button class="member-filter" data-member-filter="<?= e($m) ?>"><?= e($m) ?></button><?php endforeach; ?></div><div class="item-stack filter-targets"><?php foreach($chores as $item) render_item_card($item,'chores',$settings); if(!$chores): ?><p class="empty">No chores yet.</p><?php endif; ?></div></section>
<?php elseif ($page === 'meals'):
    $mealView = $_GET['meal_view'] ?? 'weekly';
    if(!in_array($mealView, ['lists','weekly','library','add','grocery','favorites'], true)) $mealView = 'weekly';
    $library = normalize_menu_library($settings['menu_library'] ?? []);
    $mealPlan = normalize_weekly_meal_plan($settings['meal_plan'] ?? [], $library);
    $menuIndex = menu_index_by_id($library);
    $groceryIdeas = meal_plan_grocery_items($settings);
    $canMealEdit = can_edit_items($user);
?>
<section class="meal-blueprint-shell">
    <?php render_meal_tabs($mealView); ?>
    <?php if($mealView === 'lists'): ?>
        <section class="panel lists-dashboard-panel"><div class="panel-head"><div><p class="eyebrow">Lists Dashboard</p><h2>Groceries, errands, reminders, to-dos</h2><p class="muted">Lists now live inside Meals so groceries and meal planning stay together.</p></div><?php if(can_edit_items($user)): ?><button class="btn primary" onclick="window.listModal.showModal()">+ List Item</button><?php endif; ?></div><div class="filters"><button class="filter active" data-list-filter="all">All</button><button class="filter" data-list-filter="grocery">Groceries</button><button class="filter" data-list-filter="todo">To-dos</button><button class="filter" data-list-filter="errand">Errands</button><button class="filter" data-list-filter="reminder">Reminders</button></div><div class="list-stack list-targets"><?php foreach($listItems as $li) render_list_item($li,'meals'); if(!$listItems): ?><p class="empty">No list items yet.</p><?php endif; ?></div></section>
    <?php elseif($mealView === 'weekly'): ?>
        <form method="post" class="weekly-meal-planner">
            <input type="hidden" name="action" value="save_weekly_meal_plan">
            <div class="meal-blueprint-head">
                <div class="meal-title-block"><div class="meal-page-icon">🍽️</div><div><h2>Weekly Meal Planner</h2><p>Plan your family&apos;s meals for the whole week</p></div></div>
                <div class="meal-head-actions"><a class="btn violet" href="index.php?page=meals&meal_view=grocery">View Grocery List</a><?php if($canMealEdit): ?><button class="btn success" type="submit">Save Meal Plan</button><?php else: ?><span class="access-note">Read-only meal view</span><?php endif; ?></div>
            </div>
            <div class="meal-table-wrap" role="region" aria-label="Weekly meal planner table" tabindex="0">
                <table class="weekly-meal-table">
                    <thead><tr><th>Day</th><?php foreach(meal_slots() as $slot): ?><th><?= e($slot) ?></th><?php endforeach; ?></tr></thead>
                    <tbody>
                    <?php foreach(meal_days() as $day): ?>
                        <tr style="--day-color: <?= e(meal_day_color($day)) ?>">
                            <th scope="row"><span><?= e($day) ?></span></th>
                            <?php foreach(meal_slots() as $slot): $selectedId = $mealPlan[$day][$slot] ?? ''; $selected = $menuIndex[$selectedId] ?? (meals_by_slot($library,$slot)[0] ?? []); ?>
                                <td>
                                    <div class="meal-choice meal-picker <?= $canMealEdit ? '' : 'is-locked' ?>" data-meal-picker>
                                        <input type="hidden" name="meal_plan[<?= e($day) ?>][<?= e($slot) ?>]" value="<?= e($selected['id'] ?? '') ?>" data-meal-input>
                                        <button class="meal-picker-trigger" type="button" data-meal-trigger <?= $canMealEdit ? '' : 'disabled' ?> aria-label="Choose <?= e($day . ' ' . $slot) ?> meal" aria-expanded="false">
                                            <img src="<?= e($selected['image'] ?? 'assets/meals/custom_meal.png') ?>" alt="" width="220" height="120" loading="lazy" data-meal-img>
                                            <span class="meal-picker-copy"><strong data-meal-title><?= e($selected['title'] ?? 'Select meal') ?></strong><small><?= e($slot) ?></small></span>
                                            <b aria-hidden="true">⌄</b>
                                        </button>
                                        <?php if($canMealEdit): ?>
                                        <div class="meal-option-list" data-meal-options role="listbox" aria-label="<?= e($day . ' ' . $slot) ?> meal options">
                                            <?php foreach(meals_by_slot($library,$slot) as $meal): ?>
                                                <button type="button" role="option" class="meal-option <?= ($meal['id'] ?? '') === ($selected['id'] ?? '') ? 'active' : '' ?>" data-meal-id="<?= e($meal['id']) ?>" data-img="<?= e($meal['image']) ?>" data-title="<?= e($meal['title']) ?>" aria-selected="<?= ($meal['id'] ?? '') === ($selected['id'] ?? '') ? 'true' : 'false' ?>">
                                                    <img src="<?= e($meal['image']) ?>" alt="" width="220" height="120" loading="lazy">
                                                    <span><strong><?= e($meal['title']) ?></strong><small><?= e($meal['category'] ?? 'Filipino Menu') ?></small></span>
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </form>
    <?php elseif($mealView === 'library'): ?>
        <section class="panel meal-library-panel"><div class="panel-head"><div><p class="eyebrow">Filipino Menu Library</p><h2>Breakfast, lunch, snacks, and dinner</h2></div><a class="btn primary" href="index.php?page=meals&meal_view=add">+ Add New Menu</a></div><?php foreach(meal_slots() as $slot): ?><h3 class="slot-heading"><?= e($slot) ?></h3><div class="menu-library-grid"><?php foreach(meals_by_slot($library,$slot) as $meal) render_menu_card($meal, 'library'); ?></div><?php endforeach; ?></section>
    <?php elseif($mealView === 'add'): ?>
        <section class="grid dashboard-grid"><form method="post" enctype="multipart/form-data" class="panel settings-form"><input type="hidden" name="action" value="add_menu_item"><p class="eyebrow">Add New Menu</p><h2>Create a reusable meal option</h2><label>Menu name<input name="menu_title" placeholder="Example: Garlic Butter Bangus" required></label><div class="form-grid two"><label>Meal slot<select name="menu_slot"><?php foreach(meal_slots() as $slot): ?><option><?= e($slot) ?></option><?php endforeach; ?></select></label><label>Category<input name="menu_category" placeholder="Filipino Dinner"></label></div><label>Ingredients<textarea name="menu_ingredients" rows="7" placeholder="Add one ingredient per line or separate with commas"></textarea></label><label>Menu picture<input name="menu_image" type="file" accept="image/png,image/jpeg,image/webp"><small class="field-help">Optional. PNG, JPG, JPEG, or WEBP up to 5 MB. This picture appears in the weekly meal picker and menu library.</small></label><label class="toggle-inline"><input type="checkbox" name="menu_favorite" checked> Add to favorite meals</label><?php if($canMealEdit): ?><button class="btn primary">Save New Menu</button><?php else: ?><p class="access-note">Your role can view meals but cannot add menu items.</p><?php endif; ?></form><aside class="panel"><p class="eyebrow">Meal Planner Blueprint</p><h2>How this works</h2><p class="muted">Custom menu items become selectable inside the weekly planner table. Ingredients automatically feed the Grocery List view.</p><div class="mini-meta"><span>Weekly planner</span><span>Menu library</span><span>Grocery generator</span><span>Favorites</span></div></aside></section>
    <?php elseif($mealView === 'grocery'): ?>
        <section class="panel"><div class="panel-head"><div><p class="eyebrow">Grocery List</p><h2>Generated from weekly meal plan</h2><p class="muted">Ingredients are grouped from the selected meals for Monday to Sunday.</p></div><a class="btn ghost" href="index.php?page=meals&meal_view=lists">Open Lists Dashboard</a></div><div class="grocery-blueprint-grid"><?php foreach($groceryIdeas as $idea): ?><article class="grocery-blueprint-item"><div><strong><?= e($idea['title']) ?></strong><p><?= (int)$idea['count'] ?> meal<?= (int)$idea['count'] === 1 ? '' : 's' ?> • <?= e(implode(', ', array_slice(array_unique($idea['meals']),0,3))) ?></p></div><?php if($canMealEdit): ?><form method="post"><input type="hidden" name="action" value="create_list_item"><input type="hidden" name="return" value="meals"><input type="hidden" name="list_type" value="grocery"><input type="hidden" name="title" value="<?= e($idea['title']) ?>"><input type="hidden" name="notes" value="From weekly meal planner"><button class="chip-btn" type="submit">+ Add</button></form><?php endif; ?></article><?php endforeach; if(!$groceryIdeas): ?><p class="empty">No grocery items yet. Select meals in the weekly planner first.</p><?php endif; ?></div></section>
    <?php elseif($mealView === 'favorites'): $favorites=array_values(array_filter($library, fn($meal)=>!empty($meal['favorite']))); ?>
        <section class="panel"><div class="panel-head"><div><p class="eyebrow">Favorite Meals</p><h2>Fast-pick family meals</h2></div><a class="btn ghost" href="index.php?page=meals&meal_view=library">Manage Library</a></div><div class="menu-library-grid"><?php foreach($favorites as $meal) render_menu_card($meal, 'favorites'); if(!$favorites): ?><p class="empty">No favorite meals yet.</p><?php endif; ?></div></section>
    <?php endif; ?>
</section>
<?php elseif ($page === 'lists'): ?>
<section class="panel"><div class="panel-head"><div><p class="eyebrow">Lists Dashboard moved</p><h2>Lists are now inside Meals</h2><p class="muted">Use Meals → Lists Dashboard to manage groceries, errands, reminders, and to-dos.</p></div><a class="btn primary" href="index.php?page=meals&meal_view=lists">Open Lists Dashboard</a></div></section>
<?php elseif ($page === 'rewards'): $goal=(int)($settings['daily_goal'] ?? 40); $progress=min(100,$goal?round(((int)($user['points'] ?? 0)%$goal)/$goal*100):0); ?>
<section class="panel"><div class="panel-head"><div><p class="eyebrow">Rewards System</p><h2>Points, stars, streaks, milestones</h2></div><div class="streak-tile"><span><?= (int)($user['streak'] ?? 0) ?></span><small>day streak</small></div></div><div class="reward-summary"><div><b><?= (int)($user['points'] ?? 0) ?></b><span>Total points</span></div><div><b><?= (int)($user['stars'] ?? 0) ?></b><span>Stars earned</span></div><div><b><?= (int)$stats['completion'] ?>%</b><span>Today complete</span></div></div><div class="bar"><span style="width:<?= (int)$progress ?>%"></span></div><p class="muted">Next milestone progress based on your daily goal of <?= $goal ?> points.</p></section><section class="badge-grid"><?php $badges=[['Starter','Complete your first item',($user['points']??0)>0],['Helper','Earn 50 points',($user['points']??0)>=50],['Star Collector','Earn 10 stars',($user['stars']??0)>=10],['Streak Mode','Reach 3 days',($user['streak']??0)>=3]]; foreach($badges as $b): ?><div class="panel badge-card <?= $b[2]?'earned':'' ?>"><div class="badge-icon">🏆</div><h3><?= e($b[0]) ?></h3><p><?= e($b[1]) ?></p></div><?php endforeach; ?></section>
<?php elseif ($page === 'guardian'):
    $guardianSettings = guardian_settings_for($hubId);
    $guardianDevices = guardian_devices_for($hubId);
    $guardianApps = guardian_apps_for($hubId);
    $guardianEvents = guardian_policy_events_for($hubId, 14);
    $guardianMembers = guardian_child_members($settings);
    $guardianCanManage = can_manage_rewards($user);
    $guardianPolicies = [];
    foreach ($guardianMembers as $memberName) $guardianPolicies[$memberName] = guardian_policy_for_member($hubId, (string)$memberName);
    $lockedCount = count(array_filter($guardianPolicies, fn($p)=>!empty($p['locked'])));
?>
<section class="guardian-hero panel">
    <div>
        <p class="eyebrow">Guardian Mode</p>
        <h2>Task-gated app access for iOS and Android devices</h2>
        <p class="muted">Connect child devices, list blocked games/apps, and let HomeSyncHub publish lock/unlock policies automatically when chores or tasks are completed.</p>
    </div>
    <div class="guardian-hero-stats">
        <span><strong><?= (int)$lockedCount ?></strong><small>Locked profiles</small></span>
        <span><strong><?= count($guardianDevices) ?></strong><small>Devices</small></span>
        <span><strong><?= count(array_filter($guardianApps, fn($a)=>!empty($a['enabled']))) ?></strong><small>Blocked apps</small></span>
    </div>
</section>

<section class="guardian-grid">
    <article class="panel guardian-settings-card">
        <p class="eyebrow">Access Rules</p>
        <h2>Unlock condition</h2>
        <?php if($guardianCanManage): ?>
        <form method="post" class="settings-form mini-form">
            <input type="hidden" name="action" value="guardian_save_settings">
            <div class="toggle-row"><label><input type="checkbox" name="guardian_enabled" <?= !empty($guardianSettings['enabled'])?'checked':'' ?>> Enable Guardian Mode</label></div>
            <label>Unlock rule<select name="guardian_unlock_rule"><option value="all_due" <?= ($guardianSettings['unlock_rule']??'all_due')==='all_due'?'selected':'' ?>>Unlock only when all due tasks/chores are done</option><option value="per_completion" <?= ($guardianSettings['unlock_rule']??'')==='per_completion'?'selected':'' ?>>Unlock temporarily after each completion</option></select></label>
            <label>Temporary unlock duration<input name="device_unlock_minutes" type="number" min="5" max="1440" value="<?= (int)($guardianSettings['unlock_minutes'] ?? 120) ?>"></label>
            <label>Offline device behavior<select name="guardian_offline_behavior"><option value="keep_last_policy" <?= ($guardianSettings['offline_behavior']??'')==='keep_last_policy'?'selected':'' ?>>Keep last policy</option><option value="lock_when_offline" <?= ($guardianSettings['offline_behavior']??'')==='lock_when_offline'?'selected':'' ?>>Lock when offline</option><option value="allow_when_offline" <?= ($guardianSettings['offline_behavior']??'')==='allow_when_offline'?'selected':'' ?>>Allow when offline</option></select></label>
            <label>HTTPS device adapter webhook<input name="device_unlock_webhook_url" placeholder="https://your-device-agent.example/policy" value="<?= e($guardianSettings['webhook_url'] ?? '') ?>"></label>
            <button class="btn primary full" type="submit">Save Guardian Rules</button>
        </form>
        <?php else: ?><p class="access-note">Only a Family Hub Admin or Super Admin can change Guardian Mode rules.</p><?php endif; ?>
        <p class="muted small">This web app publishes the policy. Real app blocking still requires a native iOS Screen Time agent or Android Device Policy/approved blocker agent installed on each child device.</p>
    </article>

    <article class="panel guardian-add-card">
        <p class="eyebrow">Connected Devices</p>
        <h2>Add child device</h2>
        <?php if($guardianCanManage): ?>
        <form method="post" class="settings-form mini-form">
            <input type="hidden" name="action" value="guardian_add_device">
            <label>Child profile<select name="member"><?php foreach($guardianMembers as $memberName): ?><option value="<?= e($memberName) ?>"><?= e($memberName) ?></option><?php endforeach; ?></select></label>
            <label>Device name<input name="device_name" placeholder="Example: Shawn iPad" required></label>
            <label>Platform<select name="platform"><option value="ios">iOS / iPadOS</option><option value="android">Android</option><option value="web">Web / Test Agent</option></select></label>
            <button class="btn primary full" type="submit">Add Device</button>
        </form>
        <?php else: ?><p class="access-note">Admin access is required to enroll or remove devices.</p><?php endif; ?>
    </article>

    <article class="panel guardian-add-card">
        <p class="eyebrow">Blocked Apps</p>
        <h2>Add game or app</h2>
        <?php if($guardianCanManage): ?>
        <form method="post" class="settings-form mini-form">
            <input type="hidden" name="action" value="guardian_add_app">
            <label>Child profile<select name="member"><?php foreach($guardianMembers as $memberName): ?><option value="<?= e($memberName) ?>"><?= e($memberName) ?></option><?php endforeach; ?></select></label>
            <label>App name<input name="app_name" placeholder="Example: Roblox, Minecraft, YouTube" required></label>
            <label>Platform<select name="platform"><option value="all">All platforms</option><option value="ios">iOS / iPadOS</option><option value="android">Android</option><option value="web">Web / Test Agent</option></select></label>
            <label>Identifier / package / token note<input name="app_identifier" placeholder="Android package, iOS token label, or adapter id"></label>
            <button class="btn primary full" type="submit">Add Blocked App</button>
        </form>
        <?php else: ?><p class="access-note">Admin access is required to edit blocked apps.</p><?php endif; ?>
    </article>
</section>

<section class="guardian-policy-grid">
    <?php foreach($guardianPolicies as $memberName => $policy): ?>
    <article class="panel guardian-policy-card <?= !empty($policy['locked']) ? 'is-locked' : 'is-unlocked' ?>">
        <div class="guardian-policy-head">
            <div><p class="eyebrow"><?= e($memberName) ?></p><h2><?= !empty($policy['locked']) ? 'Apps Locked' : 'Apps Unlocked' ?></h2></div>
            <span class="guardian-state-pill"><?= e(strtoupper((string)$policy['state'])) ?></span>
        </div>
        <div class="guardian-policy-metrics">
            <span><strong><?= count($policy['required_items'] ?? []) ?></strong><small>due tasks/chores</small></span>
            <span><strong><?= count($policy['blocked_apps'] ?? []) ?></strong><small>blocked apps</small></span>
            <span><strong><?= count($policy['devices'] ?? []) ?></strong><small>devices</small></span>
        </div>
        <?php if(!empty($policy['required_items'])): ?>
            <div class="guardian-list compact"><strong>Complete before unlock</strong><?php foreach(array_slice($policy['required_items'],0,4) as $req): ?><span><?= e($req['type']) ?> · <?= e($req['title']) ?></span><?php endforeach; ?></div>
        <?php else: ?>
            <p class="access-note success-note">No pending due chores or tasks for this profile.</p>
        <?php endif; ?>
        <?php if(!empty($policy['unlock_until'])): ?><p class="muted small">Temporary unlock valid until <?= e(format_dt($policy['unlock_until'])) ?>.</p><?php endif; ?>
        <?php if($guardianCanManage): ?><form method="post"><input type="hidden" name="action" value="guardian_manual_sync"><input type="hidden" name="member" value="<?= e($memberName) ?>"><button class="btn ghost full" type="submit">Refresh policy now</button></form><?php endif; ?>
    </article>
    <?php endforeach; ?>
</section>

<section class="grid dashboard-grid guardian-lists-grid">
    <article class="panel guardian-table-panel">
        <div class="panel-headline"><div><p class="eyebrow">Device Registry</p><h2>Enrolled child devices</h2></div><?php if($guardianCanManage): ?><form method="post"><input type="hidden" name="action" value="guardian_manual_sync"><button class="btn ghost">Sync All</button></form><?php endif; ?></div>
        <div class="guardian-device-list">
            <?php foreach($guardianDevices as $device): ?>
            <article class="guardian-device-row">
                <div><strong><?= e($device['device_name'] ?? 'Device') ?></strong><small><?= e($device['member'] ?? 'Family') ?> · <?= e(strtoupper((string)($device['platform'] ?? 'web'))) ?> · <?= e($device['status'] ?? 'active') ?> · policy <?= e($device['policy_state'] ?? 'unknown') ?></small><code>index.php?action=guardian_policy&amp;token=<?= e($device['adapter_token'] ?? '') ?></code></div>
                <?php if($guardianCanManage): ?><form method="post" class="inline-actions"><input type="hidden" name="device_id" value="<?= e($device['id'] ?? '') ?>"><?php if(($device['status'] ?? 'active')==='active'): ?><button class="btn ghost" name="action" value="guardian_pause_device">Pause</button><?php else: ?><button class="btn success" name="action" value="guardian_activate_device">Activate</button><?php endif; ?><button class="btn danger" name="action" value="guardian_archive_device" onclick="return confirm('Remove this Guardian device?')">Remove</button></form><?php endif; ?>
            </article>
            <?php endforeach; ?>
            <?php if(!$guardianDevices): ?><p class="empty small-empty">No Guardian devices yet. Add the child iPad, iPhone, Android phone, or Android tablet here.</p><?php endif; ?>
        </div>
    </article>

    <article class="panel guardian-table-panel">
        <p class="eyebrow">Blocked Apps</p><h2>Games and software to restrict</h2>
        <div class="guardian-app-list">
            <?php foreach($guardianApps as $app): ?>
            <article class="guardian-app-row <?= empty($app['enabled']) ? 'is-disabled' : '' ?>">
                <div><strong><?= e($app['app_name'] ?? 'App') ?></strong><small><?= e($app['member'] ?? 'Family') ?> · <?= e(strtoupper((string)($app['platform'] ?? 'all'))) ?><?= !empty($app['app_identifier']) ? ' · ' . e($app['app_identifier']) : '' ?></small></div>
                <?php if($guardianCanManage): ?><form method="post"><input type="hidden" name="app_id" value="<?= e($app['id'] ?? '') ?>"><?php if(!empty($app['enabled'])): ?><button class="btn ghost" name="action" value="guardian_disable_app">Disable</button><?php else: ?><button class="btn success" name="action" value="guardian_enable_app">Enable</button><?php endif; ?></form><?php endif; ?>
            </article>
            <?php endforeach; ?>
            <?php if(!$guardianApps): ?><p class="empty small-empty">Add games or apps that should stay blocked until the child completes the required HomeSyncHub work.</p><?php endif; ?>
        </div>
    </article>
</section>

<section class="panel guardian-events-panel">
    <p class="eyebrow">Audit Log</p><h2>Recent Guardian policy events</h2>
    <div class="timeline compact-timeline">
        <?php foreach($guardianEvents as $event): ?>
            <div class="timeline-item"><span><?= e(strtoupper((string)($event['state'] ?? ''))) ?></span><div><strong><?= e($event['member'] ?? 'Family') ?> · <?= e($event['reason'] ?? 'Policy update') ?></strong><small><?= e(format_dt($event['created_at'] ?? '', 'Recently')) ?> · <?= e($event['webhook_status'] ?? 'Recorded locally') ?></small></div></div>
        <?php endforeach; ?>
        <?php if(!$guardianEvents): ?><p class="empty small-empty">No policy events yet. Create a device/app rule or complete a chore to generate the first policy update.</p><?php endif; ?>
    </div>
</section>

<?php elseif ($page === 'workspaces'): $workspaceStore = read_store(); $activeWorkspaceId = $hubId; $activeWorkspace = workspace_by_id($workspaceStore, $activeWorkspaceId) ?: []; $linkedWorkspaces = accessible_workspaces_for_user($user, $workspaceStore); $joinableWorkspaces = available_family_hubs_for_join($workspaceStore, $user); $workspaceOptions = $linkedWorkspaces; $workspaceMembers = workspace_members_for($activeWorkspaceId, true); $currentMembership = current_membership_for_user($user, $activeWorkspaceId); $currentFamilyStatus = family_status_label($user, $activeWorkspace, $currentMembership); $currentRoleLevel = role_badge($user); $userInitials = user_initials((string)($user['name'] ?? 'User')); $profilePhoto = user_profile_photo($user); $profileBgStyle = ''; $profileBgClass = ''; $canSwitchFamilyHub = count($workspaceOptions) > 1; ?>
<section class="grid dashboard-grid">
  <div class="panel wide">
    <div class="panel-head"><div><p class="eyebrow">Family Hub System</p><h2>Private family hubs</h2><p class="muted">Each family hub is isolated. Calendar, meals, chores, rewards, members, lists, photos, settings, and history stay inside the active family hub.</p></div><span class="role-chip"><?= e(role_badge($user)) ?></span></div>
    <div class="workspace-code-card active-family-hub-profile-panel"><form method="post" class="active-family-hub-profile-card workspace-profile-card<?= e($profileBgClass) ?>"<?= $profileBgStyle ?> aria-label="Active Family Hub"><input type="hidden" name="action" value="switch_workspace"><input type="hidden" name="return" value="workspaces"><div class="family-profile-avatar family-profile-avatar-xl" aria-hidden="true"><?php if($profilePhoto !== ''): ?><img class="profile-avatar-img" src="<?= e($profilePhoto) ?>" alt=""><?php else: ?><?= e($userInitials) ?><?php endif; ?></div><div class="family-profile-info"><div class="family-profile-name"><?= e($user['name'] ?? 'User') ?></div><div class="family-profile-row"><span class="row-icon">👥</span><span class="row-label">Family Hub</span><strong><?= e($activeWorkspace['name'] ?? 'Family Hub') ?></strong></div><div class="family-profile-row"><span class="row-icon">💼</span><span class="row-label">Role</span><strong><?= e($currentRoleLevel) ?></strong></div><div class="family-profile-row"><span class="row-icon">🛡️</span><span class="row-label">Status</span><strong class="hub-status"><i></i><?= e($currentFamilyStatus) ?></strong></div><div class="family-profile-switch"><select name="workspace_id" aria-label="Switch active family hub"><?php foreach($workspaceOptions as $ws): ?><option value="<?= e($ws['id']) ?>" <?= ($ws['id']??'')===$activeWorkspaceId?'selected':'' ?>><?= e($ws['name'] ?? 'Family Hub') ?></option><?php endforeach; ?></select><button class="hub-switch-btn" type="submit" <?= $canSwitchFamilyHub ? '' : 'disabled' ?>>Switch</button></div></div></form></div>
    <div class="role-table workspace-table family-hub-options-table"><div class="role-row role-head"><span>Family Hub</span><span>Status</span><span>Switch to Family Hub</span></div><?php foreach($linkedWorkspaces as $ws): ?><form method="post" class="role-row family-hub-option-row"><input type="hidden" name="action" value="switch_workspace"><input type="hidden" name="return" value="workspaces"><input type="hidden" name="workspace_id" value="<?= e($ws['id']) ?>"><span><strong><?= e($ws['name'] ?? 'Workspace') ?></strong><small><?= ($ws['id'] ?? '')===$activeWorkspaceId ? 'Currently active family hub' : 'Linked family hub' ?></small></span><span><span class="pill <?= ($ws['status'] ?? 'active')==='active'?'pill-done':'' ?>"><?= e($ws['status'] ?? 'active') ?></span></span><span><?php if(($ws['id'] ?? '')!==$activeWorkspaceId): ?><button class="btn primary">Switch to Family Hub</button><?php else: ?><span class="access-note">Selected</span><?php endif; ?></span></form><?php endforeach; ?></div>
  </div>
  <aside class="panel family-hub-setup-panel">
    <p class="eyebrow">Family Hub Setup</p><h2>Join, create, or switch</h2><p class="muted">Use only the Family Hub actions below: join an available Family Hub, create a new Family Hub, or switch to one already linked to your account.</p>
    <form method="post" class="settings-form"><input type="hidden" name="action" value="create_personal_workspace"><label>New Family Hub name<input name="family_hub_name" placeholder="Example: Cabornay Family Hub" required></label><button class="btn primary full">Create Family Hub</button></form>
    <hr class="soft-rule">
    <form method="post" class="settings-form" onsubmit="return confirm('You are about to join a Family Hub. Do you want to proceed?')"><input type="hidden" name="action" value="join_workspace"><label>Join Family Hub<select name="family_hub_id" required><option value="">Select Family Hub</option><?php foreach($joinableWorkspaces as $familyHub): ?><option value="<?= e($familyHub['id'] ?? '') ?>"><?= e($familyHub['name'] ?? 'Family Hub') ?></option><?php endforeach; ?></select><small class="field-help">Choose from available Family Hubs.</small></label><?php if(!$joinableWorkspaces): ?><p class="access-note">No additional Family Hubs are available to join.</p><?php endif; ?><button class="btn ghost full">Join Family Hub</button></form>
  </aside></section>
<section class="panel"><div class="panel-head"><div><p class="eyebrow">Members in active family hub</p><h2>Manage linked users</h2><p class="muted">Admins can manage only this family hub. Super Admin can manage every workspace and restore archived members.</p></div></div><div class="role-table"><div class="role-row role-head"><span>Member</span><span>Role</span><span>Status</span><span>Action</span></div><?php foreach($workspaceMembers as $m): ?><form method="post" class="role-row"><input type="hidden" name="return" value="workspaces"><input type="hidden" name="workspace_id" value="<?= e($activeWorkspaceId) ?>"><input type="hidden" name="member_id" value="<?= e($m['id'] ?? '') ?>"><span><strong><?= e($m['user_name'] ?? '') ?></strong><small><?= e($m['email'] ?? '') ?></small></span><span><?php if(can_manage_access($user)): ?><select name="member_role"><?php foreach(workspace_role_options() as $roleChoice): ?><option <?= ($m['role'] ?? '')===$roleChoice?'selected':'' ?>><?= e($roleChoice) ?></option><?php endforeach; ?></select><?php else: ?><?= e($m['role'] ?? 'Member') ?><?php endif; ?></span><span><span class="pill"><?= e($m['status'] ?? 'active') ?></span></span><span class="row-actions"><?php if(can_manage_access($user)): ?><button class="btn primary" name="action" value="update_workspace_member_role">Save</button><?php if(($m['status'] ?? '')==='active'): ?><button class="btn danger" name="action" value="archive_workspace_member" onclick="return confirm('Archive this member/admin from the active family hub?')">Archive</button><?php else: ?><button class="btn success" name="action" value="restore_workspace_member">Restore</button><?php endif; ?><?php else: ?><small class="access-note">View only</small><?php endif; ?></span></form><?php endforeach; ?></div></section>


<?php elseif ($page === 'sync'): ?>
<section class="grid dashboard-grid"><div class="panel"><div class="panel-head"><div><p class="eyebrow">Calendar Syncing</p><h2>External calendar connections</h2></div><a class="btn ghost" href="index.php?page=calendar&action=export_ics">Download .ics</a></div><p class="muted">This build stores provider connections and exports a feed. Real two-way Google/iCloud sync needs OAuth credentials and API setup on your server.</p><div class="provider-grid"><?php foreach(['Google Calendar'=>'two-way ready','Apple iCloud'=>'two-way ready','Outlook'=>'one-way ready','Cozi'=>'one-way ready','Yahoo'=>'one-way ready'] as $name=>$mode): ?><div class="provider-card"><b><?= e($name) ?></b><span><?= e($mode) ?></span></div><?php endforeach; ?></div><div class="connection-list"><?php foreach($connections as $c): ?><article class="list-row"><div><strong><?= e($c['provider']) ?> — <?= e($c['label']) ?></strong><p><?= e($c['account']) ?> • <?= e($c['sync_mode']) ?> • <?= e($c['status']) ?></p></div><form method="post"><input type="hidden" name="action" value="delete_connection"><input type="hidden" name="connection_id" value="<?= e($c['id']) ?>"><button class="icon-btn danger">×</button></form></article><?php endforeach; if(!$connections): ?><p class="empty">No calendar connections saved yet.</p><?php endif; ?></div></div><aside class="panel"><p class="eyebrow">Add connection</p><h2>Integration record</h2><?php if(!can_manage_sync($user)): ?><p class="access-note">Sync settings require workspace Admin or Super Admin access.</p><?php endif; ?><form method="post" class="settings-form"><input type="hidden" name="action" value="save_connection"><label>Provider<select name="provider"><option>Google Calendar</option><option>Apple iCloud</option><option>Outlook</option><option>Cozi</option><option>Yahoo</option></select></label><label>Calendar label<input name="label" placeholder="Family calendar"></label><label>Account/email<input name="account" placeholder="name@example.com"></label><label>Sync mode<select name="sync_mode"><option value="two-way-ready">Two-way ready</option><option value="one-way">One-way</option><option value="local-feed">Local .ics feed</option></select></label><button class="btn primary full">Save Connection</button></form></aside></section>
<?php elseif ($page === 'magic'): ?>
<section class="grid dashboard-grid"><div class="panel"><p class="eyebrow">Magic Import</p><h2>Convert pasted schedules into items</h2><p class="muted">Paste text from an email, school notice, flyer, or list. Supported prefixes: Event:, Task:, Chore:, Meal:, Grocery:, Todo:, plus dated lines like 2026-05-18 18:30 Soccer practice.</p><form method="post" class="settings-form"><input type="hidden" name="action" value="magic_import"><textarea name="import_text" rows="10" placeholder="Event: Dentist appointment&#10;2026-05-20 18:30 Football training&#10;Grocery: Apples&#10;Chore: Take out trash"></textarea><button class="btn primary">Import Items</button></form></div><aside class="panel"><p class="eyebrow">Sidekick Smart Assistant</p><h2>Generate simple meal plans</h2><p class="muted">This local helper uses built-in meal-plan templates to create dinner plans immediately. External AI automation can be connected when provider credentials are available.</p><form method="post" class="settings-form"><input type="hidden" name="action" value="sidekick_generate"><label>Planning focus<input name="focus" placeholder="budget, healthy, kid-friendly"></label><label>How many days<input name="days" type="number" min="1" max="7" value="3"></label><button class="btn primary full">Generate Meals</button></form></aside></section>
<?php elseif ($page === 'display'): $todayItems=items_on_date($items,app_now()->format('Y-m-d')); $sleep=is_sleeping($settings); ?>
<section class="display-board screensaver-display <?= $sleep?'sleeping':'' ?>">
  <div class="screensaver-frame standard-brand-frame"><img src="assets/brand/home-sync-hub-dashboard-banner-default.png" width="1400" height="170" decoding="async" alt="HomeSyncHub Family Dashboard Overview screensaver"></div>
  <div class="screensaver-live-row"><div><p class="eyebrow"><?= e($settings['device_name']) ?></p><h2 id="liveClock"><?= e(app_now()->format('h:i A')) ?></h2><p><?= e(app_now()->format('l, d F Y')) ?> • <?= e($settings['weather_summary']) ?></p></div><a class="btn ghost" href="index.php?page=settings">Screensaver Settings</a></div>
  <?php if($sleep): ?><div class="sleep-overlay"><h2>Sleep Mode</h2><p>Display wakes at <?= e($settings['sleep_end']) ?>.</p></div><?php endif; ?>
  <div class="display-grid"><div class="panel"><h2>Today</h2><div class="item-stack"><?php foreach($todayItems as $item) render_item_card($item,'display',$settings,true); if(!$todayItems): ?><p class="empty">Nothing scheduled today.</p><?php endif; ?></div></div><div class="panel"><h2>Screensaver Cards</h2><div class="screensaver-stack"><?php foreach(array_slice($photos,0,6) as $photo): ?><div class="photo-card" style="--photo-color: <?= e($photo['color']) ?>"><b><?= e($photo['title']) ?></b><span><?= e($photo['caption']) ?></span></div><?php endforeach; ?></div><form method="post" class="settings-form mini-form"><input type="hidden" name="action" value="add_photo"><label>Card title<input name="photo_title" placeholder="Family trip"></label><label>Caption<input name="photo_caption" placeholder="Screensaver caption"></label><label>Color<input name="photo_color" type="color" value="#49d9ff"></label><button class="btn primary full">Add screensaver card</button></form></div></div>
</section>
<?php elseif ($page === 'profile'):
    $profileStore = read_store();
    $activeWorkspaceId = current_workspace_id_for_user($user);
    $activeWorkspace = workspace_by_id($profileStore, $activeWorkspaceId) ?? ['name'=>'Family Hub','status'=>'active'];
    $profileMembership = current_membership_for_user($user, $activeWorkspaceId);
    $currentRoleLevel = is_super_admin($user) ? 'Platform Super Admin' : workspace_role_for_user($user, $activeWorkspaceId);
    $currentFamilyStatus = family_status_label($user, $activeWorkspace, $profileMembership);
    $workspaceOptions = accessible_workspaces_for_user($user, $profileStore, false);
    $canSwitchFamilyHub = count($workspaceOptions) > 1 || is_super_admin($user);
?>
<section class="hsh-profile-page-wrap">
    <div class="hsh-profile-title"><p class="eyebrow">HomeSyncHub Profile</p><h2>Ultra-legendary account identity</h2><p class="muted">Manage your visible name, photo, active Family Hub, role level, and session controls.</p></div>
    <div class="hsh-profile-card hsh-profile-page-card" aria-label="HomeSyncHub profile page">
        <div class="hsh-profile-orb hsh-profile-orb-xl" aria-hidden="true"><?php if(user_profile_photo($user) !== ''): ?><img class="profile-avatar-img" src="<?= e(user_profile_photo($user)) ?>" alt=""><?php else: ?><?= e(user_initials((string)($user['name'] ?? 'User'))) ?><?php endif; ?><span></span><small>Level <?= is_super_admin($user) ? '999' : ((int)($user['points'] ?? 0)) ?></small></div>
        <div class="hsh-profile-main">
            <div class="hsh-profile-heading"><div><h2><?= e($user['name'] ?? 'User') ?></h2><p>Master Control Identity · Family Hub Command Center</p></div><b>⚡ <?= e(strtoupper($currentRoleLevel)) ?></b></div>
            <div class="hsh-profile-info-grid">
                <div class="hsh-info-card"><i>👥</i><span>Family Hub</span><strong><?= e($activeWorkspace['name'] ?? 'Family Hub') ?></strong></div>
                <div class="hsh-info-card"><i>🛡️</i><span>Role</span><strong><?= e($currentRoleLevel) ?></strong></div>
                <div class="hsh-info-card"><i>💎</i><span>Status</span><strong class="hsh-active-status"><em></em><?= e($currentFamilyStatus) ?></strong></div>
            </div>
            <div class="hsh-profile-action-row">
                <form method="post" class="hsh-switch-form">
                    <input type="hidden" name="action" value="switch_workspace">
                    <input type="hidden" name="return" value="profile">
                    <select name="workspace_id" aria-label="Switch active family hub"><?php foreach($workspaceOptions as $ws): ?><option value="<?= e($ws['id']) ?>" <?= ($ws['id']??'')===$activeWorkspaceId?'selected':'' ?>><?= e($ws['name'] ?? 'Family Hub') ?></option><?php endforeach; ?></select>
                    <button class="hsh-switch-btn" type="submit" <?= $canSwitchFamilyHub ? '' : 'disabled' ?>>Switch</button>
                </form>
                <a class="hsh-profile-link" href="index.php?page=settings">Edit Profile Photo</a>
                <form method="post" class="profile-logout-form"><input type="hidden" name="action" value="logout"><button class="hsh-logout-btn" type="submit">Logout</button></form>
            </div>
        </div>
    </div>
</section>

<?php elseif ($page === 'admin'): ?>
<?php if(!can_manage_system($user)): ?>
<section class="panel"><p class="eyebrow">Super Admin</p><h2>Super Admin access required</h2><p class="muted">This area controls the full platform across all private workspaces. Your current role is <?= e(role_badge($user)) ?>.</p></section>
<?php else: $adminUsers=users_for_admin(); $allWorkspaces=workspaces_for_admin(true); ?>
<section class="grid dashboard-grid"><div class="panel wide"><div class="panel-head"><div><p class="eyebrow">Super Admin</p><h2>Workspace archive, delete, and recovery</h2><p class="muted">Archive keeps a workspace recoverable. Delete permanently removes the workspace and its calendar, meals, chores, rewards, lists, members, settings, and access links from this local system.</p></div></div><form method="post" class="settings-form inline-create"><input type="hidden" name="action" value="create_workspace_super"><label>Create workspace<input name="workspace_name" placeholder="Family name or workspace name"></label><button class="btn primary">Create Workspace</button></form><div class="role-table admin-workspace-table"><div class="role-row role-head"><span>Workspace</span><span>Members</span><span>Action</span></div><?php foreach($allWorkspaces as $ws): ?><form method="post" class="role-row"><input type="hidden" name="workspace_id" value="<?= e($ws['id']) ?>"><span><strong><?= e($ws['name'] ?? 'Workspace') ?></strong><small>Status: <?= e($ws['status'] ?? 'active') ?></small></span><span><?= (int)($ws['member_count'] ?? 0) ?> active</span><span><?php if(($ws['status'] ?? 'active')==='active'): ?><button class="btn danger" name="action" value="archive_workspace" onclick="return confirm('Archive this workspace? Data will be preserved for recovery.')">Archive</button><?php else: ?><button class="btn success" name="action" value="restore_workspace">Restore</button><?php endif; ?><?php if(($ws['id'] ?? '') !== 'workspace_system'): ?><button class="btn danger hard-delete-btn" name="action" value="delete_workspace" onclick="return confirm('Permanently delete this workspace? This cannot be undone and all workspace data will be removed from this local system.')">Delete</button><?php else: ?><span class="access-note">Protected</span><?php endif; ?></span></form><?php endforeach; ?></div></div><aside class="panel"><p class="eyebrow">Platform users</p><h2>Edit names, emails, archive, restore</h2><p class="muted">Super Admin can update registered email addresses and display names for Super Admin, Admins, and Members. Archive remains soft-delete only.</p><div class="role-permission-list"><?php foreach($adminUsers as $au): ?><form method="post" class="admin-user-card"><input type="hidden" name="target_user_id" value="<?= e($au['id']) ?>"><label class="admin-name-edit">Display name<input name="display_name" value="<?= e($au['name'] ?? 'User') ?>" required></label><label class="admin-name-edit">Registered email<input name="email" type="email" value="<?= e($au['email'] ?? '') ?>" required></label><small><?= e($au['role'] ?? 'User') ?> · <?= e($au['status'] ?? 'active') ?><?php if(!empty($au['terms_accepted_at'])): ?> · Terms accepted <?= e(format_dt($au['terms_accepted_at'])) ?><?php endif; ?></small><button class="btn primary" name="action" value="superadmin_update_user_identity">Save Name + Email</button><?php if(!is_super_admin_role((string)($au['role'] ?? ''))): ?><?php if(($au['status'] ?? 'active')==='active'): ?><button class="btn danger" name="action" value="archive_user" onclick="return confirm('Archive this user? Workspaces and history remain recoverable.')">Archive User</button><?php else: ?><button class="btn success" name="action" value="restore_user">Restore User</button><?php endif; ?><?php else: ?><span class="access-note">Protected Super Admin: name and email editable, archive blocked.</span><?php endif; ?></form><?php endforeach; ?></div><hr class="soft-rule"><p class="access-note">Default bootstrap: superadmin@homesynchub.local / ChangeMe123! — change before public deployment.</p></aside></section>
<?php endif; ?>
<?php elseif ($page === 'settings'): ?>
<section class="grid dashboard-grid"><form method="post" class="panel settings-form"><input type="hidden" name="action" value="save_settings"><p class="eyebrow">Settings</p><h2>App, profiles, display, weather</h2><div class="form-grid three"><label>Theme<select name="theme"><option value="dark" <?= ($settings['theme']??'')==='dark'?'selected':'' ?>>Dark</option><option value="light" <?= ($settings['theme']??'')==='light'?'selected':'' ?>>Light</option><option value="auto" <?= ($settings['theme']??'')==='auto'?'selected':'' ?>>Auto</option></select></label><label>Site view<select name="view_mode"><option value="auto" <?= ($settings['view_mode']??'auto')==='auto'?'selected':'' ?>>Auto detect</option><option value="mobile" <?= ($settings['view_mode']??'')==='mobile'?'selected':'' ?>>Mobile Site</option><option value="desktop" <?= ($settings['view_mode']??'')==='desktop'?'selected':'' ?>>Desktop Site</option></select></label><label>Accent<select name="accent"><option value="ocean" <?= ($settings['accent']??'')==='ocean'?'selected':'' ?>>Ocean</option><option value="violet" <?= ($settings['accent']??'')==='violet'?'selected':'' ?>>Violet</option><option value="sunset" <?= ($settings['accent']??'')==='sunset'?'selected':'' ?>>Sunset</option><option value="forest" <?= ($settings['accent']??'')==='forest'?'selected':'' ?>>Forest</option><option value="rose" <?= ($settings['accent']??'')==='rose'?'selected':'' ?>>Rose</option></select></label><label>Daily point goal<input name="daily_goal" type="number" min="10" max="200" value="<?= (int)($settings['daily_goal'] ?? 40) ?>"></label></div><label>Home message<input name="home_message" value="<?= e($settings['home_message'] ?? '') ?>"></label><h3>Color-coded profiles</h3><div class="profile-editor"><?php foreach(profiles_for($settings) as $p): ?><div class="profile-edit-row"><input name="profile_avatar[]" value="<?= e($p['avatar']) ?>" aria-label="Avatar"><input name="profile_name[]" value="<?= e($p['name']) ?>" aria-label="Name"><input name="profile_color[]" type="color" value="<?= e($p['color']) ?>" aria-label="Color"></div><?php endforeach; ?><div class="profile-edit-row"><input name="profile_avatar[]" value="👤"><input name="profile_name[]" placeholder="Add member"><input name="profile_color[]" type="color" value="#44d7a8"></div></div><h3>Weather + reminders</h3><div class="form-grid three"><label>Default reminder<input name="reminder_minutes" type="number" min="0" max="1440" value="<?= (int)($settings['reminder_minutes'] ?? 30) ?>"></label><label>Weather location<input name="weather_location" value="<?= e($settings['weather_location'] ?? '') ?>"></label><label>Weather summary<input name="weather_summary" value="<?= e($settings['weather_summary'] ?? '') ?>"></label></div><h3>Touchscreen display</h3><div class="form-grid three"><label>Device name<input name="device_name" value="<?= e($settings['device_name'] ?? '') ?>"></label><label>Sleep start<input name="sleep_start" type="time" value="<?= e($settings['sleep_start'] ?? '22:30') ?>"></label><label>Sleep end<input name="sleep_end" type="time" value="<?= e($settings['sleep_end'] ?? '06:30') ?>"></label></div><div class="toggle-row"><label><input type="checkbox" name="sleep_enabled" <?= !empty($settings['sleep_enabled'])?'checked':'' ?>> Sleep mode enabled</label><label><input type="checkbox" name="parental_lock" <?= !empty($settings['parental_lock'])?'checked':'' ?>> Parental lock enabled</label><label><input type="checkbox" name="screensaver_enabled" <?= !empty($settings['screensaver_enabled'])?'checked':'' ?>> Photo screensaver enabled</label></div><h3>Completion rewards and device access</h3><div class="form-grid three"><label>Unlock duration minutes<input name="device_unlock_minutes" type="number" min="5" max="1440" value="<?= (int)($settings['device_unlock_minutes'] ?? 120) ?>"></label><label>HTTPS unlock webhook<input name="device_unlock_webhook_url" placeholder="https://your-device-adapter/unlock" value="<?= e($settings['device_unlock_webhook_url'] ?? '') ?>"></label></div><div class="toggle-row"><label><input type="checkbox" name="device_unlock_enabled" <?= !empty($settings['device_unlock_enabled'])?'checked':'' ?>> Grant device access after successful completion</label></div><p class="muted small">For iOS/Android, this PWA records an unlock grant and can call a device-control adapter. A native iOS Screen Time/Android Device Policy app is required to enforce real device restrictions.</p><button class="btn primary">Save Settings</button></form><aside class="panel profile-settings-panel"><p class="eyebrow">My Profile</p><h2>Photo and name</h2><form method="post" enctype="multipart/form-data" class="settings-form mini-form profile-media-form"><input type="hidden" name="action" value="save_my_profile"><input type="hidden" name="return" value="settings"><div class="profile-media-preview active-family-hub-profile-card"><div class="family-profile-avatar"><?php if(user_profile_photo($user) !== ''): ?><img class="profile-avatar-img" src="<?= e(user_profile_photo($user)) ?>" alt="Profile photo"><?php else: ?><?= e(user_initials((string)($user['name'] ?? 'User'))) ?><?php endif; ?></div><strong><?= e($user['name'] ?? 'User') ?></strong></div><label>Display name<input name="display_name" value="<?= e($user['name'] ?? '') ?>" required></label><label>Profile photo<input name="profile_photo" type="file" accept="image/png,image/jpeg,image/webp"><small class="field-help">Replaces the initials/logo on the left side of the Active Family Hub card.</small></label><button class="btn primary full" type="submit">Save Profile</button></form><hr class="soft-rule"><p class="eyebrow">Current Access</p><h2><?= e(role_badge($user)) ?></h2><p class="muted"><?= e(role_description(role_badge($user))) ?></p><div class="role-matrix"><strong>Hierarchy</strong><span>Super Admin → Workspace Admin → Member</span><small>Each workspace has its own Admin/Member role. A user can be Member in one workspace and Admin in another.</small></div><hr class="soft-rule"><p class="eyebrow">Active Family Hub</p><h2><?= e(workspace_name($hubId)) ?></h2><p class="muted">Family Hub access and member management are handled on the Family Hubs page.</p><a class="btn primary full" href="index.php?page=workspaces">Open Family Hubs</a><form method="post" class="logout-form"><input type="hidden" name="action" value="logout"><button class="btn ghost full">Log out</button></form></aside></section>
<section class="grid dashboard-grid security-grid">
    <div class="panel security-panel">
        <p class="eyebrow">Account Security</p>
        <h2>Password recovery and change</h2>
        <p class="muted">Use a strong password. Forgotten-password recovery sends a reset link to the registered email.</p>
        <form method="post" class="settings-form mini-form">
            <input type="hidden" name="action" value="change_password">
            <label>Current password<input name="current_password" type="password" required></label>
            <label>New password<input name="new_password" type="password" minlength="8" required></label>
            <label>Confirm new password<input name="new_password_confirm" type="password" minlength="8" required></label>
            <button class="btn primary full" type="submit">Change Password</button>
        </form>
    </div>
    <aside class="panel security-panel">
        <p class="eyebrow">Two-Factor Authentication</p>
        <h2><?= !empty($user['two_factor_enabled']) ? '2FA Enabled' : 'Authenticator App 2FA' ?></h2>
        <p class="muted">Compatible with Google Authenticator, Microsoft Authenticator, Authy, 1Password, and other TOTP apps.</p>
        <?php if(!empty($user['two_factor_enabled'])): ?>
            <div class="access-note">Your account requires a 6-digit authenticator code after password login.</div>
            <form method="post" class="settings-form mini-form" onsubmit="return confirm('Disable 2FA for this account?')">
                <input type="hidden" name="action" value="disable_2fa">
                <label>Password<input name="password" type="password" required></label>
                <label>Authenticator code<input name="totp_code" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" required></label>
                <button class="btn danger full" type="submit">Disable 2FA</button>
            </form>
        <?php else: $pendingSecret = (string)($user['two_factor_pending_secret'] ?? ''); ?>
            <?php if($pendingSecret === ''): ?>
                <form method="post"><input type="hidden" name="action" value="start_2fa_setup"><button class="btn primary full" type="submit">Generate 2FA Setup Key</button></form>
            <?php else: ?>
                <?php $otpUri = otpauth_uri_for_user($user, $pendingSecret); $qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=240x240&margin=10&data=' . rawurlencode($otpUri); ?>
                <div class="totp-setup-box totp-qr-setup">
                    <div class="totp-qr-card">
                        <img src="<?= e($qrUrl) ?>" width="240" height="240" alt="Scan this QR barcode with Google Authenticator or Microsoft Authenticator">
                    </div>
                    <div>
                        <strong>Scan barcode or enter setup key</strong>
                        <p class="muted small">Open Google Authenticator, Microsoft Authenticator, Authy, 1Password, or another TOTP app. Scan the barcode, or choose manual entry and paste the setup key.</p>
                        <code><?= e($pendingSecret) ?></code>
                        <small>Manual setup URI: <?= e($otpUri) ?></small>
                    </div>
                </div>
                <form method="post" class="settings-form mini-form">
                    <input type="hidden" name="action" value="confirm_2fa_setup">
                    <label>6-digit code from app<input name="totp_code" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" required></label>
                    <button class="btn primary full" type="submit">Confirm and Enable 2FA</button>
                </form>
                <form method="post"><input type="hidden" name="action" value="start_2fa_setup"><button class="btn ghost full" type="submit">Regenerate Setup Key</button></form>
            <?php endif; ?>
        <?php endif; ?>
    </aside>
</section>


<?php else: ?><section class="panel"><h2>Page not found</h2><p class="muted">Choose a section from the navigation.</p></section><?php endif; ?>
<?php render_shell_end($settings,$page); ?>
