<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CARL Control Panel</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>
    <script>
        // DEBUG: Log on page load to verify template version
        console.log('=== CARL DEBUG v1.0.5 ===');
        document.addEventListener('DOMContentLoaded', () => {
            const devmodeToggle = document.getElementById('toggle-devmode');
            const coreSettings = document.querySelector('[data-accordion="core-settings"]');
            console.log('DEVMODE toggle element:', devmodeToggle);
            console.log('Core Settings accordion:', coreSettings);
            if (coreSettings) {
                console.log('Core Settings innerHTML length:', coreSettings.innerHTML.length);
                console.log('Core Settings contains DEVMODE:', coreSettings.innerHTML.includes('DEVMODE'));
            }
            if (!devmodeToggle) {
                console.error('!!! DEVMODE TOGGLE NOT FOUND IN DOM !!!');
            }
        });
    </script>
    <div class="container">
        <header>
            <div class="header-left">
                <h1>CARL Control Panel</h1>
                <div id="workspace-info" class="workspace-info">
                    <span id="workspace-path" class="workspace-path">Not connected</span>
                    <button id="btn-change-workspace" class="btn btn-icon" title="Manage Workspaces">⚙</button>
                </div>
            </div>
            <div class="header-right">
                <span id="save-status" class="save-status-inline"></span>
                <button id="btn-refresh" class="btn btn-icon btn-refresh" title="Refresh" onclick="refreshApp()">↻</button>
                <div id="status" class="status disconnected">
                    <span class="status-dot"></span>
                    <span class="status-text">Checking...</span>
                </div>
            </div>
        </header>

        <!-- Update Notification Banner -->
        <div id="update-banner" class="update-banner" style="display: none;">
            <div class="update-banner-content">
                <div class="update-info">
                    <span class="update-icon">↑</span>
                    <span class="update-text">
                        <strong>Update available</strong>
                        <span><span id="update-version">v0.0.0</span> ready</span>
                    </span>
                </div>
                <div class="update-actions">
                    <button id="btn-update-download" class="btn btn-primary btn-small">Download Update</button>
                    <button id="btn-update-dismiss" class="btn btn-secondary btn-small">Later</button>
                </div>
                <div id="update-pip-actions" class="update-pip-actions" style="display: none;">
                    <code id="pip-update-command" class="pip-command">pip install --upgrade carl-control-panel</code>
                    <button id="btn-copy-pip" class="btn btn-primary btn-small" onclick="copyPipCommand()">Copy</button>
                    <button class="btn btn-secondary btn-small" onclick="dismissUpdate()">Later</button>
                </div>
            </div>
            <div id="update-progress" class="update-progress" style="display: none;">
                <div class="progress-bar">
                    <div id="update-progress-fill" class="progress-fill" style="width: 0%"></div>
                </div>
                <span id="update-progress-text" class="progress-text">Downloading... 0%</span>
            </div>
            <div id="update-ready" class="update-ready" style="display: none;">
                <span>Download complete!</span>
                <button id="btn-update-apply" class="btn btn-primary btn-small">Install & Restart</button>
            </div>
        </div>

        <main>
            <!-- Main Navigation Tabs (only shown when connected) -->
            <div id="main-nav" class="main-nav" style="display: none;">
                <button class="nav-tab active" data-view="settings">Settings</button>
                <button class="nav-tab" data-view="domains">Domains</button>
                <button class="nav-tab" data-view="addons">Addons</button>
            </div>

            <!-- Setup View (shown when no CARL found, or for workspace management) -->
            <section id="setup-view" class="view">
                <div class="card setup-card">
                    <div class="setup-header">
                        <button id="btn-back-from-setup" class="btn btn-icon btn-back" title="Back" style="display: none;">←</button>
                        <div class="setup-titles">
                            <h2 id="setup-title">Welcome to CARL Control Panel</h2>
                            <p id="setup-subtitle" class="card-description">No CARL installation found. Let's set one up!</p>
                        </div>
                    </div>

                    <div class="setup-form">
                        <div class="form-group">
                            <label for="workspace-input">Workspace Path</label>
                            <input type="text" id="workspace-input" placeholder="C:\Users\you\projects">
                            <span class="form-hint">Select a workspace folder (we'll create .claude if needed)</span>
                        </div>

                        <div class="setup-actions">
                            <button id="btn-initialize" class="btn btn-primary">Initialize CARL</button>
                            <button id="btn-browse" class="btn btn-secondary">Browse Existing</button>
                        </div>

                        <div id="setup-error" class="error-message"></div>
                    </div>

                    <div class="setup-info">
                        <h3>What gets created:</h3>
                        <ul>
                            <li><code>.carl/manifest</code> - Main configuration file</li>
                            <li><code>.carl/global</code> - Global rules (defaults to always active)</li>
                            <li><code>.carl/context</code> - Context bracket rules (token-aware)</li>
                            <li><code>.carl/commands</code> - Command rulesets w/ *star syntax (*report, *discuss)</li>
                        </ul>
                    </div>
                </div>
            </section>

            <!-- Settings Tab Content -->
            <section id="settings-view" class="view">
                <!-- Hooks Setup Card (shown if hooks not installed) -->
                <div id="hooks-card" class="card hooks-card" style="display: none;">
                    <h2>Setup Hooks</h2>
                    <p class="card-description">Install hooks to enable session context tracking and rule injection</p>

                    <div class="hooks-status" id="hooks-status">
                        <span class="status-indicator"></span>
                        <span class="status-text">Checking hooks status...</span>
                    </div>

                    <!-- Step 1: Install Hooks -->
                    <div class="hooks-step" id="hooks-step-install">
                        <h3>Step 1: Install Hook Files</h3>
                        <p>Choose where to install CARL hooks:</p>

                        <div class="hooks-location-options">
                            <label class="radio-option selected" data-location="global">
                                <input type="radio" name="hooks-location" value="global" checked>
                                <div class="option-content">
                                    <strong>Global (Recommended)</strong>
                                    <span class="option-path">~/.claude/hooks/</span>
                                    <span class="option-desc">Works for all projects. Install once, use everywhere.</span>
                                </div>
                            </label>
                            <label class="radio-option" data-location="project">
                                <input type="radio" name="hooks-location" value="project">
                                <div class="option-content">
                                    <strong>Project Only</strong>
                                    <span class="option-path" id="project-hooks-path">.claude/hooks/</span>
                                    <span class="option-desc">Isolated to this workspace. Requires setup per project.</span>
                                </div>
                            </label>
                        </div>

                        <button id="btn-install-hooks" class="btn btn-primary">Install Hooks</button>
                        <div id="install-result" class="result-message"></div>
                    </div>

                    <!-- Step 2: Wire Hooks (3 tabs) -->
                    <div class="hooks-step" id="hooks-step-wire" style="display: none;">
                        <h3>Step 2: Wire Hooks to Claude Code</h3>
                        <p>Add hook configuration to <code>~/.claude/settings.json</code></p>

                        <div class="tabs">
                            <button class="tab-btn active" data-tab="auto">Auto-append</button>
                            <button class="tab-btn" data-tab="manual">Manual Copy</button>
                            <button class="tab-btn" data-tab="claude">Claude Prompt</button>
                        </div>

                        <div class="tab-content active" id="tab-auto">
                            <p>Let the control panel automatically update your settings.json file.</p>
                            <button id="btn-auto-wire" class="btn btn-primary">Auto-append to settings.json</button>
                            <div id="auto-wire-result" class="result-message"></div>
                        </div>

                        <div class="tab-content" id="tab-manual">
                            <p>Copy this JSON snippet and add it to your <code>~/.claude/settings.json</code>:</p>
                            <div class="code-block">
                                <pre id="hooks-snippet"></pre>
                                <button id="btn-copy-snippet" class="btn btn-small">Copy</button>
                            </div>
                        </div>

                        <div class="tab-content" id="tab-claude">
                            <p>Copy this prompt and paste it into Claude Code to have it wire the hooks for you:</p>
                            <div class="code-block">
                                <pre id="claude-prompt"></pre>
                                <button id="btn-copy-prompt" class="btn btn-small">Copy</button>
                            </div>
                        </div>
                    </div>

                    <!-- Hooks Complete -->
                    <div class="hooks-complete" id="hooks-complete" style="display: none;">
                        <span class="success-icon">✓</span>
                        <span>Hooks installed and wired!</span>
                        <button id="btn-hide-hooks" class="btn btn-small btn-secondary">Hide this card</button>
                    </div>
                </div>

                <!-- Hook Update Notification (shown when hooks are outdated) -->
                <div id="hook-update-notification" class="card hook-update-card" style="display: none;">
                    <div class="hook-update-header">
                        <div class="hook-update-icon">⚠️</div>
                        <div class="hook-update-text">
                            <h3>Hook Updates Available</h3>
                            <p>Newer versions of installed hooks are available. Update to get the latest features and fixes.</p>
                        </div>
                    </div>
                    <ul id="hook-update-list" class="hook-update-list">
                        <!-- Populated by JS -->
                    </ul>
                    <div class="hook-update-actions">
                        <button id="btn-update-hooks" class="btn btn-primary" onclick="updateOutdatedHooks()">Update Hooks</button>
                        <button class="btn btn-secondary" onclick="dismissHookUpdate()">Later</button>
                    </div>
                </div>

                <!-- CLAUDE.md Integration Card (shown if CARL block missing) -->
                <div id="claudemd-card" class="card claudemd-card" style="display: none;">
                    <h2>CARL Integration Required</h2>
                    <p class="card-description warning-text">Claude ignores CARL rules unless CLAUDE.md has the integration block!</p>

                    <div class="claudemd-status" id="claudemd-status">
                        <span class="status-indicator warning"></span>
                        <span class="status-text">Checking CLAUDE.md...</span>
                    </div>

                    <!-- Setup Step -->
                    <div class="claudemd-step" id="claudemd-step-setup">
                        <p>Add the CARL integration block to your CLAUDE.md file so Claude follows CARL rules.</p>

                        <div class="claudemd-path-section">
                            <div class="claudemd-path-row">
                                <span class="path-label">Target:</span>
                                <code id="claudemd-target-path" class="path-value">Detecting...</code>
                                <button id="btn-claudemd-change" class="btn btn-small btn-secondary">Change</button>
                            </div>
                        </div>

                        <div class="tabs">
                            <button class="tab-btn active" data-tab="claudemd-auto">Auto-add (Recommended)</button>
                            <button class="tab-btn" data-tab="claudemd-manual">Manual Copy</button>
                            <button class="tab-btn" data-tab="claudemd-claude">Claude Prompt</button>
                        </div>

                        <div class="tab-content active" id="tab-claudemd-auto">
                            <p>Let the control panel automatically add the CARL block to your CLAUDE.md file.</p>
                            <button id="btn-claudemd-auto" class="btn btn-primary">Auto-add to CLAUDE.md</button>
                            <div id="claudemd-auto-result" class="result-message"></div>
                        </div>

                        <div class="tab-content" id="tab-claudemd-manual">
                            <p>Copy this block and add it to your <code>CLAUDE.md</code> file:</p>
                            <div class="code-block">
                                <pre id="claudemd-snippet"></pre>
                                <button id="btn-copy-claudemd-snippet" class="btn btn-small">Copy</button>
                            </div>
                        </div>

                        <div class="tab-content" id="tab-claudemd-claude">
                            <p>Copy this prompt and paste it into Claude Code:</p>
                            <div class="code-block">
                                <pre id="claudemd-prompt"></pre>
                                <button id="btn-copy-claudemd-prompt" class="btn btn-small">Copy</button>
                            </div>
                        </div>

                        <div class="claudemd-dismiss-section">
                            <button id="btn-claudemd-dismiss" class="btn btn-small btn-text">Dismiss (already configured manually)</button>
                        </div>
                    </div>

                    <!-- Complete -->
                    <div class="claudemd-complete" id="claudemd-complete" style="display: none;">
                        <span class="success-icon">✓</span>
                        <span>CARL integration configured!</span>
                    </div>
                </div>

                <div class="card accordion" data-accordion="core-settings">
                    <div class="card-header accordion-header" onclick="toggleSettingsAccordion('core-settings')">
                        <div class="card-title">
                            <h2>Core Settings</h2>
                            <p class="card-description">Global toggles for CARL behavior</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div class="toggle-group">
                            <div class="toggle-item">
                                <div class="toggle-info">
                                    <label for="toggle-devmode">DEVMODE</label>
                                    <span class="toggle-description">Append debug section to every response</span>
                                </div>
                                <label class="switch">
                                    <input type="checkbox" id="toggle-devmode" data-key="DEVMODE">
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Installed Resources Section (only shown when resources are wired) -->
                <div id="installed-resources-settings" class="card accordion" data-accordion="installed-resources" style="display: none;">
                    <div class="card-header accordion-header" onclick="toggleSettingsAccordion('installed-resources')">
                        <div class="card-title">
                            <h2>Installed Resources</h2>
                            <p class="card-description">Global toggles for active hooks and resources</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div id="resource-toggles-list" class="toggle-group">
                            <!-- Dynamically populated by JS -->
                        </div>
                    </div>
                </div>

                <!-- Active Sessions Card -->
                <div class="card accordion sessions-card" data-accordion="active-sessions">
                    <div class="card-header accordion-header">
                        <div class="card-title" onclick="toggleSettingsAccordion('active-sessions')">
                            <h2>Active Sessions <button id="btn-refresh-sessions" class="btn-icon-inline" title="Refresh sessions" onclick="event.stopPropagation(); loadSessions();">↻</button></h2>
                            <p class="card-description">Per-session overrides</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section" onclick="toggleSettingsAccordion('active-sessions')">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div id="sessions-list" class="sessions-list">
                            <div class="loading">Loading sessions...</div>
                        </div>

                        <div id="no-sessions" class="no-sessions" style="display: none;">
                            <p>No active sessions found. Sessions are registered when Claude Code starts.</p>
                        </div>
                    </div>
                </div>

            </section>

            <!-- Domains View -->
            <section id="domains-view" class="view">
                <div class="card">
                    <div class="card-header">
                        <h2>CARL Domains</h2>
                        <div class="card-header-actions">
                            <button id="btn-import-domains" class="btn btn-secondary btn-small">Import from...</button>
                            <button id="btn-create-domain" class="btn btn-primary btn-small">Create Domain</button>
                        </div>
                    </div>
                    <p class="card-description">Manage operational rules that load based on recall keywords</p>

                    <div class="domain-search">
                        <input type="text" id="domain-search-input" placeholder="Search domains..." oninput="filterDomains()">
                    </div>

                    <div id="domains-list" class="domains-list">
                        <div class="loading">Loading domains...</div>
                    </div>
                </div>
            </section>

            <!-- Addons View -->
            <section id="addons-view" class="view">
                <!-- INSTALLED Section -->
                <div class="section-divider">
                    <h3>Installed</h3>
                    <p>Addons currently active in your workspace</p>
                </div>

                <!-- Installed Workflow Resources -->
                <div id="installed-resources-card" class="card accordion" data-accordion="installed-resources" style="display: none;">
                    <div class="card-header accordion-header">
                        <div class="card-title" onclick="toggleSettingsAccordion('installed-resources')">
                            <h2>Workflow Resources <button id="btn-refresh-resources" class="btn-icon-inline" title="Refresh" onclick="event.stopPropagation(); loadOptionalHooks();">↻</button></h2>
                            <p class="card-description">Hooks, commands, and skills enhancing your Claude Code workflows</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section" onclick="toggleSettingsAccordion('installed-resources')">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div id="installed-resources-list" class="optional-hooks-list"></div>
                        <div id="no-installed-resources" class="no-addons" style="display: none;">
                            <p>No workflow resources installed. Browse available resources below.</p>
                        </div>
                    </div>
                </div>

                <!-- Installed Domain Packs -->
                <div id="installed-packs-card" class="card accordion" data-accordion="installed-packs" style="display: none;">
                    <div class="card-header accordion-header">
                        <div class="card-title" onclick="toggleSettingsAccordion('installed-packs')">
                            <h2>Domain / Rule Packs <button id="btn-refresh-addons" class="btn-icon-inline" title="Refresh" onclick="event.stopPropagation(); loadAddons();">↻</button></h2>
                            <p class="card-description">Domains and rules imported into your workspace</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section" onclick="toggleSettingsAccordion('installed-packs')">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div id="installed-addons-list" class="addons-list">
                            <div class="loading">Loading...</div>
                        </div>
                        <div id="no-installed-addons" class="no-addons" style="display: none;">
                            <p>No domain packs installed. Browse available packs below.</p>
                        </div>
                    </div>
                </div>

                <!-- AVAILABLE Section -->
                <div class="section-divider">
                    <h3>Available</h3>
                    <p>Addons ready to install from bundled collection and your library</p>
                </div>

                <!-- Available Workflow Resources -->
                <div id="available-resources-card" class="card accordion" data-accordion="available-resources" style="display: none;">
                    <div class="card-header accordion-header">
                        <div class="card-title" onclick="toggleSettingsAccordion('available-resources')">
                            <h2>Workflow Resources</h2>
                            <p class="card-description">Hooks, commands, and skills to extend Claude Code capabilities</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section" onclick="toggleSettingsAccordion('available-resources')">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div id="available-resources-list" class="optional-hooks-list"></div>
                        <div id="no-available-resources" class="no-addons" style="display: none;">
                            <p>All workflow resources are installed!</p>
                        </div>
                    </div>
                </div>

                <!-- Available Domain Packs -->
                <div class="card accordion" data-accordion="available-packs">
                    <div class="card-header accordion-header">
                        <div class="card-title" onclick="toggleSettingsAccordion('available-packs')">
                            <h2>Domain / Rule Packs</h2>
                            <p class="card-description">Prepackaged domains and rules to customize for your needs</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section" onclick="toggleSettingsAccordion('available-packs')">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <div id="available-addons-list" class="addons-list">
                            <div class="loading">Loading...</div>
                        </div>
                        <div id="no-available-addons" class="no-addons" style="display: none;">
                            <p>No domain packs available. Create your own using Export below.</p>
                        </div>
                    </div>
                </div>

                <!-- CREATE Section -->
                <div class="section-divider">
                    <h3>Create</h3>
                    <p>Package and share your own configurations</p>
                </div>

                <div class="card accordion" data-accordion="export-pack">
                    <div class="card-header accordion-header">
                        <div class="card-title" onclick="toggleSettingsAccordion('export-pack')">
                            <h2>Export Pack <button id="btn-open-export" class="btn-icon-inline btn-icon-accent" title="Create pack" onclick="event.stopPropagation(); openExportModal();">+</button></h2>
                            <p class="card-description">Package your domains into a shareable domain pack</p>
                        </div>
                        <button class="accordion-toggle" aria-label="Toggle section" onclick="toggleSettingsAccordion('export-pack')">
                            <span class="accordion-icon">▶</span>
                        </button>
                    </div>
                    <div class="accordion-content">
                        <p class="card-description">Use the + button to open the export wizard and create a new domain pack.</p>
                    </div>
                </div>
            </section>
        </main>

        <!-- Create Domain Modal -->
        <div id="create-domain-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeCreateDomainModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>Create New Domain</h3>
                    <button class="modal-close" onclick="closeCreateDomainModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="domain-name">Domain Name</label>
                        <input type="text" id="domain-name" placeholder="MYDOMAIN" autocomplete="off">
                        <span class="form-hint">Will be auto-uppercased. Letters and underscores only.</span>
                    </div>
                    <div class="form-group">
                        <label for="domain-recall">Recall Keywords</label>
                        <textarea id="domain-recall" placeholder="keyword1, keyword2, write code" rows="2"></textarea>
                        <span class="form-hint">Comma-separated. These trigger domain loading.</span>
                    </div>
                    <div class="form-group">
                        <label for="domain-rules">Initial Rules (optional)</label>
                        <textarea id="domain-rules" placeholder="First rule text&#10;Second rule text" rows="4"></textarea>
                        <span class="form-hint">One rule per line. Rule 0 (description) is auto-generated.</span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeCreateDomainModal()">Cancel</button>
                    <button id="btn-confirm-create" class="btn btn-primary" onclick="confirmCreateDomain()">Create Domain</button>
                </div>
                <div id="create-domain-error" class="result-message"></div>
            </div>
        </div>

        <!-- Delete Domain Confirmation Modal -->
        <div id="delete-domain-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeDeleteDomainModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Delete Domain</h3>
                    <button class="modal-close" onclick="closeDeleteDomainModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete <strong id="delete-domain-name"></strong>?</p>
                    <p class="text-warning">This will remove the domain file and all manifest entries. This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeDeleteDomainModal()">Cancel</button>
                    <button id="btn-confirm-delete" class="btn btn-danger" onclick="confirmDeleteDomain()">Delete</button>
                </div>
            </div>
        </div>

        <!-- Delete Rule Confirmation Modal -->
        <div id="delete-rule-modal" class="modal modal-confirm" style="display: none;">
            <div class="modal-overlay" onclick="closeDeleteRuleModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Delete Rule</h3>
                    <button class="modal-close" onclick="closeDeleteRuleModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Delete rule <strong id="delete-rule-index"></strong>?</p>
                    <p class="text-warning">This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeDeleteRuleModal()">Cancel</button>
                    <button id="btn-confirm-delete-rule" class="btn btn-danger" onclick="confirmDeleteRule()">Delete</button>
                </div>
            </div>
        </div>

        <!-- Delete Command Confirmation Modal -->
        <div id="delete-command-modal" class="modal modal-confirm" style="display: none;">
            <div class="modal-overlay" onclick="closeDeleteCommandModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Delete Command</h3>
                    <button class="modal-close" onclick="closeDeleteCommandModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Delete <strong id="delete-command-name"></strong> command?</p>
                    <p class="text-warning">This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeDeleteCommandModal()">Cancel</button>
                    <button id="btn-confirm-delete-command" class="btn btn-danger" onclick="confirmDeleteCommand()">Delete</button>
                </div>
            </div>
        </div>

        <!-- Domain Detail Modal (Rule Editor) -->
        <div id="domain-detail-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeDomainDetailModal()"></div>
            <div class="modal-content modal-large">
                <div class="modal-header">
                    <h3><span id="detail-domain-name">DOMAIN</span> Rules</h3>
                    <button class="modal-close" onclick="closeDomainDetailModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <!-- Domain Config Section -->
                    <div class="detail-section">
                        <h4>Configuration</h4>
                        <div class="config-grid">
                            <div class="config-item" id="config-recall-item">
                                <label>Recall Keywords</label>
                                <input type="text" id="detail-recall" placeholder="keyword1, keyword2">
                            </div>
                            <div class="config-item" id="config-exclude-item">
                                <label>Exclude Keywords</label>
                                <input type="text" id="detail-exclude" placeholder="(optional)">
                            </div>
                        </div>
                        <button id="btn-save-config" class="btn btn-small btn-primary" onclick="saveDomainConfig()">Save Config</button>
                        <span id="config-save-status" class="save-status-inline"></span>
                    </div>

                    <!-- Rules Section -->
                    <div class="detail-section">
                        <div class="section-header">
                            <h4>Rules</h4>
                            <button class="btn btn-small btn-primary" onclick="addNewRule()">+ Add Rule</button>
                        </div>
                        <div id="rules-list" class="rules-list">
                            <div class="loading">Loading rules...</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeDomainDetailModal()">Close</button>
                </div>
            </div>
        </div>

        <!-- Add Rule Modal -->
        <div id="add-rule-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeAddRuleModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Add Rule</h3>
                    <button class="modal-close" onclick="closeAddRuleModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="new-rule-text">Rule Text</label>
                        <textarea id="new-rule-text" placeholder="Enter the rule instruction..." rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeAddRuleModal()">Cancel</button>
                    <button id="btn-confirm-add-rule" class="btn btn-primary" onclick="confirmAddRule()">Add Rule</button>
                </div>
                <div id="add-rule-error" class="result-message"></div>
            </div>
        </div>

        <!-- Bracket Rule Modal (Add/Edit) -->
        <div id="bracket-rule-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeBracketRuleModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3 id="bracket-rule-modal-title">Add Rule</h3>
                    <button class="modal-close" onclick="closeBracketRuleModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label id="bracket-rule-modal-label">Rule Text</label>
                        <textarea id="bracket-rule-text" placeholder="Enter the rule instruction..." rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeBracketRuleModal()">Cancel</button>
                    <button id="btn-confirm-bracket-rule" class="btn btn-primary" onclick="confirmBracketRule()">Save</button>
                </div>
                <div id="bracket-rule-error" class="result-message"></div>
            </div>
        </div>

        <!-- Add Command Modal -->
        <div id="add-command-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeAddCommandModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Add Star Command</h3>
                    <button class="modal-close" onclick="closeAddCommandModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="new-command-name">Command Name</label>
                        <input type="text" id="new-command-name" placeholder="e.g., review (becomes *review)">
                        <small class="form-hint">Enter without asterisk. Will be converted to uppercase.</small>
                    </div>
                    <div class="form-group">
                        <label for="new-command-rule">First Rule</label>
                        <textarea id="new-command-rule" placeholder="Enter the primary rule instruction..." rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeAddCommandModal()">Cancel</button>
                    <button class="btn btn-primary" onclick="confirmAddCommand()">Create Command</button>
                </div>
                <div id="add-command-error" class="result-message"></div>
            </div>
        </div>

        <!-- Edit Command Modal -->
        <div id="edit-command-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeEditCommandModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>Edit Command: <span id="edit-command-title"></span></h3>
                    <button class="modal-close" onclick="closeEditCommandModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="edit-command-name">Command Name</label>
                        <input type="text" id="edit-command-name" placeholder="e.g., review">
                        <small class="form-hint">Enter without asterisk. Will be converted to uppercase.</small>
                    </div>
                    <div class="form-group">
                        <label>Rules</label>
                        <div id="edit-command-rules" class="edit-rules-list"></div>
                        <button type="button" class="btn btn-small btn-secondary" onclick="addEditRule()">+ Add Rule</button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeEditCommandModal()">Cancel</button>
                    <button class="btn btn-primary" onclick="saveEditCommand()">Save Changes</button>
                </div>
            </div>
        </div>

        <!-- Export Commands Modal -->
        <div id="export-commands-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeExportCommandsModal()"></div>
            <div class="modal-content modal-medium">
                <div class="modal-header">
                    <h3>Export Commands</h3>
                    <button class="modal-close" onclick="closeExportCommandsModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="export-commands-name">Addon Name</label>
                        <input type="text" id="export-commands-name" placeholder="My Commands Pack">
                        <small class="form-hint">Display name shown when importing (not the filename).</small>
                    </div>
                    <div class="form-group">
                        <label for="export-commands-description">Description</label>
                        <textarea id="export-commands-description" placeholder="What this command pack provides..." rows="2"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Select Commands to Export</label>
                        <div class="export-select-controls">
                            <button type="button" class="btn-link" onclick="selectAllExportCommands(true)">Select All</button>
                            <span class="separator">|</span>
                            <button type="button" class="btn-link" onclick="selectAllExportCommands(false)">Select None</button>
                        </div>
                        <div id="export-commands-list" class="checkbox-list"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeExportCommandsModal()">Cancel</button>
                    <button class="btn btn-primary" onclick="exportCommands()">Export & Save</button>
                </div>
            </div>
        </div>

        <!-- Addon Preview/Import Modal -->
        <div id="preview-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closePreviewModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2 id="preview-modal-title">Preview Addon</h2>
                    <button class="modal-close" onclick="closePreviewModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div id="preview-metadata" class="preview-section">
                        <p id="preview-description" class="preview-description"></p>
                        <div id="preview-meta-info" class="preview-meta"></div>
                    </div>

                    <div class="preview-section">
                        <h3>Domains to Install</h3>
                        <p class="form-hint">Select which domains to include. Conflicting domains are marked.</p>
                        <div id="preview-domains-list" class="checkbox-list"></div>
                    </div>

                    <div id="preview-conflicts" class="preview-conflicts" style="display: none;">
                        <h3>Conflicts Detected</h3>
                        <p class="form-hint">These domains already exist in your workspace.</p>
                        <div class="conflict-options">
                            <label class="radio-option">
                                <input type="radio" name="conflict-mode" value="skip" checked>
                                <span>
                                    <strong>Skip</strong>
                                    <small>Keep existing domains unchanged</small>
                                </span>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="conflict-mode" value="merge">
                                <span>
                                    <strong>Merge</strong>
                                    <small>Append selected rules to existing domains</small>
                                </span>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="conflict-mode" value="overwrite">
                                <span>
                                    <strong>Overwrite</strong>
                                    <small>Replace existing domains entirely</small>
                                </span>
                            </label>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closePreviewModal()">Cancel</button>
                    <button id="btn-install-addon" class="btn btn-primary" onclick="installAddon()">Install Selected</button>
                </div>
            </div>
        </div>

        <!-- Export Modal -->
        <div id="export-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeExportModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Export Addon</h2>
                    <button class="modal-close" onclick="closeExportModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="export-section">
                        <h3>Addon Metadata</h3>
                        <div class="form-group">
                            <label for="export-name">Name *</label>
                            <input type="text" id="export-name" placeholder="My Awesome Addon">
                        </div>
                        <div class="form-group">
                            <label for="export-description">Description</label>
                            <textarea id="export-description" placeholder="What this addon provides..."></textarea>
                        </div>
                        <div class="form-group">
                            <label for="export-author">Author</label>
                            <input type="text" id="export-author" placeholder="Your name">
                        </div>
                        <div class="form-group">
                            <label for="export-tags">Tags (comma-separated)</label>
                            <input type="text" id="export-tags" placeholder="development, productivity">
                        </div>
                    </div>

                    <div class="export-section">
                        <h3>Select Domains</h3>
                        <p class="form-hint">Choose which domains to include in the addon.</p>
                        <div id="export-domains-list" class="checkbox-list">
                            <div class="loading">Loading domains...</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeExportModal()">Cancel</button>
                    <button id="btn-export-addon" class="btn btn-primary" onclick="exportAddon()">Export Addon</button>
                </div>
            </div>
        </div>

        <!-- Export Result Modal -->
        <div id="export-result-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeExportResultModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Addon Exported</h2>
                    <button class="modal-close" onclick="closeExportResultModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Your addon has been created. You can copy the JSON below or save it to the addons library.</p>
                    <div class="code-block export-code-block">
                        <pre id="export-result-json"></pre>
                        <button id="btn-copy-export" class="btn btn-small" onclick="copyExportedAddon()">Copy JSON</button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeExportResultModal()">Close</button>
                    <button id="btn-save-addon" class="btn btn-primary" onclick="saveExportedAddon()">Save to Library</button>
                </div>
            </div>
        </div>

        <!-- Uninstall Addon Modal -->
        <div id="uninstall-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeUninstallModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Uninstall Addon</h2>
                    <button class="modal-close" onclick="closeUninstallModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p id="uninstall-addon-name" class="addon-name-display"></p>

                    <!-- Domains section (if any) -->
                    <div id="uninstall-domains-section" style="display: none;">
                        <h4>Domains to remove:</h4>
                        <div id="uninstall-domains-list" class="uninstall-list"></div>
                    </div>

                    <!-- Commands section (if any) -->
                    <div id="uninstall-commands-section" style="display: none;">
                        <h4>Commands from this pack:</h4>
                        <div class="uninstall-options">
                            <label class="radio-option">
                                <input type="radio" name="uninstall-command-action" value="remove_all" checked>
                                <div class="radio-text">
                                    <span class="radio-label">Remove all commands</span>
                                    <span class="radio-desc">Full cleanup - delete all commands from this pack</span>
                                </div>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="uninstall-command-action" value="keep_all">
                                <div class="radio-text">
                                    <span class="radio-label">Keep all commands</span>
                                    <span class="radio-desc">Commands stay in your COMMANDS domain (untracked)</span>
                                </div>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="uninstall-command-action" value="selected">
                                <div class="radio-text">
                                    <span class="radio-label">Choose which to remove</span>
                                    <span class="radio-desc">Select specific commands to delete</span>
                                </div>
                            </label>
                        </div>

                        <div id="uninstall-commands-list" class="uninstall-list" style="display: none;"></div>
                    </div>

                    <!-- Merged domains section (rules were merged into existing domains) -->
                    <div id="uninstall-merged-section" style="display: none;">
                        <h4>Merged rules (manual cleanup required):</h4>
                        <p class="form-hint">Rules from this addon were merged into existing domains. These cannot be automatically removed. Review and clean up manually in the Domains tab.</p>
                        <div id="uninstall-merged-list" class="uninstall-list"></div>
                    </div>

                    <p id="uninstall-empty-message" style="display: none;">
                        This addon has no domains or commands to remove.
                    </p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeUninstallModal()">Cancel</button>
                    <button id="btn-confirm-uninstall" class="btn btn-danger" onclick="confirmUninstall()">Uninstall</button>
                </div>
            </div>
        </div>

        <!-- Remove Workspace Modal -->
        <div id="remove-workspace-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeRemoveWorkspaceModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Remove Workspace</h3>
                    <button class="modal-close" onclick="closeRemoveWorkspaceModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Remove <strong id="remove-workspace-name"></strong> from the workspace list?</p>
                    <p class="text-muted">This only removes it from this app - no files will be deleted. You can re-add it later with "Browse Existing".</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeRemoveWorkspaceModal()">Cancel</button>
                    <button id="btn-confirm-remove-workspace" class="btn btn-danger" onclick="confirmRemoveWorkspace()">Remove</button>
                </div>
            </div>
        </div>

        <!-- Bootstrap Claude Modal -->
        <div id="bootstrap-claude-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeBootstrapClaudeModal()"></div>
            <div class="modal-content modal-small">
                <div class="modal-header">
                    <h3>Create .claude Structure</h3>
                    <button class="modal-close" onclick="closeBootstrapClaudeModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <p>No CARL hooks detected (globally or in this project).</p>
                    <p>To set up CARL for the first time, we'll create:</p>
                    <ul class="bootstrap-list">
                        <li><code>.claude/</code> - Claude Code config directory</li>
                        <li><code>.claude/hooks/</code> - Hook scripts location</li>
                        <li><code>.claude/settings.json</code> - Hook wiring config</li>
                    </ul>
                    <p class="text-muted">After this, you'll install hooks and wire them to settings.json.</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeBootstrapClaudeModal()">Cancel</button>
                    <button id="btn-confirm-bootstrap" class="btn btn-primary" onclick="confirmBootstrapClaude()">Create .claude</button>
                </div>
            </div>
        </div>

        <!-- Import Domains Modal -->
        <div id="import-domains-modal" class="modal" style="display: none;">
            <div class="modal-overlay" onclick="closeImportDomainsModal()"></div>
            <div class="modal-content modal-medium">
                <div class="modal-header">
                    <h3>Import Domains</h3>
                    <button class="modal-close" onclick="closeImportDomainsModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div id="import-source-section">
                        <p>Select a <code>.carl</code> folder to import domains from:</p>
                        <div class="import-source-row">
                            <code id="import-source-path" class="path-value">No source selected</code>
                            <button id="btn-clear-import-source" class="btn btn-small btn-text" onclick="clearImportSource()" style="display: none;">Clear</button>
                            <button id="btn-browse-import-source" class="btn btn-secondary btn-small" onclick="browseImportSource()">Browse...</button>
                        </div>
                    </div>

                    <div id="import-domains-section" style="display: none;">
                        <h4>Available Domains</h4>
                        <p class="form-hint">Select domains to import into your current workspace.</p>
                        <div id="import-domains-list" class="checkbox-list">
                            <!-- Populated by JS -->
                        </div>

                        <div id="import-conflicts-warning" class="import-warning" style="display: none;">
                            <p><strong>⚠️ Conflicts:</strong> Some domains already exist. Importing will overwrite them.</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeImportDomainsModal()">Cancel</button>
                    <button id="btn-confirm-import" class="btn btn-primary" onclick="confirmImportDomains()" disabled>Import Selected</button>
                </div>
            </div>
        </div>

    </div>

    <script src="{{ url_for('static', filename='js/app.js') }}"></script>
</body>
</html>
