// ============================================
// PROJECT DNA - iPhone 15 Pro Multi-App OS
// ====================================================================

// Character Registry - Define all available characters
const Characters = {
    maya: {
        id: 'maya',
        name: 'Maya',
        avatarGradient: 'from-pink-500 to-yellow-400',
        startNode: 'maya_start',
        preview: 'Your girlfriend',
        available: true
    },
    emma: {
        id: 'emma',
        name: 'Emma',
        avatarGradient: 'from-purple-500 to-blue-400',
        startNode: 'emma_start',
        preview: 'Your college crush...',
        available: true  // Enabled for story content
    }
};

// GameState Object - Multi-Character Support
const GameState = {
    view: 'HOME', // 'HOME', 'MESSAGES', 'MESSAGES_LIST', 'GALLERY', 'SETTINGS'
    stats: {
        affection: 0,
        heat: 0,
        resentment: 0,
        loyalty: 50
    },
    currentDay: 1,
    timeOfDay: 'Evening', // Morning, Afternoon, Evening, Night
    clues: [], // For investigation mechanic
    activeChat: null,  // Current character ID being chatted with
    // Per-character chat logs
    chatLogs: {
        maya: [],
        emma: []
    },
    // Per-character story progress
    currentNodeIds: {
        maya: null,
        emma: null
    },
    // Per-character day tracking to ensure independent progression
    storyDays: {
        maya: 1,
        emma: 1
    },
    inventory: {
        unlockedPhotos: [],
        contacts: ['maya', 'emma']  // Characters unlocked for chatting
    },
    settings: {
        soundEnabled: true,
        wallpaper: 'https://images.unsplash.com/photo-1557683316-973673baf926?q=80&w=390&h=844&fit=crop',
        darkMode: false
    },
    flags: {},
    isPatreonUnlocked: false, // New Global State for Patreon Gate
    currentNode: null,
    relationshipState: 'dating', // dating, strained, broken, obsessed
    fastForward: false,
    canSleep: false,
    lastCompletedCharacter: null, // Tracks which character's day was just finished
    lastChoiceState: {}, // Stores { nodeId, logLength } per character for Rewind
    pendingNodes: {}, // Tracks nodes that should trigger upon opening chat
    notifications: {
        messages: 0,
        social: 0,
        gallery: 0
    }
};

// Social Feed Content
const FeedContent = {
    // We are now using a single pool of content since the user requested specific "kinkystagram" files
    // and we want them available immediately regardless of day.
    pool: [
        { id: 'kinky_ashley', user: 'Ashley', avatar: 'kinkystagram_Ashley', image: 'kinkystagram_Ashley', likes: 1205, caption: 'Feeling cute today 💕', liked: false },
        { id: 'kinky_billie_1', user: 'Billie', avatar: 'kinkystagram_billie_eilish', image: 'kinkystagram_billie_eilish', likes: 5405, caption: 'Bad energy 🖤', liked: false },
        { id: 'kinky_billie_2', user: 'Billie', avatar: 'kinkystagram_billie_eilish', image: 'kinkystagram_billie_eilish_bikini', likes: 8600, caption: 'Sun kissed ☀️', liked: false }
    ]
};


// Sound Effects Manager
const SoundManager = {
    bgm: null,
    play: function (soundId) {
        if (!GameState.settings.soundEnabled) return;
        const audio = document.getElementById(`sound-${soundId}`);
        if (audio) {
            audio.currentTime = 0;
            audio.play().catch(e => { /* Ignore autoplay errors */ });
        }
    },
    playBGM: function (soundId) {
        if (!GameState.settings.soundEnabled) return;
        if (this.bgm) {
            this.bgm.pause();
            this.bgm.currentTime = 0;
        }
        this.bgm = new Audio(`sounds/${soundId}.mp3`);
        this.bgm.loop = true;
        this.bgm.volume = 0.5; // Lower volume for background
        this.bgm.play().catch(e => console.log("BGM play failed:", e));
    },
    stopBGM: function () {
        if (this.bgm) {
            // Fade out effect
            const fadeOut = setInterval(() => {
                if (this.bgm.volume > 0.05) {
                    this.bgm.volume -= 0.05;
                } else {
                    clearInterval(fadeOut);
                    this.bgm.pause();
                    this.bgm.currentTime = 0;
                    this.bgm = null;
                }
            }, 50);
        }
    }
};

// ============================================
// Multi-Character Helper Functions
// ============================================

// Get the current character's chat log
function getChatLog() {
    const charId = GameState.activeChat;
    if (!charId || !GameState.chatLogs[charId]) return [];
    return GameState.chatLogs[charId];
}

// Add a message to the current character's chat log
function addToChatLog(message) {
    const charId = GameState.activeChat;
    if (!charId) return;
    if (!GameState.chatLogs[charId]) GameState.chatLogs[charId] = [];
    GameState.chatLogs[charId].push(message);
}

// Get the current character's node ID
function getCurrentNodeId() {
    const charId = GameState.activeChat;
    if (!charId) return null;
    return GameState.currentNodeIds[charId];
}

// Set the current character's node ID
function setCurrentNodeId(nodeId) {
    const charId = GameState.activeChat;
    if (!charId) return;
    GameState.currentNodeIds[charId] = nodeId;
}

// Get the current character data from registry
function getCurrentCharacter() {
    const charId = GameState.activeChat;
    if (!charId) return null;
    return Characters[charId];
}


// Day Advancement Logic
function advanceDay(nextNodeId) {
    const screen = document.getElementById('screen-renderer');

    // Fade out effect
    screen.style.transition = 'opacity 1.5s ease';
    screen.style.opacity = '0';

    setTimeout(() => {
        // Logic updates
        GameState.currentDay++;
        GameState.timeOfDay = 'Morning';

        // Reset view to Home
        GameState.view = 'HOME';
        screen.style.opacity = '1';
        renderHomeScreen();

        // Notification of new day
        setTimeout(() => {
            showIOSModal(
                `Day ${GameState.currentDay} Start`,
                "You've rested well. New messages might be waiting for you.",
                [{
                    text: "Start Day", bold: true, callback: (btn) => {
                        if (btn) btn.disabled = true; // Prevent double-tap
                        // Stay on Home screen as per user request
                        renderHomeScreen();
                    }
                }]
            );
        }, 500);

    }, 1500);
}

// iOs Modal Helper
function showIOSModal(title, body, buttons = []) {
    const container = document.getElementById('phone-frame');
    if (!container) return;

    // Default to OK button if none provided to prevent stuck state
    if (buttons.length === 0) {
        buttons = [{ text: 'OK' }];
    }

    let buttonsHtml = '';
    buttons.forEach(btn => {
        buttonsHtml += `<button class="ios-modal-btn ${btn.bold ? 'bold' : ''}">${btn.text}</button>`;
    });

    const overlay = document.createElement('div');
    overlay.className = 'ios-modal-overlay';
    overlay.innerHTML = `
        <div class="ios-modal">
            <div class="ios-modal-content">
                <div class="ios-modal-title">${title}</div>
                <div class="ios-modal-body">${body}</div>
            </div>
            <div class="ios-modal-footer">
                ${buttonsHtml}
            </div>
        </div>
    `;

    container.appendChild(overlay);
    setTimeout(() => overlay.classList.add('active'), 10);

    const btnElems = overlay.querySelectorAll('.ios-modal-btn');
    btnElems.forEach((btn, i) => {
        btn.onclick = () => {
            if (btn.disabled) return;
            btn.disabled = true; // Prevent rapid multiple clicks
            overlay.classList.remove('active');
            setTimeout(() => overlay.remove(), 300);
            if (buttons[i].callback) buttons[i].callback(btn);
        };
    });
}

