<?php
require_once 'includes/init.php';

if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

$currentUserId = $_SESSION['user_id'];
$chatUserId = isset($_GET['user']) ? sanitizeInput($_GET['user']) : '';

if (empty($chatUserId)) {
    redirect(APP_URL . '/chats.php');
}

$db = getDB();

// Get chat partner info
$stmt = $db->prepare("SELECT id, unique_id, name, profile_photo, is_ghost_mode FROM users WHERE unique_id = ? AND status = 'approved'");
$stmt->execute([$chatUserId]);
$chatPartner = $stmt->fetch();

if (!$chatPartner) {
    redirect(APP_URL . '/chats.php?error=user_not_found');
}

// Get chat cleared info
$stmt = $db->prepare("
    SELECT cleared_at FROM chat_cleared 
    WHERE user_id = ? AND chat_with_id = ?
");
$stmt->execute([$currentUserId, $chatPartner['id']]);
$chatCleared = $stmt->fetch();

// Get messages between users
$clearedCondition = $chatCleared ? "AND m.created_at > '{$chatCleared['cleared_at']}'" : '';
$stmt = $db->prepare("
    SELECT m.*, 
        sender.unique_id as sender_unique_id,
        sender.name as sender_name,
        sender.profile_photo as sender_photo,
        (SELECT status FROM message_status WHERE message_id = m.id AND user_id = ?) as read_status,
        (SELECT GROUP_CONCAT(reaction) FROM message_reactions WHERE message_id = m.id) as reactions
    FROM messages m
    JOIN users sender ON m.sender_id = sender.id
    WHERE ((m.sender_id = ? AND m.receiver_id = ? AND m.deleted_by_sender = 0)
       OR (m.sender_id = ? AND m.receiver_id = ? AND m.deleted_by_receiver = 0))
    AND m.is_deleted_for_all = 0
    $clearedCondition
    ORDER BY m.created_at ASC
");
$stmt->execute([$chatPartner['id'], $currentUserId, $chatPartner['id'], $chatPartner['id'], $currentUserId]);
$messages = $stmt->fetchAll();

// Mark messages as read
$stmt = $db->prepare("
    INSERT INTO message_status (message_id, user_id, status)
    SELECT m.id, ?, 'read' FROM messages m
    WHERE m.sender_id = ? AND m.receiver_id = ?
    AND m.id NOT IN (SELECT message_id FROM message_status WHERE user_id = ?)
    ON DUPLICATE KEY UPDATE status = 'read', updated_at = NOW()
");
$stmt->execute([$currentUserId, $chatPartner['id'], $currentUserId, $currentUserId]);

// Get shared media count
$stmt = $db->prepare("
    SELECT COUNT(*) FROM messages 
    WHERE ((sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?))
    AND message_type IN ('image', 'video', 'gif')
    AND is_deleted_for_all = 0
");
$stmt->execute([$currentUserId, $chatPartner['id'], $chatPartner['id'], $currentUserId]);
$sharedMediaCount = $stmt->fetchColumn();

// Get chat theme
$stmt = $db->prepare("
    SELECT background_color, message_color, text_color, background_image 
    FROM chat_themes 
    WHERE user_id = ? AND chat_with_id = ?
");
$stmt->execute([$currentUserId, $chatPartner['id']]);
$chatTheme = $stmt->fetch();

// Set default WhatsApp theme if no theme exists
if (!$chatTheme) {
    $chatTheme = [
        'background_color' => '#ECE5DD',
        'message_color' => '#DCF8C6',
        'text_color' => '#111B21',
        'background_image' => null
    ];
}

$pageTitle = $chatPartner['name'];
$hideFooter = true;
$hideBottomNav = true;

include 'includes/header.php';
?>

<div class="relative flex flex-col h-screen w-full max-w-md mx-auto bg-background-light dark:bg-background-dark overflow-hidden border-x border-slate-200 dark:border-slate-800" id="chat-container">
    <!-- Top Navigation Bar -->
    <div class="sticky top-0 z-10 flex flex-col bg-background-light/95 dark:bg-background-dark/95 backdrop-blur-md border-b border-slate-200 dark:border-slate-800">
        <div class="flex items-center p-3 pb-1 justify-between gap-3">
            <div class="flex items-center gap-3 flex-1 min-w-0">
                <a href="chats.php" class="text-slate-600 dark:text-slate-400 hover:text-primary transition-colors shrink-0">
                    <span class="material-symbols-outlined">arrow_back</span>
                </a>
                <div class="relative shrink-0">
                    <?php if ($chatPartner['profile_photo']): ?>
                    <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full size-10 border-2 border-primary/20" style="background-image: url('uploads/images/<?php echo htmlspecialchars($chatPartner['profile_photo']); ?>')"></div>
                    <?php else: ?>
                    <div class="size-10 rounded-full bg-primary/10 flex items-center justify-center border-2 border-primary/20">
                        <span class="material-symbols-outlined text-primary">person</span>
                    </div>
                    <?php endif; ?>
                    <div id="online-indicator-<?php echo $chatPartner['id']; ?>" class="absolute bottom-0 right-0 size-2.5 bg-slate-400 rounded-full border-2 border-background-light dark:border-background-dark transition-colors"></div>
                </div>
                <div class="flex flex-col min-w-0">
                    <h2 class="text-slate-900 dark:text-slate-100 text-base font-bold leading-tight tracking-tight truncate"><?php echo htmlspecialchars($chatPartner['name']); ?></h2>
                    <p id="typing-status" class="text-xs font-medium h-4 transition-colors">
                        <span class="online-text text-slate-400">Offline</span>
                    </p>
                </div>
            </div>
            <div class="flex items-center gap-2 text-slate-600 dark:text-slate-400 shrink-0">
                <button onclick="toggleDarkMode()" class="hover:text-primary transition-colors p-1">
                    <span class="material-symbols-outlined" id="darkModeIcon"><?php echo isset($_COOKIE['darkMode']) && $_COOKIE['darkMode'] === 'true' ? 'light_mode' : 'dark_mode'; ?></span>
                </button>
                <button onclick="toggleChatMenu()" class="hover:text-primary transition-colors p-1">
                    <span class="material-symbols-outlined">more_vert</span>
                </button>
            </div>
        </div>
        <div class="h-0.5 w-full bg-gradient-to-r from-transparent via-primary/20 to-transparent"></div>
    </div>

    <!-- Chat Menu Dropdown -->
    <div id="chat-menu" class="hidden absolute top-16 right-4 bg-white dark:bg-slate-800 rounded-xl shadow-lg border border-slate-200 dark:border-slate-700 z-20 py-2 min-w-[180px]">
        <a href="chat-theme.php?user=<?php echo $chatPartner['unique_id']; ?>" class="flex items-center gap-3 px-4 py-2.5 hover:bg-slate-100 dark:hover:bg-slate-700 text-sm">
            <span class="material-symbols-outlined text-slate-500">palette</span>
            Chat Theme
        </a>
        <a href="media-gallery.php?user=<?php echo $chatPartner['unique_id']; ?>" class="flex items-center gap-3 px-4 py-2.5 hover:bg-slate-100 dark:hover:bg-slate-700 text-sm">
            <span class="material-symbols-outlined text-slate-500">photo_library</span>
            Shared Media (<?php echo $sharedMediaCount; ?>)
        </a>
        <button onclick="clearChat()" class="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-slate-100 dark:hover:bg-slate-700 text-sm text-left">
            <span class="material-symbols-outlined text-slate-500">clear_all</span>
            Clear Chat
        </button>
        <div class="border-t border-slate-200 dark:border-slate-700 my-1"></div>
        <button onclick="blockUser()" class="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-slate-100 dark:hover:bg-slate-700 text-sm text-left text-red-500">
            <span class="material-symbols-outlined">block</span>
            Block User
        </button>
    </div>

    <!-- Chat History -->
    <div class="flex-1 overflow-y-auto p-4 space-y-3" id="messages-container" style="background-color: <?php echo $chatTheme['background_color']; ?>; background-image: url('<?php echo $chatTheme['background_image'] ? 'uploads/themes/' . $chatTheme['background_image'] : ''; ?>'); background-size: cover; background-position: center; background-attachment: fixed; background-blend: overlay;">
        <?php if (empty($messages)): ?>
        <div class="flex flex-col items-center justify-center h-full text-center">
            <div class="size-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-4">
                <span class="material-symbols-outlined text-3xl text-slate-400">chat</span>
            </div>
            <p class="text-sm text-slate-500 dark:text-slate-400">Start a conversation with <?php echo htmlspecialchars($chatPartner['name']); ?></p>
        </div>
        <?php else: ?>
            <?php 
            $currentDate = '';
            foreach ($messages as $msg): 
                $msgDate = date('Y-m-d', strtotime($msg['created_at']));
                $showDate = false;
                if ($msgDate !== $currentDate) {
                    $currentDate = $msgDate;
                    $showDate = true;
                }
            ?>
                <?php if ($showDate): ?>
                <div class="flex justify-center my-4">
                    <span class="px-3 py-1 rounded-full bg-slate-200 dark:bg-slate-800 text-[11px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                        <?php echo formatDate($msg['created_at']); ?>
                    </span>
                </div>
                <?php endif; ?>

                <?php if ($msg['sender_id'] == $currentUserId): ?>
                <!-- Sent Message -->
                <div class="flex flex-col items-end gap-0.5 ml-auto max-w-[85%] message-group" data-message-id="<?php echo $msg['id']; ?>">
                    <?php if ($msg['reply_to_id']): ?>
                        <?php 
                        $stmt = $db->prepare("SELECT message, sender_id FROM messages WHERE id = ?");
                        $stmt->execute([$msg['reply_to_id']]);
                        $replyMsg = $stmt->fetch();
                        ?>
                        <div class="bg-slate-200 dark:bg-slate-700 px-3 py-1.5 rounded-t-xl rounded-bl-xl text-xs mb-0.5 border-l-2 border-primary">
                            <p class="text-slate-500 dark:text-slate-400 truncate max-w-[200px]">
                                <?php echo $replyMsg ? htmlspecialchars(substr($replyMsg['message'], 0, 50)) : 'Message deleted'; ?>
                            </p>
                        </div>
                    <?php endif; ?>
                    
                    <div class="message-bubble-sent text-white p-3 rounded-2xl rounded-br-none message-shadow relative group cursor-pointer" onclick="showMessageOptions(<?php echo $msg['id']; ?>)" style="background-color: <?php echo $chatTheme['message_color']; ?>;">
                        <?php if ($msg['is_forwarded']): ?>
                        <p class="text-[10px] opacity-70 mb-1 flex items-center gap-1">
                            <span class="material-symbols-outlined text-[12px]">forward</span> Forwarded
                        </p>
                        <?php endif; ?>
                        
                        <!-- Swipe hint for long press -->
                        <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                            <span class="material-symbols-outlined text-[16px] text-white/50">more_horiz</span>
                        </div>
                        
                        <?php if ($msg['message_type'] === 'image'): ?>
                        <img src="<?php echo htmlspecialchars($msg['file_url']); ?>" class="max-w-full rounded-lg mb-2 cursor-pointer" onclick="openMediaViewer('<?php echo htmlspecialchars($msg['file_url']); ?>', 'image')">
                        <?php if ($msg['message']): ?>
                        <p class="text-[15px] leading-[1.4] font-normal" style="color: white;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                        <?php endif; ?>
                        <?php elseif ($msg['message_type'] === 'video'): ?>
                        <video src="<?php echo htmlspecialchars($msg['file_url']); ?>" controls class="max-w-full rounded-lg mb-2"></video>
                        <?php if ($msg['message']): ?>
                        <p class="text-[15px] leading-[1.4] font-normal" style="color: white;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                        <?php endif; ?>
                        <?php elseif ($msg['message_type'] === 'gif'): ?>
                        <img src="<?php echo htmlspecialchars($msg['file_url']); ?>" class="max-w-full rounded-lg mb-2">
                        <?php elseif ($msg['message_type'] === 'voice'): ?>
                        <div class="flex items-center gap-3">
                            <button onclick="playVoiceMessage(this, '<?php echo htmlspecialchars($msg['file_url']); ?>')" class="size-10 bg-white/20 rounded-full flex items-center justify-center hover:bg-white/30 transition-colors">
                                <span class="material-symbols-outlined text-white">play_arrow</span>
                            </button>
                            <div class="flex-1">
                                <div class="h-8 bg-white/20 rounded-full overflow-hidden">
                                    <div class="h-full bg-white/40 rounded-full" style="width: 30%"></div>
                                </div>
                                <p class="text-xs mt-1 opacity-80">Voice Message</p>
                            </div>
                        </div>
                        <?php else: ?>
                        <p class="text-[15px] leading-[1.4] font-normal" style="color: white;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                        <?php endif; ?>
                    </div>
                    
                    <div class="flex items-center gap-1 mr-1">
                        <span class="text-[10px] text-slate-400"><?php echo formatTime($msg['created_at']); ?></span>
                        <?php if ($msg['read_status'] === 'read'): ?>
                        <span class="material-symbols-outlined text-[14px] text-primary" style="font-variation-settings: 'FILL' 1">done_all</span>
                        <?php elseif ($msg['read_status'] === 'delivered'): ?>
                        <span class="material-symbols-outlined text-[14px] text-slate-400">done_all</span>
                        <?php else: ?>
                        <span class="material-symbols-outlined text-[14px] text-slate-400">done</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php else: ?>
                <!-- Received Message -->
                <div class="flex items-end gap-2 max-w-[85%] message-group" data-message-id="<?php echo $msg['id']; ?>">
                    <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full size-8 shrink-0 mb-1 <?php echo $msg['sender_photo'] ? '' : 'bg-primary/10 flex items-center justify-center'; ?>" style="<?php echo $msg['sender_photo'] ? "background-image: url('uploads/images/" . htmlspecialchars($msg['sender_photo']) . "')" : ''; ?>">
                        <?php if (!$msg['sender_photo']): ?>
                        <span class="material-symbols-outlined text-primary text-sm">person</span>
                        <?php endif; ?>
                    </div>
                    <div class="flex flex-col gap-0.5 w-full">
                        <?php if ($msg['reply_to_id']): ?>
                            <?php 
                            $stmt = $db->prepare("SELECT message FROM messages WHERE id = ?");
                            $stmt->execute([$msg['reply_to_id']]);
                            $replyMsg = $stmt->fetch();
                            ?>
                            <div class="bg-slate-100 dark:bg-slate-700 px-3 py-1.5 rounded-t-xl rounded-br-xl text-xs mb-0.5 border-l-2 border-primary">
                                <p class="text-slate-500 dark:text-slate-400 truncate max-w-[200px]">
                                    <?php echo $replyMsg ? htmlspecialchars(substr($replyMsg['message'], 0, 50)) : 'Message deleted'; ?>
                                </p>
                            </div>
                        <?php endif; ?>
                        
                        <div class="bg-white dark:bg-slate-800 p-3 rounded-2xl rounded-bl-none message-shadow relative group cursor-pointer" onclick="showMessageOptions(<?php echo $msg['id']; ?>, true)" style="color: <?php echo $chatTheme['text_color']; ?>; background-color: rgba(255, 255, 255, 0.9); backdrop-filter: blur(10px);">
                            <?php if ($msg['is_forwarded']): ?>
                            <p class="text-[10px] opacity-70 mb-1 flex items-center gap-1">
                                <span class="material-symbols-outlined text-[12px]">forward</span> Forwarded
                            </p>
                            <?php endif; ?>
                            
                            <?php if ($msg['message_type'] === 'image'): ?>
                            <img src="<?php echo htmlspecialchars($msg['file_url']); ?>" class="max-w-full rounded-lg mb-2 cursor-pointer" onclick="openMediaViewer('<?php echo htmlspecialchars($msg['file_url']); ?>', 'image')">
                            <?php if ($msg['message']): ?>
                            <p class="text-sm leading-relaxed" style="color: <?php echo $chatTheme['text_color']; ?>;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                            <?php endif; ?>
                            <?php elseif ($msg['message_type'] === 'video'): ?>
                            <video src="<?php echo htmlspecialchars($msg['file_url']); ?>" controls class="max-w-full rounded-lg mb-2"></video>
                            <?php if ($msg['message']): ?>
                            <p class="text-sm leading-relaxed" style="color: <?php echo $chatTheme['text_color']; ?>;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                            <?php endif; ?>
                            <?php elseif ($msg['message_type'] === 'gif'): ?>
                            <img src="<?php echo htmlspecialchars($msg['file_url']); ?>" class="max-w-full rounded-lg mb-2">
                            <?php elseif ($msg['message_type'] === 'voice'): ?>
                            <div class="flex items-center gap-3">
                                <button onclick="playVoiceMessage(this, '<?php echo htmlspecialchars($msg['file_url']); ?>')" class="size-10 bg-slate-200 rounded-full flex items-center justify-center hover:bg-slate-300 transition-colors">
                                    <span class="material-symbols-outlined text-slate-700">play_arrow</span>
                                </button>
                                <div class="flex-1">
                                    <div class="h-8 bg-slate-200 rounded-full overflow-hidden">
                                        <div class="h-full bg-slate-400 rounded-full" style="width: 30%"></div>
                                    </div>
                                    <p class="text-xs mt-1 opacity-70">Voice Message</p>
                                </div>
                            </div>
                            <?php else: ?>
                            <p class="text-[15px] leading-[1.4] font-normal" style="color: <?php echo $chatTheme['text_color']; ?>;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></p>
                            <?php endif; ?>
                        </div>
                        <span class="text-[10px] text-slate-400 ml-1"><?php echo formatTime($msg['created_at']); ?></span>
                    </div>
                </div>
                <?php endif; ?>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <!-- Typing Indicator -->
        <div id="typing-indicator" class="hidden flex items-center gap-2 px-2">
            <div class="flex gap-1">
                <div class="size-1.5 bg-slate-400 rounded-full typing-dot"></div>
                <div class="size-1.5 bg-slate-400 rounded-full typing-dot"></div>
                <div class="size-1.5 bg-slate-400 rounded-full typing-dot"></div>
            </div>
            <span class="text-[10px] text-slate-400 italic">typing...</span>
        </div>
    </div>

    <!-- Bottom Input Bar -->
    <div class="p-3 bg-background-light dark:bg-background-dark border-t border-slate-200 dark:border-slate-800">
        <form id="message-form" class="flex items-center gap-2" enctype="multipart/form-data">
            <input type="hidden" name="receiver_id" value="<?php echo $chatPartner['id']; ?>">
            <input type="hidden" name="reply_to" id="reply_to" value="">
            
            <!-- Reply Preview -->
            <div id="reply-preview" class="hidden absolute bottom-20 left-4 right-4 bg-slate-100 dark:bg-slate-800 p-2 rounded-lg border-l-2 border-primary">
                <div class="flex items-center justify-between">
                    <p class="text-xs text-slate-500 truncate flex-1" id="reply-text">Replying to message</p>
                    <button type="button" onclick="cancelReply()" class="text-slate-400 hover:text-slate-600">
                        <span class="material-symbols-outlined text-sm">close</span>
                    </button>
                </div>
            </div>

            <div class="flex flex-1 items-center gap-2 bg-slate-100 dark:bg-slate-800 px-3 py-2 rounded-full border border-slate-200 dark:border-slate-700">
                <button type="button" onclick="toggleEmojiPicker()" class="text-slate-500 dark:text-slate-400 hover:text-primary transition-colors">
                    <span class="material-symbols-outlined">sentiment_satisfied</span>
                </button>
                <input type="text" name="message" id="message-input" class="flex-1 bg-transparent border-none focus:ring-0 text-sm text-slate-900 dark:text-slate-100 placeholder-slate-500 dark:placeholder-slate-400" placeholder="Type a message..." autocomplete="off">
                <button type="button" onclick="toggleGifPicker()" class="text-slate-500 dark:text-slate-400 hover:text-primary transition-colors">
                    <span class="material-symbols-outlined">gif</span>
                </button>
                <button type="button" id="voice-record-btn" onclick="toggleVoiceRecording()" class="text-slate-500 dark:text-slate-400 hover:text-primary transition-colors">
                    <span class="material-symbols-outlined">mic</span>
                </button>
                <label class="text-slate-500 dark:text-slate-400 hover:text-primary transition-colors cursor-pointer">
                    <span class="material-symbols-outlined">attach_file</span>
                    <input type="file" name="attachment" class="hidden" accept="image/*,video/*,.gif" onchange="handleFileSelect(this)">
                </label>
            </div>
            <button type="submit" id="send-btn" class="size-10 flex items-center justify-center bg-primary text-white rounded-full shadow-lg shadow-primary/20 hover:scale-105 transition-transform active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed">
                <span class="material-symbols-outlined translate-x-0.5" style="font-variation-settings: 'FILL' 1">send</span>
            </button>
        </form>
        <div class="h-safe-bottom"></div>
    </div>
</div>

<!-- Voice Recording Modal -->
<div id="voice-recording-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-2xl overflow-hidden slide-up">
        <div class="p-6 text-center">
            <div class="mb-4">
                <div class="size-20 mx-auto bg-red-100 dark:bg-red-900/20 rounded-full flex items-center justify-center animate-pulse">
                    <span class="material-symbols-outlined text-3xl text-red-500">mic</span>
                </div>
            </div>
            <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">Recording...</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400 mb-4">Tap to stop recording</p>
            <div class="flex items-center justify-center gap-2 mb-6">
                <span class="text-2xl font-mono text-slate-700 dark:text-slate-300" id="recording-timer">00:00</span>
                <div class="flex gap-1">
                    <span class="w-1 h-4 bg-red-500 animate-pulse"></span>
                    <span class="w-1 h-6 bg-red-500 animate-pulse" style="animation-delay: 0.1s"></span>
                    <span class="w-1 h-8 bg-red-500 animate-pulse" style="animation-delay: 0.2s"></span>
                    <span class="w-1 h-6 bg-red-500 animate-pulse" style="animation-delay: 0.3s"></span>
                    <span class="w-1 h-4 bg-red-500 animate-pulse" style="animation-delay: 0.4s"></span>
                </div>
            </div>
            <div class="flex gap-3">
                <button onclick="cancelVoiceRecording()" class="flex-1 py-3 bg-slate-100 dark:bg-slate-700 rounded-lg font-medium text-slate-700 dark:text-slate-300">
                    Cancel
                </button>
                <button onclick="stopVoiceRecording()" class="flex-1 py-3 bg-red-500 text-white rounded-lg font-medium hover:bg-red-600 transition-colors">
                    Stop
                </button>
            </div>
<!-- Message Options Modal -->
<div id="message-options" class="hidden fixed inset-0 bg-black/50 z-50 flex items-end sm:items-center justify-center p-4">
    <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-2xl overflow-hidden slide-up">
        <div class="p-4 border-b border-slate-200 dark:border-slate-700">
            <div class="flex items-center gap-3 flex-1">
                <img src="<?php echo $chatPartner['profile_photo'] ? 'uploads/images/' . htmlspecialchars($chatPartner['profile_photo']) : 'assets/images/default-avatar.png'; ?>" 
                     alt="<?php echo htmlspecialchars($chatPartner['name']); ?>" 
                     class="w-10 h-10 rounded-full object-cover border-2 border-white dark:border-slate-700">
                <div>
                    <h2 class="font-semibold text-slate-900 dark:text-slate-100"><?php echo htmlspecialchars($chatPartner['name']); ?></h2>
                    <p class="text-xs text-slate-500 dark:text-slate-400">Online</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <button onclick="showMessageOptions()" class="size-10 rounded-full flex items-center justify-center hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors">
                    <span class="material-symbols-outlined text-slate-600 dark:text-slate-400">more_vert</span>
                </button>
            </div>
        </div>
        <div class="py-2">
            <button onclick="replyToMessage()" class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-100 dark:hover:bg-slate-700 text-left">
                <span class="material-symbols-outlined text-primary">reply</span>
                <span>Reply</span>
            </button>
            <button onclick="copyMessage()" class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-100 dark:hover:bg-slate-700 text-left">
                <span class="material-symbols-outlined text-primary">content_copy</span>
                <span>Copy</span>
            </button>
            <button onclick="forwardMessage()" class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-100 dark:hover:bg-slate-700 text-left">
                <span class="material-symbols-outlined text-primary">forward</span>
                <span>Forward</span>
            </button>
            <button onclick="deleteMessage()" class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-100 dark:hover:bg-slate-700 text-left text-red-500">
                <span class="material-symbols-outlined">delete</span>
                <span>Delete</span>
            </button>
        </div>
        <div class="p-4 border-t border-slate-200 dark:border-slate-700">
            <button onclick="closeMessageOptions()" class="w-full py-2 bg-slate-100 dark:bg-slate-700 rounded-lg font-medium">Cancel</button>
        </div>
    </div>
</div>

<!-- Quick Reply Modal -->
<div id="quick-reply-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-end sm:items-center justify-center p-4">
    <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-2xl overflow-hidden slide-up">
        <div class="p-4 border-b border-slate-200 dark:border-slate-700">
            <div class="flex items-center justify-between">
                <h3 class="font-semibold text-slate-900 dark:text-slate-100">Quick Reply</h3>
                <button onclick="closeQuickReply()" class="text-slate-400 hover:text-slate-600">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
        </div>
        <div class="p-4">
            <!-- Quick Reply Options -->
            <div class="grid grid-cols-2 gap-2 mb-4">
                <button onclick="sendQuickReply('👍')" class="py-3 px-4 bg-green-100 dark:bg-green-900/20 text-green-700 dark:text-green-400 rounded-xl hover:bg-green-200 dark:hover:bg-green-900/30 transition-colors text-sm font-medium">
                    👍 👍
                </button>
                <button onclick="sendQuickReply('❤️')" class="py-3 px-4 bg-red-100 dark:bg-red-900/20 text-red-700 dark:text-red-400 rounded-xl hover:bg-red-200 dark:hover:bg-red-900/30 transition-colors text-sm font-medium">
                    ❤️ ❤️
                </button>
                <button onclick="sendQuickReply('😂')" class="py-3 px-4 bg-yellow-100 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-400 rounded-xl hover:bg-yellow-200 dark:hover:bg-yellow-900/30 transition-colors text-sm font-medium">
                    😂 😂
                </button>
                <button onclick="sendQuickReply('😊')" class="py-3 px-4 bg-blue-100 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 rounded-xl hover:bg-blue-200 dark:hover:bg-blue-900/30 transition-colors text-sm font-medium">
                    😊 😊
                </button>
                <button onclick="sendQuickReply('👏')" class="py-3 px-4 bg-purple-100 dark:bg-purple-900/20 text-purple-700 dark:text-purple-400 rounded-xl hover:bg-purple-200 dark:hover:bg-purple-900/30 transition-colors text-sm font-medium">
                    👏 👏
                </button>
                <button onclick="sendQuickReply('🙏')" class="py-3 px-4 bg-orange-100 dark:bg-orange-900/20 text-orange-700 dark:text-orange-400 rounded-xl hover:bg-orange-200 dark:hover:bg-orange-900/30 transition-colors text-sm font-medium">
                    🙏 🙏
                </button>
            </div>
            
            <!-- Custom Reply Input -->
            <div class="bg-slate-50 dark:bg-slate-700 rounded-xl p-3">
                <input type="text" id="quick-reply-text" placeholder="Type a quick reply..." class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 text-sm focus:outline-none focus:ring-2 focus:ring-primary">
                <div class="flex gap-2 mt-2">
                    <button onclick="sendCustomQuickReply()" class="flex-1 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors">
                        Send
                    </button>
                    <button onclick="closeQuickReply()" class="py-2 px-4 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-lg text-sm font-medium hover:bg-slate-300 dark:hover:bg-slate-600 transition-colors">
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Media Viewer -->
<div id="media-viewer" class="hidden fixed inset-0 bg-black z-50 flex items-center justify-center">
    <button onclick="closeMediaViewer()" class="absolute top-4 right-4 text-white z-10">
        <span class="material-symbols-outlined text-3xl">close</span>
    </button>
    <img id="viewer-image" src="" class="max-w-full max-h-full">
</div>

<script>
    let selectedMessageId = null;
    let selectedMessageText = '';
    let isReceivedMessage = false;
    let lastMessageId = <?php echo !empty($messages) ? end($messages)['id'] : 0; ?>;
    let chatPartnerId = <?php echo $chatPartner['id']; ?>;
    
    // WhatsApp-style time formatting - MUST be defined first
    function formatWhatsAppTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
        } else if (days === 1) {
            return 'Yesterday';
        } else if (days < 7) {
            return date.toLocaleDateString('en-US', { weekday: 'short' });
        } else {
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
        }
    }
    
    // Legacy formatTime function (alias for compatibility)
    function formatTime(timestamp) {
        return formatWhatsAppTime(timestamp);
    }
    
    // Scroll to bottom
    function scrollToBottom() {
        const container = document.getElementById('messages-container');
        container.scrollTop = container.scrollHeight;
    }
    
    // Initial scroll
    scrollToBottom();
    
    // Send message with better handling
    document.getElementById('message-form').addEventListener('submit', function(e) {
        e.preventDefault();
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        const fileInput = this.querySelector('[name="attachment"]');
        const hasFile = fileInput && fileInput.files.length > 0;
        
        if (!message && !hasFile) return;
        
        // Show sending indicator
        const sendBtn = document.getElementById('send-btn');
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<span class="material-symbols-outlined">schedule</span>';
        
        const formData = new FormData(this);
        
        // Add temporary message to UI immediately
        if (message) {
            const tempId = 'temp-' + Date.now();
            const container = document.getElementById('messages-container');
            const emptyState = container.querySelector('.flex-col.items-center');
            if (emptyState) emptyState.remove();
            
            const div = document.createElement('div');
            div.className = 'flex flex-col items-end gap-0.5 ml-auto max-w-[85%] fade-in message-group';
            div.setAttribute('data-message-id', tempId);
            div.innerHTML = `
                <div class="message-bubble-sent text-white p-3 rounded-2xl rounded-br-none message-shadow opacity-70">
                    <p class="text-sm leading-relaxed">${escapeHtml(message)}</p>
                </div>
                <div class="flex items-center gap-1 mr-1 message-status">
                    <span class="text-[10px] text-slate-400">${formatWhatsAppTime(new Date())}</span>
                    <span class="material-symbols-outlined text-[14px] text-slate-400 status-icon">schedule</span>
                </div>
            `;
            container.appendChild(div);
            scrollToBottom();
        }
        
        fetch('api/send-message.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(r => r.json())
        .then(data => {
            sendBtn.disabled = false;
            sendBtn.innerHTML = '<span class="material-symbols-outlined translate-x-0.5" style="font-variation-settings: \'FILL\' 1">send</span>';
            
            if (data.success) {
                input.value = '';
                cancelReply();
                fileInput.value = '';
                
                // Remove temp message and add real one
                const tempMsg = document.querySelector('[data-message-id^="temp-"]');
                if (tempMsg) tempMsg.remove();
                
                addMessageToUI(data.data);
            } else {
                showToast(data.message || 'Failed to send message', 'error');
                // Update temp message to show error
                const tempMsg = document.querySelector('[data-message-id^="temp-"]');
                if (tempMsg) {
                    const statusIcon = tempMsg.querySelector('.status-icon');
                    if (statusIcon) {
                        statusIcon.textContent = 'error';
                        statusIcon.classList.add('text-red-500');
                    }
                }
            }
        })
        .catch(err => {
            sendBtn.disabled = false;
            sendBtn.innerHTML = '<span class="material-symbols-outlined translate-x-0.5" style="font-variation-settings: \'FILL\' 1">send</span>';
            showToast('Network error. Please try again.', 'error');
        });
    });
    
    // Add message to UI immediately after sending
    function addMessageToUI(data) {
        const container = document.getElementById('messages-container');
        const emptyState = container.querySelector('.flex-col.items-center');
        if (emptyState) emptyState.remove();
        
        const div = document.createElement('div');
        div.className = 'flex flex-col items-end gap-0.5 ml-auto max-w-[85%] fade-in message-group';
        div.setAttribute('data-message-id', data.id);
        
        let messageContent = '';
        if (data.message_type === 'gif') {
            messageContent = `<img src="${data.file_url}" alt="GIF" class="max-w-full rounded-lg">`;
        } else if (data.message_type === 'voice') {
            messageContent = `
                <div class="flex items-center gap-3">
                    <button onclick="playVoiceMessage(this, '${data.file_url}')" class="size-10 bg-white/20 rounded-full flex items-center justify-center hover:bg-white/30 transition-colors">
                        <span class="material-symbols-outlined text-white">play_arrow</span>
                    </button>
                    <div class="flex-1">
                        <div class="h-8 bg-white/20 rounded-full overflow-hidden">
                            <div class="h-full bg-white/40 rounded-full" style="width: 30%"></div>
                        </div>
                        <p class="text-xs mt-1 opacity-80">Voice Message</p>
                    </div>
                </div>
            `;
        } else if (data.message_type === 'image') {
            messageContent = `<img src="${data.file_url}" alt="Image" class="max-w-full rounded-lg mb-2"><p class="text-[15px] leading-[1.4] font-normal" style="color: white;">${escapeHtml(data.message)}</p>`;
        } else {
            messageContent = `<p class="text-[15px] leading-[1.4] font-normal" style="color: white;">${escapeHtml(data.message)}</p>`;
        }
        
        div.innerHTML = `
            <div class="message-bubble-sent text-white p-3 rounded-2xl rounded-br-none message-shadow" style="background-color: <?php echo $chatTheme['message_color']; ?>;">
                ${messageContent}
            </div>
            <div class="flex items-center gap-1 mr-1 message-status">
                <span class="text-[10px] text-slate-400">${formatWhatsAppTime(new Date())}</span>
                <span class="material-symbols-outlined text-[14px] text-slate-400 status-icon">done</span>
            </div>
        `;
        container.appendChild(div);
        
        // Scroll to bottom immediately
        scrollToBottom();
        lastMessageId = data.id;
        
        // Update status to delivered after 1 second
        setTimeout(() => {
            const statusIcon = div.querySelector('.status-icon');
            if (statusIcon) {
                statusIcon.textContent = 'done_all';
            }
        }, 1000);
        
        // Update status to read after 2 seconds (if user is viewing)
        setTimeout(() => {
            const statusIcon = div.querySelector('.status-icon');
            if (statusIcon) {
                statusIcon.classList.remove('text-slate-400');
                statusIcon.classList.add('text-primary');
            }
        }, 2000);
    }
    
    // WhatsApp-style time formatting
    function formatWhatsAppTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
        } else if (days === 1) {
            return 'Yesterday';
        } else if (days < 7) {
            return date.toLocaleDateString('en-US', { weekday: 'short' });
        } else {
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
        }
    }
    
    // Legacy formatTime function (alias for compatibility)
    function formatTime(timestamp) {
        return formatWhatsAppTime(timestamp);
    }
    
    // Initial online status check
    updateOnlineStatus();
    
    // Poll for new messages - every 1 second for instant delivery
    setInterval(() => {
        fetch(`api/get-messages.php?user=<?php echo $chatUserId; ?>&last_id=${lastMessageId}`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success && data.data.length > 0) {
                data.data.forEach(msg => {
                    addReceivedMessageToUI(msg);
                });
                scrollToBottom();
                // Play notification sound if window not focused
                if (document.hidden) {
                    showToast('New message from <?php echo htmlspecialchars($chatPartner['name']); ?>', 'info');
                }
            }
        })
        .catch(err => console.error('Error fetching messages:', err));
        
        // Check online status
        updateOnlineStatus();
    }, 1000);
    
    function addReceivedMessageToUI(msg) {
        const container = document.getElementById('messages-container');
        const div = document.createElement('div');
        div.className = 'flex items-end gap-2 max-w-[85%] fade-in';
        
        let messageContent = '';
        if (msg.message_type === 'gif') {
            messageContent = `<img src="${msg.file_url}" alt="GIF" class="max-w-full rounded-lg mb-2">`;
        } else if (msg.message_type === 'voice') {
            messageContent = `
                <div class="flex items-center gap-3">
                    <button onclick="playVoiceMessage(this, '${msg.file_url}')" class="size-10 bg-slate-200 rounded-full flex items-center justify-center hover:bg-slate-300 transition-colors">
                        <span class="material-symbols-outlined text-slate-700">play_arrow</span>
                    </button>
                    <div class="flex-1">
                        <div class="h-8 bg-slate-200 rounded-full overflow-hidden">
                            <div class="h-full bg-slate-400 rounded-full" style="width: 30%"></div>
                        </div>
                        <p class="text-xs mt-1 opacity-70">Voice Message</p>
                    </div>
                </div>
            `;
        } else if (msg.message_type === 'image') {
            messageContent = `<img src="${msg.file_url}" alt="Image" class="max-w-full rounded-lg mb-2 cursor-pointer" onclick="openMediaViewer('${msg.file_url}', 'image')"><p class="text-[15px] leading-[1.4] font-normal" style="color: <?php echo $chatTheme['text_color']; ?>;">${escapeHtml(msg.message)}</p>`;
        } else {
            messageContent = `<p class="text-[15px] leading-[1.4] font-normal" style="color: <?php echo $chatTheme['text_color']; ?>;">${escapeHtml(msg.message)}</p>`;
        }
        
        // WhatsApp-style status icons
        let statusIcon = '<span class="material-symbols-outlined text-[14px] text-slate-400">done</span>';
        if (msg.read_status === 'delivered') {
            statusIcon = '<span class="material-symbols-outlined text-[14px] text-slate-400">done_all</span>';
        } else if (msg.read_status === 'read') {
            statusIcon = '<span class="material-symbols-outlined text-[14px] text-primary" style="font-variation-settings: \'FILL\' 1">done_all</span>';
        }
        
        div.innerHTML = `
            <div class="bg-center bg-no-repeat aspect-square bg-cover rounded-full size-8 shrink-0 mb-1 ${msg.sender_photo ? '' : 'bg-primary/10 flex items-center justify-center'}" style="${msg.sender_photo ? `background-image: url('uploads/images/${msg.sender_photo}')` : ''}">
                        ${msg.sender_photo ? '' : '<span class="material-symbols-outlined text-primary text-sm">person</span>'}
                    </div>
            <div class="flex flex-col gap-0.5 w-full">
                <div class="bg-white dark:bg-slate-800 p-3 rounded-2xl rounded-bl-none message-shadow" style="color: <?php echo $chatTheme['text_color']; ?>;">
                    ${messageContent}
                </div>
                <div class="flex items-center gap-1 ml-1">
                    <span class="text-[10px] text-slate-400">${formatTime(msg.created_at)}</span>
                    ${statusIcon}
                </div>
            </div>
        `;
        container.appendChild(div);
        lastMessageId = msg.id;
        
        // Update status to delivered after 1 second
        setTimeout(() => {
            const statusElement = div.querySelector('.material-symbols-outlined.text-slate-400');
            if (statusElement && msg.read_status === 'sent') {
                statusElement.textContent = 'done_all';
            }
        }, 1000);
    }
    
    // Typing indicator
    let typingTimeout;
    const messageInput = document.getElementById('message-input');
    messageInput.addEventListener('input', () => {
        clearTimeout(typingTimeout);
        fetch('api/typing.php', {
            method: 'POST',
            body: JSON.stringify({ user_id: chatPartnerId, typing: true }),
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
        });
        
        typingTimeout = setTimeout(() => {
            fetch('api/typing.php', {
                method: 'POST',
                body: JSON.stringify({ user_id: chatPartnerId, typing: false }),
                headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            });
        }, 2000);
    });
    
    // Update online status
    function updateOnlineStatus() {
        fetch(`api/user-status.php?user=${chatPartnerId}`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const indicator = document.getElementById(`online-indicator-${chatPartnerId}`);
                const statusText = document.querySelector('#typing-status .online-text');
                
                // Update status text
                const typingStatus = document.getElementById('typing-status');
                
                if (data.data.is_typing) {
                    indicator.classList.remove('bg-slate-400', 'bg-green-500');
                    indicator.classList.add('bg-primary', 'animate-pulse');
                    typingStatus.innerHTML = '<span class="text-primary italic">typing...</span>';
                    document.getElementById('typing-indicator').classList.remove('hidden');
                    scrollToBottom();
                } else if (data.data.is_online) {
                    indicator.classList.remove('bg-slate-400', 'bg-primary', 'animate-pulse');
                    indicator.classList.add('bg-green-500');
                    typingStatus.innerHTML = '<span class="text-green-500 online-text">Online</span>';
                    document.getElementById('typing-indicator').classList.add('hidden');
                } else {
                    indicator.classList.remove('bg-green-500', 'bg-primary', 'animate-pulse');
                    indicator.classList.add('bg-slate-400');
                    if (data.data.last_seen) {
                        typingStatus.innerHTML = '<span class="text-slate-400 online-text">Last seen ' + formatWhatsAppTime(data.data.last_seen) + '</span>';
                    } else {
                        typingStatus.innerHTML = '<span class="text-slate-400 online-text">Offline</span>';
                    }
                    document.getElementById('typing-indicator').classList.add('hidden');
                }
            }
        });
    }
    
    // Message options
    function showMessageOptions(msgId, isReceived = false) {
        selectedMessageId = msgId;
        isReceivedMessage = isReceived;
        document.getElementById('message-options').classList.remove('hidden');
    }
    
    function closeMessageOptions() {
        document.getElementById('message-options').classList.add('hidden');
        selectedMessageId = null;
    }
    
    function replyToMessage() {
        document.getElementById('reply_to').value = selectedMessageId;
        document.getElementById('reply-preview').classList.remove('hidden');
        document.getElementById('reply-text').textContent = 'Replying to message';
        document.getElementById('message-input').focus();
        closeMessageOptions();
    }
    
    function cancelReply() {
        document.getElementById('reply_to').value = '';
        document.getElementById('reply-preview').classList.add('hidden');
    }
    
    function copyMessage() {
        if (selectedMessageText) {
            navigator.clipboard.writeText(selectedMessageText);
            showToast('Message copied', 'success');
        }
        closeMessageOptions();
    }
    
    function forwardMessage() {
        // Implementation for forwarding
        showToast('Forward feature coming soon', 'info');
        closeMessageOptions();
    }
    
    function deleteMessage() {
        if (!confirm('Delete this message?')) return;
        
        fetch('api/delete-message.php', {
            method: 'POST',
            body: JSON.stringify({ message_id: selectedMessageId, for_all: false }),
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.querySelector(`[data-message-id="${selectedMessageId}"]`).remove();
                showToast('Message deleted', 'success');
            }
        });
        closeMessageOptions();
    }
    
    // Chat menu
    function toggleChatMenu() {
        const menu = document.getElementById('chat-menu');
        menu.classList.toggle('hidden');
    }
    
    function clearChat() {
        if (!confirm('Clear this chat? Messages will only be cleared on your side.')) return;
        
        fetch('api/clear-chat.php', {
            method: 'POST',
            body: JSON.stringify({ user_id: chatPartnerId }),
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.getElementById('messages-container').innerHTML = `
                    <div class="flex flex-col items-center justify-center h-full text-center">
                        <div class="size-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-4">
                            <span class="material-symbols-outlined text-3xl text-slate-400">chat</span>
                        </div>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Chat cleared</p>
                    </div>
                `;
                showToast('Chat cleared successfully', 'success');
            }
        });
        toggleChatMenu();
    }
    
    function blockUser() {
        showToast('Block feature coming soon', 'info');
        toggleChatMenu();
    }
    
    // Media viewer
    function openMediaViewer(url, type) {
        event.stopPropagation();
        if (type === 'image') {
            document.getElementById('viewer-image').src = url;
            document.getElementById('media-viewer').classList.remove('hidden');
        }
    }
    
    function closeMediaViewer() {
        document.getElementById('media-viewer').classList.add('hidden');
    }
    
    function handleFileSelect(input) {
        if (input.files.length > 0) {
            document.getElementById('message-input').placeholder = `File: ${input.files[0].name}`;
        }
    }
    
    // Emoji Picker
    function toggleEmojiPicker() {
        const existingPicker = document.getElementById('emoji-picker');
        if (existingPicker) {
            existingPicker.remove();
            return;
        }
        
        const emojis = ['😀', '😂', '🥰', '😍', '🤔', '😢', '😡', '👍', '👎', '❤️', '🎉', '🔥', '👏', '🙏', '💯', '😊', '😭', '😅', '🤣', '😘', '🤗', '🤩', '😎', '🥳', '😴', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '🤯', '🤠', '🥳', '😎', '🤓', '🧐', '😕', '😟', '🙁', '☹️', '😮', '😯', '😲', '😳', '🥺', '😦', '😧', '😨', '😰', '😥', '😢', '😭', '😱', '😖', '😣', '😞', '😓', '😩', '😫', '🥱', '😤', '😡', '😠', '🤬', '😈', '👿', '💀', '☠️', '💩', '🤡', '👹', '👺', '👻', '👽', '👾', '🤖', '🎃', '😺', '😸', '😹', '😻', '😼', '😽', '🙀', '😿', '😾'];
        
        const picker = document.createElement('div');
        picker.id = 'emoji-picker';
        picker.className = 'absolute bottom-20 left-4 right-4 bg-white dark:bg-slate-800 rounded-2xl shadow-lg border border-slate-200 dark:border-slate-700 p-3 z-50 max-h-48 overflow-y-auto';
        
        let emojiHTML = '<div class="grid grid-cols-8 gap-2">';
        emojis.forEach(emoji => {
            emojiHTML += `<button type="button" class="text-2xl hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg p-1 transition-colors" onclick="insertEmoji('${emoji}')">${emoji}</button>`;
        });
        emojiHTML += '</div>';
        
        picker.innerHTML = emojiHTML;
        document.getElementById('chat-container').appendChild(picker);
    }
    
    function insertEmoji(emoji) {
        const input = document.getElementById('message-input');
        input.value += emoji;
        input.focus();
    }
    
    // GIF Picker functionality
    function toggleGifPicker() {
        const existingPicker = document.getElementById('gif-picker');
        if (existingPicker) {
            existingPicker.remove();
            return;
        }
        
        const picker = document.createElement('div');
        picker.id = 'gif-picker';
        picker.className = 'absolute bottom-20 left-4 right-4 bg-white dark:bg-slate-800 rounded-xl shadow-lg border border-slate-200 dark:border-slate-700 z-30 p-4 max-h-80 overflow-y-auto';
        picker.innerHTML = `
            <div class="flex items-center justify-between mb-3">
                <h3 class="font-semibold text-slate-900 dark:text-slate-100">Search GIFs</h3>
                <button onclick="this.parentElement.parentElement.remove()" class="text-slate-400 hover:text-slate-600">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <div class="relative mb-3">
                <input type="text" id="gif-search" placeholder="Search GIFs..." class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 pr-10">
                <button onclick="searchGifs()" class="absolute right-2 top-1/2 transform -translate-y-1/2 text-primary">
                    <span class="material-symbols-outlined">search</span>
                </button>
            </div>
            <div class="mb-3">
                <p class="text-xs text-slate-500 dark:text-slate-400 mb-2">Trending:</p>
                <div class="flex flex-wrap gap-2">
                    <button onclick="quickSearch('buggu love')" class="px-3 py-1 bg-red-100 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-full text-xs hover:bg-red-200 dark:hover:bg-red-900/30 transition-colors">💕 Buggu Love</button>
                    <button onclick="quickSearch('buggu romantic')" class="px-3 py-1 bg-pink-100 dark:bg-pink-900/20 text-pink-600 dark:text-pink-400 rounded-full text-xs hover:bg-pink-200 dark:hover:bg-pink-900/30 transition-colors">🌹 Buggu Romantic</button>
                    <button onclick="quickSearch('buggu kiss')" class="px-3 py-1 bg-orange-100 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 rounded-full text-xs hover:bg-orange-200 dark:hover:bg-orange-900/30 transition-colors">😘 Buggu Kiss</button>
                    <button onclick="quickSearch('buggu hug')" class="px-3 py-1 bg-purple-100 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-full text-xs hover:bg-purple-200 dark:hover:bg-purple-900/30 transition-colors">🤗 Buggu Hug</button>
                    <button onclick="quickSearch('buggu i love you')" class="px-3 py-1 bg-red-100 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-full text-xs hover:bg-red-200 dark:hover:bg-red-900/30 transition-colors">❤️ Buggu I Love You</button>
                    <button onclick="quickSearch('buggu good morning')" class="px-3 py-1 bg-yellow-100 dark:bg-yellow-900/20 text-yellow-600 dark:text-yellow-400 rounded-full text-xs hover:bg-yellow-200 dark:hover:bg-yellow-900/30 transition-colors">☀️ Buggu Good Morning</button>
                    <button onclick="quickSearch('buggu good night')" class="px-3 py-1 bg-indigo-100 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 rounded-full text-xs hover:bg-indigo-200 dark:hover:bg-indigo-900/30 transition-colors">🌙 Buggu Good Night</button>
                    <button onclick="quickSearch('love')" class="px-3 py-1 bg-red-100 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-full text-xs hover:bg-red-200 dark:hover:bg-red-900/30 transition-colors">� Love</button>
                    <button onclick="quickSearch('romantic')" class="px-3 py-1 bg-pink-100 dark:bg-pink-900/20 text-pink-600 dark:text-pink-400 rounded-full text-xs hover:bg-pink-200 dark:hover:bg-pink-900/30 transition-colors">🌹 Romantic</button>
                    <button onclick="quickSearch('funny')" class="px-3 py-1 bg-blue-100 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 rounded-full text-xs hover:bg-blue-200 dark:hover:bg-blue-900/30 transition-colors">😂 Funny</button>
                </div>
            </div>
            <div id="gif-results" class="grid grid-cols-3 gap-2">
                <div class="text-center text-slate-500 col-span-3 py-4">
                    <span class="material-symbols-outlined text-2xl">search</span>
                    <p class="text-sm mt-1">Search for GIFs</p>
                </div>
            </div>
        `;
        
        document.body.appendChild(picker);
        document.getElementById('gif-search').focus();
        
        // Auto-search on input (after 3 characters)
        let searchTimeout;
        document.getElementById('gif-search').addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            const query = e.target.value.trim();
            if (query.length >= 3) {
                searchTimeout = setTimeout(() => searchGifs(), 500);
            }
        });
        
        // Search on Enter
        document.getElementById('gif-search').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') searchGifs();
        });
        
        // Load trending GIFs initially
        loadTrendingGifs();
    }
    
    function quickSearch(query) {
        document.getElementById('gif-search').value = query;
        searchGifs();
    }
    
    function loadTrendingGifs() {
        const resultsDiv = document.getElementById('gif-results');
        resultsDiv.innerHTML = `
            <div class="text-center text-slate-500 col-span-3 py-4">
                <span class="material-symbols-outlined animate-spin">refresh</span>
                <p class="text-sm mt-1">Loading trending GIFs...</p>
            </div>
        `;
        
        // Load trending GIFs
        fetch(`https://api.giphy.com/v1/gifs/trending?api_key=GlVGYHkr3WSBnllca54iNt0yFbjz7L65&limit=9&rating=g`)
            .then(r => r.json())
            .then(data => {
                if (data.data && data.data.length > 0) {
                    resultsDiv.innerHTML = data.data.map(gif => `
                        <img src="${gif.images.fixed_height.url}" 
                             alt="${gif.title}" 
                             class="w-full h-24 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity"
                             onclick="selectGif('${gif.images.fixed_height.url}', '${gif.title}')">
                    `).join('');
                } else {
                    resultsDiv.innerHTML = `
                        <div class="text-center text-slate-500 col-span-3 py-4">
                            <span class="material-symbols-outlined text-2xl">search_off</span>
                            <p class="text-sm mt-1">No GIFs found</p>
                        </div>
                    `;
                }
            })
            .catch(err => {
                console.error('Trending GIFs error:', err);
                resultsDiv.innerHTML = `
                    <div class="text-center text-slate-500 col-span-3 py-4">
                        <span class="material-symbols-outlined text-2xl">error</span>
                        <p class="text-sm mt-1">Failed to load GIFs</p>
                    </div>
                `;
            });
    }
    
    function searchGifs() {
        const query = document.getElementById('gif-search').value.trim();
        const resultsDiv = document.getElementById('gif-results');
        
        if (!query) {
            loadTrendingGifs();
            return;
        }
        
        resultsDiv.innerHTML = `
            <div class="text-center text-slate-500 col-span-3 py-4">
                <span class="material-symbols-outlined animate-spin">refresh</span>
                <p class="text-sm mt-1">Searching...</p>
            </div>
        `;
        
        // Using Giphy API
        fetch(`https://api.giphy.com/v1/gifs/search?api_key=GlVGYHkr3WSBnllca54iNt0yFbjz7L65&q=${encodeURIComponent(query)}&limit=9&rating=g`)
            .then(r => r.json())
            .then(data => {
                if (data.data && data.data.length > 0) {
                    resultsDiv.innerHTML = data.data.map(gif => `
                        <img src="${gif.images.fixed_height.url}" 
                             alt="${gif.title}" 
                             class="w-full h-24 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity"
                             onclick="selectGif('${gif.images.fixed_height.url}', '${gif.title}')">
                    `).join('');
                } else {
                    resultsDiv.innerHTML = `
                        <div class="text-center text-slate-500 col-span-3 py-4">
                            <span class="material-symbols-outlined text-2xl">search_off</span>
                            <p class="text-sm mt-1">No GIFs found</p>
                        </div>
                    `;
                }
            })
            .catch(err => {
                console.error('GIF search error:', err);
                resultsDiv.innerHTML = `
                    <div class="text-center text-slate-500 col-span-3 py-4">
                        <span class="material-symbols-outlined text-2xl">error</span>
                        <p class="text-sm mt-1">Failed to load GIFs</p>
                    </div>
                `;
            });
    }
    
    function selectGif(url, title) {
        const input = document.getElementById('message-input');
        document.getElementById('gif-picker').remove();
        input.focus();
        
        // Auto-send the GIF
        const formData = new FormData();
        formData.append('receiver_id', <?php echo $chatPartner['id']; ?>);
        formData.append('message', '[GIF]');
        formData.append('gif_url', url);
        
        fetch('api/send-message.php', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                addMessageToUI({
                    id: data.data.id,
                    message: '',
                    message_type: 'gif',
                    file_url: url,
                    created_at: new Date().toISOString()
                });
            } else {
                showToast('Failed to send GIF', 'error');
            }
        });
    }
    
    // Voice Recording functionality
    let mediaRecorder;
    let audioChunks;
    let recordingStartTime;
    let recordingTimer;
    
    function toggleVoiceRecording() {
        const modal = document.getElementById('voice-recording-modal');
        if (modal.classList.contains('hidden')) {
            startVoiceRecording();
        } else {
            stopVoiceRecording();
        }
    }
    
    async function startVoiceRecording() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            mediaRecorder = new MediaRecorder(stream);
            audioChunks = [];
            
            mediaRecorder.ondataavailable = (event) => {
                audioChunks.push(event.data);
            };
            
            mediaRecorder.onstop = () => {
                const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                sendVoiceMessage(audioBlob);
                stream.getTracks().forEach(track => track.stop());
            };
            
            mediaRecorder.start();
            recordingStartTime = Date.now();
            
            // Show modal
            document.getElementById('voice-recording-modal').classList.remove('hidden');
            
            // Update timer
            updateRecordingTimer();
            recordingTimer = setInterval(updateRecordingTimer, 1000);
            
            // Update button
            document.getElementById('voice-record-btn').classList.add('text-red-500');
            
        } catch (err) {
            console.error('Error accessing microphone:', err);
            showToast('Microphone access denied', 'error');
        }
    }
    
    function updateRecordingTimer() {
        const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
        const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
        const seconds = (elapsed % 60).toString().padStart(2, '0');
        document.getElementById('recording-timer').textContent = `${minutes}:${seconds}`;
    }
    
    function stopVoiceRecording() {
        if (mediaRecorder && mediaRecorder.state !== 'inactive') {
            mediaRecorder.stop();
        }
        
        clearInterval(recordingTimer);
        document.getElementById('voice-recording-modal').classList.add('hidden');
        document.getElementById('voice-record-btn').classList.remove('text-red-500');
    }
    
    function cancelVoiceRecording() {
        if (mediaRecorder && mediaRecorder.state !== 'inactive') {
            mediaRecorder.stop();
        }
        
        clearInterval(recordingTimer);
        document.getElementById('voice-recording-modal').classList.add('hidden');
        document.getElementById('voice-record-btn').classList.remove('text-red-500');
        document.getElementById('recording-timer').textContent = '00:00';
    }
    
    function sendVoiceMessage(audioBlob) {
        const formData = new FormData();
        formData.append('receiver_id', <?php echo $chatPartner['id']; ?>);
        formData.append('message', '[Voice Message]');
        formData.append('voice_message', audioBlob, 'voice.webm');
        
        fetch('api/send-message.php', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                addMessageToUI({
                    id: data.data.id,
                    message: '[Voice Message]',
                    message_type: 'voice',
                    file_url: data.data.file_url,
                    created_at: new Date().toISOString()
                });
            } else {
                showToast('Failed to send voice message', 'error');
            }
        })
        .catch(err => {
            console.error('Voice message error:', err);
            showToast('Failed to send voice message', 'error');
        });
    }
    
    // Voice message player
    function playVoiceMessage(button, audioUrl) {
        const isPlaying = button.classList.contains('playing');
        
        // Stop all other voice messages
        document.querySelectorAll('.voice-play-btn').forEach(btn => {
            if (btn !== button) {
                btn.classList.remove('playing');
                btn.querySelector('.material-symbols-outlined').textContent = 'play_arrow';
                const audio = btn.parentElement.querySelector('audio');
                if (audio) {
                    audio.pause();
                    audio.remove();
                }
            }
        });
        
        if (!isPlaying) {
            // Create audio element
            const audio = new Audio(audioUrl);
            audio.className = 'hidden';
            button.parentElement.appendChild(audio);
            
            // Update button
            button.classList.add('playing', 'voice-play-btn');
            button.querySelector('.material-symbols-outlined').textContent = 'pause';
            
            // Play audio
            audio.play().catch(err => {
                console.error('Audio play error:', err);
                button.classList.remove('playing');
                button.querySelector('.material-symbols-outlined').textContent = 'play_arrow';
                showToast('Failed to play voice message', 'error');
                audio.remove();
            });
            
            // Update progress bar
            const progressBar = button.parentElement.querySelector('.bg-white\\/40, .bg-slate-400');
            
            audio.addEventListener('timeupdate', () => {
                const progress = (audio.currentTime / audio.duration) * 100;
                if (progressBar) {
                    progressBar.style.width = progress + '%';
                }
            });
            
            audio.addEventListener('ended', () => {
                button.classList.remove('playing');
                button.querySelector('.material-symbols-outlined').textContent = 'play_arrow';
                if (progressBar) {
                    progressBar.style.width = '0%';
                }
                audio.remove();
            });
            
            audio.addEventListener('error', () => {
                button.classList.remove('playing');
                button.querySelector('.material-symbols-outlined').textContent = 'play_arrow';
                showToast('Failed to play voice message', 'error');
                audio.remove();
            });
        } else {
            // Pause audio
            const audio = button.parentElement.querySelector('audio');
            if (audio) {
                audio.pause();
                audio.remove();
            }
            button.classList.remove('playing');
            button.querySelector('.material-symbols-outlined').textContent = 'play_arrow';
        }
    }
    
    // Quick Reply functions
    function showQuickReply() {
        document.getElementById('quick-reply-modal').classList.remove('hidden');
        document.getElementById('quick-reply-text').focus();
    }
    
    function closeQuickReply() {
        document.getElementById('quick-reply-modal').classList.add('hidden');
    }
    
    function sendQuickReply(emoji) {
        const input = document.getElementById('message-input');
        input.value = emoji;
        
        // Trigger form submit
        const form = document.getElementById('message-form');
        const formData = new FormData(form);
        
        fetch('api/send-message.php', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                input.value = '';
                addMessageToUI(data.data);
                closeQuickReply();
            } else {
                showToast('Failed to send message', 'error');
            }
        });
    }
    
    function sendCustomQuickReply() {
        const input = document.getElementById('message-input');
        const quickReplyText = document.getElementById('quick-reply-text');
        
        if (quickReplyText.value.trim()) {
            input.value = quickReplyText.value;
            closeQuickReply();
            
            // Trigger form submit
            const form = document.getElementById('message-form');
            const formData = new FormData(form);
            
            fetch('api/send-message.php', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    input.value = '';
                    addMessageToUI(data.data);
                    quickReplyText.value = '';
                } else {
                    showToast('Failed to send message', 'error');
                }
            });
        }
    }
    
    // WhatsApp-style long press and swipe functionality
    let touchStartX = 0;
    let touchStartY = 0;
    let touchEndX = 0;
    let touchEndY = 0;
    let longPressTimer;
    let isLongPress = false;
    
    // Add touch event listeners to all message bubbles
    document.addEventListener('DOMContentLoaded', function() {
        const messageBubbles = document.querySelectorAll('.message-bubble-sent');
        messageBubbles.forEach(bubble => {
            bubble.addEventListener('touchstart', handleTouchStart, { passive: false });
            bubble.addEventListener('touchmove', handleTouchMove, { passive: false });
            bubble.addEventListener('touchend', handleTouchEnd, { passive: false });
            bubble.addEventListener('mousedown', handleMouseDown);
            bubble.addEventListener('mouseup', handleMouseUp);
        });
    });
    
    function handleTouchStart(e) {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
        isLongPress = false;
        
        // Start long press timer
        longPressTimer = setTimeout(() => {
            isLongPress = true;
            showQuickReply();
        }, 500);
    }
    
    function handleTouchMove(e) {
        touchEndX = e.touches[0].clientX;
        touchEndY = e.touches[0].clientY;
        
        // Clear long press timer if moved too much
        if (Math.abs(touchEndX - touchStartX) > 10 || Math.abs(touchEndY - touchStartY) > 10) {
            clearTimeout(longPressTimer);
        }
    }
    
    function handleTouchEnd(e) {
        touchEndX = e.changedTouches[0].clientX;
        touchEndY = e.changedTouches[0].clientY;
        
        clearTimeout(longPressTimer);
        
        // Check for swipe left (quick reply)
        if (!isLongPress && touchStartX - touchEndX > 50 && Math.abs(touchEndY - touchStartY) < 30) {
            showQuickReply();
        }
    }
    
    function handleMouseDown(e) {
        touchStartX = e.clientX;
        touchStartY = e.clientY;
        isLongPress = false;
        
        // Start long press timer
        longPressTimer = setTimeout(() => {
            isLongPress = true;
            showQuickReply();
        }, 500);
    }
    
    function handleMouseUp(e) {
        clearTimeout(longPressTimer);
    }
    
    // Auto-logout checker - runs every 30 seconds
