<!DOCTYPE html>
<!--
  Familiar - Self-hosted AI Agent
  Copyright (c) 2026 George Scott Foley
  
  Licensed under the MIT License
  For commercial licensing, contact: licensing@familiar.ai
-->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Familiar Dashboard</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">
</head>
<body>
    <div class="app">
        <!-- Header -->
        <header>
            <div class="logo">
                <i class="fas fa-dragon"></i>
                <span id="header-name">{{ creature_name }}</span>
                {% if version %}<span style="font-size:0.6rem; color:var(--text-dim); margin-left:6px;">v{{ version }}</span>{% endif %}
            </div>
            <div class="status-badge">
                <div class="status-dot" id="status-dot"></div>
                <span id="status-text">Connecting...</span>
            </div>
        </header>
        
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="nav-section collapsed">
                <h4>Main</h4>
                <div class="nav-section-items">
                    <div class="nav-item active" data-panel="chat">
                        <i class="fas fa-comments"></i>
                        <span>Chat</span>
                    </div>
                    <div class="nav-item" data-panel="roundtable">
                        <i class="fas fa-users-round"></i>
                        <span>Round Table</span>
                    </div>
                    <div class="nav-item" data-panel="terminal">
                        <i class="fas fa-terminal"></i>
                        <span>Terminal</span>
                    </div>
                    <div class="nav-item" data-panel="shell" id="shell-nav" style="display:none">
                        <i class="fas fa-terminal"></i>
                        <span>Shell<span class="shell-nav-badge">HOST</span></span>
                    </div>
                    <div class="nav-item" data-panel="briefing">
                        <i class="fas fa-sun"></i>
                        <span>Briefing</span>
                    </div>
                    <div class="nav-item" data-panel="calendar">
                        <i class="fas fa-calendar-alt"></i>
                        <span>Calendar</span>
                    </div>
                    <div class="nav-item" data-panel="workspace" id="workspace-nav" style="display:none">
                        <i class="fas fa-th-large" id="workspace-nav-icon"></i>
                        <span id="workspace-nav-label">Workspace</span>
                    </div>
                    <div class="nav-item" data-panel="media">
                        <i class="fas fa-headphones"></i>
                        <span>Media</span>
                    </div>
                    <div class="nav-item" data-panel="gallery">
                        <i class="fas fa-images"></i>
                        <span>Gallery</span>
                    </div>
                    <div class="nav-item" data-panel="email">
                        <i class="fas fa-envelope"></i>
                        <span>Email Triage<span class="em-badge" id="em-badge" style="display:none">0</span></span>
                    </div>
                    <div class="nav-item" data-panel="messages">
                        <i class="fas fa-comment-dots"></i>
                        <span>Messages<span class="msg-badge" id="msg-badge" style="display:none">0</span></span>
                    </div>
                    <div class="nav-item" data-panel="social">
                        <i class="fas fa-share-alt"></i>
                        <span>Social<span class="sc-badge" id="sc-badge" style="display:none">0</span></span>
                    </div>
                    <div class="nav-item" data-panel="tarot">
                        <i class="fas fa-layer-group"></i>
                        <span>Setup</span>
                    </div>
                    <div class="nav-item" data-panel="apps">
                        <i class="fas fa-th"></i>
                        <span>My Apps</span>
                    </div>
                </div>
            </div>

            <div class="nav-section collapsed">
                <h4>Manage</h4>
                <div class="nav-section-items">
                    <div class="nav-item" data-panel="connect">
                        <i class="fas fa-plug"></i>
                        <span>Connect</span>
                    </div>
                    <div class="nav-item" data-panel="models">
                        <i class="fas fa-cube"></i>
                        <span>Models</span>
                    </div>
                    <div class="nav-item" data-panel="tasks">
                        <i class="fas fa-check-square"></i>
                        <span>Tasks</span>
                    </div>
                    <div class="nav-item" data-panel="memory">
                        <i class="fas fa-brain"></i>
                        <span>Memory</span>
                    </div>
                    <div class="nav-item" data-panel="skills">
                        <i class="fas fa-puzzle-piece"></i>
                        <span>Skills</span>
                    </div>
                    <div class="nav-item" data-panel="training">
                        <i class="fas fa-graduation-cap"></i>
                        <span>Training</span>
                    </div>
                    <div class="nav-item" data-panel="marketplace">
                        <i class="fas fa-store"></i>
                        <span>Marketplace</span>
                    </div>
                    <div class="nav-item" data-panel="server">
                        <i class="fas fa-server"></i>
                        <span>Server</span>
                    </div>
                </div>
            </div>

            <div class="nav-section collapsed">
                <h4>System</h4>
                <div class="nav-section-items">
                    <div class="nav-item" data-panel="nodes">
                        <i class="fas fa-network-wired"></i>
                        <span>Mesh Nodes</span>
                    </div>
                    <div class="nav-item" data-panel="activity">
                        <i class="fas fa-wave-square"></i>
                        <span>Activity</span>
                    </div>
                    <div class="nav-item" data-panel="settings">
                        <i class="fas fa-cog"></i>
                        <span>Settings</span>
                    </div>
                </div>
            </div>
        </nav>

        <!-- Main Content -->
        <main>
            <div id="update-banner-slot"></div>
            <!-- Chat Panel -->
            <div id="chat-panel" class="panel active">
                <!-- Creature Widget (collapsible) -->
                <div id="creature-widget" style="display:none; background:var(--bg-dark); border-bottom:1px solid var(--border); position:relative;">
                    <button id="creature-collapse-btn" onclick="toggleCreatureWidget()"
                        style="position:absolute; top:4px; right:8px; background:none; border:none; color:var(--text-dim); cursor:pointer; font-size:0.75rem; padding:4px 6px; z-index:2; opacity:0.7;"
                        title="Collapse familiar">
                        <i class="fas fa-chevron-up"></i>
                    </button>
                    <div id="creature-widget-body" style="padding:16px; text-align:center;">
                        <div id="creature-sprite" style="font-family:'Courier New',monospace; font-size:18px; line-height:1.05; letter-spacing:0;"></div>
                        <div style="margin-top:6px; font-size:0.8rem;">
                            <span id="creature-name" style="font-weight:600; color:var(--text);"></span>
                            <span style="color:var(--text-dim);"> the </span>
                            <span id="creature-species" style="color:var(--text-dim);"></span>
                            <span style="color:var(--text-dim); margin-left:8px;">&#183;</span>
                            <span id="creature-stage" style="color:var(--text-dim); margin-left:8px;"></span>
                        </div>
                    </div>
                    <div id="creature-widget-collapsed" style="display:none; padding:6px 12px; cursor:pointer; text-align:center;" onclick="toggleCreatureWidget()">
                        <span id="creature-name-mini" style="font-size:0.75rem; color:var(--text-dim);"></span>
                        <i class="fas fa-chevron-down" style="font-size:0.6rem; color:var(--text-dim); margin-left:6px;"></i>
                    </div>
                </div>
                <div id="provider-warning-banner" style="display:none; background:linear-gradient(135deg,#78350f,#92400e); color:#fef3c7; padding:10px 14px; border-radius:8px; margin:0 0 8px 0; font-size:0.85rem; line-height:1.4; align-items:center; gap:10px;">
                    <div style="display:flex; align-items:center; gap:8px; flex:1;">
                        <i class="fas fa-exclamation-triangle" style="font-size:1rem;"></i>
                        <span id="provider-warning-text"></span>
                    </div>
                    <div style="display:flex; gap:8px; margin-top:6px;">
                        <a id="provider-warning-link" href="#" target="_blank" rel="noopener"
                           style="background:#fef3c7; color:#78350f; padding:4px 12px; border-radius:6px; font-size:0.8rem; font-weight:600; text-decoration:none;">
                            Top Up Credits
                        </a>
                        <button onclick="document.getElementById('provider-warning-banner').style.display='none'"
                                style="background:none; border:1px solid #fef3c7; color:#fef3c7; padding:4px 10px; border-radius:6px; font-size:0.8rem; cursor:pointer;">
                            Dismiss
                        </button>
                    </div>
                </div>
                <div id="cred-alert-banner" class="cred-alert-banner" style="display:none">
                    <div class="cred-alert-content">
                        <i class="fas fa-key cred-alert-icon"></i>
                        <span id="cred-alert-text"></span>
                    </div>
                    <div class="cred-alert-actions">
                        <button class="cred-alert-fix-btn" onclick="switchPanel('settings'); switchSettingsTab('credentials');">
                            Fix in Settings
                        </button>
                        <button class="cred-alert-dismiss-btn" onclick="dismissCredAlert()">
                            Dismiss
                        </button>
                    </div>
                </div>
                <!-- Latest Briefing Card — persists until replaced -->
                <div id="latest-briefing-card" class="card" style="display:none;margin:8px 12px;padding:12px 16px;border-left:3px solid var(--accent);max-height:300px;overflow-y:auto;font-size:0.85rem;line-height:1.5;position:relative;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                        <span style="font-weight:600;font-size:0.8rem;"><i class="fas fa-sun" style="color:var(--accent);margin-right:6px;"></i>Latest Briefing</span>
                        <div style="display:flex;align-items:center;gap:8px;">
                            <span id="latest-briefing-time" style="font-size:0.7rem;color:var(--text-dim);"></span>
                            <button onclick="refreshBriefing()" id="latest-briefing-refresh-btn" class="btn btn-secondary" style="font-size:0.7rem;padding:3px 8px;" title="Update briefing now">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button onclick="document.getElementById('latest-briefing-card').style.display='none'" class="btn btn-secondary" style="font-size:0.7rem;padding:3px 8px;" title="Dismiss">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div id="latest-briefing-body"></div>
                </div>
                <div class="messages" id="messages">
                    <div class="message assistant" id="initial-greeting">
                        <noscript>
                        <p>👋 Hi{% if owner_name %}, {{ owner_name }}{% endif %}! I'm {{ creature_name }}{% if creature_species_label %} the{% if creature_color_name %} {{ creature_color_name|capitalize }}{% endif %} {{ creature_species_label }}{% endif %}. How can I help you today?</p>
                        </noscript>
                    </div>
                </div>
                <div class="fi-bar fi-full" data-fi-id="chat" data-fi-variant="full" id="chat-input-wrap" role="toolbar" aria-label="Chat input">
                    <button class="fi-voice" id="voice-btn" aria-label="Voice input" aria-pressed="false" title="Voice input">
                        <i class="fas fa-microphone"></i>
                    </button>
                    <button class="fi-attach" id="attach-btn" aria-label="Attach file" title="Attach files">
                        <i class="fas fa-paperclip"></i>
                    </button>
                    <input type="file" class="fi-file-input" id="chat-file-input" multiple style="display:none"
                        accept=".pdf,.docx,.doc,.xlsx,.xls,.csv,.tsv,.txt,.md,.json,.xml,.html,.htm,.rtf,.png,.jpg,.jpeg,.tiff,.tif,.bmp,.gif,.webp" />
                    <div class="fi-input-col">
                        <div class="fi-file-chips chat-file-chips" id="chat-file-chips"></div>
                        <textarea class="fi-input" id="chat-input" rows="1" placeholder="Type a message..." aria-label="Message input"></textarea>
                    </div>
                    <button class="fi-tts" id="tts-toggle" aria-label="Read responses aloud" title="Read responses aloud">
                        <i class="fas fa-volume-up"></i>
                    </button>
                    <button class="fi-send" id="send-btn" aria-label="Send message">
                        <i class="fas fa-paper-plane"></i>
                        Send
                    </button>
                </div>
            </div>
            
            <!-- Round Table Panel -->
            <div id="roundtable-panel" class="panel">
                <div style="display:flex; flex-direction:column; height:100%; overflow:hidden;">

                    <!-- Top bar: title + sub-tabs -->
                    <div style="padding:0 20px; border-bottom:1px solid var(--border); background:var(--bg-dark); flex-shrink:0;">
                        <div style="display:flex; align-items:center; gap:0; border-bottom:none;">
                            <div style="display:flex; align-items:center; gap:10px; padding:12px 0; margin-right:20px;">
                                <i class="fas fa-users-round" style="color:var(--accent); font-size:1rem;"></i>
                                <span style="font-weight:700; font-size:0.95rem; color:var(--text);">Round Table</span>
                            </div>
                            <button class="rt-tab active" id="rt-tab-chat" onclick="switchRtTab('chat')">
                                <i class="fas fa-gavel"></i> Chat
                            </button>
                            <button class="rt-tab" id="rt-tab-advisors" onclick="switchRtTab('advisors')">
                                <i class="fas fa-id-card"></i> Advisors
                            </button>
                            <button class="rt-tab" id="rt-tab-groups" onclick="switchRtTab('groups')">
                                <i class="fas fa-layer-group"></i> Groups
                            </button>
                        </div>
                    </div>

                    <!-- ── SUB-PANEL: Chat ── -->
                    <div id="rt-subpanel-chat" style="display:flex; flex-direction:column; flex:1; overflow:hidden;">
                        <!-- Chat controls -->
                        <div style="padding:10px 20px; border-bottom:1px solid var(--border); background:var(--bg-dark); flex-shrink:0; display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
                            <div style="display:flex; background:var(--bg); border:1px solid var(--border); border-radius:8px; overflow:hidden;">
                                <button id="rt-mode-chairman" onclick="setRtMode('chairman')"
                                    style="padding:5px 12px; font-size:0.78rem; border:none; cursor:pointer; background:var(--accent); color:#fff; font-weight:600;">
                                    <i class="fas fa-gavel"></i> Chairman
                                </button>
                                <button id="rt-mode-manual" onclick="setRtMode('manual')"
                                    style="padding:5px 12px; font-size:0.78rem; border:none; cursor:pointer; background:none; color:var(--text-dim);">
                                    <i class="fas fa-sliders"></i> Manual
                                </button>
                            </div>
                            <div id="rt-chairman-hint" style="font-size:0.78rem; color:var(--text-dim);">
                                Chairman routes your question to the right advisors automatically.
                            </div>
                            <!-- Manual seat selector -->
                            <div id="rt-seats-row" style="display:none; width:100%;">
                                <div id="rt-seats" style="display:flex; flex-wrap:wrap; gap:6px; align-items:center;"></div>
                            </div>
                            <!-- Save group button (shown after manual convene) -->
                            <div id="rt-save-group-row" style="display:none; margin-left:auto;">
                                <button onclick="showSaveGroupDialog()" style="font-size:0.78rem; background:none; border:1px solid var(--border); color:var(--text-dim); border-radius:6px; padding:5px 10px; cursor:pointer;">
                                    <i class="fas fa-bookmark"></i> Save Group
                                </button>
                            </div>
                        </div>
                        <!-- Response area -->
                        <div id="rt-responses" style="flex:1; overflow-y:auto; padding:16px 20px; display:flex; flex-direction:column; gap:14px;">
                            <div id="rt-chairman-card" style="display:none; background:linear-gradient(135deg,color-mix(in srgb,#f59e0b 8%,var(--bg-dark)),var(--bg-dark)); border:1.5px solid #f59e0b55; border-radius:12px; overflow:hidden;">
                                <div style="display:flex; align-items:center; gap:10px; padding:11px 16px; border-bottom:1px solid #f59e0b33; background:color-mix(in srgb,#f59e0b 10%,transparent);">
                                    <i class="fas fa-gavel" style="color:var(--warning-dim); font-size:1rem; width:18px; text-align:center;"></i>
                                    <span style="font-weight:700; font-size:0.9rem; color:var(--warning-dim);">Chairman</span>
                                    <span id="rt-chairman-label" style="font-size:0.75rem; color:var(--text-dim); margin-left:4px;"></span>
                                </div>
                                <div id="rt-chairman-body" style="padding:14px 16px; font-size:0.87rem; line-height:1.6; color:var(--text);"></div>
                            </div>
                            <div id="rt-advisor-grid" style="display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:14px;"></div>
                            <div id="rt-synthesis-card" style="display:none; background:color-mix(in srgb,var(--accent) 6%,var(--bg-dark)); border:1.5px solid color-mix(in srgb,var(--accent) 40%,transparent); border-radius:12px; overflow:hidden;">
                                <div style="display:flex; align-items:center; gap:10px; padding:11px 16px; border-bottom:1px solid color-mix(in srgb,var(--accent) 20%,transparent);">
                                    <i class="fas fa-scale-balanced" style="color:var(--accent); font-size:1rem; width:18px; text-align:center;"></i>
                                    <span style="font-weight:700; font-size:0.9rem; color:var(--accent);">Chairman's Synthesis</span>
                                </div>
                                <div id="rt-synthesis-body" style="padding:14px 16px; font-size:0.87rem; line-height:1.6; color:var(--text);"></div>
                            </div>
                            <div id="rt-empty" style="text-align:center; color:var(--text-dim); padding:60px 20px; font-size:0.9rem;">
                                <i class="fas fa-gavel" style="font-size:2.5rem; margin-bottom:14px; display:block; opacity:0.25;"></i>
                                Ask the Chairman anything — or switch to Manual to pick your advisors.<br>
                                <span style="font-size:0.8rem;">New here? Check the <a href="#" onclick="switchRtTab('advisors');return false;" style="color:var(--accent);">Advisors</a> tab to meet the team.</span>
                            </div>
                            <div id="rt-local-warn" style="display:none; background:color-mix(in srgb,#f59e0b 12%,transparent); border:1px solid #f59e0b44; border-radius:8px; padding:10px 14px; font-size:0.82rem; color:#fbbf24;">
                                <i class="fas fa-triangle-exclamation" style="margin-right:6px;"></i>
                                Local Ollama model — requests queue sequentially. Switch to a cloud provider in Settings for true parallelism.
                            </div>
                        </div>
                        <!-- Input -->
                        <div class="fi-bar fi-chat" data-fi-id="roundtable" data-fi-variant="chat" role="toolbar" aria-label="Round Table chat" style="background:var(--bg-dark); flex-shrink:0;">
                            <button class="fi-voice" aria-label="Voice input" aria-pressed="false" title="Voice input"><i class="fas fa-microphone"></i></button>
                            <textarea class="fi-input" id="rt-input" rows="1" placeholder="Ask the Chairman anything..." aria-label="Round Table input"></textarea>
                            <button class="fi-send" id="rt-send-btn" aria-label="Convene the Round Table">
                                <i class="fas fa-gavel"></i> <span id="rt-btn-label">Convene</span>
                            </button>
                        </div>
                    </div>

                    <!-- ── SUB-PANEL: Advisors ── -->
                    <div id="rt-subpanel-advisors" style="display:none; flex:1; overflow-y:auto; padding:20px;">
                        <p style="color:var(--text-dim); font-size:0.85rem; margin:0 0 16px;">
                            Meet your advisory team. Each advisor is a specialist — the Chairman decides who to call, or you can seat them yourself in Manual mode.
                        </p>
                        <div id="rt-advisor-cards" style="display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:14px;"></div>
                    </div>

                    <!-- ── SUB-PANEL: Groups ── -->
                    <div id="rt-subpanel-groups" style="display:none; flex:1; overflow-y:auto; padding:20px;">
                        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:16px;">
                            <p style="color:var(--text-dim); font-size:0.85rem; margin:0;">
                                Save your favourite advisor combinations for quick access.
                            </p>
                            <button onclick="showSaveGroupDialog()" style="background:var(--accent); color:#fff; border:none; border-radius:8px; padding:7px 14px; font-size:0.82rem; font-weight:600; cursor:pointer; display:flex; align-items:center; gap:6px;">
                                <i class="fas fa-plus"></i> New Group
                            </button>
                        </div>
                        <div id="rt-groups-list"></div>
                    </div>

                </div>

                <!-- Save Group Dialog (modal) -->
                <div id="rt-save-dialog" class="rt-save-overlay">
                    <div class="rt-save-card">
                        <div class="rt-save-title">Save Advisor Group</div>
                        <div class="rt-save-label" id="rt-save-dialog-seats-label"></div>
                        <input id="rt-save-dialog-name" class="rt-save-input" type="text" placeholder="Group name (e.g. Security Team)"
                            onkeydown="if(event.key==='Enter')saveRtGroup()" />
                        <div style="display:flex;gap:8px;justify-content:flex-end;">
                            <button class="btn btn-secondary" onclick="document.getElementById('rt-save-dialog').classList.remove('show')">Cancel</button>
                            <button class="btn btn-primary" onclick="saveRtGroup()">Save</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Terminal Panel -->
            <div id="terminal-panel" class="panel">
                <div class="terminal-header">
                    <span class="terminal-title">familiar $</span>
                    <span class="terminal-model" id="terminal-model"></span>
                </div>
                <div class="panel-intro" id="intro-terminal"></div>
                <div class="terminal-output" id="terminal-output"></div>
                <div class="terminal-input-bar">
                    <span class="terminal-prompt">&rsaquo;</span>
                    <input type="text" class="terminal-input" id="terminal-input"
                           placeholder="Type a command..." autocomplete="off" spellcheck="false" />
                </div>
            </div>

            <!-- Shell Panel -->
            <div id="shell-panel" class="panel">
                <div class="shell-header">
                    <span class="shell-title">host $</span>
                    <span class="shell-status" id="shell-status"></span>
                    <button class="shell-kill-btn" id="shell-kill-btn" onclick="shellKill()">Kill</button>
                </div>
                <div class="panel-intro" id="intro-shell"></div>
                <div class="shell-output" id="shell-output"></div>
                <div class="shell-input-bar">
                    <span class="shell-prompt">$</span>
                    <input type="text" class="shell-input" id="shell-input"
                           placeholder="Enter a command..." autocomplete="off" spellcheck="false" />
                </div>
            </div>

            <!-- Briefing Panel -->
            <div id="briefing-panel" class="panel">
                <div class="panel-header">
                    <h2>Daily Briefing</h2>
                    <button class="btn btn-primary" onclick="forceRefreshBriefing()">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>
                <div class="panel-intro" id="intro-briefing"></div>
                <div id="briefing-content" class="card">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
                <div class="panel-chat">
                    <div class="panel-chat-messages" id="briefing-chat-messages"></div>
                    <div class="fi-bar fi-chat" data-fi-id="briefing" data-fi-variant="chat" role="toolbar" aria-label="Briefing chat">
                        <button class="fi-voice" aria-label="Voice input" aria-pressed="false" title="Voice input"><i class="fas fa-microphone"></i></button>
                        <textarea class="fi-input" id="briefing-chat-input" rows="1" placeholder="Ask about your briefing..." aria-label="Briefing chat input"></textarea>
                        <button class="fi-send" aria-label="Send"><i class="fas fa-paper-plane"></i></button>
                    </div>
                </div>
            </div>

            <!-- Calendar Panel -->
            <div id="calendar-panel" class="panel">
                <div class="panel-header">
                    <h2>Calendar</h2>
                    <button class="btn btn-primary" onclick="loadCalendar()">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>
                <div class="panel-intro" id="intro-calendar"></div>
                <div class="mp-tab-bar cal-view-bar" style="margin-bottom:14px;">
                    <button class="mp-tab" id="cal-tab-day" onclick="switchCalendarView('day')">Day</button>
                    <button class="mp-tab active" id="cal-tab-week" onclick="switchCalendarView('week')">Week</button>
                    <button class="mp-tab" id="cal-tab-month" onclick="switchCalendarView('month')">Month</button>
                </div>
                <div id="cal-sources" class="cal-sources" style="display:none;"></div>
                <div id="cal-content" class="card">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
            </div>

            <!-- Email Panel -->
            <div id="email-panel" class="panel">
                <div class="panel-header">
                    <h2>Email</h2>
                    <button class="btn btn-primary" id="email-refresh-btn" onclick="emailRefreshActive()">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>
                <div class="panel-intro" id="intro-email"></div>
                <div class="mp-tab-bar" style="margin-bottom:14px;">
                    <button class="mp-tab active" id="email-tab-inbox" onclick="switchEmailTab('inbox')"><i class="fas fa-inbox"></i> Inbox</button>
                    <button class="mp-tab" id="email-tab-sorted" onclick="switchEmailTab('sorted')"><i class="fas fa-brain"></i> Smart Sort</button>
                    <button class="mp-tab" id="email-tab-sent" onclick="switchEmailTab('sent')"><i class="fas fa-paper-plane"></i> Sent</button>
                </div>
                <div id="email-content">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
                <div id="email-sorted-content" style="display:none;">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
                <div id="email-sent-content" style="display:none;">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
                <div class="panel-chat">
                    <div class="panel-chat-messages" id="email-chat-messages"></div>
                    <div class="fi-bar fi-chat" data-fi-id="email" data-fi-variant="chat" role="toolbar" aria-label="Email chat">
                        <button class="fi-voice" aria-label="Voice input" aria-pressed="false" title="Voice input"><i class="fas fa-microphone"></i></button>
                        <textarea class="fi-input" id="email-chat-input" rows="1" placeholder="Ask about your emails..." aria-label="Email chat input"></textarea>
                        <button class="fi-send" aria-label="Send"><i class="fas fa-paper-plane"></i></button>
                    </div>
                </div>
                <!-- Email detail overlay -->
                <div id="email-detail-overlay" class="em-overlay" style="display:none" role="dialog" aria-modal="true" aria-label="Email detail" onclick="if(event.target===this)closeEmailDetail()">
                    <div class="em-detail">
                        <button class="em-detail-close" onclick="closeEmailDetail()" aria-label="Close">&times;</button>
                        <div id="email-detail-content">
                            <div class="loading"><div class="spinner"></div></div>
                        </div>
                        <div id="email-reply-section" style="display:none; margin-top:16px; border-top:1px solid var(--border, #333); padding-top:16px;">
                            <div style="display:flex; align-items:center; gap:8px; margin-bottom:8px;">
                                <h3 style="margin:0;">Reply</h3>
                                <select id="email-send-from" style="font-size:0.8rem; padding:2px 8px; border-radius:4px; border:1px solid var(--border,rgba(255,255,255,0.1)); background:var(--bg-input); color:var(--text); margin-left:auto;" title="Send from account">
                                    <option value="">Loading accounts...</option>
                                </select>
                            </div>
                            <div class="fi-bar fi-compose">
                                <textarea class="fi-input" id="email-reply-body" rows="5" placeholder="Type your reply..." aria-label="Email reply"></textarea>
                            </div>
                            <div style="display:flex; gap:8px; margin-top:8px; justify-content:flex-end;">
                                <button class="btn btn-secondary" onclick="closeReplySection()">Cancel</button>
                                <button class="btn btn-primary" id="email-send-btn" onclick="sendEmailReply()">
                                    <i class="fas fa-paper-plane"></i> Send
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Tasks Panel -->
            <div id="tasks-panel" class="panel">
                <div class="panel-header">
                    <h2>Tasks</h2>
                    <button class="btn btn-primary" onclick="showAddTaskModal()">
                        <i class="fas fa-plus"></i> Add Task
                    </button>
                </div>
                <div class="panel-intro" id="intro-tasks"></div>
                <div id="tasks-list">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
            </div>
            
            <!-- Memory Panel -->
            <div id="memory-panel" class="panel">
                <div class="panel-header">
                    <h2>Memory</h2>
                    <div style="display:flex;gap:8px;align-items:center">
                        <button class="btn btn-primary" id="mem-action-btn" onclick="memActionBtn()">
                            <i class="fas fa-plus"></i> <span id="mem-action-label">Add Memory</span>
                        </button>
                    </div>
                </div>
                <!-- Unified search bar -->
                <div style="margin-bottom:10px">
                    <div style="display:flex;gap:6px;align-items:center" data-fi-id="mt-search">
                        <input type="text" class="fi-input" id="mt-unified-search" placeholder="Search all memories, knowledge, and files..." aria-label="Search all memories" style="flex:1;min-height:34px;max-height:34px;border:1px solid var(--border);border-radius:8px;font-size:0.85em">
                        <button class="btn btn-secondary" onclick="mtUnifiedSearch()" style="font-size:0.85em;padding:6px 12px"><i class="fas fa-search"></i></button>
                        <button class="btn btn-secondary" id="mt-search-clear" onclick="mtClearSearch()" style="font-size:0.85em;padding:6px 10px;display:none"><i class="fas fa-times"></i></button>
                    </div>
                </div>
                <!-- Unified search results (overlays tabs when active) -->
                <div id="mt-search-results" style="display:none"></div>
                <div class="mp-tab-bar" id="mt-tab-bar" style="margin-bottom:14px;">
                    <button class="mp-tab active" id="mt-tab-brain" onclick="memSwitchTab('brain')"><i class="fas fa-brain"></i> Brain</button>
                    <button class="mp-tab" id="mt-tab-working" onclick="memSwitchTab('working')"><i class="fas fa-bolt"></i> Working</button>
                    <button class="mp-tab" id="mt-tab-knowledge" onclick="memSwitchTab('knowledge')"><i class="fas fa-book"></i> Knowledge</button>
                    <button class="mp-tab" id="mt-tab-notes" onclick="memSwitchTab('notes')"><i class="fas fa-sticky-note"></i> Notes</button>
                    <button class="mp-tab" id="mt-tab-files" onclick="memSwitchTab('files')"><i class="fas fa-folder-open"></i> Files</button>
                    <button class="mp-tab" id="mt-tab-downloads" onclick="memSwitchTab('downloads')"><i class="fas fa-download"></i> Downloads</button>
                </div>
                <div class="panel-intro" id="intro-memory"></div>

                <!-- Brain tab: episodic memories -->
                <div id="mt-brain" class="mt-section">
                    <div id="memory-list">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <!-- Knowledge tab: general markdown topics -->
                <div id="mt-knowledge" class="mt-section" style="display:none">
                    <div style="display:flex;gap:8px;margin-bottom:12px;align-items:center" data-fi-id="mt-knowledge">
                        <input type="text" class="fi-input" id="mt-knowledge-search" placeholder="Search knowledge..." aria-label="Search knowledge" style="flex:1;min-height:34px;max-height:34px;border:1px solid var(--border);border-radius:6px;font-size:0.85em">
                        <button class="btn btn-secondary" onclick="mtLoadKnowledge()" style="font-size:0.85em"><i class="fas fa-search"></i></button>
                    </div>
                    <div id="mt-knowledge-list">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <!-- Notes tab: job-class markdown notes -->
                <div id="mt-notes" class="mt-section" style="display:none">
                    <div style="display:flex;gap:8px;margin-bottom:12px;align-items:center;flex-wrap:wrap" data-fi-id="mt-notes">
                        <select id="mt-notes-namespace" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85em" onchange="mtLoadNotes()">
                            <option value="nonprofit">Nonprofit</option>
                            <option value="social_worker">Social Worker</option>
                            <option value="chef">Chef</option>
                            <option value="artist">Artist</option>
                            <option value="business_buddy">Business Buddy</option>
                            <option value="helper">Helper</option>
                            <option value="security_analyst">Security Analyst</option>
                            <option value="osint_researcher">OSINT Researcher</option>
                            <option value="network_admin">Network Admin</option>
                        </select>
                        <input type="text" class="fi-input" id="mt-notes-search" placeholder="Search notes..." aria-label="Search notes" style="flex:1;min-width:120px;min-height:34px;max-height:34px;border:1px solid var(--border);border-radius:6px;font-size:0.85em">
                        <button class="btn btn-secondary" onclick="mtLoadNotes()" style="font-size:0.85em"><i class="fas fa-search"></i></button>
                    </div>
                    <div id="mt-notes-list">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <!-- Files tab: FileStore browser -->
                <div id="mt-files" class="mt-section" style="display:none">
                    <div style="display:flex;gap:8px;margin-bottom:12px;align-items:center;flex-wrap:wrap" data-fi-id="mem-files">
                        <input type="text" class="fi-input" id="mem-files-search" placeholder="Search files..." aria-label="Search files" style="flex:1;min-width:150px;min-height:34px;max-height:34px;border:1px solid var(--border);border-radius:6px;font-size:0.85em">
                        <select id="mem-files-job-filter" style="padding:6px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:0.85em" onchange="memLoadFiles()">
                            <option value="">All Job Classes</option>
                            <option value="nonprofit">Nonprofit</option>
                            <option value="social_worker">Social Worker</option>
                            <option value="business">Business</option>
                            <option value="kitchen">Kitchen</option>
                            <option value="studio">Studio</option>
                            <option value="security">Security</option>
                            <option value="osint">OSINT</option>
                            <option value="network">Network</option>
                            <option value="general">General</option>
                        </select>
                        <label class="btn btn-primary" style="font-size:0.85em;cursor:pointer;margin:0">
                            <i class="fas fa-upload" style="margin-right:4px"></i>Upload
                            <input type="file" id="mem-files-upload-input" multiple style="display:none" onchange="memUploadGeneralFiles()">
                        </label>
                    </div>
                    <div id="mem-files-stats" style="font-size:0.8em;color:var(--text-dim);margin-bottom:10px"></div>
                    <div id="mem-files-list">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <!-- Working Memory tab: short-term buffer -->
                <div id="mt-working" class="mt-section" style="display:none">
                    <div id="mt-working-list">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <!-- Downloads tab: generated artifacts -->
                <div id="mt-downloads" class="mt-section" style="display:none">
                    <div id="mt-downloads-list">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>
            </div>
            
            <!-- Skills Panel -->
            <div id="skills-panel" class="panel">
                <div class="panel-header">
                    <h2>Skills</h2>
                </div>
                <div class="panel-intro" id="intro-skills"></div>
                <div id="skills-list">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
            </div>
            
            <!-- Messages Panel -->
            <div id="messages-panel" class="panel">
                <div class="msg-container">
                    <div class="msg-contacts" id="msg-contacts">
                        <div class="msg-contacts-header">
                            <span>Conversations</span>
                            <button class="msg-new-btn" onclick="toggleNewConvPicker()" title="New conversation"><i class="fas fa-plus"></i></button>
                        </div>
                        <div id="msg-contact-list">
                            <div class="msg-empty">Loading...</div>
                        </div>
                        <div id="msg-new-picker" style="display:none"></div>
                    </div>
                    <div class="msg-chat" id="msg-chat">
                        <div class="msg-chat-header" id="msg-chat-header" style="display:none">
                            <span class="msg-chat-name" id="msg-chat-name"></span>
                            <span class="msg-chat-status" id="msg-chat-status"></span>
                        </div>
                        <div class="msg-history" id="msg-history">
                            <div class="msg-empty"><i class="fas fa-comment-dots" style="font-size:2rem;opacity:0.3"></i>Select a conversation or start a new one</div>
                        </div>
                        <div class="msg-typing" id="msg-typing" style="display:none">
                            <span class="msg-typing-dots">typing...</span>
                        </div>
                        <div class="fi-bar fi-chat" data-fi-id="peer-msg" data-fi-variant="chat" id="msg-input-wrap" role="toolbar" aria-label="Peer message" style="display:none">
                            <button class="fi-voice" aria-label="Voice input" aria-pressed="false" title="Voice input"><i class="fas fa-microphone"></i></button>
                            <textarea class="fi-input" id="msg-input" rows="1" placeholder="Type a message..." aria-label="Peer message input"></textarea>
                            <button class="fi-send" aria-label="Send message"><i class="fas fa-paper-plane"></i></button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Social Panel -->
            <div id="social-panel" class="panel">
                <div class="panel-header">
                    <h2>Social</h2>
                </div>
                <div id="social-content">
                    <div class="sc-tab-bar">
                        <button class="sc-tab active" onclick="switchSocialTab('feed')">Feed</button>
                        <button class="sc-tab" onclick="switchSocialTab('compose')">Compose</button>
                        <button class="sc-tab" onclick="switchSocialTab('notifications')">Notifications</button>
                    </div>
                    <div class="sc-error-banner" id="sc-error-banner"></div>
                    <div id="sc-feed-tab">
                        <div class="sc-filter-chips" id="sc-filter-chips">
                            <button class="sc-chip active" onclick="filterSocialFeed('')">All</button>
                            <button class="sc-chip" onclick="filterSocialFeed('bluesky')">Bluesky</button>
                            <button class="sc-chip" onclick="filterSocialFeed('mastodon')">Mastodon</button>
                        </div>
                        <div class="sc-feed-panel" id="sc-feed-list">
                            <div class="loading"><div class="spinner"></div></div>
                        </div>
                    </div>
                    <div id="sc-compose-tab" style="display:none">
                        <div class="sc-compose-panel">
                            <div class="sc-checkbox-row" id="sc-platform-checks"></div>
                            <textarea class="sc-compose-textarea" id="sc-compose-text" placeholder="What's on your mind?" maxlength="300" oninput="updateSocialCharCount()"></textarea>
                            <div class="sc-char-count" id="sc-char-count">0 / 300</div>
                            <button class="sc-post-btn" id="sc-post-btn" onclick="socialPost()">Post</button>
                        </div>
                    </div>
                    <div id="sc-notif-tab" style="display:none">
                        <div class="sc-notif-panel" id="sc-notif-list">
                            <div class="loading"><div class="spinner"></div></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Connect Panel -->
            <div id="connect-panel" class="panel">
                <div class="panel-header">
                    <h2>Connect Services</h2>
                </div>
                <div class="panel-intro" id="intro-connect"></div>
                <div id="connect-content">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
            </div>

            <!-- Nodes Panel -->
            <div id="nodes-panel" class="panel">
                <div class="panel-header">
                    <h2>Mesh Network</h2>
                </div>
                <div class="panel-intro" id="intro-nodes"></div>
                <div id="mesh-topology" class="mesh-section" style="display:none">
                    <svg id="mesh-topo-svg" viewBox="0 0 600 400"></svg>
                </div>
                <div id="nodes-content">
                    <div class="loading"><div class="spinner"></div></div>
                </div>
                <div id="mesh-transports" class="mesh-section" style="display:none"></div>
                <div id="mesh-nodes" class="mesh-section" style="display:none"></div>
                <div id="mesh-peers" class="mesh-section" style="display:none"></div>
                <div id="mesh-trust" class="mesh-section" style="display:none"></div>
                <div id="mesh-memory" class="mesh-section" style="display:none"></div>
                <div id="mesh-models" class="mesh-section" style="display:none"></div>
                <div id="mesh-dross" class="mesh-section" style="display:none"></div>
                <div id="mesh-rendezvous" class="mesh-section" style="display:none"></div>
                <div id="mesh-controls" class="mesh-section" style="display:none"></div>
            </div>
            
            <!-- Tarot Panel -->
            <div id="tarot-panel" class="panel">
                <div class="panel-header"><h2>Setup Spread</h2></div>
                <div class="panel-intro" id="intro-tarot"></div>
                <div id="tarot-content"><div class="loading"><div class="spinner"></div></div></div>
            </div>

            <!-- Models Panel -->
            <div id="models-panel" class="panel">
                <div class="panel-header"><h2>Model Library</h2></div>
                <div class="panel-intro" id="intro-models"></div>
                <div id="models-content"><div class="loading"><div class="spinner"></div></div></div>
            </div>

            <!-- Marketplace Panel -->
            <div id="marketplace-panel" class="panel">
                <div class="panel-header"><h2>Marketplace</h2></div>
                <div class="panel-intro" id="intro-marketplace"></div>
                <div class="mp-tab-bar">
                    <button class="mp-tab active" onclick="switchMarketplaceTab('catalog')">Browse Catalog</button>
                    <button class="mp-tab" onclick="switchMarketplaceTab('plugins')">Plugin Store</button>
                </div>
                <div id="mp-catalog-tab">
                    <div class="mp-stats-bar" id="mp-stats-bar"></div>
                    <div class="mp-filter-bar" id="mp-catalog-filters">
                        <button class="mp-filter-btn active" onclick="filterCatalog(this, '')">All</button>
                        <button class="mp-filter-btn" onclick="filterCatalog(this, 'species')">Species</button>
                        <button class="mp-filter-btn" onclick="filterCatalog(this, 'job')">Jobs</button>
                        <button class="mp-filter-btn" onclick="filterCatalog(this, 'skill')">Skills</button>
                        <button class="mp-filter-btn" onclick="filterCatalog(this, 'tool')">Tools</button>
                        <button class="mp-filter-btn" onclick="filterCatalog(this, 'familiar')">Bundles</button>
                        <input class="mp-search" placeholder="Search catalog..." oninput="debounceCatalogSearch()" id="mp-catalog-search">
                        <button class="mp-import-btn" onclick="showImportDialog()"><i class="fas fa-file-import"></i> Import Package</button>
                    </div>
                    <div class="mp-grid" id="mp-catalog-grid"><div class="loading"><div class="spinner"></div></div></div>
                </div>
                <div id="mp-plugins-tab" style="display:none">
                    <div class="mp-filter-bar" id="mp-plugin-filters">
                        <button class="mp-filter-btn active" onclick="filterPlugins(this, '')">All</button>
                        <input class="mp-search" placeholder="Search plugins..." oninput="debouncePluginSearch()" id="mp-plugin-search">
                    </div>
                    <div class="mp-grid" id="mp-plugins-grid"><div class="loading"><div class="spinner"></div></div></div>
                </div>
            </div>

            <!-- Server Panel -->
            <div id="server-panel" class="panel">
                <div class="panel-header">
                    <h2>Server</h2>
                </div>
                <div id="server-content">
                    <div class="sv-tab-bar">
                        <button class="sv-tab active" onclick="switchServerTab('overview')">Overview</button>
                        <button class="sv-tab" onclick="switchServerTab('services')">Services</button>
                        <button class="sv-tab" onclick="switchServerTab('credentials')"><i class="fas fa-key" style="margin-right:4px"></i>Credentials</button>
                        <button class="sv-tab" onclick="switchServerTab('logs')">Logs</button>
                    </div>
                    <div id="sv-overview-tab">
                        <div id="sv-runtime-info"></div>
                        <div class="sv-grid" id="sv-overview-grid">
                            <div class="loading"><div class="spinner"></div></div>
                        </div>
                    </div>
                    <div id="sv-services-tab" style="display:none">
                        <div id="sv-services-list">
                            <div class="loading"><div class="spinner"></div></div>
                        </div>
                    </div>
                    <div id="sv-credentials-tab" style="display:none">
                        <div id="sv-credentials-list">
                            <div class="loading"><div class="spinner"></div></div>
                        </div>
                    </div>
                    <div id="sv-logs-tab" style="display:none">
                        <div class="sv-log-controls">
                            <select id="sv-log-service" onchange="loadServerLogs()">
                                <option value="">Select a service...</option>
                            </select>
                            <button class="sv-btn" onclick="loadServerLogs()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                        <div class="sv-log-box" id="sv-log-output">Select a service to view logs.</div>
                    </div>
                </div>
            </div>

            <!-- Apps Panel -->
            <div id="apps-panel" class="panel">
                <div class="panel-header">
                    <h2><i class="fas fa-th" style="margin-right:8px"></i>My Apps</h2>
                </div>
                <div id="apps-content">
                    <div class="ap-grid" id="ap-grid">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>
            </div>

            <!-- Training / Corpus Panel -->
            <div id="training-panel" class="panel">
                <div class="panel-header"><h2>Training Corpus</h2></div>
                <div id="training-content">
                    <div class="tr-tab-bar">
                        <button class="tr-tab active" onclick="switchTrainingTab('overview')">Overview</button>
                        <button class="tr-tab" onclick="switchTrainingTab('memories')">Memories</button>
                        <button class="tr-tab" onclick="switchTrainingTab('entries')">Corpus Entries</button>
                        <button class="tr-tab" onclick="switchTrainingTab('coops')">Co-ops</button>
                    </div>
                    <!-- Overview Tab -->
                    <div id="tr-overview-tab">
                        <div id="tr-consent-block"><div class="loading"><div class="spinner"></div></div></div>
                        <div id="tr-run-stats"></div>
                        <div id="tr-phi-block"></div>
                    </div>
                    <!-- Memories Tab -->
                    <div id="tr-memories-tab" style="display:none">
                        <div class="tr-filter-bar">
                            <input type="text" id="tr-mem-search" placeholder="Filter by name or topic…" oninput="renderFilteredMemories()">
                            <select id="tr-mem-filter" onchange="renderFilteredMemories()">
                                <option value="all">All files</option>
                                <option value="eligible">Eligible only</option>
                                <option value="ineligible">Not eligible</option>
                            </select>
                        </div>
                        <div id="tr-memory-list"><div class="loading"><div class="spinner"></div></div></div>
                    </div>
                    <!-- Entries Tab -->
                    <div id="tr-entries-tab" style="display:none">
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                            <span id="tr-entries-count" style="font-size:0.82rem;color:var(--text-dim)"></span>
                            <div style="display:flex;gap:8px;">
                                <button class="tr-btn" onclick="trEntriesPage(-1)"><i class="fas fa-chevron-left"></i></button>
                                <button class="tr-btn" onclick="trEntriesPage(1)"><i class="fas fa-chevron-right"></i></button>
                            </div>
                        </div>
                        <div id="tr-entry-list"><div class="loading"><div class="spinner"></div></div></div>
                    </div>
                    <!-- Co-ops Tab -->
                    <div id="tr-coops-tab" style="display:none">
                        <div class="tr-empty">
                            <i class="fas fa-people-group"></i>
                            Co-op contribution UI coming soon.<br>
                            Use <code>contribute_to_coop</code> in the chat to pool your corpus with a co-op.
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tarot Detail Overlay -->
            <div class="tarot-detail-overlay" id="tarot-detail-overlay" onclick="if(event.target===this)this.classList.remove('show')">
                <div class="tarot-detail-modal" id="tarot-detail-modal"></div>
            </div>

            <!-- Settings Panel -->
            <div id="settings-panel" class="panel">
                <div class="panel-header">
                    <h2>Settings</h2>
                </div>
                <div class="panel-intro" id="intro-settings"></div>

                <div class="set-tab-bar">
                    <button class="set-tab active" onclick="switchSettingsTab('general')"><i class="fas fa-sliders" style="margin-right:4px"></i>General</button>
                    <button class="set-tab" onclick="switchSettingsTab('credentials')"><i class="fas fa-key" style="margin-right:4px"></i>Credentials</button>
                    <button class="set-tab" onclick="switchSettingsTab('activity')"><i class="fas fa-history" style="margin-right:4px"></i>Activity</button>
                    <div style="flex:1"></div>
                    <button class="btn btn-primary" style="font-size:0.78rem;padding:4px 12px" onclick="switchToNewUI()"><i class="fas fa-sparkles" style="margin-right:4px"></i>Try New UI</button>
                </div>

                <div id="set-general-tab">

                <div class="card" id="accounts-card">
                    <h3><i class="fas fa-plug" style="margin-right:6px;color:var(--accent)"></i>Connected Accounts</h3>
                    <div id="accounts-content">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <div class="card">
                    <h3>LLM Provider</h3>
                    <div id="provider-select-wrap"></div>
                </div>

                <div class="card" id="routing-card">
                    <h3>Model Routing</h3>
                    <div id="routing-content">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <div class="card" id="ollama-loaded-card">
                    <h3><i class="fas fa-microchip" style="margin-right:6px;"></i>Ollama Loaded Models</h3>
                    <div id="ollama-loaded-content">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                <div class="card" id="presets-card" style="display:none;">
                    <h3><i class="fas fa-bookmark" style="margin-right:6px;"></i>Routing Presets</h3>
                    <div id="presets-content"></div>
                </div>

                <div class="card">
                    <h3>Agent</h3>
                    <div class="stat-row">
                        <span>Memory</span>
                        <div class="toggle on" id="toggle-memory"></div>
                    </div>
                    <div class="stat-row">
                        <span>Skills</span>
                        <div class="toggle on" id="toggle-skills"></div>
                    </div>
                    <div class="stat-row">
                        <span>PII / PHI Detection</span>
                        <div class="toggle" id="toggle-pii"></div>
                    </div>
                    <div id="pii-status" style="font-size:0.75rem;color:var(--text-dim);margin-top:4px;padding-left:4px;"></div>
                </div>

                <div class="card" id="budget-card">
                    <h3><i class="fas fa-coins" style="color:var(--accent);margin-right:6px;"></i>Usage &amp; Budget</h3>
                    <div class="stat-row">
                        <span>Daily Budget Limit</span>
                        <div class="toggle" id="toggle-budget"></div>
                    </div>
                    <div id="budget-limit-row" style="display:none; margin-top:12px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:6px;">Daily limit (USD)</label>
                        <div style="display:flex; align-items:center; gap:8px;">
                            <span style="color:var(--text-dim); font-size:0.9rem;">$</span>
                            <input type="number" id="budget-amount" min="0.01" step="0.50" value="10.00"
                                style="width:90px; padding:5px 8px; background:var(--bg-input); border:1px solid var(--border); border-radius:6px; color:var(--text-primary); font-size:0.9rem;">
                            <button class="btn btn-primary" style="padding:5px 14px; font-size:0.82rem;" id="budget-save-btn">Save</button>
                        </div>
                    </div>
                    <div id="budget-spend-row" style="margin-top:10px; font-size:0.78rem; color:var(--text-dim);"></div>
                </div>

                <div class="card" id="briefing-card">
                    <h3><i class="fas fa-sun" style="color:var(--accent);margin-right:6px;"></i>Daily Briefing</h3>
                    <div class="stat-row">
                        <span>8 AM Briefing</span>
                        <div class="toggle" id="toggle-briefing" onclick="toggleBriefing()"></div>
                    </div>
                    <div id="briefing-time-row" style="display:none; margin-top:12px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:6px;">Delivery time</label>
                        <div style="display:flex; align-items:center; gap:8px;">
                            <input type="time" id="briefing-time-input" value="08:00"
                                style="padding:5px 8px; background:var(--bg-input); border:1px solid var(--border); border-radius:6px; color:var(--text-primary); font-size:0.9rem;">
                            <button class="btn btn-primary" style="padding:5px 14px; font-size:0.82rem;" onclick="saveBriefingTime()">Save</button>
                        </div>
                    </div>
                    <div id="briefing-status" style="margin-top:8px; font-size:0.75rem; color:var(--text-dim);"></div>
                </div>

                <div class="card" id="news-topics-card">
                    <h3><i class="fas fa-newspaper" style="color:var(--accent);margin-right:6px;"></i>News Topics</h3>
                    <p style="font-size:0.8rem; color:var(--text-dim); margin:0 0 12px;">Track up to 5 topics in your daily briefing.</p>
                    <div id="news-topics-list" style="margin-bottom:12px; min-height:24px;"></div>
                    <div id="news-add-row" style="display:flex; gap:8px; align-items:center;">
                        <input type="text" id="news-topic-input" maxlength="60" placeholder="e.g. climate, AI, trans rights"
                            style="flex:1; padding:6px 10px; background:var(--bg-input); border:1px solid var(--border); border-radius:6px; color:var(--text-primary); font-size:0.85rem;"
                            onkeydown="if(event.key==='Enter') addNewsTopic()">
                        <button class="btn btn-primary" style="padding:6px 14px; font-size:0.82rem;" onclick="addNewsTopic()">Add</button>
                    </div>
                    <div id="news-topics-msg" style="margin-top:6px; font-size:0.75rem; color:var(--text-dim);"></div>
                </div>

                <div class="card" id="familiar-card">
                    <h3>Change My Familiar</h3>
                    <div id="familiar-preview" style="text-align:center; font-family:'Courier New',monospace; font-size:14px; line-height:1.05; margin-bottom:14px;"></div>
                    <div style="margin-bottom:12px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Name</label>
                        <input type="text" id="familiar-name" maxlength="32" placeholder="Familiar name" style="width:100%;" />
                    </div>
                    <div style="margin-bottom:12px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Species</label>
                        <select id="familiar-species" onchange="previewFamiliar()">
                            <option value="fox">Fox</option>
                            <option value="owl">Owl</option>
                            <option value="cat">Cat</option>
                            <option value="dragon">Dragon</option>
                            <option value="wolf">Wolf</option>
                            <option value="frog">Frog</option>
                        </select>
                    </div>
                    <div style="margin-bottom:12px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Stage</label>
                        <select id="familiar-stage" onchange="previewFamiliar()">
                            <option value="baby">Baby</option>
                            <option value="juvenile">Juvenile</option>
                            <option value="adult">Adult</option>
                        </select>
                    </div>
                    <div style="margin-bottom:10px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Body Color</label>
                        <div class="color-swatches" id="swatches-body"></div>
                        <div style="display:flex;align-items:center;gap:6px;margin-top:6px;">
                            <input type="color" id="hex-body" style="width:28px;height:28px;padding:0;border:1px solid #333;border-radius:4px;background:transparent;cursor:pointer;">
                            <input type="text" id="hex-body-text" maxlength="7" placeholder="#RRGGBB" style="width:80px;padding:4px 6px;background:#252540;border:1px solid #333;border-radius:4px;color:#eaeaea;font-family:monospace;font-size:12px;">
                        </div>
                    </div>
                    <div style="margin-bottom:10px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Eye Color</label>
                        <div class="color-swatches" id="swatches-eyes"></div>
                        <div style="display:flex;align-items:center;gap:6px;margin-top:6px;">
                            <input type="color" id="hex-eyes" style="width:28px;height:28px;padding:0;border:1px solid #333;border-radius:4px;background:transparent;cursor:pointer;">
                            <input type="text" id="hex-eyes-text" maxlength="7" placeholder="#RRGGBB" style="width:80px;padding:4px 6px;background:#252540;border:1px solid #333;border-radius:4px;color:#eaeaea;font-family:monospace;font-size:12px;">
                        </div>
                    </div>
                    <div style="margin-bottom:14px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Accent Color</label>
                        <div class="color-swatches" id="swatches-accent"></div>
                        <div style="display:flex;align-items:center;gap:6px;margin-top:6px;">
                            <input type="color" id="hex-accent" style="width:28px;height:28px;padding:0;border:1px solid #333;border-radius:4px;background:transparent;cursor:pointer;">
                            <input type="text" id="hex-accent-text" maxlength="7" placeholder="#RRGGBB" style="width:80px;padding:4px 6px;background:#252540;border:1px solid #333;border-radius:4px;color:#eaeaea;font-family:monospace;font-size:12px;">
                        </div>
                    </div>
                    <div style="margin-bottom:14px;">
                        <label style="display:block; font-size:0.8rem; color:var(--text-dim); margin-bottom:4px;">Voice Color</label>
                        <div class="color-swatches" id="swatches-voice"></div>
                        <div style="display:flex;align-items:center;gap:6px;margin-top:6px;">
                            <input type="color" id="hex-voice" style="width:28px;height:28px;padding:0;border:1px solid #333;border-radius:4px;background:transparent;cursor:pointer;">
                            <input type="text" id="hex-voice-text" maxlength="7" placeholder="#RRGGBB" style="width:80px;padding:4px 6px;background:#252540;border:1px solid #333;border-radius:4px;color:#eaeaea;font-family:monospace;font-size:12px;">
                        </div>
                    </div>
                    <button class="btn btn-primary" style="width:100%;" onclick="saveFamiliar()">Save Changes</button>
                    <button class="btn" style="width:100%; margin-top:8px; background:var(--bg-input); border:1px solid var(--border);" onclick="resetFamiliar()">Reset to Baby</button>
                </div>

                <div class="card">
                    <h3><i class="fas fa-hat-wizard"></i> Job Class</h3>
                    <p style="color: var(--text-secondary); margin-bottom: 12px; font-size: 0.85rem;">Choose your familiar's specialization</p>
                    <div id="job-class-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;"></div>
                </div>

                <div class="card">
                    <h3>Host Shell</h3>
                    <div class="stat-row">
                        <span>Enable</span>
                        <div class="toggle" id="toggle-shell" onclick="toggleShell()"></div>
                    </div>
                    <div style="font-size: 0.75rem; color: var(--text-dim); margin-top: 8px;">
                        Allows running host system commands from the dashboard.
                    </div>
                </div>

                <!-- Mesh Gateway controls moved to Mesh Network panel -->

                <div class="card">
                    <h3>Downloads</h3>
                    <div style="display:flex; flex-direction:column; gap:10px;">
                        <button class="btn btn-secondary" onclick="downloadTome()" style="width:100%; text-align:left;">
                            <i class="fas fa-book"></i> Download User Guide (PDF)
                        </button>
                        <button class="btn btn-secondary" onclick="downloadBundle()" style="width:100%; text-align:left;">
                            <i class="fas fa-file-archive"></i> Download Installer Bundle
                        </button>
                    </div>
                </div>

                <div class="card" id="email-intel-card">
                    <h3><i class="fas fa-brain" style="margin-right:6px;color:var(--accent)"></i>Email Intelligence</h3>
                    <div id="email-intel-content">
                        <div class="loading"><div class="spinner"></div></div>
                    </div>
                </div>

                </div><!-- /set-general-tab -->

                <div id="set-credentials-tab" style="display:none">
                    <div id="cred-summary-bar" style="background:var(--bg-input);border-radius:10px;padding:12px 16px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;font-size:0.85rem;">
                        <span id="cred-summary-text" style="color:var(--text-dim)">Loading credential status...</span>
                        <button class="btn btn-secondary" onclick="loadCredentialCards()" style="padding:4px 12px;font-size:0.78rem;"><i class="fas fa-sync-alt" style="margin-right:4px"></i>Refresh</button>
                    </div>
                    <div class="cred-filter-bar" id="cred-filter-bar">
                        <button class="cred-filter active" data-cat="all" onclick="filterCredentials('all')">All</button>
                        <button class="cred-filter" data-cat="llm" onclick="filterCredentials('llm')">LLM</button>
                        <button class="cred-filter" data-cat="integrations" onclick="filterCredentials('integrations')">Integrations</button>
                        <button class="cred-filter" data-cat="apis" onclick="filterCredentials('apis')">APIs</button>
                        <button class="cred-filter" data-cat="social" onclick="filterCredentials('social')">Social</button>
                        <button class="cred-filter" data-cat="selfhosted" onclick="filterCredentials('selfhosted')">Self-Hosted</button>
                        <button class="cred-filter" data-cat="channels" onclick="filterCredentials('channels')">Channels</button>
                        <button class="cred-filter" data-cat="security" onclick="filterCredentials('security')">Security</button>
                    </div>
                    <div id="cred-cards-grid"></div>
                </div><!-- /set-credentials-tab -->

                <div id="set-activity-tab" style="display:none">
                    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
                        <h3 style="margin:0;font-size:1rem;">Credential Activity Log</h3>
                        <button class="btn btn-secondary" onclick="loadCredentialAudit()" style="padding:4px 12px;font-size:0.78rem;"><i class="fas fa-sync-alt" style="margin-right:4px"></i>Refresh</button>
                    </div>
                    <div id="cred-audit-list" style="display:flex;flex-direction:column;gap:6px;"></div>
                </div><!-- /set-activity-tab -->

            </div>

            <!-- Activity Monitor Panel -->
            <div id="activity-panel" class="panel">
                <div class="panel-header">
                    <h2><i class="fas fa-wave-square" style="color:var(--accent);margin-right:8px;"></i>Activity Monitor</h2>
                    <div class="act-header-meta">
                        <span id="activity-updated" class="act-updated"></span>
                        <button class="btn btn-secondary" onclick="loadActivity()"><i class="fas fa-sync-alt"></i></button>
                    </div>
                </div>

                <!-- KPI Row — persistent from analytics.db -->
                <div class="activity-kpi-grid" style="grid-template-columns:repeat(4,1fr);">
                    <div class="card">
                        <div class="kpi-value" id="kpi-today-cost">$0.00</div>
                        <div class="kpi-label">Today's Cost</div>
                        <div class="act-kpi-sub" id="kpi-today-calls">0 calls</div>
                    </div>
                    <div class="card">
                        <div class="kpi-value" id="kpi-month-cost">$0.00</div>
                        <div class="kpi-label">This Month</div>
                        <div class="act-kpi-sub" id="kpi-month-calls">0 calls</div>
                    </div>
                    <div class="card">
                        <div class="kpi-value" id="kpi-projected">$0.00</div>
                        <div class="kpi-label">Projected</div>
                        <div class="act-kpi-sub" id="kpi-daily-avg">$0.00/day avg</div>
                    </div>
                    <div class="card">
                        <div class="kpi-value" id="kpi-active-model">—</div>
                        <div class="kpi-label">Active Model</div>
                        <div class="act-kpi-sub" id="kpi-alltime-cost">$0.00 all time</div>
                    </div>
                </div>

                <!-- Monthly Spend Card -->
                <div class="card act-spend-card" id="monthly-spend-card">
                    <div class="act-spend-header">
                        <span class="act-spend-title">Monthly Spend Breakdown</span>
                        <span id="spend-vs-last" class="act-updated"></span>
                    </div>
                    <div class="act-spend-content">
                        <div class="act-spend-bar-wrap">
                            <div class="act-spend-bar" id="spend-bar">
                                <div id="spend-bar-interactive" class="act-spend-bar-int"></div>
                                <div id="spend-bar-proactive" class="act-spend-bar-pro"></div>
                            </div>
                            <div class="act-spend-legend">
                                <span><span class="act-trigger-interactive">&#9632;</span> Interactive: <span id="spend-interactive">$0.00</span></span>
                                <span><span class="act-trigger-proactive">&#9632;</span> Proactive: <span id="spend-proactive">$0.00</span></span>
                            </div>
                        </div>
                        <div class="act-spend-tokens">
                            <div>Today's tokens: <span id="kpi-today-tokens">0</span></div>
                            <div>Month tokens: <span id="kpi-month-tokens">0</span></div>
                        </div>
                    </div>
                </div>

                <!-- Tabs -->
                <div class="wizard-tabs" id="activity-tabs">
                    <button class="wizard-tab active" data-atab="calllog">Call Log</button>
                    <button class="wizard-tab" data-atab="tools">Tools</button>
                    <button class="wizard-tab" data-atab="llm">LLM Providers</button>
                    <button class="wizard-tab" data-atab="health">Health</button>
                    <button class="wizard-tab" data-atab="errors">Errors <span id="activity-error-badge"></span></button>
                    <button class="wizard-tab" data-atab="alerts">Alerts <span id="activity-alert-badge"></span></button>
                    <button class="wizard-tab" data-atab="skills">Skills</button>
                    <button class="wizard-tab" data-atab="trends">Trends</button>
                </div>

                <!-- Tab Contents -->
                <div id="atab-calllog" class="card act-tab-content"></div>
                <div id="atab-tools" class="card act-tab-content" style="display:none;"></div>
                <div id="atab-llm" class="card act-tab-content" style="display:none;"></div>
                <div id="atab-health" class="card" style="display:none;"></div>
                <div id="atab-errors" class="card act-tab-content" style="display:none;"></div>
                <div id="atab-alerts" class="card" style="display:none;"></div>
                <div id="atab-skills" class="card" style="display:none;"></div>
                <div id="atab-trends" class="card" style="display:none;"></div>
            </div>

            <!-- Workspace Panel -->
            <div id="workspace-panel" class="panel">
                <div class="panel-header" style="display:flex; justify-content:space-between; align-items:center; padding:16px;">
                    <h2 id="workspace-title" style="margin:0;">Workspace</h2>
                    <button class="btn btn-secondary" onclick="loadWorkspace()" title="Refresh">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
                <div class="panel-intro" id="intro-workspace"></div>
                <p id="workspace-description" style="padding:0 16px; color:var(--text-dim); font-size:0.85rem;"></p>
                <div id="workspace-overview"></div>
                <div id="workspace-tabs" class="workspace-tabs"></div>
                <div id="workspace-content"></div>
                <div class="panel-chat" style="padding:12px 16px; border-top:1px solid var(--border);">
                    <div id="workspace-chat-messages" style="max-height:200px; overflow-y:auto; margin-bottom:8px;"></div>
                    <div class="fi-bar fi-chat" data-fi-id="workspace" data-fi-variant="chat" role="toolbar" aria-label="Workspace chat" style="border-top:none; padding:0;">
                        <button class="fi-voice" aria-label="Voice input" aria-pressed="false" title="Voice input"><i class="fas fa-microphone"></i></button>
                        <textarea class="fi-input" id="workspace-chat-input" rows="1" placeholder="Ask about this workspace..." aria-label="Workspace chat input"></textarea>
                        <button class="fi-send" aria-label="Send"><i class="fas fa-paper-plane"></i></button>
                    </div>
                </div>
            </div>

            <!-- Media Panel -->
            <div id="media-panel" class="panel">
                <div class="panel-header" style="display:flex; justify-content:space-between; align-items:center; padding:16px;">
                    <h2 style="margin:0;">Media</h2>
                    <button class="btn btn-secondary" onclick="loadMedia()" title="Refresh">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
                <div class="panel-intro" id="intro-media"></div>
                <div class="media-tab-bar">
                    <div class="media-tab active" onclick="switchMediaTab('radio')"><i class="fas fa-broadcast-tower"></i>Radio</div>
                    <div class="media-tab" onclick="switchMediaTab('podcasts')"><i class="fas fa-podcast"></i>Podcasts</div>
                    <div class="media-tab" onclick="switchMediaTab('favorites')"><i class="fas fa-heart"></i>Favorites</div>
                    <div class="media-tab" onclick="switchMediaTab('history')"><i class="fas fa-clock"></i>History</div>
                    <div class="media-tab" onclick="switchMediaTab('music')"><i class="fas fa-music"></i>Library</div>
                    <div class="media-tab" onclick="switchMediaTab('video')"><i class="fas fa-video"></i>Video</div>
                </div>

                <!-- Radio Tab -->
                <div id="media-radio" class="media-tab-content">
                    <div class="media-search-bar" data-fi-id="radio-search">
                        <input type="text" class="fi-input" id="radio-search-input" placeholder="Search stations..." aria-label="Search radio stations" />
                        <select id="radio-genre-select"><option value="">All Genres</option></select>
                        <button onclick="searchRadio()"><i class="fas fa-search"></i> Search</button>
                    </div>
                    <div id="radio-results" class="media-grid"></div>
                </div>

                <!-- Podcasts Tab -->
                <div id="media-podcasts" class="media-tab-content" style="display:none">
                    <div class="media-search-bar" data-fi-id="podcast-search">
                        <input type="text" class="fi-input" id="podcast-search-input" placeholder="Search podcasts..." aria-label="Search podcasts" />
                        <button onclick="searchPodcasts()"><i class="fas fa-search"></i> Search</button>
                    </div>
                    <div id="podcast-results" class="media-grid"></div>
                    <div id="podcast-episodes" class="episode-list"></div>
                </div>

                <!-- Favorites Tab -->
                <div id="media-favorites" class="media-tab-content" style="display:none">
                    <div id="favorites-content"></div>
                </div>

                <!-- History Tab -->
                <div id="media-history" class="media-tab-content" style="display:none">
                    <div id="history-content"></div>
                </div>

                <!-- Music Library Tab -->
                <div id="media-music" class="media-tab-content" style="display:none">
                    <div class="media-search-bar" data-fi-id="music-search">
                        <input type="text" class="fi-input" id="music-search-input" placeholder="Search library..."
                               aria-label="Search music library" />
                        <button onclick="document.getElementById('music-upload-input').click()">
                            <i class="fas fa-upload"></i> Upload
                        </button>
                        <input type="file" id="music-upload-input" accept=".mp3,.wav,.ogg,.flac,.m4a,.aac,.wma"
                               multiple style="display:none" onchange="uploadMusicFiles(this.files)" />
                    </div>
                    <div id="music-dropzone" class="music-dropzone">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <p>Drop music files here or click Upload</p>
                    </div>
                    <div class="music-upload-progress" id="music-upload-progress"></div>
                    <div id="music-library" class="media-grid"></div>
                </div>

                <!-- Video Tab -->
                <div id="media-video" class="media-tab-content" style="display:none">
                    <div class="media-search-bar" data-fi-id="video-search">
                        <input type="text" class="fi-input" id="video-search-input" placeholder="Search videos..."
                               aria-label="Search videos" />
                        <select id="video-quality-select">
                            <option>360p</option><option selected>720p</option><option>1080p</option>
                        </select>
                        <button onclick="searchVideos()"><i class="fas fa-search"></i> Search</button>
                    </div>
                    <div class="video-platform-bar">
                        <span class="video-platform-chip active" data-platform="all" onclick="toggleVideoPlatform(this)"><i class="fas fa-globe"></i> All</span>
                        <span class="video-platform-chip" data-platform="youtube" onclick="toggleVideoPlatform(this)"><i class="fab fa-youtube"></i> YouTube</span>
                        <span class="video-platform-chip" data-platform="vimeo" onclick="toggleVideoPlatform(this)"><i class="fab fa-vimeo-v"></i> Vimeo</span>
                        <span class="video-platform-chip" data-platform="dailymotion" onclick="toggleVideoPlatform(this)"><i class="fab fa-dailymotion"></i> Dailymotion</span>
                        <span class="video-platform-chip" data-platform="twitch" onclick="toggleVideoPlatform(this)"><i class="fab fa-twitch"></i> Twitch</span>
                        <span class="video-platform-chip" data-platform="rumble" onclick="toggleVideoPlatform(this)"><i class="fas fa-tower-broadcast"></i> Rumble</span>
                        <span class="video-platform-chip" data-platform="odysee" onclick="toggleVideoPlatform(this)"><i class="fas fa-play-circle"></i> Odysee</span>
                    </div>
                    <div id="video-results" class="media-grid"></div>
                </div>
            </div>

            <!-- Gallery Vault Panel -->
            <div id="gallery-panel" class="panel">
                <div class="panel-header" style="display:flex; justify-content:space-between; align-items:center; padding:16px;">
                    <h2 style="margin:0;">Gallery Vault</h2>
                    <button class="btn btn-secondary" onclick="loadGallery()" title="Refresh">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
                <div class="panel-intro" id="intro-gallery"></div>
                <div class="gallery-tab-bar">
                    <div class="gallery-tab active" onclick="switchGalleryTab('vault')"><i class="fas fa-th"></i>Vault</div>
                    <div class="gallery-tab" onclick="switchGalleryTab('register')"><i class="fas fa-plus-circle"></i>Register</div>
                    <div class="gallery-tab" onclick="switchGalleryTab('verify')"><i class="fas fa-shield-alt"></i>Verify</div>
                </div>

                <!-- Vault Tab -->
                <div id="gallery-vault" class="gallery-tab-content">
                    <div id="gallery-vault-grid" class="gallery-grid"></div>
                    <div id="gallery-vault-detail" class="gallery-detail" style="display:none"></div>
                </div>

                <!-- Register Tab -->
                <div id="gallery-register" class="gallery-tab-content" style="display:none">
                    <div id="gallery-upload-zone" class="gallery-upload-zone" onclick="document.getElementById('gallery-file-input').click()">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <div style="font-size:1.1rem; font-weight:600; margin-bottom:4px;">Drop artwork here or click to upload</div>
                        <div style="font-size:0.8rem;">Supports PNG, JPG, GIF, WebP, BMP</div>
                        <input type="file" id="gallery-file-input" accept="image/*" style="display:none" onchange="handleGalleryFile(this)">
                    </div>
                    <div id="gallery-upload-preview" style="display:none; text-align:center; padding:12px 16px;">
                        <img id="gallery-preview-img" style="max-height:200px; border-radius:8px; border:1px solid var(--border);">
                        <div id="gallery-preview-name" style="margin-top:8px; font-size:0.85rem; color:var(--text-dim);"></div>
                    </div>
                    <div class="gallery-form" id="gallery-register-form" style="display:none">
                        <div>
                            <label>Title *</label>
                            <input type="text" id="gallery-reg-title" placeholder="Artwork title">
                        </div>
                        <div>
                            <label>Artist *</label>
                            <input type="text" id="gallery-reg-artist" placeholder="Artist name">
                        </div>
                        <div>
                            <label>Medium</label>
                            <input type="text" id="gallery-reg-medium" placeholder="e.g. Digital, Oil on Canvas">
                        </div>
                        <div>
                            <label>Dimensions</label>
                            <input type="text" id="gallery-reg-dimensions" placeholder="e.g. 1920x1080, 24x36 inches">
                        </div>
                        <div class="full-width">
                            <label>Description</label>
                            <textarea id="gallery-reg-description" placeholder="Describe your artwork..."></textarea>
                        </div>
                        <div>
                            <label>Tags (comma-separated)</label>
                            <input type="text" id="gallery-reg-tags" placeholder="landscape, sunset, oil">
                        </div>
                        <div>
                            <label>License</label>
                            <select id="gallery-reg-license">
                                <option value="All Rights Reserved">All Rights Reserved</option>
                                <option value="CC BY 4.0">CC BY 4.0</option>
                                <option value="CC BY-SA 4.0">CC BY-SA 4.0</option>
                                <option value="CC BY-NC 4.0">CC BY-NC 4.0</option>
                                <option value="CC BY-NC-SA 4.0">CC BY-NC-SA 4.0</option>
                                <option value="CC0 (Public Domain)">CC0 (Public Domain)</option>
                            </select>
                        </div>
                        <div class="full-width">
                            <label>Watermark Types</label>
                            <div class="gallery-wm-checks">
                                <label><input type="checkbox" id="gallery-wm-visible" checked> Visible overlay</label>
                                <label><input type="checkbox" id="gallery-wm-invisible" checked> Invisible (LSB)</label>
                                <label><input type="checkbox" id="gallery-wm-certificate" checked> Certificate</label>
                            </div>
                        </div>
                        <div class="full-width" style="text-align:right; padding-top:8px;">
                            <button class="btn btn-primary" onclick="registerArtwork()" id="gallery-register-btn">
                                <i class="fas fa-lock"></i> Register &amp; Notarize
                            </button>
                        </div>
                    </div>
                    <div id="gallery-register-result" style="display:none; padding:16px;"></div>
                </div>

                <!-- Verify Tab -->
                <div id="gallery-verify" class="gallery-tab-content" style="display:none">
                    <div style="padding:16px;">
                        <label style="font-size:0.85rem; color:var(--text-dim); margin-bottom:6px; display:block;">Select Artwork</label>
                        <select id="gallery-verify-select" style="width:100%; padding:8px 12px; border-radius:6px; border:1px solid var(--border); background:var(--bg-input); color:var(--text); font-size:0.9rem;" onchange="verifyArtwork(this.value)">
                            <option value="">— Choose artwork to verify —</option>
                        </select>
                    </div>
                    <div id="gallery-verify-result" class="gallery-verify-result" style="display:none"></div>
                </div>
            </div>
        </main>

        <!-- Right Panel -->
        <aside class="right-panel">
            <!-- Music Player Launcher -->
            <div id="webamp-launcher" class="card" style="text-align:center;cursor:pointer" onclick="showWebamp()">
                <i class="fas fa-compact-disc" style="font-size:1.5rem;color:var(--accent)"></i>
                <div style="font-size:0.8rem;margin-top:4px;color:var(--text-dim)">Music Player</div>
            </div>
            <!-- Fallback audio element (used when Webamp is not supported) -->
            <audio id="webamp-fallback-audio" preload="none" style="display:none"></audio>

            <div class="card rp-collapsed">
                <h3>System Status</h3>
                <div class="rp-body">
                    <div class="stat-row">
                        <span>Provider</span>
                        <span class="stat-value" id="stat-provider">Loading...</span>
                    </div>
                    <div class="stat-row">
                        <span>Memory</span>
                        <span class="stat-value" id="stat-memory">0 entries</span>
                    </div>
                    <div class="stat-row">
                        <span>Skills</span>
                        <span class="stat-value" id="stat-skills">0</span>
                    </div>
                    <div class="stat-row">
                        <span>Tools</span>
                        <span class="stat-value" id="stat-tools">0</span>
                    </div>
                </div>
            </div>

            <div class="card rp-collapsed">
                <h3>Connected Nodes</h3>
                <div class="rp-body">
                    <div id="nodes-sidebar">
                        <div class="node-item">
                            <div class="node-dot"></div>
                            <div>
                                <div style="font-weight: 500;">Gateway</div>
                                <div style="font-size: 0.75rem; color: var(--text-dim);">This device</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card rp-collapsed" id="quick-actions-card">
                <h3>Quick Actions</h3>
                <div class="rp-body">
                    <div id="quick-actions-default">
                        <button class="btn btn-secondary" style="width: 100%; margin-bottom: 8px;" onclick="quickCommand('daily_briefing')">
                            <i class="fas fa-sun"></i> Morning Briefing
                        </button>
                        <button class="btn btn-secondary" style="width: 100%; margin-bottom: 8px;" onclick="quickCommand('triage_inbox')">
                            <i class="fas fa-envelope"></i> Sort Inbox
                        </button>
                        <button class="btn btn-secondary" style="width: 100%;" onclick="quickCommand('check_deadlines')">
                            <i class="fas fa-clock"></i> Check Deadlines
                        </button>
                    </div>
                    <div id="quick-actions-workspace" style="display:none;"></div>
                </div>
            </div>
        </aside>
    </div>

    <!-- Webamp Player Container -->
    <div id="webamp-container"></div>

    <!-- Add Task Modal -->
    <div class="modal-overlay" id="task-modal">
        <div class="modal">
            <h3 id="task-modal-title">Add Task</h3>
            <input type="hidden" id="task-id" value="" />
            <div class="form-group">
                <label>Title</label>
                <input type="text" id="task-title" placeholder="What needs to be done?" />
            </div>
            <div class="form-group">
                <label>Priority</label>
                <select id="task-priority">
                    <option value="normal">Normal</option>
                    <option value="high">High</option>
                    <option value="urgent">Urgent</option>
                    <option value="low">Low</option>
                </select>
            </div>
            <div class="form-group">
                <label>Due Date</label>
                <input type="text" id="task-due" placeholder="tomorrow, next week, 2024-03-15" />
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="task-category">
                    <option value="general">General</option>
                    <option value="grants">Grants</option>
                    <option value="donors">Donors</option>
                    <option value="board">Board</option>
                    <option value="events">Events</option>
                    <option value="compliance">Compliance</option>
                </select>
            </div>
            <div id="task-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="task-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="task-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('task-file-input','tasks',document.getElementById('task-id').value,'helper','task-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('task-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="addTask()">Add Task</button>
            </div>
        </div>
    </div>
    
    <!-- Add Memory Modal -->
    <div class="modal-overlay" id="memory-modal">
        <div class="modal">
            <h3>Add Memory</h3>
            <div class="form-group">
                <label>Key</label>
                <input type="text" id="memory-key" placeholder="e.g., user_name, favorite_color" />
            </div>
            <div class="form-group">
                <label>Value</label>
                <textarea id="memory-value" rows="3" placeholder="What should I remember?"></textarea>
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="memory-category">
                    <option value="fact">Fact</option>
                    <option value="preference">Preference</option>
                    <option value="user_info">User Info</option>
                    <option value="task">Task</option>
                </select>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('memory-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="addMemory()">Save</button>
            </div>
        </div>
    </div>
    
    <!-- Memory Tree Detail Modal -->
    <div class="modal-overlay" id="mt-detail-modal">
        <div class="modal modal-md">
            <div id="mt-detail-body"></div>
            <div class="actions" style="margin-top:12px">
                <button class="btn btn-secondary" onclick="hideModal('mt-detail-modal')">Close</button>
            </div>
        </div>
    </div>

    <!-- Memory Tree Topic Modal -->
    <div class="modal-overlay" id="mt-topic-modal">
        <div class="modal modal-md">
            <h3 id="mt-topic-title">Topic</h3>
            <div id="mt-topic-meta" style="font-size:0.8em;color:var(--text-dim);margin-bottom:12px"></div>
            <div id="mt-topic-new-slug-wrap" style="display:none;margin-bottom:12px">
                <label style="font-size:0.85em;margin-bottom:4px;display:block">Topic Name</label>
                <input type="text" id="mt-topic-new-slug" placeholder="e.g., meeting-notes, project-plan" style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text)">
            </div>
            <input type="hidden" id="mt-topic-slug">
            <input type="hidden" id="mt-topic-ns">
            <div class="form-group">
                <label>Content (Markdown)</label>
                <textarea id="mt-topic-body" rows="12" style="font-family:monospace;font-size:0.85em;width:100%;padding:10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text);resize:vertical" placeholder="Write your content here..."></textarea>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="document.getElementById('mt-topic-modal').style.display='none'">Cancel</button>
                <button class="btn btn-primary" onclick="mtSaveNewTopic()">Save</button>
            </div>
        </div>
    </div>

    <!-- Donor Detail Slide-Out Panel -->
    <div class="np-detail-overlay" id="np-detail-overlay" onclick="npCloseDetail()"></div>
    <div class="np-detail-panel" id="np-detail-panel">
        <div class="np-detail-header">
            <h3 id="np-detail-name">Donor Details</h3>
            <button class="np-detail-close" onclick="npCloseDetail()">&times;</button>
        </div>
        <div class="np-detail-body" id="np-detail-body">
            <!-- Populated dynamically -->
        </div>
        <div class="np-detail-actions" id="np-detail-actions">
            <!-- Populated dynamically -->
        </div>
    </div>

    <!-- Add Donor Modal -->
    <div class="modal-overlay" id="np-donor-modal">
        <div class="modal">
            <h3 id="np-donor-modal-title">Add Donor</h3>
            <input type="hidden" id="np-donor-id" value="" />
            <div class="form-group">
                <label>Name *</label>
                <input type="text" id="np-donor-name" placeholder="Full name" />
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="email" id="np-donor-email" placeholder="email@example.com" />
            </div>
            <div class="form-group">
                <label>Phone</label>
                <input type="tel" id="np-donor-phone" placeholder="(555) 123-4567" />
            </div>
            <div class="form-group">
                <label>Tags</label>
                <input type="text" id="np-donor-tags" placeholder="major_donor, board_member (comma-separated)" />
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="np-donor-notes" rows="2" placeholder="Additional notes..."></textarea>
            </div>
            <!-- File attachments (visible when editing existing donor) -->
            <div id="np-donor-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="np-donor-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="np-donor-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('np-donor-file-input','donors',document.getElementById('np-donor-id').value,'nonprofit','np-donor-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-donor-modal')">Cancel</button>
                <button class="btn btn-primary" id="np-donor-save-btn" onclick="npSaveDonor()">Save</button>
            </div>
        </div>
    </div>

    <!-- Log Donation Modal -->
    <div class="modal-overlay" id="np-donation-modal">
        <div class="modal">
            <h3>Log Donation</h3>
            <input type="hidden" id="np-donation-donor-id" value="" />
            <div class="form-group">
                <label>Donor *</label>
                <input type="text" id="np-donation-donor" placeholder="Donor name" list="np-donor-list" />
                <datalist id="np-donor-list"></datalist>
            </div>
            <div class="form-group">
                <label>Amount *</label>
                <input type="number" id="np-donation-amount" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Date</label>
                <input type="date" id="np-donation-date" />
            </div>
            <div class="form-group">
                <label>Fund</label>
                <select id="np-donation-fund">
                    <option value="General">General</option>
                </select>
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="np-donation-category">
                    <option value="individual_donations">Individual Donation</option>
                    <option value="corporate_donations">Corporate Donation</option>
                    <option value="grants">Grant Payment</option>
                    <option value="events">Event Revenue</option>
                    <option value="membership_dues">Membership Dues</option>
                    <option value="other_income">Other Income</option>
                </select>
            </div>
            <div class="form-group">
                <label>Description</label>
                <input type="text" id="np-donation-desc" placeholder="Annual gift, event ticket, etc." />
            </div>
            <!-- File attachments (visible after saving donation) -->
            <div id="np-donation-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="np-donation-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="np-donation-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('np-donation-file-input','donations',document.getElementById('np-donation-saved-id').value,'nonprofit','np-donation-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <input type="hidden" id="np-donation-saved-id" value="" />
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-donation-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="npSaveDonation()">Log Donation</button>
            </div>
        </div>
    </div>

    <!-- Log Expense Modal -->
    <div class="modal-overlay" id="np-expense-modal">
        <div class="modal">
            <h3>Log Expense</h3>
            <div class="form-group">
                <label>Amount *</label>
                <input type="number" id="np-expense-amount" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Date</label>
                <input type="date" id="np-expense-date" />
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="np-expense-category">
                    <option value="salaries">Salaries</option>
                    <option value="benefits">Benefits</option>
                    <option value="rent">Rent</option>
                    <option value="utilities">Utilities</option>
                    <option value="supplies">Supplies</option>
                    <option value="travel">Travel</option>
                    <option value="professional_services">Professional Services</option>
                    <option value="insurance">Insurance</option>
                    <option value="fundraising">Fundraising</option>
                    <option value="program_services">Program Services</option>
                    <option value="other_expense">Other Expense</option>
                </select>
            </div>
            <div class="form-group">
                <label>Vendor</label>
                <input type="text" id="np-expense-vendor" placeholder="Vendor/payee name" />
            </div>
            <div class="form-group">
                <label>Fund</label>
                <select id="np-expense-fund">
                    <option value="General">General</option>
                </select>
            </div>
            <div class="form-group">
                <label>Description</label>
                <input type="text" id="np-expense-desc" placeholder="What was this for?" />
            </div>
            <!-- File attachments (visible after saving expense) -->
            <div id="np-expense-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments (receipts, invoices)</label>
                    <div id="np-expense-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="np-expense-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('np-expense-file-input','expenses',document.getElementById('np-expense-saved-id').value,'nonprofit','np-expense-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <input type="hidden" id="np-expense-saved-id" value="" />
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-expense-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="npSaveExpense()">Log Expense</button>
            </div>
        </div>
    </div>

    <!-- Add Grant Modal -->
    <div class="modal-overlay" id="np-grant-modal">
        <div class="modal">
            <h3 id="np-grant-modal-title">Add Grant</h3>
            <input type="hidden" id="np-grant-id" value="" />
            <div class="form-group">
                <label>Grant Name *</label>
                <input type="text" id="np-grant-name" placeholder="Community Impact Grant" />
            </div>
            <div class="form-group">
                <label>Funder</label>
                <input type="text" id="np-grant-funder" placeholder="Foundation or agency name" />
            </div>
            <div class="form-group">
                <label>Amount</label>
                <input type="number" id="np-grant-amount" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="np-grant-status">
                    <option value="prospect">Prospect</option>
                    <option value="applied">Applied</option>
                    <option value="awarded">Awarded</option>
                    <option value="declined">Declined</option>
                    <option value="completed">Completed</option>
                </select>
            </div>
            <div class="form-group">
                <label>Application Deadline</label>
                <input type="date" id="np-grant-deadline" />
            </div>
            <div class="form-group">
                <label>Report Due</label>
                <input type="date" id="np-grant-report-due" />
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="np-grant-notes" rows="2" placeholder="Grant details..."></textarea>
            </div>
            <!-- File attachments (visible when editing existing grant) -->
            <div id="np-grant-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="np-grant-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="np-grant-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="npUploadGrantFiles()"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-grant-modal')">Cancel</button>
                <button class="btn btn-primary" id="np-grant-save-btn" onclick="npSaveGrant()">Save</button>
            </div>
        </div>
    </div>

    <!-- Add Note Modal -->
    <div class="modal-overlay" id="np-note-modal">
        <div class="modal">
            <h3 id="np-note-modal-title">Add Note</h3>
            <input type="hidden" id="np-note-id" value="" />
            <div class="form-group">
                <label>Category</label>
                <select id="np-note-category">
                    <option value="general">General</option>
                    <option value="board">Board</option>
                    <option value="fundraising">Fundraising</option>
                    <option value="meeting">Meeting</option>
                    <option value="call">Call</option>
                    <option value="compliance">Compliance</option>
                </select>
            </div>
            <div class="form-group">
                <label>Content *</label>
                <textarea id="np-note-content" rows="4" placeholder="Meeting notes, action items, etc."></textarea>
            </div>
            <!-- File attachments (visible after saving note) -->
            <div id="np-note-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="np-note-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="np-note-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('np-note-file-input','notes',document.getElementById('np-note-id').value,'nonprofit','np-note-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-note-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="npSaveNote()">Save Note</button>
            </div>
        </div>
    </div>

    <!-- Import Donors Modal -->
    <div class="modal-overlay" id="np-import-modal">
        <div class="modal">
            <h3>Import Donors</h3>
            <div class="form-group">
                <label>CSV File</label>
                <input type="file" id="np-import-file" accept=".csv,.xlsx" />
                <div style="font-size:0.75rem;color:var(--text-dim);margin-top:4px">
                    Expected columns: name, email, phone, tags, amount, notes
                </div>
            </div>
            <div id="np-import-preview" style="display:none;margin-top:12px">
                <div style="font-size:0.8rem;color:var(--text-dim);margin-bottom:4px" id="np-import-count"></div>
                <div style="max-height:200px;overflow:auto;font-size:0.75rem;border:1px solid var(--border);border-radius:8px;padding:8px" id="np-import-rows"></div>
            </div>
            <div id="np-import-result" style="display:none;margin-top:12px;padding:12px;border-radius:8px"></div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-import-modal')">Cancel</button>
                <button class="btn btn-primary" id="np-import-btn" onclick="npDoImport()" disabled>Import</button>
            </div>
        </div>
    </div>

    <!-- Thank-You Letter Generator Modal -->
    <div class="modal-overlay" id="np-thankyou-modal">
        <div class="modal" style="max-width:520px">
            <h3>Generate Thank-You Letter</h3>
            <div class="form-group">
                <label>Donor Name</label>
                <input type="text" id="np-ty-donor" placeholder="Jane Smith">
            </div>
            <div class="form-group">
                <label>Gift Amount ($)</label>
                <input type="number" id="np-ty-amount" step="0.01" placeholder="100.00">
            </div>
            <div class="form-group">
                <label>Gift Date</label>
                <input type="date" id="np-ty-date">
            </div>
            <div class="form-group">
                <label>Organization Name</label>
                <input type="text" id="np-ty-org" placeholder="Your Organization">
            </div>
            <div class="form-group">
                <label>Impact Area</label>
                <input type="text" id="np-ty-impact" placeholder="e.g. youth programs, community services">
            </div>
            <div class="form-group">
                <label>Personal Note (optional)</label>
                <textarea id="np-ty-note" rows="2" placeholder="Add a personal touch..."></textarea>
            </div>
            <div class="form-group">
                <label>Signer Name</label>
                <input type="text" id="np-ty-signer" placeholder="Executive Director name">
            </div>
            <div id="np-ty-status" style="display:none;margin-top:8px;padding:8px 12px;border-radius:8px;font-size:0.85rem"></div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-thankyou-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="npGenerateThankYou()"><i class="fas fa-file-word"></i> Generate Letter</button>
            </div>
        </div>
    </div>

    <!-- Donation Receipt Generator Modal -->
    <div class="modal-overlay" id="np-receipt-modal">
        <div class="modal modal-sm">
            <h3>Generate Donation Receipt</h3>
            <div class="form-group">
                <label>Donor Name</label>
                <input type="text" id="np-rcpt-donor" placeholder="Jane Smith">
            </div>
            <div class="form-group">
                <label>Amount ($)</label>
                <input type="number" id="np-rcpt-amount" step="0.01" placeholder="100.00">
            </div>
            <div class="form-group">
                <label>Date of Gift</label>
                <input type="date" id="np-rcpt-date">
            </div>
            <div class="form-group">
                <label>Description</label>
                <input type="text" id="np-rcpt-desc" placeholder="Charitable donation">
            </div>
            <div id="np-rcpt-status" style="display:none;margin-top:8px;padding:8px 12px;border-radius:8px;font-size:0.85rem"></div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('np-receipt-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="npGenerateReceipt()"><i class="fas fa-file-word"></i> Generate Receipt</button>
            </div>
        </div>
    </div>

    <!-- Social Worker: Case Modal -->
    <div class="modal-overlay" id="sw-case-modal">
        <div class="modal" style="max-width:520px">
            <h3 id="sw-case-modal-title">New Case</h3>
            <input type="hidden" id="sw-case-id">
            <div class="form-group">
                <label>Client Name *</label>
                <input type="text" id="sw-case-name" placeholder="Client name or identifier">
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="sw-case-category">
                    <option value="general">General</option>
                    <option value="housing">Housing</option>
                    <option value="mental_health">Mental Health</option>
                    <option value="substance_use">Substance Use</option>
                    <option value="child_welfare">Child Welfare</option>
                    <option value="domestic_violence">Domestic Violence</option>
                    <option value="elder_care">Elder Care</option>
                    <option value="disability">Disability</option>
                    <option value="immigration">Immigration</option>
                    <option value="employment">Employment</option>
                    <option value="food_insecurity">Food Insecurity</option>
                </select>
            </div>
            <div class="form-group">
                <label>Priority</label>
                <select id="sw-case-priority">
                    <option value="low">Low</option>
                    <option value="normal" selected>Normal</option>
                    <option value="high">High</option>
                    <option value="urgent">Urgent</option>
                </select>
            </div>
            <div class="form-group">
                <label>Phone</label>
                <input type="tel" id="sw-case-phone" placeholder="555-1234">
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="email" id="sw-case-email" placeholder="client@example.com">
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="sw-case-notes" rows="3" placeholder="Initial notes about this case..."></textarea>
            </div>
            <div id="sw-case-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Documents</label>
                    <div id="sw-case-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sw-case-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="swUploadCaseFiles()"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sw-case-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="swSaveCase()"><i class="fas fa-save"></i> Save Case</button>
            </div>
        </div>
    </div>

    <!-- Social Worker: Resource Modal -->
    <div class="modal-overlay" id="sw-resource-modal">
        <div class="modal" style="max-width:480px">
            <h3 id="sw-resource-modal-title">Add Resource</h3>
            <input type="hidden" id="sw-resource-id">
            <div class="form-group">
                <label>Resource Name *</label>
                <input type="text" id="sw-resource-name" placeholder="e.g. City Food Bank">
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="sw-resource-category">
                    <option value="housing">Housing</option>
                    <option value="food">Food</option>
                    <option value="mental_health">Mental Health</option>
                    <option value="substance_use">Substance Use</option>
                    <option value="employment">Employment</option>
                    <option value="legal">Legal Aid</option>
                    <option value="medical">Medical</option>
                    <option value="childcare">Childcare</option>
                    <option value="financial">Financial Aid</option>
                    <option value="domestic_violence">Domestic Violence</option>
                    <option value="general" selected>General</option>
                </select>
            </div>
            <div class="form-group">
                <label>Phone</label>
                <input type="tel" id="sw-resource-phone" placeholder="555-1234">
            </div>
            <div class="form-group">
                <label>Address</label>
                <input type="text" id="sw-resource-address" placeholder="123 Main St">
            </div>
            <div class="form-group">
                <label>Website</label>
                <input type="url" id="sw-resource-website" placeholder="https://...">
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="sw-resource-notes" rows="2" placeholder="Hours, eligibility, etc."></textarea>
            </div>
            <div id="sw-resource-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="sw-resource-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sw-resource-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('sw-resource-file-input','resources',document.getElementById('sw-resource-id').value,'social_worker','sw-resource-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sw-resource-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="swSaveResource()"><i class="fas fa-save"></i> Save Resource</button>
            </div>
        </div>
    </div>

    <!-- Social Worker: Case Note Modal -->
    <div class="modal-overlay" id="sw-note-modal">
        <div class="modal" style="max-width:480px">
            <h3>Add Case Note</h3>
            <div class="form-group">
                <label>Case</label>
                <select id="sw-note-case"><option value="">General</option></select>
            </div>
            <div class="form-group">
                <label>Type</label>
                <select id="sw-note-category">
                    <option value="progress">Progress Note</option>
                    <option value="assessment">Assessment</option>
                    <option value="plan">Service Plan</option>
                    <option value="contact">Contact Log</option>
                    <option value="referral">Referral</option>
                </select>
            </div>
            <div class="form-group">
                <label>Note *</label>
                <textarea id="sw-note-content" rows="4" placeholder="Case note content..."></textarea>
            </div>
            <div id="sw-note-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="sw-note-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sw-note-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('sw-note-file-input','case_notes',document.getElementById('sw-note-saved-id').value,'social_worker','sw-note-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <input type="hidden" id="sw-note-saved-id" value="" />
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sw-note-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="swSaveNote()"><i class="fas fa-save"></i> Save Note</button>
            </div>
        </div>
    </div>

    <!-- Social Worker: Crisis Event Modal -->
    <div class="modal-overlay" id="sw-crisis-modal">
        <div class="modal" style="max-width:480px">
            <h3>Log Crisis Event</h3>
            <div class="form-group">
                <label>Case</label>
                <select id="sw-crisis-case"><option value="">Unlinked</option></select>
            </div>
            <div class="form-group">
                <label>Severity</label>
                <select id="sw-crisis-severity">
                    <option value="low">Low</option>
                    <option value="moderate" selected>Moderate</option>
                    <option value="high">High</option>
                    <option value="critical">Critical</option>
                </select>
            </div>
            <div class="form-group">
                <label>Summary *</label>
                <textarea id="sw-crisis-summary" rows="3" placeholder="Describe the crisis event..."></textarea>
            </div>
            <div class="form-group">
                <label>Outcome</label>
                <textarea id="sw-crisis-outcome" rows="2" placeholder="Intervention taken, result..."></textarea>
            </div>
            <div id="sw-crisis-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="sw-crisis-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sw-crisis-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('sw-crisis-file-input','crisis_events',document.getElementById('sw-crisis-saved-id').value,'social_worker','sw-crisis-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <input type="hidden" id="sw-crisis-saved-id" value="" />
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sw-crisis-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="swSaveCrisis()"><i class="fas fa-save"></i> Log Crisis</button>
            </div>
        </div>
    </div>

    <!-- Assessment Modal (PHQ-9, GAD-7, C-SSRS, AUDIT, DAST-10, ACE) -->
    <div class="modal-overlay" id="sw-assessment-modal">
        <div class="modal" style="max-width:520px">
            <h3><i class="fas fa-clipboard-check"></i> Clinical Assessment</h3>
            <div class="form-group">
                <label>Case *</label>
                <select id="sw-assess-case"><option value="">Select case...</option></select>
            </div>
            <div class="form-group">
                <label>Assessment Tool *</label>
                <select id="sw-assess-tool" onchange="swUpdateAssessmentFields()">
                    <option value="PHQ-9">PHQ-9 (Depression, 0-27)</option>
                    <option value="GAD-7">GAD-7 (Anxiety, 0-21)</option>
                    <option value="C-SSRS">C-SSRS (Suicide Risk)</option>
                    <option value="AUDIT">AUDIT (Alcohol, 0-40)</option>
                    <option value="DAST-10">DAST-10 (Drugs, 0-10)</option>
                    <option value="ACE">ACE (Adverse Childhood, 0-10)</option>
                </select>
            </div>
            <div id="sw-assess-score-group" class="form-group">
                <label>Score *</label>
                <input type="number" id="sw-assess-score" min="0" placeholder="Enter score">
            </div>
            <div id="sw-assess-severity-group" class="form-group">
                <label>Severity</label>
                <select id="sw-assess-severity">
                    <option value="none">None</option>
                    <option value="minimal">Minimal</option>
                    <option value="mild">Mild</option>
                    <option value="moderate">Moderate</option>
                    <option value="moderately_severe">Moderately Severe</option>
                    <option value="severe">Severe</option>
                </select>
            </div>
            <div id="sw-assess-cssrs-group" style="display:none">
                <div class="form-group">
                    <label>Risk Level</label>
                    <select id="sw-assess-risk">
                        <option value="low">Low</option>
                        <option value="moderate">Moderate</option>
                        <option value="high">High</option>
                    </select>
                </div>
                <div class="form-group" style="display:flex;gap:16px;flex-wrap:wrap">
                    <label><input type="checkbox" id="sw-assess-ideation"> Suicidal Ideation</label>
                    <label><input type="checkbox" id="sw-assess-plan"> Has Plan</label>
                    <label><input type="checkbox" id="sw-assess-intent"> Has Intent</label>
                </div>
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="sw-assess-notes" rows="2" placeholder="Clinical notes..."></textarea>
            </div>
            <div id="sw-assessment-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments (signed forms, etc.)</label>
                    <div id="sw-assessment-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sw-assessment-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('sw-assessment-file-input','assessments',document.getElementById('sw-assessment-saved-id').value,'social_worker','sw-assessment-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <input type="hidden" id="sw-assessment-saved-id" value="" />
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sw-assessment-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="swSaveAssessment()"><i class="fas fa-save"></i> Save Assessment</button>
            </div>
        </div>
    </div>

    <!-- Safety Plan Modal (Stanley-Brown) -->
    <div class="modal-overlay" id="sw-safety-plan-modal">
        <div class="modal modal-md modal-scroll">
            <h3><i class="fas fa-shield-heart"></i> Safety Plan (Stanley-Brown)</h3>
            <div class="form-group">
                <label>Case *</label>
                <select id="sw-sp-case"><option value="">Select case...</option></select>
            </div>
            <div class="form-group">
                <label>1. Warning Signs</label>
                <textarea id="sw-sp-warnings" rows="2" placeholder="One per line: thoughts, feelings, situations..."></textarea>
            </div>
            <div class="form-group">
                <label>2. Internal Coping Strategies</label>
                <textarea id="sw-sp-coping" rows="2" placeholder="One per line: things I can do alone..."></textarea>
            </div>
            <div class="form-group">
                <label>3. Social Contacts (People for Distraction)</label>
                <textarea id="sw-sp-social" rows="2" placeholder="One per line: name, phone..."></textarea>
            </div>
            <div class="form-group">
                <label>4. Professional Contacts</label>
                <textarea id="sw-sp-professional" rows="2" placeholder="One per line: clinician, agency, crisis line..."></textarea>
            </div>
            <div class="form-group">
                <label>5. Making the Environment Safe</label>
                <textarea id="sw-sp-environment" rows="2" placeholder="Steps to make environment safe..."></textarea>
            </div>
            <div class="form-group">
                <label>6. Reasons for Living</label>
                <textarea id="sw-sp-reasons" rows="2" placeholder="One per line: motivations..."></textarea>
            </div>
            <div id="sw-safety-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments (signed plan, etc.)</label>
                    <div id="sw-safety-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sw-safety-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('sw-safety-file-input','safety_plans',document.getElementById('sw-safety-saved-id').value,'social_worker','sw-safety-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <input type="hidden" id="sw-safety-saved-id" value="" />
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sw-safety-plan-modal')">Cancel</button>
                <button class="btn btn-primary" onclick="swSaveSafetyPlan()"><i class="fas fa-save"></i> Save Plan</button>
            </div>
        </div>
    </div>

    <!-- ════════ Artist Modals ════════ -->

    <!-- Artist: Piece Modal -->
    <div class="modal-overlay" id="art-piece-modal">
        <div class="modal">
            <h3 id="art-piece-modal-title">Add Piece</h3>
            <input type="hidden" id="art-piece-id" value="" />
            <div class="form-group">
                <label>Name *</label>
                <input type="text" id="art-piece-name" placeholder="e.g. Celadon Bowl #12" />
            </div>
            <div class="form-group">
                <label>Type</label>
                <select id="art-piece-type">
                    <option value="bowl">Bowl</option>
                    <option value="vase">Vase</option>
                    <option value="mug">Mug</option>
                    <option value="plate">Plate</option>
                    <option value="sculpture">Sculpture</option>
                    <option value="tile">Tile</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="art-piece-status">
                    <option value="concept">Concept</option>
                    <option value="in_progress">In Progress</option>
                    <option value="drying">Drying</option>
                    <option value="bisque_fire">Bisque Fire</option>
                    <option value="glazing">Glazing</option>
                    <option value="glaze_fire">Glaze Fire</option>
                    <option value="finished">Finished</option>
                    <option value="listed">Listed</option>
                    <option value="sold">Sold</option>
                </select>
            </div>
            <div class="form-group">
                <label>Price</label>
                <input type="number" id="art-piece-price" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="art-piece-notes" rows="2" placeholder="Clay body, glaze, dimensions..."></textarea>
            </div>
            <div id="art-piece-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Photos / Attachments</label>
                    <div id="art-piece-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="art-piece-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('art-piece-file-input','pieces',document.getElementById('art-piece-id').value,'artist','art-piece-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('art-piece-modal')">Cancel</button>
                <button class="btn btn-primary" id="art-piece-save-btn" onclick="artSavePiece()">Save</button>
            </div>
        </div>
    </div>

    <!-- Artist: Generate Image Modal -->
    <div class="modal-overlay" id="art-gen-modal" onclick="if(event.target===this)hideModal('art-gen-modal')">
        <div class="modal modal-md">
            <h3><i class="fas fa-wand-magic-sparkles" style="margin-right:8px"></i>Generate Image</h3>
            <div class="form-group">
                <label>Prompt *</label>
                <textarea id="art-gen-prompt" rows="3" placeholder="A serene mountain lake at sunset, oil painting style..."></textarea>
            </div>
            <div class="form-group">
                <label>Style</label>
                <select id="art-gen-style">
                    <option value="">Auto</option>
                    <option value="oil painting">Oil Painting</option>
                    <option value="watercolor">Watercolor</option>
                    <option value="photograph">Photograph</option>
                    <option value="digital art">Digital Art</option>
                    <option value="anime">Anime</option>
                    <option value="pencil sketch">Pencil Sketch</option>
                    <option value="pixel art">Pixel Art</option>
                    <option value="3d render">3D Render</option>
                </select>
            </div>
            <div style="display:flex;gap:12px">
                <div class="form-group" style="flex:1">
                    <label>Width</label>
                    <select id="art-gen-width">
                        <option value="512">512</option>
                        <option value="768">768</option>
                        <option value="1024" selected>1024</option>
                        <option value="1536">1536</option>
                        <option value="2048">2048</option>
                    </select>
                </div>
                <div class="form-group" style="flex:1">
                    <label>Height</label>
                    <select id="art-gen-height">
                        <option value="512">512</option>
                        <option value="768">768</option>
                        <option value="1024" selected>1024</option>
                        <option value="1536">1536</option>
                        <option value="2048">2048</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>Provider</label>
                <select id="art-gen-provider">
                    <option value="auto">Auto-detect</option>
                    <option value="gemini">Gemini</option>
                    <option value="openai">DALL-E 3</option>
                    <option value="comfyui">ComfyUI (local)</option>
                    <option value="a1111">Automatic1111 (local)</option>
                </select>
            </div>
            <div class="form-group">
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                    <input type="checkbox" id="art-gen-register" />
                    Register in Gallery with provenance chain
                </label>
            </div>
            <div id="art-gen-result" style="display:none;margin-bottom:16px">
                <img id="art-gen-preview" style="max-width:100%;border-radius:8px;margin-bottom:8px" />
                <div id="art-gen-result-text" style="font-size:0.85em;color:var(--text-dim)"></div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('art-gen-modal')">Cancel</button>
                <button class="btn btn-primary" id="art-gen-btn" onclick="artGenerateImage()">
                    <i class="fas fa-wand-magic-sparkles"></i> Generate
                </button>
            </div>
        </div>
    </div>

    <!-- Artist: Commission Modal -->
    <div class="modal-overlay" id="art-commission-modal">
        <div class="modal">
            <h3 id="art-commission-modal-title">New Commission</h3>
            <input type="hidden" id="art-commission-id" value="" />
            <div class="form-group">
                <label>Client *</label>
                <input type="text" id="art-commission-client" placeholder="Client name" />
            </div>
            <div class="form-group">
                <label>Description *</label>
                <textarea id="art-commission-desc" rows="2" placeholder="What they want..."></textarea>
            </div>
            <div class="form-group">
                <label>Price</label>
                <input type="number" id="art-commission-price" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Deposit</label>
                <input type="number" id="art-commission-deposit" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Due Date</label>
                <input type="date" id="art-commission-due" />
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="art-commission-status">
                    <option value="inquiry">Inquiry</option>
                    <option value="quoted">Quoted</option>
                    <option value="accepted">Accepted</option>
                    <option value="in_progress">In Progress</option>
                    <option value="completed">Completed</option>
                    <option value="delivered">Delivered</option>
                </select>
            </div>
            <div id="art-commission-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>References / Attachments</label>
                    <div id="art-commission-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="art-commission-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('art-commission-file-input','commissions',document.getElementById('art-commission-id').value,'artist','art-commission-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('art-commission-modal')">Cancel</button>
                <button class="btn btn-primary" id="art-commission-save-btn" onclick="artSaveCommission()">Save</button>
            </div>
        </div>
    </div>

    <!-- Artist: Show Modal -->
    <div class="modal-overlay" id="art-show-modal">
        <div class="modal">
            <h3 id="art-show-modal-title">Add Show</h3>
            <input type="hidden" id="art-show-id" value="" />
            <div class="form-group">
                <label>Event Name *</label>
                <input type="text" id="art-show-name" placeholder="Spring Art Fair" />
            </div>
            <div class="form-group">
                <label>Venue</label>
                <input type="text" id="art-show-venue" placeholder="Gallery / Market location" />
            </div>
            <div class="form-group">
                <label>Date</label>
                <input type="date" id="art-show-date" />
            </div>
            <div class="form-group">
                <label>Type</label>
                <select id="art-show-type">
                    <option value="exhibition">Exhibition</option>
                    <option value="craft_market">Craft Market</option>
                    <option value="studio_tour">Studio Tour</option>
                    <option value="gallery_opening">Gallery Opening</option>
                    <option value="art_fair">Art Fair</option>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="art-show-status">
                    <option value="planned">Planned</option>
                    <option value="confirmed">Confirmed</option>
                    <option value="completed">Completed</option>
                    <option value="cancelled">Cancelled</option>
                </select>
            </div>
            <div id="art-show-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="art-show-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="art-show-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('art-show-file-input','shows',document.getElementById('art-show-id').value,'artist','art-show-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('art-show-modal')">Cancel</button>
                <button class="btn btn-primary" id="art-show-save-btn" onclick="artSaveShow()">Save</button>
            </div>
        </div>
    </div>

    <!-- Artist: Client Modal -->
    <div class="modal-overlay" id="art-client-modal">
        <div class="modal" style="max-width:480px">
            <h3 id="art-client-modal-title">Add Client</h3>
            <input type="hidden" id="art-client-id" value="" />
            <div class="form-group">
                <label>Name *</label>
                <input type="text" id="art-client-name" placeholder="Client name" />
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="email" id="art-client-email" placeholder="email@example.com" />
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="art-client-notes" rows="2" placeholder="Preferences, past orders..."></textarea>
            </div>
            <div id="art-client-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="art-client-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="art-client-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('art-client-file-input','clients',document.getElementById('art-client-id').value,'artist','art-client-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('art-client-modal')">Cancel</button>
                <button class="btn btn-primary" id="art-client-save-btn" onclick="artSaveClient()">Save</button>
            </div>
        </div>
    </div>

    <!-- ════════ Chef Modals ════════ -->

    <!-- Chef: Recipe Modal -->
    <div class="modal-overlay" id="chef-recipe-modal">
        <div class="modal">
            <h3 id="chef-recipe-modal-title">Add Recipe</h3>
            <input type="hidden" id="chef-recipe-id" value="" />
            <div class="form-group">
                <label>Recipe Name *</label>
                <input type="text" id="chef-recipe-name" placeholder="e.g. Sourdough Boule" />
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="chef-recipe-category">
                    <option value="appetizer">Appetizer</option>
                    <option value="entree">Entree</option>
                    <option value="dessert">Dessert</option>
                    <option value="bread">Bread</option>
                    <option value="sauce">Sauce</option>
                    <option value="beverage">Beverage</option>
                    <option value="side">Side</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label>Servings</label>
                <input type="number" id="chef-recipe-servings" placeholder="4" min="1" />
            </div>
            <div class="form-group">
                <label>Cost per Serving</label>
                <input type="number" id="chef-recipe-cost" placeholder="0.00" step="0.01" min="0" />
            </div>
            <div class="form-group">
                <label>Prep Time (min)</label>
                <input type="number" id="chef-recipe-prep" placeholder="30" min="0" />
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="chef-recipe-notes" rows="2" placeholder="Instructions, tips..."></textarea>
            </div>
            <div id="chef-recipe-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Photos / Documents</label>
                    <div id="chef-recipe-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="chef-recipe-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('chef-recipe-file-input','recipes',document.getElementById('chef-recipe-id').value,'chef','chef-recipe-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('chef-recipe-modal')">Cancel</button>
                <button class="btn btn-primary" id="chef-recipe-save-btn" onclick="chefSaveRecipe()">Save</button>
            </div>
        </div>
    </div>

    <!-- Chef: Menu Modal -->
    <div class="modal-overlay" id="chef-menu-modal">
        <div class="modal">
            <h3 id="chef-menu-modal-title">Add Menu</h3>
            <input type="hidden" id="chef-menu-id" value="" />
            <div class="form-group">
                <label>Menu Name *</label>
                <input type="text" id="chef-menu-name" placeholder="e.g. Spring Tasting Menu" />
            </div>
            <div class="form-group">
                <label>Type</label>
                <select id="chef-menu-type">
                    <option value="dinner">Dinner</option>
                    <option value="lunch">Lunch</option>
                    <option value="brunch">Brunch</option>
                    <option value="tasting">Tasting</option>
                    <option value="catering">Catering</option>
                    <option value="special">Special Event</option>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="chef-menu-status">
                    <option value="draft">Draft</option>
                    <option value="active">Active</option>
                    <option value="archived">Archived</option>
                </select>
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="chef-menu-notes" rows="2" placeholder="Menu items, pairings..."></textarea>
            </div>
            <div id="chef-menu-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments</label>
                    <div id="chef-menu-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="chef-menu-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('chef-menu-file-input','menus',document.getElementById('chef-menu-id').value,'chef','chef-menu-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('chef-menu-modal')">Cancel</button>
                <button class="btn btn-primary" id="chef-menu-save-btn" onclick="chefSaveMenu()">Save</button>
            </div>
        </div>
    </div>

    <!-- Chef: Vendor Modal -->
    <div class="modal-overlay" id="chef-vendor-modal">
        <div class="modal" style="max-width:480px">
            <h3 id="chef-vendor-modal-title">Add Vendor</h3>
            <input type="hidden" id="chef-vendor-id" value="" />
            <div class="form-group">
                <label>Vendor Name *</label>
                <input type="text" id="chef-vendor-name" placeholder="e.g. Local Farms Co-op" />
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="chef-vendor-category">
                    <option value="produce">Produce</option>
                    <option value="meat">Meat & Poultry</option>
                    <option value="seafood">Seafood</option>
                    <option value="dairy">Dairy</option>
                    <option value="dry_goods">Dry Goods</option>
                    <option value="beverage">Beverage</option>
                    <option value="equipment">Equipment</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label>Contact</label>
                <input type="text" id="chef-vendor-contact" placeholder="Contact person" />
            </div>
            <div class="form-group">
                <label>Phone</label>
                <input type="tel" id="chef-vendor-phone" placeholder="555-1234" />
            </div>
            <div class="form-group">
                <label>Order Day</label>
                <select id="chef-vendor-order-day">
                    <option value="">Any</option>
                    <option value="monday">Monday</option>
                    <option value="tuesday">Tuesday</option>
                    <option value="wednesday">Wednesday</option>
                    <option value="thursday">Thursday</option>
                    <option value="friday">Friday</option>
                </select>
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="chef-vendor-notes" rows="2" placeholder="Minimum orders, specialties..."></textarea>
            </div>
            <div id="chef-vendor-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Attachments (price lists, contracts)</label>
                    <div id="chef-vendor-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="chef-vendor-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('chef-vendor-file-input','vendors',document.getElementById('chef-vendor-id').value,'chef','chef-vendor-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('chef-vendor-modal')">Cancel</button>
                <button class="btn btn-primary" id="chef-vendor-save-btn" onclick="chefSaveVendor()">Save</button>
            </div>
        </div>
    </div>

    <!-- ════════ Security / OSINT / Network Modals ════════ -->

    <!-- Security: Incident Modal -->
    <div class="modal-overlay" id="sec-incident-modal">
        <div class="modal">
            <h3 id="sec-incident-modal-title">Log Incident</h3>
            <input type="hidden" id="sec-incident-id" value="" />
            <div class="form-group">
                <label>Title *</label>
                <input type="text" id="sec-incident-name" placeholder="e.g. Brute force SSH attempt" />
            </div>
            <div class="form-group">
                <label>Severity</label>
                <select id="sec-incident-severity">
                    <option value="info">Info</option>
                    <option value="low">Low</option>
                    <option value="medium" selected>Medium</option>
                    <option value="high">High</option>
                    <option value="critical">Critical</option>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="sec-incident-status">
                    <option value="open">Open</option>
                    <option value="investigating">Investigating</option>
                    <option value="contained">Contained</option>
                    <option value="resolved">Resolved</option>
                </select>
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea id="sec-incident-notes" rows="3" placeholder="What happened, affected systems, IOCs..."></textarea>
            </div>
            <div id="sec-incident-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Evidence / Attachments</label>
                    <div id="sec-incident-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="sec-incident-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('sec-incident-file-input','incidents',document.getElementById('sec-incident-id').value,'security_analyst','sec-incident-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('sec-incident-modal')">Cancel</button>
                <button class="btn btn-primary" id="sec-incident-save-btn" onclick="secSaveIncident()">Save</button>
            </div>
        </div>
    </div>

    <!-- OSINT: Investigation Modal -->
    <div class="modal-overlay" id="osint-investigation-modal">
        <div class="modal">
            <h3 id="osint-investigation-modal-title">New Investigation</h3>
            <input type="hidden" id="osint-investigation-id" value="" />
            <div class="form-group">
                <label>Subject *</label>
                <input type="text" id="osint-investigation-name" placeholder="e.g. Domain analysis: example.com" />
            </div>
            <div class="form-group">
                <label>Type</label>
                <select id="osint-investigation-type">
                    <option value="domain">Domain</option>
                    <option value="email">Email</option>
                    <option value="ip">IP Address</option>
                    <option value="person">Person</option>
                    <option value="organization">Organization</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select id="osint-investigation-status">
                    <option value="open">Open</option>
                    <option value="in_progress">In Progress</option>
                    <option value="completed">Completed</option>
                    <option value="archived">Archived</option>
                </select>
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="osint-investigation-notes" rows="3" placeholder="Findings, leads, sources..."></textarea>
            </div>
            <div id="osint-investigation-files-section" style="display:none">
                <div class="form-group">
                    <label><i class="fas fa-paperclip" style="margin-right:4px"></i>Evidence / Reports</label>
                    <div id="osint-investigation-files-list" style="margin-bottom:8px"></div>
                    <div style="display:flex;gap:8px;align-items:center">
                        <input type="file" id="osint-investigation-file-input" multiple style="font-size:0.85em;flex:1" />
                        <button class="btn btn-secondary" style="font-size:0.8em;padding:4px 12px;white-space:nowrap" onclick="flUploadFiles('osint-investigation-file-input','investigations',document.getElementById('osint-investigation-id').value,'osint_researcher','osint-investigation-files-list')"><i class="fas fa-upload" style="margin-right:4px"></i>Upload</button>
                    </div>
                </div>
            </div>
            <div class="actions">
                <button class="btn btn-secondary" onclick="hideModal('osint-investigation-modal')">Cancel</button>
                <button class="btn btn-primary" id="osint-investigation-save-btn" onclick="osintSaveInvestigation()">Save</button>
            </div>
        </div>
    </div>

    <!-- Grant Search Modal -->
    <div class="modal-overlay" id="np-grant-search-modal" onclick="if(event.target===this)hideModal('np-grant-search-modal')">
        <div class="modal modal-lg modal-scroll">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
                <h3 style="margin:0"><i class="fas fa-magnifying-glass-dollar"></i> Search Federal Grants</h3>
                <button class="btn btn-secondary" onclick="hideModal('np-grant-search-modal')" style="padding:4px 10px;font-size:18px" aria-label="Close">&times;</button>
            </div>
            <p style="color:var(--text-dim);font-size:0.85em;margin:0 0 12px">Search <a href="https://grants.gov" target="_blank" rel="noopener" style="color:var(--accent)">Grants.gov</a> for federal funding opportunities. Filter by keyword, category, and posting date.</p>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px">
                <input type="text" id="np-gs-keyword" placeholder="Keywords (e.g. housing, youth, STEM)" style="flex:2;min-width:160px" onkeydown="if(event.key==='Enter')npSearchGrants()">
                <select id="np-gs-category" style="flex:1;min-width:140px">
                    <option value="">All Categories</option>
                    <option value="AG">Agriculture</option>
                    <option value="AR">Arts</option>
                    <option value="BC">Business &amp; Commerce</option>
                    <option value="CD">Community Development</option>
                    <option value="ED">Education</option>
                    <option value="ELT">Employment &amp; Training</option>
                    <option value="EN">Energy</option>
                    <option value="ENV">Environment</option>
                    <option value="FN">Food &amp; Nutrition</option>
                    <option value="HL">Health</option>
                    <option value="HO">Housing</option>
                    <option value="HU">Humanities</option>
                    <option value="ISS">Income Security &amp; Social Services</option>
                    <option value="LJL">Law &amp; Justice</option>
                    <option value="NR">Natural Resources</option>
                    <option value="ST">Science &amp; Technology</option>
                    <option value="T">Transportation</option>
                    <option value="O">Other</option>
                </select>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
                <select id="np-gs-posted" style="flex:1;min-width:130px">
                    <option value="">Posted: Any time</option>
                    <option value="3">Last 3 days</option>
                    <option value="7">Last week</option>
                    <option value="14">Last 2 weeks</option>
                    <option value="28">Last 4 weeks</option>
                    <option value="56">Last 8 weeks</option>
                </select>
                <select id="np-gs-sort" style="flex:1;min-width:130px">
                    <option value="">Sort: Relevance</option>
                    <option value="closeDateAsc">Close date (soonest)</option>
                    <option value="closeDateDesc">Close date (latest)</option>
                    <option value="openDate">Posted date (newest)</option>
                </select>
                <button class="btn btn-primary" onclick="npSearchGrants()" id="np-gs-btn"><i class="fas fa-search"></i> Search</button>
            </div>
            <div id="np-gs-results" style="margin-top:16px"></div>
        </div>
    </div>

    <!-- Legislation Search Modal -->
    <div class="modal-overlay" id="np-legis-modal" onclick="if(event.target===this)hideModal('np-legis-modal')">
        <div class="modal modal-lg modal-scroll">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
                <h3 style="margin:0"><i class="fas fa-landmark"></i> Track Legislation</h3>
                <button class="btn btn-secondary" onclick="hideModal('np-legis-modal')" style="padding:4px 10px;font-size:18px" aria-label="Close">&times;</button>
            </div>
            <p style="color:var(--text-dim);font-size:0.85em;margin:0 0 12px">Search federal and state legislation. Track bills that affect your mission, funding, or clients.</p>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px">
                <input type="text" id="np-leg-query" placeholder="Keywords (e.g. affordable housing, SNAP benefits)" style="flex:2;min-width:180px" onkeydown="if(event.key==='Enter')npSearchLegislation()">
                <select id="np-leg-level" style="min-width:100px" onchange="_legLevelChanged(this.value)">
                    <option value="federal">Federal</option>
                    <option value="state">State</option>
                    <option value="city">City</option>
                </select>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
                <span id="np-leg-congress-wrap">
                    <select id="np-leg-congress" style="min-width:120px">
                        <option value="119">119th (2025-26)</option>
                        <option value="118">118th (2023-24)</option>
                        <option value="117">117th (2021-22)</option>
                    </select>
                </span>
                <span id="np-leg-city-wrap" style="display:none">
                    <select id="np-leg-city" style="min-width:140px">
                        <option value="seattle">Seattle</option>
                        <option value="nyc">New York City</option>
                        <option value="chicago">Chicago</option>
                        <option value="la">Los Angeles</option>
                        <option value="portland">Portland</option>
                        <option value="denver">Denver</option>
                        <option value="philadelphia">Philadelphia</option>
                        <option value="san_francisco">San Francisco</option>
                    </select>
                </span>
                <span id="np-leg-state-wrap" style="display:none">
                    <select id="np-leg-state" style="min-width:120px">
                        <option value="">Select State</option>
                        <option value="AL">Alabama</option><option value="AK">Alaska</option><option value="AZ">Arizona</option>
                        <option value="AR">Arkansas</option><option value="CA">California</option><option value="CO">Colorado</option>
                        <option value="CT">Connecticut</option><option value="DE">Delaware</option><option value="FL">Florida</option>
                        <option value="GA">Georgia</option><option value="HI">Hawaii</option><option value="ID">Idaho</option>
                        <option value="IL">Illinois</option><option value="IN">Indiana</option><option value="IA">Iowa</option>
                        <option value="KS">Kansas</option><option value="KY">Kentucky</option><option value="LA">Louisiana</option>
                        <option value="ME">Maine</option><option value="MD">Maryland</option><option value="MA">Massachusetts</option>
                        <option value="MI">Michigan</option><option value="MN">Minnesota</option><option value="MS">Mississippi</option>
                        <option value="MO">Missouri</option><option value="MT">Montana</option><option value="NE">Nebraska</option>
                        <option value="NV">Nevada</option><option value="NH">New Hampshire</option><option value="NJ">New Jersey</option>
                        <option value="NM">New Mexico</option><option value="NY">New York</option><option value="NC">North Carolina</option>
                        <option value="ND">North Dakota</option><option value="OH">Ohio</option><option value="OK">Oklahoma</option>
                        <option value="OR">Oregon</option><option value="PA">Pennsylvania</option><option value="RI">Rhode Island</option>
                        <option value="SC">South Carolina</option><option value="SD">South Dakota</option><option value="TN">Tennessee</option>
                        <option value="TX">Texas</option><option value="UT">Utah</option><option value="VT">Vermont</option>
                        <option value="VA">Virginia</option><option value="WA" selected>Washington</option><option value="WV">West Virginia</option>
                        <option value="WI">Wisconsin</option><option value="WY">Wyoming</option><option value="DC">Washington DC</option>
                    </select>
                </span>
                <button class="btn btn-primary" onclick="npSearchLegislation()" id="np-leg-btn"><i class="fas fa-search"></i> Search</button>
            </div>
            <div id="np-leg-results" style="margin-top:16px"></div>
        </div>
    </div>

    <!-- Bill Watchlist Modal -->
    <div class="modal-overlay" id="np-watchlist-modal" onclick="if(event.target===this)hideModal('np-watchlist-modal')">
        <div class="modal" style="max-width:520px">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
                <h3 style="margin:0"><i class="fas fa-bell"></i> Bill Keyword Watchlist</h3>
                <button class="btn btn-secondary" onclick="hideModal('np-watchlist-modal')" style="padding:4px 10px;font-size:18px" aria-label="Close">&times;</button>
            </div>
            <p style="color:var(--text-dim);font-size:0.85em;margin:0 0 12px">Add keywords to automatically flag new bills that match your mission areas. Matching bills will be highlighted when you search.</p>
            <div style="display:flex;gap:8px;margin-bottom:16px">
                <input type="text" id="np-wl-keyword" placeholder="e.g. homelessness, child welfare, SNAP" style="flex:1" onkeydown="if(event.key==='Enter')npAddWatchKeyword()">
                <button class="btn btn-primary" onclick="npAddWatchKeyword()"><i class="fas fa-plus"></i> Add</button>
            </div>
            <div id="np-wl-list"></div>
        </div>
    </div>

    <!-- Credential Update Modal -->
    <div class="modal-overlay" id="cred-update-modal" style="display:none">
        <div class="modal" style="max-width:480px">
            <h3 id="cred-modal-title">Update Credential</h3>
            <p id="cred-modal-hint" class="cred-modal-hint"></p>
            <div id="cred-modal-fields"></div>
            <div id="cred-modal-error" class="cred-modal-error"></div>
            <div id="cred-modal-success" class="cred-modal-success"></div>
            <div class="cred-modal-footer">
                <a id="cred-modal-docs" class="cred-modal-docs" href="#" target="_blank" rel="noopener"><i class="fas fa-external-link-alt" style="margin-right:3px"></i>Docs</a>
                <button class="btn btn-secondary" onclick="closeCredModal()">Cancel</button>
                <button class="btn btn-primary" id="cred-modal-save" onclick="saveCredModal()"><i class="fas fa-check" style="margin-right:4px"></i>Save &amp; Test</button>
            </div>
        </div>
    </div>

    <script>
        // Jinja bridge — server-injected values for static JS files
        const _SERVER = {
            apiKey: '{{ injected_api_key|default("", true) }}',
            isNewSetup: {{ 'true' if is_new_setup else 'false' }},
            version: '{{ version }}',
        };
    </script>
    <script src="{{ url_for('static', filename='js/core.js') }}"></script>
    <script src="{{ url_for('static', filename='js/calendar.js') }}"></script>
    <script src="{{ url_for('static', filename='js/messages.js') }}"></script>
    <script src="{{ url_for('static', filename='js/email.js') }}"></script>
    <script src="{{ url_for('static', filename='js/social.js') }}"></script>
    <script src="{{ url_for('static', filename='js/mesh.js') }}"></script>
    <script src="{{ url_for('static', filename='js/connect.js') }}"></script>
    <script src="{{ url_for('static', filename='js/terminal.js') }}"></script>
    <script src="{{ url_for('static', filename='js/settings.js') }}"></script>
    <script src="{{ url_for('static', filename='js/workspace.js') }}"></script>
    <script src="{{ url_for('static', filename='js/chat.js') }}"></script>
    <script src="{{ url_for('static', filename='js/briefing.js') }}"></script>
    <script src="{{ url_for('static', filename='js/memory.js') }}"></script>
    <script src="{{ url_for('static', filename='js/media.js') }}"></script>
    <script src="{{ url_for('static', filename='js/ui.js') }}"></script>
    <script src="{{ url_for('static', filename='js/server.js') }}"></script>
    <script>
        
        // ── chat.js (input/voice) loaded via <script src> ──
        // ── briefing.js loaded via <script src> ──
        // ── calendar.js loaded via <script src> ──
        // ── messages.js loaded via <script src> ──
        // ── email.js loaded via <script src> ──
        // ── memory.js loaded via <script src> ──
        // ── social.js loaded via <script src> ──
        // ── mesh.js loaded via <script src> ──
        // ── connect.js loaded via <script src> ──
        // ── terminal.js loaded via <script src> ──
        // ── settings.js loaded via <script src> ──
        // ── workspace.js loaded via <script src> ──
        // ── ui.js (routing presets) loaded via <script src> ──
        // ── chat.js (species greetings) loaded via <script src> ──
        // ── media.js loaded via <script src> ──
        // ── ui.js (part 2) loaded via <script src> ──
        // ── server.js loaded via <script src> ──

    </script>
    <!-- Webamp (Winamp 2.9 reimplementation) — MIT licensed -->
    <script src="https://unpkg.com/webamp@1.5.0/built/webamp.bundle.min.js"
            onload="initWebamp()"
            onerror="console.warn('Webamp CDN unavailable, using fallback audio')"
            async></script>
    <!-- Plyr (HTML5 media player) — MIT licensed -->
    <link rel="stylesheet" href="https://cdn.plyr.io/3.7.8/plyr.css" />
    <script src="https://cdn.plyr.io/3.7.8/plyr.js" async
            onerror="console.warn('Plyr CDN unavailable, using iframe fallback')"></script>
</body>
</html>