// Patreon Gate Modal
function showPatreonGateModal(onUnlock) {
    const container = document.getElementById('phone-frame');
    if (!container) return;

    const overlay = document.createElement('div');
    overlay.className = 'ios-modal-overlay';
    overlay.innerHTML = `
        <div class="ios-modal" style="background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(25px); -webkit-backdrop-filter: blur(25px);">
            <div class="ios-modal-content">
                <div class="ios-modal-title" style="font-size: 1.2rem; margin-bottom: 8px;">Patreon Exclusive</div>
                <div class="ios-modal-body" style="margin-bottom: 16px;">
                    This content is locked for Patreon supporters. Please enter your access code.
                </div>
                <input type="text" id="patreon-code-input" placeholder="Enter Access Code" 
                    style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #ccc; font-size: 16px; text-align: center; margin-bottom: 8px; background: rgba(255,255,255,0.5);">
                <div id="patreon-error-msg" style="color: #ff3b30; font-size: 13px; font-weight: 500; height: 16px; opacity: 0; transition: opacity 0.3s;">
                    Invalid Code
                </div>
            </div>
            <div class="ios-modal-footer">
                <button class="ios-modal-btn bold" id="patreon-submit-btn">Unlock Content</button>
                <button class="ios-modal-btn" style="color: #ff3b30;" onclick="this.closest('.ios-modal-overlay').remove()">Cancel</button>
            </div>
        </div>
    `;

    container.appendChild(overlay);
    setTimeout(() => overlay.classList.add('active'), 10);

    const submitBtn = overlay.querySelector('#patreon-submit-btn');
    const input = overlay.querySelector('#patreon-code-input');
    const errorMsg = overlay.querySelector('#patreon-error-msg');

    const handleSubmit = () => {
        const code = input.value.trim();
        if (code === 'JHVCH911') {
            // Success
            GameState.isPatreonUnlocked = true;
            saveGame(); // Persist immediately

            overlay.classList.remove('active');
            setTimeout(() => {
                overlay.remove();
                if (onUnlock) onUnlock();
            }, 300);
        } else {
            // Failure
            errorMsg.style.opacity = '1';
            input.style.borderColor = '#ff3b30';
            // Simple shake animation
            input.animate([
                { transform: 'translateX(0)' },
                { transform: 'translateX(-10px)' },
                { transform: 'translateX(10px)' },
                { transform: 'translateX(0)' }
            ], { duration: 300 });
        }
    };

    submitBtn.onclick = handleSubmit;

    // Allow Enter key
    input.onkeypress = (e) => {
        if (e.key === 'Enter') handleSubmit();
    };

    // Adjust focus cleanup
    input.focus();
}

// View Switcher
function switchView(newView) {
    GameState.view = newView;
    const screenRenderer = document.getElementById('screen-renderer');
    if (!screenRenderer) return;

    screenRenderer.innerHTML = '';

    // Play app open sound
    if (newView !== 'HOME') {
        SoundManager.play('app-open');
    }

    // Handle BGM for Kinkystagram
    if (newView === 'SOCIAL') {
        SoundManager.playBGM('kinkystagram_soundtrack');
    } else {
        SoundManager.stopBGM();
    }

    // Clear notifications for the opened app
    if (newView === 'MESSAGES' || newView === 'MESSAGES_LIST') GameState.notifications.messages = 0;
    if (newView === 'SOCIAL') GameState.notifications.social = 0;
    if (newView === 'GALLERY') GameState.notifications.gallery = 0;

    switch (newView) {
        case 'HOME':
            renderHomeScreen();
            break;
        case 'MESSAGES':
            renderMessagesView();
            break;
        case 'MESSAGES_LIST':
            renderContactListView();
            break;
        case 'GALLERY':
            renderGalleryView();
            break;
        case 'NOTES':
            renderNotesView();
            break;
        case 'SOCIAL':
            renderSocialFeedView();
            break;
        case 'SETTINGS':
            renderSettingsView();
            break;
        case 'SAVE_MANAGER':
            renderSaveManagerView();
            break;
        case 'BLACKJACK':
            BlackjackGame.init();
            BlackjackGame.render();
            break;
    }
}

// Home Screen Renderer
// Home Screen Renderer
function renderHomeScreen() {
    const screen = document.getElementById('screen-renderer');

    screen.innerHTML = `
        <div class="home-screen" style="background-image: url('${GameState.settings.wallpaper}');">
            <!-- Clock Widget -->
            <div class="pt-12 text-center text-white drop-shadow-md mb-4 relative z-10">
                 <div class="text-6xl font-light tracking-tight" id="clock-widget">22:45</div>
                 <div class="text-lg font-medium opacity-90">Day ${GameState.currentDay} • ${GameState.timeOfDay}</div>
                 <!-- DEBUG LINE -->
                 <div class="text-[10px] opacity-70 mt-1 font-mono">
                    Sleep Ready: ${GameState.canSleep ? 'YES' : 'NO'}
                 </div>
            </div>

            <!-- App Icons Grid -->
            <div class="px-6 grid grid-cols-4 gap-y-8 gap-x-6 pb-32 relative z-20">
                <!-- Messages -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('MESSAGES_LIST')">
                    <div class="app-icon bg-green-500">
                        <svg class="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
                        </svg>
                        ${GameState.notifications.messages > 0 ? `<div class="notification-badge">${GameState.notifications.messages}</div>` : ''}
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Messages</span>
                </div>
                
                <!-- Gallery -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('GALLERY')">
                    <div class="app-icon bg-white flex items-center justify-center p-1">
                        <svg class="w-full h-full" viewBox="0 0 100 100">
                            <circle cx="50" cy="35" r="15" fill="#FFD700" opacity="0.8"/>
                            <circle cx="65" cy="50" r="15" fill="#FF8C00" opacity="0.8"/>
                            <circle cx="50" cy="65" r="15" fill="#FF4500" opacity="0.8"/>
                            <circle cx="35" cy="50" r="15" fill="#9370DB" opacity="0.8"/>
                            <circle cx="40" cy="40" r="15" fill="#40E0D0" opacity="0.8"/>
                            <circle cx="60" cy="40" r="15" fill="#ADFF2F" opacity="0.8"/>
                            <circle cx="60" cy="60" r="15" fill="#4169E1" opacity="0.8"/>
                            <circle cx="40" cy="60" r="15" fill="#C71585" opacity="0.8"/>
                        </svg>
                        ${GameState.notifications.gallery > 0 ? `<div class="notification-badge">${GameState.notifications.gallery}</div>` : ''}
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Photos</span>
                </div>

                <!-- Social -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('SOCIAL')">
                    <div class="app-icon bg-gradient-to-tr from-[#f09433] via-[#e6683c] via-[#dc2743] via-[#cc2366] to-[#bc1888]">
                        <svg class="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
                        </svg>
                        ${GameState.notifications.social > 0 ? `<div class="notification-badge">${GameState.notifications.social}</div>` : ''}
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Kinkystagram</span>
                </div>
                
                <!-- Notes -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('NOTES')">
                    <div class="app-icon overflow-hidden bg-[#FFD60A] flex flex-col shadow-inner">
                        <div class="h-1/5 bg-[#FFCC00] border-b border-black/5"></div>
                        <div class="flex-1 bg-white p-1">
                            <div class="h-0.5 w-4/5 bg-gray-200 mb-1"></div>
                            <div class="h-0.5 w-3/5 bg-gray-200 mb-1"></div>
                            <div class="h-0.5 w-4/5 bg-gray-200"></div>
                        </div>
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Notes</span>
                </div>

                <!-- Blackjack -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('BLACKJACK')">
                    <div class="app-icon bg-gradient-to-br from-emerald-800 to-green-950 p-1 shadow-inner flex items-center justify-center">
                        <svg class="w-8 h-8 text-white" viewBox="0 0 24 24" fill="currentColor">
                            <!-- Card 1 (Ace) -->
                            <rect x="4" y="4" width="12" height="16" rx="1" fill="white" transform="rotate(-10 10 12)"/>
                            <text x="7" y="10" font-size="6" font-weight="bold" fill="black" transform="rotate(-10 10 12)">A</text>
                            
                            <!-- Card 2 (King) -->
                            <rect x="8" y="4" width="12" height="16" rx="1" fill="#f8fafc" stroke="#e2e8f0" stroke-width="0.5"/>
                            <text x="11" y="10" font-size="6" font-weight="bold" fill="black">K</text>
                        </svg>
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Blackjack</span>
                </div>

                <!-- Save Manager -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('SAVE_MANAGER')">
                    <div class="app-icon bg-[#007AFF] flex flex-col items-center justify-center shadow-lg">
                        <svg class="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
                        </svg>
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Save Manager</span>
                </div>

                <!-- Settings -->
                <div class="flex flex-col items-center gap-2" onclick="openApp('SETTINGS')">
                    <div class="app-icon bg-gradient-to-b from-gray-200 to-gray-400 p-1">
                        <svg class="w-full h-full text-gray-700" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.62-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>
                        </svg>
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Settings</span>
                </div>

                <!-- Sleep -->
                <div id="sleep-app" class="flex flex-col items-center gap-2 ${GameState.canSleep ? 'animate-pulse' : 'opacity-60 grayscale'}" 
                     style="cursor: pointer; pointer-events: auto !important; position: relative; z-index: 100;"
                     onclick="window.goSleep()">
                    <div class="app-icon bg-gradient-to-br from-[#0F172A] to-[#000000] flex items-center justify-center" style="pointer-events: none;">
                        <svg class="w-8 h-8 text-[#FFD60A]" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M11.1 1.08a10 10 0 0 0 10.53 10.53 8.3 8.3 0 0 1-10.53-10.53z"/>
                        </svg>
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg" style="pointer-events: none;">Sleep</span>
                </div>

                <!-- Patreon -->
                <div class="flex flex-col items-center gap-2" onclick="window.open('https://www.patreon.com/15430605/join', '_blank')">
                    <div class="app-icon bg-[#FF424D] flex items-center justify-center">
                        <svg class="w-8 h-8 text-black" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M15.3 17.5a6.6 6.6 0 1 0 0-13.2 6.6 6.6 0 0 0 0 13.2zm-12.8 5.7h4V0h-4v23.2z"/>
                        </svg>
                    </div>
                    <span class="text-[11px] text-white font-medium drop-shadow-lg">Patreon</span>
                </div>
            </div>
            
            <!-- Dock -->
            <div class="dock">
                <div class="dock-icon" onclick="openApp('MESSAGES_LIST')">
                    <div class="w-full h-full bg-green-500 rounded-[22%] flex items-center justify-center">
                        <svg class="w-7 h-7 text-white" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
                        </svg>
                        ${GameState.notifications.messages > 0 ? `<div class="notification-badge">${GameState.notifications.messages}</div>` : ''}
                    </div>
                </div>
                <div class="dock-icon" onclick="openApp('GALLERY')">
                    <svg class="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                    </svg>
                </div>
                <div class="dock-icon" onclick="openApp('SETTINGS')">
                    <svg class="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    </svg>
                </div>
            </div>
        </div>
    `;
}