function checkAutoLogout() {
    fetch('api/user-status.php')
        .then(response => response.json())
        .then(data => {
            if (!data.success && data.logged_out) {
                // Show logout message
                showToast(data.message || 'You have been logged out due to inactivity', 'warning');
                
                // Clear any ongoing operations
                if (window.typingTimeout) {
                    clearTimeout(window.typingTimeout);
                }
                
                // Redirect to login page after 2 seconds
                setTimeout(() => {
                    window.location.href = data.redirect_to || 'login.php';
                }, 2000);
            } else if (data.success) {
                // Update UI with current status
                updateOnlineStatus(data.current_user_status);
            }
        })
        .catch(error => {
            console.error('Error checking user status:', error);
            // Fallback: check after 1 minute if API fails
            setTimeout(checkAutoLogout, 60000);
        });
}

// Update online status in UI
function updateOnlineStatus(status) {
    const statusElement = document.getElementById('typing-status');
    const onlineText = document.querySelector('.online-text');
    
    if (statusElement && onlineText) {
        if (status === 'online') {
            onlineText.textContent = 'Online';
            onlineText.className = 'online-text text-slate-400';
            onlineText.style.color = '#10b981';
        } else if (status === 'away') {
            onlineText.textContent = 'Away';
            onlineText.className = 'online-text text-slate-400';
            onlineText.style.color = '#f59e0b';
        } else {
            onlineText.textContent = 'Offline';
            onlineText.className = 'online-text text-slate-400';
            onlineText.style.color = '#6b7280';
        }
    }
}

