<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>synthesized character-scene pool preview</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/4.1.0/js-yaml.min.js"></script>
    <style>
        :root {
            --primary-color: #4a6bdf;
            --secondary-color: #38b2ac;
            --bg-color: #f5f8fa;
            --card-bg-color: #ffffff;
            --text-color: #2d3748;
            --border-color: #e2e8f0;
            --hover-color: #ebf4ff;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --modal-bg: rgba(255, 255, 255, 0.8);
            --worldview-color: #805ad5;
            --worldview-light: #e9d8fd;
            --character-color: #4a6bdf;
            --character-light: #e3eaff;
            --error-color: #e53e3e;
            --warning-color: #dd6b20;
            --success-color: #38a169;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            line-height: 1.6;
            padding: 0;
            margin: 0;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
        }

        .header {
            padding: 15px 0;
            margin-bottom: 20px;
            text-align: center;
            border-bottom: 1px solid var(--border-color);
        }

        .header h1 {
            font-size: 24px;
            font-weight: 500;
            color: var(--primary-color);
        }

        .total-stats {
            margin-top: 10px;
            font-size: 14px;
            color: #718096;
        }

        .content-area {
            display: flex;
            flex: 1;
            gap: 20px;
            overflow: hidden;
            min-height: 0;
        }

        .browser-container {
            flex: 3;
            display: flex;
            flex-direction: column;
            gap: 20px;
            overflow-y: auto;
            padding-right: 10px;
        }

        .worldview-browser, .character-browser {
            background: var(--card-bg-color);
            border-radius: 12px;
            padding: 20px;
            box-shadow: var(--shadow);
            overflow-y: auto;
            position: relative;
        }

        .worldview-browser {
            flex: 1;
            border-top: 4px solid var(--worldview-color);
        }

        .character-browser {
            flex: 2;
            border-top: 4px solid var(--character-color);
        }

        .selection-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
            min-width: 320px;
            height: 100%;
            overflow-y: auto;
            padding-right: 10px;
        }

        .worldview-selection, .character-selection {
            background: var(--card-bg-color);
            border-radius: 12px;
            padding: 20px;
            box-shadow: var(--shadow);
            overflow-y: auto;
            position: relative;
            display: flex;
            flex-direction: column;
        }

        #worldview-list, #character-list {
            flex: 1;
            overflow-y: auto;
        }

        .worldview-selection {
            flex: 1;
            border-top: 4px solid var(--worldview-color);
            min-height: 200px;
        }

        .character-selection {
            flex: 2;
            border-top: 4px solid var(--character-color);
            min-height: 400px;
        }

        .section-title {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .worldview-browser .section-title {
            color: var(--worldview-color);
        }

        .character-browser .section-title {
            color: var(--character-color);
        }

        .worldview-selection .section-title {
            color: var(--worldview-color);
        }

        .character-selection .section-title {
            color: var(--character-color);
        }

        .section-title .count {
            background: var(--primary-color);
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 14px;
        }

        .character-selection .section-title .count {
            background: var(--character-color);
        }

        .worldview-selection .section-title .count {
            background: var(--worldview-color);
        }

        .folder-toggle {
            cursor: pointer;
            user-select: none;
            padding: 8px 12px;
            border-radius: 8px;
            margin: 5px 0;
            font-weight: 500;
            transition: all 0.2s;
            display: flex;
            align-items: center;
        }

        .folder-toggle:hover {
            background-color: var(--hover-color);
        }

        .folder-toggle::before {
            content: '▶';
            display: inline-block;
            margin-right: 8px;
            font-size: 10px;
            transition: transform 0.2s;
        }

        .folder-toggle.open::before {
            transform: rotate(90deg);
        }

        .folder-content {
            display: none;
            margin-left: 20px;
        }

        .folder-content.open {
            display: block;
        }

        .character-grid, .worldview-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }

        .character-card, .worldview-card {
            background-color: #f3f4f6;
            border-radius: 12px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
            border: 2px solid transparent;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            height: 100px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        .character-card:hover, .worldview-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .character-card:hover {
            background-color: var(--character-light);
        }

        .worldview-card:hover {
            background-color: var(--worldview-light);
        }

        .character-card.selected {
            border-color: var(--character-color);
            background-color: var(--character-light);
        }

        .worldview-card.selected {
            border-color: var(--worldview-color);
            background-color: var(--worldview-light);
        }

        .card-name {
            font-weight: 500;
            font-size: 16px;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
        }

        .card-type {
            font-size: 12px;
            color: #718096;
        }

        .worldview-card .card-type {
            color: var(--worldview-color);
        }

        .character-card .card-type {
            color: var(--character-color);
        }

        .modal-dialog {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1000;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(8px);
        }

        .modal-content {
            position: relative;
            background: var(--modal-bg);
            backdrop-filter: blur(20px);
            border-radius: 16px;
            padding: 25px;
            width: 80%;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            z-index: 1001;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .worldview-modal .modal-header {
            border-bottom-color: var(--worldview-color);
        }

        .character-modal .modal-header {
            border-bottom-color: var(--character-color);
        }

        .modal-title {
            font-size: 20px;
            font-weight: 500;
        }

        .worldview-modal .modal-title {
            color: var(--worldview-color);
        }

        .character-modal .modal-title {
            color: var(--character-color);
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #718096;
            transition: color 0.2s;
        }

        .modal-close:hover {
            color: #e53e3e;
        }

        .modal-body {
            white-space: pre-wrap;
            font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
            padding: 15px;
            background-color: rgba(255, 255, 255, 0.7);
            border-radius: 8px;
            overflow-x: auto;
        }

        .modal-footer {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }

        .btn {
            padding: 10px 15px;
            border-radius: 8px;
            border: none;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-worldview {
            background-color: var(--worldview-color);
            color: white;
        }

        .btn-worldview:hover {
            background-color: #6b46c1;
        }

        .btn-character {
            background-color: var(--character-color);
            color: white;
        }

        .btn-character:hover {
            background-color: #3c5bc6;
        }

        .btn-secondary {
            background-color: #e2e8f0;
            color: #4a5568;
        }

        .btn-secondary:hover {
            background-color: #cbd5e0;
        }

        .candidate-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            background-color: #f7fafc;
            border-radius: 10px;
            margin-bottom: 10px;
            transition: all 0.2s;
        }

        .worldview-item {
            border-left: 4px solid var(--worldview-color);
        }

        .worldview-item:hover {
            background-color: var(--worldview-light);
        }

        .character-item {
            border-left: 4px solid var(--character-color);
        }

        .character-item:hover {
            background-color: var(--character-light);
        }

        .candidate-info {
            display: flex;
            flex-direction: column;
        }

        .candidate-name {
            font-weight: 500;
            font-size: 15px;
            color: var(--text-color);
        }

        .candidate-path {
            font-size: 12px;
            color: #718096;
            margin-top: 3px;
        }

        .candidate-actions {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            background: none;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
            color: #718096;
        }

        .action-btn:hover {
            background-color: #e2e8f0;
        }

        .action-btn.remove:hover {
            background-color: #fed7d7;
            color: #e53e3e;
        }

        .action-btn.view:hover {
            background-color: #e3eaff;
            color: var(--primary-color);
        }

        .controls {
            margin-top: 20px;
            margin-bottom: 10px;
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        .empty-state {
            text-align: center;
            padding: 20px;
            color: #a0aec0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            flex: 1;
        }

        .empty-state svg {
            opacity: 0.6;
            margin-bottom: 15px;
        }

        .empty-state p {
            margin-top: 10px;
            font-size: 14px;
        }

        .info-message {
            margin-top: 15px;
            padding: 12px;
            border-radius: 8px;
            font-size: 14px;
            display: none;
        }

        .info-message.error {
            background-color: #fff5f5;
            color: var(--error-color);
            border-left: 4px solid var(--error-color);
        }

        .info-message.warning {
            background-color: #fffaf0;
            color: var(--warning-color);
            border-left: 4px solid var(--warning-color);
        }

        .info-message.success {
            background-color: #f0fff4;
            color: var(--success-color);
            border-left: 4px solid var(--success-color);
        }

        /* Hover tooltip */
        .tooltip {
            position: absolute;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 5px 10px;
            border-radius: 6px;
            font-size: 12px;
            z-index: 100;
            pointer-events: none;
            white-space: nowrap;
        }

        /* Responsive adjustment */
        @media (max-width: 1024px) {
            .content-area {
                flex-direction: column;
            }
            
            .browser-container, .selection-container {
                min-width: 100%;
            }
            
            .character-grid, .worldview-grid {
                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            }
            
            .modal-content {
                width: 95%;
                padding: 15px;
            }
        }

        /* Add new styles */
        .worldview-section {
            background: var(--card-bg-color);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: var(--shadow);
            border-left: 4px solid var(--worldview-color);
        }

        .worldview-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .worldview-title {
            font-size: 18px;
            font-weight: 500;
            color: var(--worldview-color);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .worldview-timestamp {
            font-size: 12px;
            color: #718096;
            opacity: 0.7;
        }

        .character-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }

        .character-count-badge {
            background: var(--worldview-color);
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 14px;
        }

        /* Custom scrollbar styles */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        /* Firefox scrollbar styles */
        * {
            scrollbar-width: thin;
            scrollbar-color: #888 #f1f1f1;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Synthesized Character-Scene Pool Preview</h1>
            <div class="total-stats">
                <span class="total-count">Total Worldview Count: <span id="total-worldview-count">Loading...</span></span>
                <span class="total-count">Total Character Count: <span id="total-character-count">Loading...</span></span>
            </div>
        </div>
        
        <div class="content-area">
            <div class="browser-container">
                <div id="worldview-characters-container">
                    <!-- Worldview and characters will be dynamically generated here -->
                </div>
            </div>
            
            <div class="selection-container">
                <div class="worldview-selection">
                    <h2 class="section-title">Selected Worldview <span class="count" id="worldview-count">0</span></h2>
                    <div id="worldview-list"></div>
                    
                    <div id="empty-worldview" class="empty-state">
                        <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                            <polyline points="9 22 9 12 15 12 15 22"></polyline>
                        </svg>
                        <p>Please select a worldview</p>
                    </div>
                </div>
                
                <div class="character-selection">
                    <h2 class="section-title">Selected Characters <span class="count" id="character-count">0</span></h2>
                    <div id="character-list"></div>
                    
                    <div id="empty-characters" class="empty-state">
                        <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                            <circle cx="9" cy="7" r="4"></circle>
                            <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                            <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                        </svg>
                        <p>Please select at least two characters</p>
                    </div>
                </div>
                
                <div class="info-message error" id="error-message"></div>
                
                <div class="controls">
                    <button id="confirm-btn" class="btn btn-character">Confirm Selection</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Character details modal -->
    <div id="character-modal" class="modal-dialog character-modal">
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="character-modal-title">Character Details</h3>
                <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body" id="character-modal-body">
                Loading...
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary modal-close-btn">Close</button>
                <button class="btn btn-character" id="character-add-btn">Add to Selection</button>
            </div>
        </div>
    </div>
    
    <!-- Worldview details modal -->
    <div id="worldview-modal" class="modal-dialog worldview-modal">
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="worldview-modal-title">Worldview Details</h3>
                <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body" id="worldview-modal-body">
                Loading...
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary modal-close-btn">Close</button>
                <button class="btn btn-worldview" id="worldview-add-btn">Set as Current Worldview</button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // State variables
            let currentCharacterModalPath = null;
            let currentWorldviewModalPath = null;
            const characters = new Set();
            let currentWorldview = null;
            
            // Content cache
            const contentCache = {};
            
            // DOM elements
            const worldviewCharactersContainer = document.getElementById('worldview-characters-container');
            const characterList = document.getElementById('character-list');
            const worldviewList = document.getElementById('worldview-list');
            const characterCount = document.getElementById('character-count');
            const worldviewCount = document.getElementById('worldview-count');
            const emptyCharacters = document.getElementById('empty-characters');
            const emptyWorldview = document.getElementById('empty-worldview');
            const errorMessage = document.getElementById('error-message');
            const totalCharacterCount = document.getElementById('total-character-count');
            
            // Modal elements
            const characterModal = document.getElementById('character-modal');
            const worldviewModal = document.getElementById('worldview-modal');
            const characterModalTitle = document.getElementById('character-modal-title');
            const worldviewModalTitle = document.getElementById('worldview-modal-title');
            const characterModalBody = document.getElementById('character-modal-body');
            const worldviewModalBody = document.getElementById('worldview-modal-body');
            const characterAddBtn = document.getElementById('character-add-btn');
            const worldviewAddBtn = document.getElementById('worldview-add-btn');
            
            // Initialize interface display
            characterList.style.display = 'none';
            worldviewList.style.display = 'none';
            emptyCharacters.style.display = 'flex';
            emptyWorldview.style.display = 'flex';
            
            // Get character total
            fetch('/api/character-total')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        totalCharacterCount.textContent = data.total_count;
                    } else {
                        totalCharacterCount.textContent = 'Get failed';
                        console.error('Get character total failed:', data.error);
                    }
                })
                .catch(error => {
                    totalCharacterCount.textContent = 'Get failed';
                    console.error('Get character total request failed:', error);
                });
            
            // Load tracking.json data
            fetch('/api/tracking')
                .then(response => response.json())
                .then(data => {
                    // Group characters by worldview path
                    const worldviewMap = new Map();
                    
                    data.forEach(record => {
                        const worldviewPath = record.from_worldview;
                        if (!worldviewMap.has(worldviewPath)) {
                            worldviewMap.set(worldviewPath, []);
                        }
                        worldviewMap.get(worldviewPath).push({
                            characterPath: record.to_character_profile,
                            separatedPath: record.separated_path,
                            characterCount: record.character_count
                        });
                    });
                    
                    // Render worldviews and characters
                    worldviewMap.forEach((characters, worldviewPath) => {
                        renderWorldviewSection(worldviewPath, characters);
                    });
                })
                .catch(error => {
                    console.error('Load tracking.json failed:', error);
                    worldviewCharactersContainer.innerHTML = '<div class="empty-state"><p>Load file failed</p></div>';
                });
            
            // Render worldview area
            function renderWorldviewSection(worldviewPath, characters) {
                const section = document.createElement('div');
                section.className = 'worldview-section';
                
                const header = document.createElement('div');
                header.className = 'worldview-header';
                
                const title = document.createElement('div');
                title.className = 'worldview-title';
                
                // Extract timestamp
                const timestamp = worldviewPath.match(/\d{8}_\d{6}/)?.[0] || '';
                const formattedTimestamp = timestamp.replace('_', ' ');
                
                const nameSpan = document.createElement('span');
                nameSpan.className = 'worldview-name';
                
                // Load worldview file content to get Name field
                fetch(`/api/file-content?path=${encodeURIComponent(worldviewPath)}`)
                    .then(response => response.text())
                    .then(content => {
                        try {
                            const worldviewData = jsyaml.load(content);
                            if (worldviewData && worldviewData.Name) {
                                nameSpan.textContent = worldviewData.Name;
                            } else {
                                nameSpan.textContent = getNameFromPath(worldviewPath);
                            }
                        } catch (e) {
                            console.error('Parse worldview YAML failed:', e);
                            nameSpan.textContent = getNameFromPath(worldviewPath);
                        }
                    })
                    .catch(error => {
                        console.error('Load worldview file failed:', error);
                        nameSpan.textContent = getNameFromPath(worldviewPath);
                    });
                
                const timestampSpan = document.createElement('span');
                timestampSpan.className = 'worldview-timestamp';
                timestampSpan.textContent = formattedTimestamp;
                
                title.appendChild(nameSpan);
                title.appendChild(timestampSpan);
                
                // Add worldview click preview functionality
                title.style.cursor = 'pointer';
                title.addEventListener('click', function() {
                    showWorldviewModal(worldviewPath, nameSpan.textContent);
                });
                
                const countBadge = document.createElement('span');
                countBadge.className = 'character-count-badge';
                countBadge.textContent = 'Loading...';
                
                header.appendChild(title);
                header.appendChild(countBadge);
                
                const characterListDiv = document.createElement('div');
                characterListDiv.className = 'character-list';
                
                // Load and render each character
                let totalCharacterCount = 0;
                const loadingPromises = characters.map(char => {
                    return fetch(`/api/separated-characters?path=${encodeURIComponent(char.separatedPath)}`)
                        .then(response => response.json())
                        .then(characterFiles => {
                            if (Array.isArray(characterFiles)) {
                                totalCharacterCount += characterFiles.length;
                                characterFiles.forEach(file => {
                                    const card = createCharacterCard(file, worldviewPath);
                                    characterListDiv.appendChild(card);
                                });
                            }
                            // Update character count label
                            countBadge.textContent = `${totalCharacterCount} characters`;
                        });
                });
                
                // Wait for all characters to load
                Promise.all(loadingPromises).catch(error => {
                    console.error('Load characters failed:', error);
                    countBadge.textContent = 'Load failed';
                });
                
                section.appendChild(header);
                section.appendChild(characterListDiv);
                worldviewCharactersContainer.appendChild(section);
            }
            
            // Create character card
            function createCharacterCard(file, worldviewPath) {
                const card = document.createElement('div');
                card.className = 'character-card';
                card.setAttribute('data-path', file.path);
                card.setAttribute('data-worldview', worldviewPath);
                
                const nameEl = document.createElement('div');
                nameEl.className = 'card-name';
                nameEl.textContent = getNameFromPath(file.path);
                
                const typeEl = document.createElement('div');
                typeEl.className = 'card-type';
                typeEl.textContent = 'Character';
                
                card.appendChild(nameEl);
                card.appendChild(typeEl);
                
                // Click event - show character details
                card.addEventListener('click', function() {
                    showCharacterModal(file.path, nameEl.textContent);
                });
                
                // Set selected state
                if (characters.has(file.path)) {
                    card.classList.add('selected');
                }
                
                return card;
            }
            
            // 显示角色详情模态框
            function showCharacterModal(path, name) {
                currentCharacterModalPath = path;
                characterModalTitle.textContent = name;
                characterModalBody.textContent = 'Loading...';
                
                // Show modal
                characterModal.style.display = 'flex';
                
                // Load file content
                fetchFileContent(path)
                    .then(content => {
                        characterModalBody.textContent = content;
                        updateCharacterAddButton();
                    })
                    .catch(error => {
                        characterModalBody.textContent = `Load failed: ${error}`;
                    });
            }
            
            // Show worldview details modal
            function showWorldviewModal(path, name) {
                currentWorldviewModalPath = path;
                worldviewModalTitle.textContent = name;
                worldviewModalBody.textContent = 'Loading...';
                
                // Show modal
                worldviewModal.style.display = 'flex';
                
                // Load file content
                fetchFileContent(path)
                    .then(content => {
                        worldviewModalBody.textContent = content;
                        updateWorldviewAddButton();
                    })
                    .catch(error => {
                        worldviewModalBody.textContent = `Load failed: ${error}`;
                    });
            }
            
            // Update character add button state
            function updateCharacterAddButton() {
                if (characters.has(currentCharacterModalPath)) {
                    characterAddBtn.textContent = 'Added';
                    characterAddBtn.disabled = true;
                } else {
                    characterAddBtn.textContent = 'Add to Selection';
                    characterAddBtn.disabled = false;
                }
            }
            
            // Update worldview add button state
            function updateWorldviewAddButton() {
                if (currentWorldview === currentWorldviewModalPath) {
                    worldviewAddBtn.textContent = 'Current Selected';
                    worldviewAddBtn.disabled = true;
                } else {
                    worldviewAddBtn.textContent = 'Set as Current Worldview';
                    worldviewAddBtn.disabled = false;
                }
            }
            
            // Extract name from path
            function getNameFromPath(path) {
                const filename = path.split('/').pop();
                return filename ? filename.replace('.yaml', '').replace(/_/g, ' ') : path;
            }
            
            // Get file content
            function fetchFileContent(path) {
                if (contentCache[path]) {
                    return Promise.resolve(contentCache[path]);
                }
                
                return fetch(`/api/file-content?path=${encodeURIComponent(path)}`)
                    .then(response => response.text())
                    .then(content => {
                        contentCache[path] = content;
                        return content;
                    });
            }
            
            // Modal event handling
            document.querySelectorAll('.modal-overlay, .modal-close, .modal-close-btn').forEach(el => {
                el.addEventListener('click', function() {
                    characterModal.style.display = 'none';
                    worldviewModal.style.display = 'none';
                });
            });
            
            // Prevent modal content area click bubbling
            document.querySelectorAll('.modal-content').forEach(el => {
                el.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            });
            
            // Character add button event
            characterAddBtn.addEventListener('click', function() {
                if (!currentCharacterModalPath) return;
                
                const name = characterModalTitle.textContent;
                const content = characterModalBody.textContent;
                
                if (addCharacter(currentCharacterModalPath, name, content)) {
                    this.textContent = 'Added';
                    this.disabled = true;
                }
            });
            
            // Worldview add button event
            worldviewAddBtn.addEventListener('click', function() {
                if (!currentWorldviewModalPath) return;
                
                const name = worldviewModalTitle.textContent;
                const content = worldviewModalBody.textContent;
                
                if (addWorldview(currentWorldviewModalPath, name, content)) {
                    this.textContent = 'Current Selected';
                    this.disabled = true;
                }
            });
            
            // Confirm selection button
            document.getElementById('confirm-btn').addEventListener('click', function() {
                // Verify selection
                if (!currentWorldview) {
                    showError('Please select a worldview');
                    return;
                }
                
                if (characters.size < 2) {
                    showError('Please select at least two characters');
                    return;
                }
                
                // Submit selection request
                fetch('/api/confirm-selection', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        selected_files: Array.from(characters),
                        selected_worldview: currentWorldview
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        const successModal = document.createElement('div');
                        successModal.style.cssText = `
                            position: fixed;
                            top: 20px;
                            left: 50%;
                            transform: translateX(-50%);
                            background: rgba(56, 161, 105, 0.9);
                            color: white;
                            padding: 15px 25px;
                            border-radius: 8px;
                            z-index: 10000;
                            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                            backdrop-filter: blur(4px);
                        `;
                        successModal.innerHTML = `
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                                    <polyline points="22 4 12 14.01 9 11.01"></polyline>
                                </svg>
                                <span>Successfully saved selection: 1 worldview and ${characters.size} characters</span>
                            </div>
                        `;
                        document.body.appendChild(successModal);
                        
                        // 3 seconds later automatically disappear
                        setTimeout(() => {
                            successModal.style.opacity = '0';
                            successModal.style.transition = 'opacity 0.5s';
                            setTimeout(() => successModal.remove(), 500);
                        }, 3000);
                    } else {
                        showError(data.error || 'Save failed');
                    }
                })
                .catch(error => {
                    showError('Save failed: ' + error);
                });
            });
            
            // Keyboard event handling
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    characterModal.style.display = 'none';
                    worldviewModal.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>