// Contact List View - Shows all available characters
function renderContactListView() {
    const screen = document.getElementById('screen-renderer');

    // Build contact rows from Characters registry
    let contactRows = '';
    for (const charId in Characters) {
        const char = Characters[charId];
        const isUnlocked = GameState.inventory.contacts.includes(charId);
        const chatLog = GameState.chatLogs[charId] || [];
        const lastMessage = chatLog.length > 0 ? chatLog[chatLog.length - 1] : null;
        const preview = lastMessage ? (lastMessage.image ? '📷 Photo' : lastMessage.text.substring(0, 30) + '...') : char.preview;

        if (isUnlocked && char.available) {
            contactRows += `
                <div onclick="openChat('${charId}')" class="flex items-center gap-3 p-3 border-b border-gray-100 !border-[var(--ios-border)] active:bg-gray-50 cursor-pointer">
                    <div class="w-12 h-12 bg-gradient-to-tr ${char.avatarGradient} rounded-full flex-shrink-0 border-2 border-white !border-[var(--ios-bg)] shadow-sm"></div>
                    <div class="flex-1 min-w-0">
                        <h3 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[15px]">${char.name}</h3>
                        <p class="text-[13px] text-gray-500 !text-[var(--ios-secondary-text)] truncate">${preview}</p>
                    </div>
                    <svg class="w-5 h-5 text-gray-300 !text-[var(--ios-secondary-text)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                    </svg>
                </div>
            `;
        } else if (isUnlocked && !char.available) {
            // Character unlocked but content not ready
            contactRows += `
                <div class="flex items-center gap-3 p-3 border-b border-gray-100 !border-[var(--ios-border)] opacity-50">
                    <div class="w-12 h-12 bg-gradient-to-tr ${char.avatarGradient} rounded-full flex-shrink-0 border-2 border-white !border-[var(--ios-bg)] shadow-sm"></div>
                    <div class="flex-1 min-w-0">
                        <h3 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[15px]">${char.name}</h3>
                        <p class="text-[13px] text-gray-400 !text-[var(--ios-secondary-text)] truncate">${char.preview}</p>
                    </div>
                    <span class="text-[11px] text-gray-400 !text-[var(--ios-secondary-text)] bg-gray-100 !bg-[var(--ios-secondary-bg)] px-2 py-1 rounded-full">Soon</span>
                </div>
            `;
        }
    }

    screen.innerHTML = `
        <!-- iOS Messages List Header -->
        <div class="messages-header pt-12 pb-3 px-4 flex items-center gap-3">
            <button onclick="goHome()" class="text-blue-500 text-[17px] font-medium" aria-label="Go Home">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
            </button>
            <div class="flex-1">
                <h2 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[17px]">Messages</h2>
            </div>
        </div>

        <!-- Contact List -->
        <div class="flex-1 overflow-y-auto bg-white !bg-[var(--ios-bg)]">
            ${contactRows}
        </div>
    `;
}

// Open a specific character's chat
function openChat(characterId) {
    if (!Characters[characterId]) {
        console.error('Character not found:', characterId);
        return;
    }

    GameState.activeChat = characterId;

    // Patreon Gate for Emma
    if (characterId === 'emma' && !GameState.isPatreonUnlocked) {
        showPatreonGateModal(() => {
            switchView('MESSAGES');
        });
        return;
    }

    switchView('MESSAGES');
}