// Auto-logout checker - runs every 30 seconds
setInterval(checkAutoLogout, 30000);

// Check on page load
document.addEventListener('DOMContentLoaded', function() {
    checkAutoLogout();
});

// Update user activity on any interaction
document.addEventListener('mousemove', function() {
    // Throttle activity updates to avoid too many API calls
    if (!window.lastActivityUpdate || Date.now() - window.lastActivityUpdate > 30000) {
        fetch('api/user-status.php')
            .then(response => response.json())
            .catch(error => console.log('Activity update failed:', error));
        window.lastActivityUpdate = Date.now();
    }
});

// Update activity on keypress (typing)
document.addEventListener('keydown', function() {
    if (!window.lastActivityUpdate || Date.now() - window.lastActivityUpdate > 30000) {
        fetch('api/user-status.php')
            .then(response => response.json())
            .catch(error => console.log('Activity update failed:', error));
        window.lastActivityUpdate = Date.now();
    }
});

// Update activity on scroll
window.addEventListener('scroll', function() {
    if (!window.lastActivityUpdate || Date.now() - window.lastActivityUpdate > 30000) {
        fetch('api/user-status.php')
            .then(response => response.json())
            .catch(error => console.log('Activity update failed:', error));
        window.lastActivityUpdate = Date.now();
    }
});

document.addEventListener('click', (e) => {
    const picker = document.getElementById('emoji-picker');
    if (picker && !e.target.closest('#emoji-picker') && !e.target.closest('[onclick="toggleEmojiPicker()"]')) {
        picker.remove();
    }
    
    const gifPicker = document.getElementById('gif-picker');
    if (gifPicker && !e.target.closest('#gif-picker') && !e.target.closest('[onclick="toggleGifPicker()"]')) {
        gifPicker.remove();
    }
});

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Click outside to close menu
document.addEventListener('click', (e) => {
    if (!e.target.closest('#chat-menu') && !e.target.closest('[onclick="toggleChatMenu()"]')) {
        document.getElementById('chat-menu').classList.add('hidden');
    }
});
</script>

<?php
function formatDate($timestamp) {
    $date = new DateTime($timestamp);
    $now = new DateTime();
    $diff = $now->diff($date);
    
    if ($diff->days === 0) {
        return 'Today';
    } elseif ($diff->days === 1) {
        return 'Yesterday';
    } else {
        return $date->format('F j, Y');
    }
}
?>

<?php include 'includes/footer.php'; ?>