// Messages View Renderer - Now uses dynamic character data
function renderMessagesView() {
    const screen = document.getElementById('screen-renderer');
    const character = getCurrentCharacter();

    // Fallback values if no character selected
    const charName = character ? character.name : 'Unknown';
    const charGradient = character ? character.avatarGradient : 'from-gray-400 to-gray-600';

    screen.innerHTML = `
        <!-- iOS Messages Header -->
        <div class="messages-header pt-2 pb-3 px-4 flex items-center gap-3">
            <button onclick="switchView('MESSAGES_LIST')" class="text-blue-500 text-[17px] font-medium" aria-label="Back">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
            </button>
            <div class="w-10 h-10 bg-gradient-to-tr ${charGradient} rounded-full flex-shrink-0 border-2 border-white !border-[var(--ios-bg)] shadow-sm"></div>
            <div class="flex-1 min-w-0">
                <h2 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[17px] truncate">${charName}</h2>
            </div>
            <div class="flex gap-2">
                <button onclick="rewindChat()" class="text-[13px] px-2 py-1 rounded-full border text-zinc-400 !text-[var(--ios-secondary-text)] border-zinc-200 !border-[var(--ios-border)] hover:bg-gray-100 transition-colors">
                    Rewind
                </button>
                <button onclick="toggleFF()" class="text-[13px] px-2 py-1 rounded-full border ${GameState.fastForward ? 'bg-orange-500 text-white border-orange-600' : 'text-zinc-400 !text-[var(--ios-secondary-text)] border-zinc-200 !border-[var(--ios-border)]'}">
                    FF
                </button>
            </div>
        </div>

        <!-- Chat Messages Container -->
        <div id="chat-box" class="flex-1 overflow-y-auto px-4 py-4 flex flex-col gap-2 bg-white !bg-[var(--ios-bg)]" style="scroll-behavior: smooth;"></div>

        <!-- Stacked Choice Area -->
        <div id="keyboard-area" class="stacked-choices-container hidden">
            <!-- Choice buttons will appear here -->
        </div>
    `;

    // activeChat should already be set by openChat()
    // Fallback to maya for backwards compatibility
    if (!GameState.activeChat) GameState.activeChat = 'maya';

    // Reuse character variable defined above (after possible activeChat update)
    const currentChar = getCurrentCharacter();
    const chatLog = getChatLog();

    if (chatLog.length > 0) {
        restoreChatLog();

        // If there's a pending node for this character (e.g. from sleeping), trigger it
        if (GameState.pendingNodes && GameState.pendingNodes[GameState.activeChat]) {
            const nextNode = GameState.pendingNodes[GameState.activeChat];
            delete GameState.pendingNodes[GameState.activeChat];

            const startDelay = GameState.fastForward ? 10 : 1000;
            setTimeout(() => loadNode(nextNode), startDelay);
        }
    } else {
        // Auto-start conversation (respect FF mode)
        const startDelay = GameState.fastForward ? 10 : 500;
        const startNode = currentChar ? currentChar.startNode : 'maya_start';
        setTimeout(() => loadNode(startNode), startDelay);
    }
}

// Gallery View Renderer
// Gallery View Renderer
function renderGalleryView() {
    const screen = document.getElementById('screen-renderer');

    const totalSlots = 30;
    const unlockedCount = GameState.inventory.unlockedPhotos.length;

    screen.innerHTML = `
        <div class="pt-12 pb-4 px-4 messages-header flex items-center gap-3">
            <button onclick="goHome()" class="text-blue-500 text-[17px] font-medium" aria-label="Go Home">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
            </button>
            <h2 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[17px]">Gallery</h2>
        </div>
        <div class="flex-1 overflow-y-auto bg-black !bg-[var(--ios-bg)]">
            <div class="gallery-grid">
                ${Array.from({ length: totalSlots }, (_, i) => {
        if (i < unlockedCount) {
            const imageId = GameState.inventory.unlockedPhotos[i];
            return `<div class="gallery-item" onclick="showFullscreenImage('images/${imageId}.jpg')">
                            <img src="images/${imageId}.jpg" class="w-full h-full object-cover" alt="${imageId}">
                        </div>`;
        } else {
            return `<div class="gallery-item gallery-item-locked">
                            <svg class="w-8 h-8 text-white/30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                            </svg>
                        </div>`;
        }
    }).join('')}
            </div>
        </div>
    `;
}

// Settings View Renderer
// Settings View Renderer
function renderSettingsView() {
    const screen = document.getElementById('screen-renderer');

    screen.innerHTML = `
        <div class="pt-12 pb-3 px-4 messages-header flex items-center gap-3">
            <button onclick="goHome()" class="text-blue-500 text-[17px] font-medium" aria-label="Go Home">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
            </button>
            <h2 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[17px]">Settings</h2>
        </div>
        <div class="flex-1 overflow-y-auto bg-white !bg-[var(--ios-bg)]">
            <div class="px-4 py-6 space-y-6">
                <!-- Wallpaper Selection -->
                <div class="py-4 border-b border-zinc-200 !border-[var(--ios-border)]">
                    <p class="text-[17px] font-medium text-gray-900 !text-[var(--ios-text)] mb-3">Wallpaper</p>
                    <div class="grid grid-cols-4 gap-3">
                        ${[...['https://images.unsplash.com/photo-1557683316-973673baf926?q=80&w=390&h=844&fit=crop'], ...GameState.inventory.unlockedPhotos.map(id => `images/${id}.jpg`)].map(url => `
                        <div onclick="setWallpaper('${url}')" class="aspect-[9/16] rounded-lg bg-cover bg-center ring-2 ring-offset-2 ${GameState.settings.wallpaper === url ? 'ring-blue-500' : 'ring-transparent'} cursor-pointer" style="background-image: url('${url}')"></div>
                        `).join('')}
                    </div>
                </div>

                <!-- Dark Mode Toggle (Re-Added) -->
                <div class="flex items-center justify-between py-4 border-b border-zinc-200 !border-[var(--ios-border)]">
                    <div>
                        <p class="text-[17px] font-medium text-gray-900 !text-[var(--ios-text)]">Dark Mode</p>
                        <p class="text-[15px] text-gray-500 !text-[var(--ios-secondary-text)] mt-1">iOS Dark Appearance</p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" ${GameState.settings.darkMode ? 'checked' : ''} 
                            onchange="toggleDarkMode(this.checked)" 
                            class="sr-only peer">
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></div>
                    </label>
                </div>

                <!-- Sound Effects Toggle -->
                <div class="flex items-center justify-between py-4 border-b border-zinc-200 !border-[var(--ios-border)]">
                    <div>
                        <p class="text-[17px] font-medium text-gray-900 !text-[var(--ios-text)]">Sound Effects</p>
                        <p class="text-[15px] text-gray-500 !text-[var(--ios-secondary-text)] mt-1">Enable iOS-style sound effects</p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" ${GameState.settings.soundEnabled ? 'checked' : ''}
                            onchange="toggleSound(this.checked)"
                            class="sr-only peer">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></div>
                    </label>
                </div>

                <!-- Reset Game -->
                <div class="py-4 border-b border-zinc-200 !border-[var(--ios-border)]">
                    <button onclick="resetGame()" class="w-full text-left">
                        <p class="text-[17px] font-medium text-red-600">Reset Game</p>
                        <p class="text-[15px] text-gray-500 !text-[var(--ios-secondary-text)] mt-1">Clear all progress and start over</p>
                    </button>
                </div>
            </div>
        </div>
    `;
}

// Show Quick Reply Bubbles in Keyboard Area
// Show Quick Reply Bubbles in Stacked UI
function showQuickReplies(options) {
    const keyboardArea = document.getElementById('keyboard-area');
    if (!keyboardArea) return;

    keyboardArea.innerHTML = '';

    const availableOptions = options.filter(opt => {
        if (opt.requires) {
            // Check heat
            if (opt.requires.heat && GameState.stats.heat < opt.requires.heat) return false;
            // Check affection
            if (opt.requires.affection && GameState.stats.affection < opt.requires.affection) return false;
            // Check corruption/resentment
            if (opt.requires.resentment && GameState.stats.resentment < opt.requires.resentment) return false;
            // Check flags conditional
            if (opt.condition) {
                // Safe eval of basic conditions
                try {
                    const stats = GameState.stats;
                    const flags = GameState.flags;
                    if (!eval(opt.condition)) return false;
                } catch (e) {
                    console.error('Condition check failed', e);
                    return false;
                }
            }
        }
        return true;
    });

    if (availableOptions.length > 0) {
        keyboardArea.classList.remove('hidden');
    }

    availableOptions.forEach(opt => {
        const btn = document.createElement('button');
        btn.className = 'choice-btn-stacked';
        btn.textContent = opt.text;
        btn.onclick = () => {
            // Save state for Rewind before proceeding
            const charId = GameState.activeChat || 'maya';
            GameState.lastChoiceState[charId] = {
                nodeId: GameState.currentNode.id,
                logLength: GameState.chatLogs[charId].length
            };

            keyboardArea.classList.add('hidden');
            keyboardArea.innerHTML = '';
            renderMessage(opt.text, 'right');

            if (opt.onSelect) {
                opt.onSelect();
            }

            if (opt.next) {
                const nextDelay = GameState.fastForward ? 10 : 500;
                setTimeout(() => loadNode(opt.next), nextDelay);
            }
        };
        keyboardArea.appendChild(btn);
    });

    // Scroll to bottom of chat
    const chatBox = document.getElementById('chat-box');
    if (chatBox) {
        setTimeout(() => {
            chatBox.scrollTo({ top: chatBox.scrollHeight, behavior: 'smooth' });
        }, 100);
    }
}

// Image Bubble Component with Blur-to-Reveal
function renderImageBubble(imageID, description = '', side = 'left', addToLog = true) {
    const chatBox = document.getElementById('chat-box');
    if (!chatBox) return;

    const messageDiv = document.createElement('div');
    messageDiv.className = `flex flex-col gap-1 ${side === 'left' ? 'items-start' : 'items-end'} spring-bounce`;

    const bubble = document.createElement('div');
    bubble.className = `message-bubble-${side} p-0 overflow-hidden max-w-[75%]`;

    const imageContainer = document.createElement('div');
    imageContainer.className = 'image-bubble-container relative';
    imageContainer.onclick = function () {
        const blur = this.querySelector('.image-blur');
        if (blur && getComputedStyle(blur).opacity !== '0') {
            blur.style.opacity = '0';
            blur.style.pointerEvents = 'none';
        } else {
            showFullscreenImage(`images/${imageID}.jpg`);
        }
    };

    const img = document.createElement('img');
    img.src = `images/${imageID}.jpg`;
    img.className = 'w-full h-auto block';
    img.alt = description;
    img.onerror = () => {
        img.style.display = 'none';
        const placeholder = document.createElement('div');
        placeholder.className = 'image-placeholder p-8 text-center text-xs text-white/40 bg-zinc-900 italic';
        placeholder.textContent = `[Image: ${imageID}]`;
        imageContainer.appendChild(placeholder);
    };

    // Blur overlay
    const blur = document.createElement('div');
    blur.className = 'image-blur';
    blur.style.cssText = 'position: absolute; inset: 0; background: rgba(0,0,0,0.8); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: opacity 0.3s; z-index: 10;';

    const blurText = document.createElement('span');
    blurText.className = 'text-white text-sm font-medium';
    blurText.textContent = 'Tap to reveal';
    blur.appendChild(blurText);

    imageContainer.appendChild(img);
    imageContainer.appendChild(blur);
    bubble.appendChild(imageContainer);
    messageDiv.appendChild(bubble);

    const timestamp = document.createElement('span');
    timestamp.className = `text-[11px] text-zinc-500 px-2 ${side === 'left' ? 'text-left' : 'text-right'}`;
    timestamp.textContent = 'Delivered';
    messageDiv.appendChild(timestamp);

    chatBox.appendChild(messageDiv);

    if (addToLog) {
        // Add to unlocked photos
        if (!GameState.inventory.unlockedPhotos.includes(imageID)) {
            GameState.inventory.unlockedPhotos.push(imageID);
        }

        // Add to chat log - use current character ID for sender
        const charId = GameState.activeChat;
        addToChatLog({
            sender: side === 'left' ? charId : 'player',
            text: '',
            image: imageID,
            imageDescription: description,
            timestamp: Date.now()
        });

        // Play sound
        if (!GameState.fastForward) {
            SoundManager.play(side === 'left' ? 'received' : 'sent');
        }
    }

    setTimeout(() => {
        chatBox.scrollTo({ top: chatBox.scrollHeight, behavior: 'smooth' });
    }, 100);
}

// Restore Chat Log - Multi-character aware
function restoreChatLog() {
    const chatBox = document.getElementById('chat-box');
    if (!chatBox) return;

    const chatLog = getChatLog();
    const charId = GameState.activeChat;

    chatBox.innerHTML = '';
    chatLog.forEach(msg => {
        if (msg.image) {
            // Check if sender matches current character (left) or player (right)
            const side = (msg.sender === charId) ? 'left' : 'right';
            renderImageBubble(msg.image, msg.imageDescription || '', side, false);
        } else {
            const side = (msg.sender === charId) ? 'left' : (msg.sender === 'system' ? 'system' : 'right');
            renderMessage(msg.text, side, false);
        }
    });

    const currentNodeId = getCurrentNodeId();
    if (currentNodeId) {
        const node = storyScript[currentNodeId];
        if (node) {
            // Re-trigger onSelect if it was a terminal node (sets canSleep = true)
            // This ensures sleep state persists if user switches views or reloads
            if (node.onSelect) {
                node.onSelect();
            }

            if (node.options && node.options.length > 0) {
                showQuickReplies(node.options);
            }
        }
    }
}

// Message Renderer
// Message Renderer
// Message Renderer
// Message Renderer
function renderMessage(text, side = 'left', addToLog = true) {
    const chatBox = document.getElementById('chat-box');
    if (!chatBox) return;

    const messageDiv = document.createElement('div');
    const bounceClass = GameState.fastForward ? '' : 'spring-bounce';

    // Handle System Messages
    if (side === 'system') {
        messageDiv.className = `flex flex-col items-center my-4 ${bounceClass}`;
        const bubble = document.createElement('div');
        bubble.className = 'bg-gray-100 text-gray-500 text-xs font-medium px-3 py-1 rounded-full text-center border border-gray-200';
        bubble.textContent = text;
        messageDiv.appendChild(bubble);
        chatBox.appendChild(messageDiv);

        if (addToLog) {
            addToChatLog({
                sender: 'system',
                text: text,
                image: null,
                timestamp: Date.now(),
                read: true
            });
        }

        // Scroll
        setTimeout(() => {
            chatBox.scrollTo({ top: chatBox.scrollHeight, behavior: 'instant' });
        }, 10);
        return;
    }

    // Handle Normal Messages
    messageDiv.className = `flex flex-col gap-1 ${side === 'left' ? 'items-start' : 'items-end'} ${bounceClass}`;

    const bubble = document.createElement('div');
    bubble.className = side === 'left' ? 'message-bubble-left' : 'message-bubble-right';

    if (side === 'right') {
        bubble.innerHTML = `
            <span class="msg-text">${text}</span>
            <div class="msg-status-container">
                <svg class="msg-status-icon" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/>
                </svg>
            </div>
        `;
    } else {
        bubble.textContent = text;
    }

    messageDiv.appendChild(bubble);

    const timestamp = document.createElement('span');
    timestamp.className = `text-[11px] text-zinc-500 px-2 ${side === 'left' ? 'text-left' : 'text-right'}`;
    timestamp.textContent = 'Delivered';
    messageDiv.appendChild(timestamp);

    chatBox.appendChild(messageDiv);

    if (addToLog) {
        const charId = GameState.activeChat;
        addToChatLog({
            sender: side === 'left' ? charId : 'player',
            text: text,
            image: null,
            timestamp: Date.now(),
            read: false
        });
    }

    // Play sound on every message (muted in FF)
    if (!GameState.fastForward) {
        if (side === 'left') {
            SoundManager.play('received');
        } else {
            SoundManager.play('sent');
        }
    }

    setTimeout(() => {
        chatBox.scrollTo({ top: chatBox.scrollHeight, behavior: 'smooth' });
    }, 10);
}

// Node Loader
async function loadNode(nodeKey) {
    const node = storyScript[nodeKey];
    if (!node) return;

    GameState.currentNode = node;
    setCurrentNodeId(nodeKey);  // Use helper for per-character tracking

    // Trigger onSelect action if present
    if (node.onSelect) {
        node.onSelect();
        // If canSleep was toggled, refresh home if active
        if (GameState.canSleep && GameState.view === 'HOME') {
            renderHomeScreen();
        }
    }

    // Clear keyboard area
    const keyboardArea = document.getElementById('keyboard-area');
    if (keyboardArea) keyboardArea.innerHTML = '';

    if (node.sender === 'player') {
        if (node.image) {
            renderImageBubble(node.image, node.imageDescription, 'right');
            SoundManager.play('sent');
        } else {
            renderMessage(node.text, 'right');
        }

        if (node.next) {
            const delay = GameState.fastForward ? 10 : 500;
            setTimeout(() => loadNode(node.next), delay);
        }
        return;
    }

    // System Messages
    if (node.sender === 'system') {
        renderMessage(node.text, 'system');
        // If system message has valid options/next, allow them.
        // Usually system messages are termini or auto-advancers.
    }

    // Show typing indicator in chat box
    const chatBox = document.getElementById('chat-box');
    let typingBubble = null;
    if (chatBox) {
        typingBubble = document.createElement('div');
        typingBubble.id = 'typing-bubble';
        typingBubble.className = 'typing-indicator animate__animated animate__fadeIn';
        typingBubble.innerHTML = `
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
        `;
        chatBox.appendChild(typingBubble);
        chatBox.scrollTo({ top: chatBox.scrollHeight, behavior: 'smooth' });
    }

    // Simulate "Seen" for player's last message
    const lastMsg = document.querySelector('.message-bubble-right:last-child .msg-status-icon');
    if (lastMsg) {
        setTimeout(() => {
            lastMsg.classList.add('read');
        }, GameState.fastForward ? 10 : 1000);
    }

    // Wait (simulate typing) - Optimized for 1-2s range
    const baseDelay = node.text ? node.text.length * 25 : 800;
    const finalDelay = GameState.fastForward ? 10 : Math.min(2200, Math.max(1200, baseDelay));

    // Skip wait if System
    const waitTime = node.sender === 'system' ? 10 : finalDelay;

    await new Promise(r => setTimeout(r, waitTime));

    if (typingBubble) typingBubble.remove();

    // Check if message has image
    if (node.image) {
        renderImageBubble(node.image, node.imageDescription || '');
        // Auto-unlock in gallery
        if (!GameState.inventory.unlockedPhotos.includes(node.image)) {
            GameState.inventory.unlockedPhotos.push(node.image);
            GameState.notifications.gallery++; // Notify user of new content
            console.log("Photo unlocked:", node.image);
        }
    } else if (node.text && node.sender !== 'system' && node.sender !== 'player') {
        // Only render messages if not handled above
        renderMessage(node.text, 'left');

        // Background Notification: If user isn't looking at this specific chat
        if (GameState.view !== 'MESSAGES' || GameState.activeChat !== node.characterId) {
            GameState.notifications.messages++;
        }
    }

    // Show choices as Quick Reply bubbles in keyboard area
    // Show choices
    if (node.options && node.options.length > 0) {
        const optionDelay = GameState.fastForward ? 10 : 300;
        setTimeout(() => {
            showQuickReplies(node.options);
        }, optionDelay);
    } else if (node.next) {
        // Automatically load next - shortened delay
        const nextDelay = GameState.fastForward ? 10 : 800;
        setTimeout(() => loadNode(node.next), nextDelay);
    }
}

// App Functions
function openApp(appName) {
    // Patreon Gate for Kinkystagram (SOCIAL)
    if (appName === 'SOCIAL' && !GameState.isPatreonUnlocked) {
        showPatreonGateModal(() => {
            switchView('SOCIAL');
        });
        return;
    }

    switchView(appName);
}

function goHome() {
    switchView('HOME');
}
function toggleDarkMode(enabled) {
    GameState.settings.darkMode = enabled;
    const phoneFrame = document.getElementById('phone-frame');
    if (phoneFrame) {
        if (enabled) {
            phoneFrame.classList.add('dark-mode');
        } else {
            phoneFrame.classList.remove('dark-mode');
        }
    }
}

function toggleSound(enabled) {
    GameState.settings.soundEnabled = enabled;
}

function setWallpaper(url) {
    GameState.settings.wallpaper = url;
    renderSettingsView(); // Refresh to show active state
}

function toggleFF() {
    GameState.fastForward = !GameState.fastForward;
    // Only update the FF button appearance, don't re-render the entire view
    const ffButton = document.querySelector('button[onclick="toggleFF()"]');
    if (ffButton) {
        if (GameState.fastForward) {
            ffButton.className = 'text-[13px] px-2 py-1 rounded-full border bg-orange-500 text-white border-orange-600';
        } else {
            ffButton.className = 'text-[13px] px-2 py-1 rounded-full border text-zinc-400 border-zinc-200';
        }
    }
}

async function rewindChat() {
    const charId = GameState.activeChat || 'maya';
    const state = GameState.lastChoiceState[charId];

    if (!state) {
        showIOSModal("Cannot Rewind", "There is no previous choice to go back to.", [{ text: "OK" }]);
        return;
    }

    // Restore log length
    GameState.chatLogs[charId] = GameState.chatLogs[charId].slice(0, state.logLength);

    // Restore node
    setCurrentNodeId(state.nodeId);

    // Clear state so we don't rewind infinitely to the same spot unless we choice again
    GameState.lastChoiceState[charId] = null;

    // Trigger re-render
    renderMessagesView();
}

window.goSleep = goSleep; // Make global for debug

function goSleep() {
    console.log("goSleep CLICKED. Status:", GameState.canSleep);

    // Debug fallback
    if (!document.getElementById('phone-frame')) {
        alert("Phone frame missing!");
        return;
    }

    if (!GameState.canSleep) {
        showIOSModal(
            "Not Tired Yet",
            "Finish your daily missions first.",
            [{ text: "OK", bold: true }]
        );
        return;
    }

    showIOSModal(
        "Bedtime",
        "Are you sure you want to end the day and go to sleep?",
        [
            { text: "Cancel", callback: null },
            {
                text: "Sleep", bold: true, callback: (btn) => {
                    if (btn) btn.disabled = true; // Double safety
                    GameState.canSleep = false;

                    // Priority: If a specific character just finished their day, advance them.
                    // Fallback: activeChat. Final fallback: 'maya'.
                    const charId = GameState.lastCompletedCharacter || GameState.activeChat || 'maya';

                    // Increment this specific character's story day
                    if (!GameState.storyDays[charId]) GameState.storyDays[charId] = 1;
                    GameState.storyDays[charId]++;

                    const nextStoryDay = GameState.storyDays[charId];

                    // Determine prefix based on active character (Maya has no prefix for morning nodes)
                    const prefix = (charId !== 'maya') ? `${charId}_` : '';
                    const nextNode = `${prefix}day${nextStoryDay}_morning`;

                    console.log(`Advancing ${charId} story to day ${nextStoryDay} node: ${nextNode}`);

                    // Reset the tracker after use
                    GameState.lastCompletedCharacter = null;

                    // Mark this node as pending so it triggers when the chat is opened
                    if (!GameState.pendingNodes) GameState.pendingNodes = {};
                    GameState.pendingNodes[charId] = nextNode;

                    advanceDay(); // No longer pass nextNode to auto-open
                }
            }
        ]
    );
}

function showFullscreenImage(src) {
    const container = document.getElementById('phone-frame');
    if (!container) return;

    const overlay = document.createElement('div');
    overlay.className = 'fullscreen-overlay';
    overlay.style.cssText = 'position: absolute; inset: 0; background: black; z-index: 2000; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s ease;';

    overlay.innerHTML = `
        <img src="${src}" style="max-width: 100%; max-height: 100%; object-fit: contain;">
        <button class="absolute top-12 right-6 text-white/80 hover:text-white transition-colors" style="background: rgba(0,0,0,0.5); border-radius: 50%; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; font-size: 24px;">&times;</button>
    `;

    container.appendChild(overlay);
    setTimeout(() => overlay.style.opacity = '1', 10);

    const close = () => {
        overlay.style.opacity = '0';
        setTimeout(() => overlay.remove(), 300);
    };

    overlay.onclick = close;

    // Accessibility for close button
    const closeBtn = overlay.querySelector('button');
    if (closeBtn) closeBtn.setAttribute('aria-label', 'Close Image');
}

// Save/Load System Helpers
function saveGame() {
    try {
        const saveData = JSON.stringify(GameState);
        localStorage.setItem('nsfw_phone_save', saveData);
        showIOSModal('Save Successful', 'Your progress has been saved to this browser.');
    } catch (e) {
        showIOSModal('Save Failed', 'Could not save to browser storage. Your cookies might be disabled.');
    }
}

function loadGame() {
    try {
        const saved = localStorage.getItem('nsfw_phone_save');
        if (saved) {
            const parsed = JSON.parse(saved);
            Object.assign(GameState, parsed);
            showIOSModal('Load Successful', 'Your progress has been restored.', [
                { text: 'Great', callback: () => switchView('HOME') }
            ]);
        } else {
            showIOSModal('No Save Found', 'There is no saved progress in this browser.');
        }
    } catch (e) {
        showIOSModal('Load Failed', 'The save data appears to be corrupted.');
    }
}

function exportSave() {
    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(GameState, null, 2));
    const downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href", dataStr);
    const date = new Date().toISOString().slice(0, 10);
    downloadAnchorNode.setAttribute("download", `phone_game_save_${date}.json`);
    document.body.appendChild(downloadAnchorNode);
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
}

function triggerImport() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.onchange = e => {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = readerEvent => {
            try {
                const content = readerEvent.target.result;
                const parsed = JSON.parse(content);
                // Basic validation
                if (parsed.storyDays && parsed.chatLogs) {
                    Object.assign(GameState, parsed);
                    showIOSModal('Import Success', 'Data restored successfully.', [
                        { text: 'Restart App', callback: () => location.reload() }
                    ]);
                } else {
                    showIOSModal('Invalid File', 'This doesn\'t look like a valid save file.');
                }
            } catch (err) {
                showIOSModal('Import Error', 'Failed to parse the save file.');
            }
        }
        reader.readAsText(file, 'UTF-8');
    }
    input.click();
}

// Save Manager View Renderer
function renderSaveManagerView() {
    const screen = document.getElementById('screen-renderer');
    screen.innerHTML = `
        <div class="flex-1 flex flex-col bg-[var(--ios-secondary-bg)]">
            <div class="pt-12 pb-4 px-4 messages-header flex items-center gap-3">
                <button onclick="goHome()" class="text-blue-500 text-[17px] font-medium" aria-label="Go Home">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                </button>
                <h2 class="font-semibold text-gray-900 !text-[var(--ios-text)] text-[17px]">Save Manager</h2>
            </div>

            <div class="flex-1 overflow-y-auto px-6 py-8 space-y-8">
                <div class="text-center space-y-2">
                    <div class="w-20 h-20 bg-blue-500 rounded-3xl mx-auto flex items-center justify-center shadow-lg">
                        <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                             <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path>
                        </svg>
                    </div>
                    <p class="text-[15px] text-gray-500 !text-[var(--ios-secondary-text)]">Manage your game progress data.</p>
                </div>

                <div class="space-y-4">
                    <!-- Browser Persistence -->
                    <div class="bg-white !bg-[var(--ios-bg)] rounded-3xl overflow-hidden shadow-sm border border-zinc-100 !border-[var(--ios-border)]">
                        <button onclick="saveGame()" class="w-full p-4 flex items-center justify-between active:bg-gray-50 transition-colors">
                            <span class="font-semibold text-[17px] text-gray-900 !text-[var(--ios-text)]">Quick Save</span>
                            <span class="text-blue-500 text-[15px]">Local Storage</span>
                        </button>
                        <div class="h-[0.5px] bg-zinc-100 !bg-[var(--ios-border)] mx-4"></div>
                        <button onclick="loadGame()" class="w-full p-4 flex items-center justify-between active:bg-gray-50 transition-colors">
                            <span class="font-semibold text-[17px] text-gray-900 !text-[var(--ios-text)]">Quick Load</span>
                            <span class="text-blue-500 text-[15px]">Restore State</span>
                        </button>
                    </div>

                    <!-- File Operations -->
                    <div class="bg-white !bg-[var(--ios-bg)] rounded-3xl overflow-hidden shadow-sm border border-zinc-100 !border-[var(--ios-border)]">
                        <button onclick="exportSave()" class="w-full p-4 flex items-center justify-between active:bg-gray-50 transition-colors">
                            <span class="font-semibold text-[17px] text-gray-900 !text-[var(--ios-text)]">Export Save</span>
                            <span class="text-zinc-400 !text-[var(--ios-secondary-text)] text-[15px]">Download JSON</span>
                        </button>
                        <div class="h-[0.5px] bg-zinc-100 !bg-[var(--ios-border)] mx-4"></div>
                        <button onclick="triggerImport()" class="w-full p-4 flex items-center justify-between active:bg-gray-50 transition-colors">
                            <span class="font-semibold text-[17px] text-gray-900 !text-[var(--ios-text)]">Import Save</span>
                            <span class="text-zinc-400 !text-[var(--ios-secondary-text)] text-[15px]">Upload File</span>
                        </button>
                    </div>
                </div>

                <div class="bg-zinc-100 !bg-[var(--ios-header-bg)] rounded-2xl p-4">
                    <p class="text-[13px] text-gray-500 !text-[var(--ios-secondary-text)] leading-relaxed italic">
                        <b>Tip:</b> Export your save periodically. It's the best way to ensure u don't lose progress if the game gets updated or if u want to play on a different device!
                    </p>
                </div>
            </div>
        </div>
    `;
}

// Unlock Phone
function unlockPhone() {
    const lockScreen = document.getElementById('lock-screen');
    const gameScreen = document.getElementById('game-screen');

    if (lockScreen) {
        lockScreen.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        lockScreen.style.opacity = '0';
        lockScreen.style.transform = 'scale(0.95)';

        // Ensure theme is applied before revealing game screen
        if (GameState.settings.darkMode) {
            toggleDarkMode(true);
        }

        setTimeout(() => {
            lockScreen.classList.add('hidden');
            if (gameScreen) {
                gameScreen.classList.remove('hidden');
                switchView('HOME');
            }
        }, 300);
    }
}

// Notes View Renderer
function renderNotesView() {
    const screen = document.getElementById('screen-renderer');

    screen.innerHTML = `
        <div class="pt-12 pb-4 px-4 messages-header flex items-center gap-3 bg-yellow-50">
            <button onclick="goHome()" class="text-yellow-600 text-[17px] font-medium" aria-label="Go Home">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
            </button>
            <h2 class="font-semibold text-gray-900 text-[17px]">Notes</h2>
        </div>
        <div class="flex-1 overflow-y-auto bg-yellow-50 !bg-[var(--ios-secondary-bg)] px-4 py-2">
            <div class="space-y-4">
                ${GameState.clues.length === 0 ?
            '<p class="text-gray-400 text-center mt-10 italic !text-[var(--ios-secondary-text)]">No notes added yet...</p>' :
            GameState.clues.map(clue => `
                    <div class="bg-white !bg-[var(--ios-secondary-bg)] p-4 rounded-lg shadow-sm border border-yellow-100 !border-[var(--ios-border)]">
                        <p class="text-xs text-gray-500 !text-[var(--ios-secondary-text)] mb-1">${new Date(clue.timestamp).toLocaleTimeString()}</p>
                        <p class="text-gray-800 !text-[var(--ios-text)] font-medium">${clue.text}</p>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

// Clue System
function unlockClue(text) {
    const existing = GameState.clues.find(c => c.text === text);
    if (!existing) {
        GameState.clues.push({
            text: text,
            timestamp: Date.now()
        });

        // Notification (visual only for now)
        const notif = document.createElement('div');
        notif.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-white/90 backdrop-blur shadow-lg rounded-full px-4 py-2 text-xs font-medium z-50 animate-bounce';
        notif.innerHTML = '📝 New Note Added';
        document.getElementById('screen-renderer').appendChild(notif);
        setTimeout(() => notif.remove(), 2000);
    }
}

// Social Feed View Renderer
function renderSocialFeedView() {
    const screen = document.getElementById('screen-renderer');
    // Using simple filtered pool
    const posts = FeedContent.pool || [];

    screen.innerHTML = `
        <div class="social-feed-container flex flex-col h-full bg-white text-black font-sans">
            <!-- Header -->
            <div class="pt-12 pb-2 px-4 flex items-center justify-between border-b border-gray-100 bg-white sticky top-0 z-30">
                <div class="font-bold text-2xl tracking-tight" style="font-family: 'Instagram Sans', sans-serif;">Kinkystagram</div>
                <div class="flex gap-4">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path></svg>
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path></svg>
                </div>
            </div>

            <!-- Stories (Horizontal Scroll) -->
            <div class="flex gap-4 p-4 overflow-x-auto border-b border-gray-50 no-scrollbar">
                ${['Your Story', 'Ashley', 'Billie', 'Maya', 'Emma'].map((name, i) => `
                    <div class="flex flex-col items-center flex-shrink-0 gap-1">
                        <div class="w-16 h-16 rounded-full p-[2px] bg-gradient-to-tr from-yellow-400 via-red-500 to-purple-600">
                            <div class="w-full h-full rounded-full bg-white p-[2px]">
                                ${name === 'Your Story' ?
            '<div class="w-full h-full bg-gray-100 flex items-center justify-center rounded-full"><span class="text-xl">+</span></div>' :
            `<img src="images/kinkystagram_${name === 'Billie' ? 'billie_eilish' : 'Ashley'}.jpg" class="w-full h-full rounded-full object-cover" onerror="this.src='https://ui-avatars.com/api/?name=${name}'">`
        }
                            </div>
                        </div>
                        <span class="text-xs truncate w-16 text-center">${name}</span>
                    </div>
                `).join('')}
            </div>

            <!-- Feed -->
            <div class="flex-1 overflow-y-auto bg-white pb-20">
                ${posts.length === 0 ? `
                    <div class="flex flex-col items-center justify-center h-40 text-gray-400">
                         <p>No new posts.</p>
                    </div>
                ` : posts.map(post => `
                    <div class="mb-4 bg-white post-container" id="post-${post.id}">
                        <!-- Post Header -->
                        <div class="flex items-center justify-between p-3">
                            <div class="flex items-center gap-2">
                                <div class="w-8 h-8 rounded-full bg-gradient-to-tr from-yellow-400 via-red-500 to-purple-600 p-[1.5px]">
                                    <div class="w-full h-full rounded-full bg-white p-[1px]">
                                        <img src="images/${post.avatar}.jpg" class="w-full h-full rounded-full object-cover" onerror="this.src='https://ui-avatars.com/api/?name=${post.user}'">
                                    </div>
                                </div>
                                <span class="font-semibold text-sm">${post.user}</span>
                            </div>
                            <svg class="w-5 h-5 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h.01M12 12h.01M19 12h.01M12 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm-14 0a1 1 0 11-2 0 1 1 0 012 0z"></path></svg>
                        </div>

                        <!-- Post Image -->
                        <div class="w-full aspect-square bg-gray-100 relative" ondblclick="toggleLike('${post.id}')">
                            <img src="images/${post.image}.jpg" loading="lazy" class="w-full h-full object-cover" onerror="this.src='https://via.placeholder.com/600?text=Image+Load+Error'">
                            <div class="like-overlay absolute inset-0 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300">
                                <svg class="w-24 h-24 text-white drop-shadow-lg fill-current" viewBox="0 0 24 24"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="flex items-center justify-between px-3 py-3">
                            <div class="flex items-center gap-4">
                                <button onclick="toggleLike('${post.id}')" class="like-btn transition-transform active:scale-125">
                                    ${post.liked ?
                `<svg class="w-7 h-7 text-red-500 fill-current" viewBox="0 0 24 24"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>` :
                `<svg class="w-7 h-7 text-black hover:text-gray-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path></svg>`
            }
                                </button>
                                <svg class="w-7 h-7 text-black hover:text-gray-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path></svg>
                                <svg class="w-7 h-7 text-black hover:text-gray-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
                            </div>
                            <svg class="w-7 h-7 text-black hover:text-gray-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"></path></svg>
                        </div>

                        <!-- Likes Count -->
                        <div class="px-3 font-semibold text-sm likes-count">
                            ${post.likes.toLocaleString()} likes
                        </div>

                        <!-- Caption -->
                        <div class="px-3 pt-1 pb-2 text-sm">
                            <span class="font-semibold mr-2">${post.user}</span>${post.caption}
                        </div>
                        
                        <!-- Timestamp -->
                        <div class="px-3 text-[10px] text-gray-500 uppercase tracking-wide">
                            2 hours ago
                        </div>
                    </div>
                `).join('')}
            </div>

            <!-- Bottom Nav -->
            <div class="h-[88px] border-t border-gray-200 bg-white flex items-start justify-around pt-3 select-none fixed bottom-0 w-full z-40 max-w-[390px]">
                <button onclick="goHome()" class="p-2 -mt-1" aria-label="Home"><svg class="w-7 h-7 text-black" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path></svg></button>
                <div class="p-2 -mt-1"><svg class="w-7 h-7 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg></div>
                <div class="p-2 -mt-1"><svg class="w-7 h-7 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></div>
                <div class="p-2 -mt-1"><svg class="w-7 h-7 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path></svg></div>
                <div class="p-2 -mt-1">
                    <div class="w-7 h-7 rounded-full bg-gray-200 overflow-hidden">
                        <img src="https://ui-avatars.com/api/?name=User" class="w-full h-full object-cover">
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Optimized Toggle Like Function
function toggleLike(postId) {
    const post = FeedContent.pool.find(p => p.id === postId);
    if (!post) return;

    // Update Data
    post.liked = !post.liked;
    post.likes += post.liked ? 1 : -1;

    // Update DOM (Efficiently)
    const postEl = document.getElementById(`post-${postId}`);
    if (postEl) {
        // Toggle Heart Icon
        const likeBtn = postEl.querySelector('.like-btn');
        if (likeBtn) {
            likeBtn.innerHTML = post.liked ?
                `<svg class="w-7 h-7 text-red-500 fill-current animate__animated animate__heartBeat" viewBox="0 0 24 24"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>` :
                `<svg class="w-7 h-7 text-black hover:text-gray-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path></svg>`;
        }

        // Update Counter
        const countEl = postEl.querySelector('.likes-count');
        if (countEl) {
            countEl.textContent = `${post.likes.toLocaleString()} likes`;
        }

        // Show Overlay Animation (if liking)
        if (post.liked) {
            const overlay = postEl.querySelector('.like-overlay');
            if (overlay) {
                overlay.classList.remove('opacity-0');
                overlay.classList.add('animate__animated', 'animate__heartBeat');
                setTimeout(() => {
                    overlay.classList.add('opacity-0');
                    overlay.classList.remove('animate__animated', 'animate__heartBeat');
                }, 800);
            }
        }
    }

    SoundManager.play('sent');
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    const gameScreen = document.getElementById('game-screen');
    if (gameScreen && !gameScreen.classList.contains('hidden')) {
        switchView('HOME');
    }
});
