

<?php $__env->startSection('content'); ?>
<div class="admin-chat-wrapper">
<div class="admin-chat-container">
    <!-- Left Sidebar - User List -->
    <div class="admin-chat-sidebar">
        <div class="admin-chat-sidebar-header">
            <h3><?php echo e(__('admin.support.support_tickets')); ?></h3>
            <div class="admin-chat-search">
                <input type="text" id="searchTickets" placeholder="<?php echo e(__('admin.support.search_by_id_placeholder')); ?>" class="form-control">
            </div>
        </div>
        <div class="admin-chat-user-list" id="ticketList">
            <?php $__empty_1 = true; $__currentLoopData = $tickets; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ticket): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <div class="admin-chat-user-item <?php echo e($selectedTicket && $selectedTicket->id === $ticket->id ? 'active' : ''); ?>" 
                     data-ticket-id="<?php echo e($ticket->id); ?>"
                     onclick="loadTicket(<?php echo e($ticket->id); ?>)">
                    <div class="admin-chat-user-avatar">
                        <?php echo e(strtoupper(substr(($ticket->user && $ticket->user->id) ? $ticket->user->id : 'U', 0, 2))); ?>

                    </div>
                    <div class="admin-chat-user-info">
                        <div class="admin-chat-user-name">
                            <?php echo e(__('admin.support.user_id')); ?>: <?php echo e(($ticket->user && $ticket->user->id) ? $ticket->user->id : 'N/A'); ?>

                        </div>
                        <div class="admin-chat-user-status">
                            <span class="status-badge status-<?php echo e($ticket->status); ?>"><?php echo e(__('admin.support.' . $ticket->status)); ?></span>
                        </div>
                    </div>
                    <?php if($ticket->unread_count > 0): ?>
                        <div class="admin-chat-unread-badge"><?php echo e($ticket->unread_count); ?></div>
                    <?php endif; ?>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <div class="admin-chat-empty"><?php echo e(__('admin.support.no_tickets_found')); ?></div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right Side - Chat Area -->
    <div class="admin-chat-main" id="chatMainArea">
        <!-- Placeholder (shown when no ticket selected) -->
        <div class="admin-chat-placeholder" id="chatPlaceholder" style="display: <?php echo e($selectedTicket ? 'none' : 'flex'); ?>;">
            <div class="admin-chat-placeholder-icon">💬</div>
            <div class="admin-chat-placeholder-text"><?php echo e(__('admin.support.select_ticket')); ?></div>
        </div>

        <!-- Chat Area (hidden when no ticket selected) -->
        <div id="chatArea" style="display: <?php echo e($selectedTicket ? 'flex' : 'none'); ?>; flex-direction: column; height: 100%;">
            <div class="admin-chat-header" id="chatHeader">
                <div class="admin-chat-header-info" id="chatHeaderInfo">
                    <?php if($selectedTicket): ?>
                    <div class="admin-chat-header-avatar">
                        <?php echo e(strtoupper(substr(($selectedTicket->user && $selectedTicket->user->id) ? $selectedTicket->user->id : 'U', 0, 2))); ?>

                    </div>
                    <div>
                        <div class="admin-chat-header-name">
                            <?php echo e(__('admin.support.user_id')); ?>: <?php echo e(($selectedTicket->user && $selectedTicket->user->id) ? $selectedTicket->user->id : 'N/A'); ?>

                        </div>
                        <div class="admin-chat-header-meta">
                            Ticket #<span id="ticketId"><?php echo e($selectedTicket->id); ?></span>
                            <span class="status-badge status-<?php echo e($selectedTicket->status); ?>" id="ticketStatus"><?php echo e(__('admin.support.' . $selectedTicket->status)); ?></span>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="admin-chat-header-actions" id="chatHeaderActions">
                    <?php if($selectedTicket): ?>
                    <form method="POST" action="<?php echo e(route('admin.support.update-status', $selectedTicket->id)); ?>" style="display: inline;" id="statusForm">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>
                        <select name="status" class="form-control" onchange="this.form.submit()" id="statusSelect">
                            <option value="open" <?php echo e(in_array($selectedTicket->status, ['open', 'pending']) ? 'selected' : ''); ?>><?php echo e(__('admin.support.open')); ?></option>
                            <option value="closed" <?php echo e(in_array($selectedTicket->status, ['closed', 'resolved']) ? 'selected' : ''); ?>><?php echo e(__('admin.support.closed')); ?></option>
                        </select>
                    </form>
                    <?php endif; ?>
                </div>
            </div>

            <div class="admin-chat-messages" id="chatMessages">
                <?php if($selectedTicket): ?>
                    <?php $__currentLoopData = $selectedTicket->messages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $message): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="admin-chat-message <?php echo e($message->sender_type === 'user' ? 'admin-chat-message-left' : 'admin-chat-message-right'); ?>" data-message-id="<?php echo e($message->id); ?>" data-sender-type="<?php echo e($message->sender_type); ?>">
                            <div class="admin-chat-message-content">
                                <?php if($message->image): ?>
                                    <div class="admin-chat-message-image">
                                        <img src="<?php echo e($message->image_url); ?>" alt="Attachment" onerror="this.style.display='none';" loading="lazy" onclick="viewImage('<?php echo e($message->image_url); ?>')" style="cursor: pointer;">
                                    </div>
                                <?php endif; ?>
                                <?php if($message->message): ?>
                                    <div class="admin-chat-message-text"><?php echo e($message->message); ?></div>
                                <?php endif; ?>
                                <div class="admin-chat-message-time"><?php echo e($message->created_at->format('H:i')); ?></div>
                                <?php if($message->sender_type === 'admin'): ?>
                                    <div class="admin-chat-message-actions">
                                        <button class="admin-chat-action-btn" onclick="editMessage(<?php echo e($message->id); ?>, '<?php echo e(addslashes($message->message)); ?>', '<?php echo e($message->image_url ?? ''); ?>')" title="Edit">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                            </svg>
                                        </button>
                                        <button class="admin-chat-action-btn" onclick="deleteMessage(<?php echo e($message->id); ?>)" title="Delete">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <polyline points="3 6 5 6 21 6"></polyline>
                                                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                            </svg>
                                        </button>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php endif; ?>
                <div id="chatEnd"></div>
            </div>

            <div class="admin-chat-input-area" id="chatInputArea">
                <form id="chatForm" method="POST" action="<?php echo e($selectedTicket ? route('admin.support.send-message', $selectedTicket->id) : '#'); ?>" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>
                    <div class="admin-chat-input-actions">
                        <button type="button" class="admin-chat-icon-btn" onclick="document.getElementById('imageInput').click()" title="Upload image">
                            📎
                        </button>
                        <input type="file" id="imageInput" name="image" accept="image/*" style="display: none;" onchange="handleImageSelect(event)">
                    </div>
                    <textarea 
                        id="messageInput" 
                        name="message" 
                        class="admin-chat-text-input" 
                        placeholder="<?php echo e(__('admin.support.type_message_placeholder')); ?>" 
                        rows="1"
                        onkeydown="handleKeyDown(event)"></textarea>
                    <button type="submit" class="admin-chat-send-btn" id="sendBtn"><?php echo e(__('admin.support.send')); ?></button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
window.__adminSupport = {
    user_id: <?php echo json_encode(__('admin.support.user_id'), 15, 512) ?>,
    open: <?php echo json_encode(__('admin.support.open'), 15, 512) ?>,
    pending: <?php echo json_encode(__('admin.support.pending'), 15, 512) ?>,
    resolved: <?php echo json_encode(__('admin.support.resolved'), 15, 512) ?>,
    closed: <?php echo json_encode(__('admin.support.closed'), 15, 512) ?>,
    select_ticket: <?php echo json_encode(__('admin.support.select_ticket'), 15, 512) ?>,
    send: <?php echo json_encode(__('admin.support.send'), 15, 512) ?>,
    sending: <?php echo json_encode(__('admin.support.sending'), 15, 512) ?>,
    edit_message: <?php echo json_encode(__('admin.support.edit_message'), 15, 512) ?>,
    message: <?php echo json_encode(__('admin.support.message'), 15, 512) ?>,
    current_image: <?php echo json_encode(__('admin.support.current_image'), 15, 512) ?>,
    replace_image: <?php echo json_encode(__('admin.support.replace_image'), 15, 512) ?>,
    save_changes: <?php echo json_encode(__('admin.support.save_changes'), 15, 512) ?>,
    cancel: <?php echo json_encode(__('admin.common.cancel'), 15, 512) ?>,
    delete_message: <?php echo json_encode(__('admin.support.delete_message'), 15, 512) ?>,
    delete_message_confirm: <?php echo json_encode(__('admin.support.delete_message_confirm'), 15, 512) ?>,
    deleting: <?php echo json_encode(__('admin.support.deleting'), 15, 512) ?>,
    delete: <?php echo json_encode(__('admin.common.delete'), 15, 512) ?>,
    save_image: <?php echo json_encode(__('admin.support.save_image'), 15, 512) ?>,
};
let currentTicketId = <?php echo e($selectedTicket ? $selectedTicket->id : 'null'); ?>;
let loadingMessages = false;

// Base URL for support routes (from Laravel route helper)
const supportBaseUrl = '<?php echo e(route("admin.support")); ?>';
const supportRoutes = {
    messages: (id) => `${supportBaseUrl}/${id}/messages`,
    sendMessage: (id) => `${supportBaseUrl}/${id}/message`,
    updateStatus: (id) => `${supportBaseUrl}/${id}/status`,
    updateMessage: (messageId) => `${supportBaseUrl}/message/${messageId}`,
    deleteMessage: (messageId) => `${supportBaseUrl}/message/${messageId}`
};

function formatMessageText(text) {
    if (!text) return '';
    return text.replace(/\n/g, '<br>');
}

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

function loadTicket(ticketId) {
    if (loadingMessages) return;
    
    currentTicketId = ticketId;
    loadingMessages = true;
    
    // Update URL
    const url = new URL(window.location.href);
    url.searchParams.set('ticket_id', ticketId);
    window.history.pushState({}, '', url);
    
    // Load messages via AJAX
    fetch(supportRoutes.messages(ticketId), {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            // Hide placeholder and show chat area
            const placeholder = document.getElementById('chatPlaceholder');
            const chatArea = document.getElementById('chatArea');
            if (placeholder) placeholder.style.display = 'none';
            if (chatArea) chatArea.style.display = 'flex';
            
            // Update active state
            document.querySelectorAll('.admin-chat-user-item').forEach(item => {
                item.classList.remove('active');
            });
            const ticketItem = document.querySelector(`[data-ticket-id="${ticketId}"]`);
            if (ticketItem) ticketItem.classList.add('active');
            
            // Update header info
            const headerInfo = document.getElementById('chatHeaderInfo');
            if (headerInfo) {
                // Safely get user ID with null checking
                const userId = (data.ticket.user && data.ticket.user.id) ? data.ticket.user.id : 'N/A';
                const userInitials = userId !== 'N/A' ? String(userId).substring(0, 2).toUpperCase() : 'NA';
                const statusKey = data.ticket.status || 'open';
                const statusText = (window.__adminSupport && window.__adminSupport[statusKey]) ? window.__adminSupport[statusKey] : statusKey;
                const userIdLabel = (window.__adminSupport && window.__adminSupport.user_id) ? window.__adminSupport.user_id : 'User ID';
                headerInfo.innerHTML = `
                    <div class="admin-chat-header-avatar">${escapeHtml(userInitials)}</div>
                    <div>
                        <div class="admin-chat-header-name">${escapeHtml(userIdLabel)}: ${escapeHtml(userId)}</div>
                        <div class="admin-chat-header-meta">
                            Ticket #<span id="ticketId">${escapeHtml(data.ticket.id || 'N/A')}</span>
                            <span class="status-badge status-${escapeHtml(data.ticket.status || 'open')}" id="ticketStatus">${escapeHtml(statusText)}</span>
                        </div>
                    </div>
                `;
            }
            
            // Update status form
            const headerActions = document.getElementById('chatHeaderActions');
            if (headerActions) {
                const statusOptions = ['open', 'closed'];
                const currentStatus = data.ticket.status || 'open';
                const isOpen = currentStatus === 'open' || currentStatus === 'pending';
                const statusSelect = statusOptions.map(status => {
                    const selected = (status === 'open' && isOpen) || (status === 'closed' && !isOpen) ? 'selected' : '';
                    const label = (window.__adminSupport && window.__adminSupport[status]) ? window.__adminSupport[status] : status;
                    return `<option value="${escapeHtml(status)}" ${selected}>${escapeHtml(label)}</option>`;
                }).join('');
                headerActions.innerHTML = `
                    <form method="POST" action="${supportRoutes.updateStatus(ticketId)}" style="display: inline;" id="statusForm">
                        <input type="hidden" name="_token" value="<?php echo e(csrf_token()); ?>">
                        <input type="hidden" name="_method" value="PUT">
                        <select name="status" class="form-control" onchange="this.form.submit()" id="statusSelect">
                            ${statusSelect}
                        </select>
                    </form>
                `;
            }
            
            // Update form action
            const chatForm = document.getElementById('chatForm');
            if (chatForm) {
                chatForm.action = supportRoutes.sendMessage(ticketId);
            }
            
            // Update last message state for comparison
            lastMessageIds = data.messages.map(m => m.id);
            lastMessageCount = data.messages.length;
            
            // Update messages
            const messagesContainer = document.getElementById('chatMessages');
            if (messagesContainer) {
                const messagesHtml = data.messages.map(msg => {
                    const messageClass = msg.sender_type === 'user' ? 'admin-chat-message-left' : 'admin-chat-message-right';
                    const imageHtml = msg.image ? `<div class="admin-chat-message-image"><img src="${escapeHtml(msg.image)}" alt="Attachment" onerror="this.style.display='none';" loading="lazy" onclick="viewImage('${escapeHtml(msg.image)}')" style="cursor: pointer;"></div>` : '';
                    const textHtml = msg.message ? `<div class="admin-chat-message-text">${formatMessageText(msg.message)}</div>` : '';
                    const actionsHtml = msg.sender_type === 'admin' ? `
                        <div class="admin-chat-message-actions">
                            <button class="admin-chat-action-btn" onclick="editMessage(${msg.id}, '${escapeHtml(msg.message || '')}', '${escapeHtml(msg.image || '')}')" title="Edit">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                </svg>
                            </button>
                            <button class="admin-chat-action-btn" onclick="deleteMessage(${msg.id})" title="Delete">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <polyline points="3 6 5 6 21 6"></polyline>
                                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                </svg>
                            </button>
                        </div>
                    ` : '';
                    return `
                        <div class="admin-chat-message ${messageClass}" data-message-id="${msg.id}" data-sender-type="${msg.sender_type}">
                            <div class="admin-chat-message-content">
                                ${imageHtml}
                                ${textHtml}
                                <div class="admin-chat-message-time">${escapeHtml(msg.time)}</div>
                                ${actionsHtml}
                            </div>
                        </div>
                    `;
                }).join('');
                messagesContainer.innerHTML = messagesHtml + '<div id="chatEnd"></div>';
            }
            
            // Only auto-scroll if user was at bottom before loading
            scrollToBottom(isUserAtBottom);
            
            // Update unread badge
            if (ticketItem) {
                const badge = ticketItem.querySelector('.admin-chat-unread-badge');
                if (badge) badge.remove();
            }
        }
        loadingMessages = false;
    })
    .catch(error => {
        console.error('Error loading messages:', error);
        alert('Failed to load messages. Please try again.');
        loadingMessages = false;
    });
}

function handleKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        const chatForm = document.getElementById('chatForm');
        if (chatForm) {
            chatForm.dispatchEvent(new Event('submit'));
        }
    }
}

function handleImageSelect(e) {
    if (e.target.files && e.target.files.length > 0) {
        const chatForm = document.getElementById('chatForm');
        if (chatForm) {
            chatForm.dispatchEvent(new Event('submit'));
        }
    }
}

// Track if user is at bottom of chat
let isUserAtBottom = true;
let userScrolled = false;

// Monitor scroll position
const messagesContainer = document.getElementById('chatMessages');
if (messagesContainer) {
    messagesContainer.addEventListener('scroll', function() {
        const container = this;
        const scrollTop = container.scrollTop;
        const scrollHeight = container.scrollHeight;
        const clientHeight = container.clientHeight;
        
        // Check if user is near bottom (within 100px)
        const isNearBottom = (scrollHeight - scrollTop - clientHeight) < 100;
        isUserAtBottom = isNearBottom;
        userScrolled = true;
    });
}

function scrollToBottom(force = false) {
    // Only auto-scroll if user is at bottom or force is true
    if (!force && !isUserAtBottom) {
        return;
    }
    
    const chatEnd = document.getElementById('chatEnd');
    if (chatEnd) {
        chatEnd.scrollIntoView({ behavior: 'smooth' });
        isUserAtBottom = true;
    }
}

// Auto-resize textarea
const messageInput = document.getElementById('messageInput');
if (messageInput) {
    messageInput.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 120) + 'px';
    });
}

// Handle form submission
const chatForm = document.getElementById('chatForm');
if (chatForm) {
    chatForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const sendBtn = document.getElementById('sendBtn');
        const originalText = sendBtn.textContent;
        
        sendBtn.disabled = true;
        sendBtn.textContent = (window.__adminSupport && window.__adminSupport.sending) ? window.__adminSupport.sending : 'Sending...';
        
        fetch(this.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                // Add new message to chat
                const messagesContainer = document.getElementById('chatMessages');
                if (messagesContainer) {
                    const msg = data.message;
                    const imageHtml = msg.image ? `<div class="admin-chat-message-image"><img src="${escapeHtml(msg.image)}" alt="Attachment" onerror="this.style.display='none';" loading="lazy" onclick="viewImage('${escapeHtml(msg.image)}')" style="cursor: pointer;"></div>` : '';
                    const textHtml = msg.message ? `<div class="admin-chat-message-text">${formatMessageText(msg.message)}</div>` : '';
                    const actionsHtml = `
                        <div class="admin-chat-message-actions">
                            <button class="admin-chat-action-btn" onclick="editMessage(${msg.id}, '${escapeHtml(msg.message || '')}', '${escapeHtml(msg.image || '')}')" title="Edit">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                </svg>
                            </button>
                            <button class="admin-chat-action-btn" onclick="deleteMessage(${msg.id})" title="Delete">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <polyline points="3 6 5 6 21 6"></polyline>
                                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                </svg>
                            </button>
                        </div>
                    `;
                    const messageHtml = `
                        <div class="admin-chat-message admin-chat-message-right" data-message-id="${msg.id}" data-sender-type="admin">
                            <div class="admin-chat-message-content">
                                ${imageHtml}
                                ${textHtml}
                                <div class="admin-chat-message-time">${escapeHtml(msg.time)}</div>
                                ${actionsHtml}
                            </div>
                        </div>
                    `;
                    messagesContainer.insertAdjacentHTML('beforeend', messageHtml);
                    
                    // Update last message state
                    lastMessageIds.push(msg.id);
                    lastMessageCount = lastMessageIds.length;
                }
                
                // Always scroll to bottom when sending new message
                scrollToBottom(true);
                
                // Clear form
                const messageInput = document.getElementById('messageInput');
                const imageInput = document.getElementById('imageInput');
                if (messageInput) {
                    messageInput.value = '';
                    messageInput.style.height = 'auto';
                }
                if (imageInput) {
                    imageInput.value = '';
                }
            } else {
                alert(data.message || 'Failed to send message');
            }
            
            sendBtn.disabled = false;
            sendBtn.textContent = originalText;
        })
        .catch(error => {
            console.error('Error sending message:', error);
            alert('Failed to send message. Please try again.');
            sendBtn.disabled = false;
            sendBtn.textContent = originalText;
        });
    });
}

// Search functionality - search by User ID
const searchInput = document.getElementById('searchTickets');
if (searchInput) {
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        document.querySelectorAll('.admin-chat-user-item').forEach(item => {
            // Search in User ID
            const userId = item.querySelector('.admin-chat-user-name');
            const text = userId ? userId.textContent.toLowerCase() : '';
            const userIdMatch = text.includes(searchTerm);
            item.style.display = userIdMatch ? 'flex' : 'none';
        });
    });
}

// Scroll to bottom on initial load
if (currentTicketId) {
    setTimeout(() => scrollToBottom(true), 100);
}

// Track last message count and IDs to detect changes
let lastMessageCount = 0;
let lastMessageIds = [];

// Poll for new messages every 5 seconds
// Only update if messages actually changed and user is at bottom
if (currentTicketId) {
    setInterval(() => {
        if (!loadingMessages && currentTicketId && isUserAtBottom) {
            // Check for new messages without full reload
            checkForNewMessages(currentTicketId);
        }
    }, 5000);
}

// Check for new messages without full reload (prevent flickering)
function checkForNewMessages(ticketId) {
    fetch(supportRoutes.messages(ticketId), {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && data.messages) {
            const currentMessageIds = data.messages.map(m => m.id).join(',');
            const currentMessageCount = data.messages.length;
            
            // Only update if messages actually changed
            if (currentMessageIds !== lastMessageIds.join(',') || currentMessageCount !== lastMessageCount) {
                // Store current state
                lastMessageIds = data.messages.map(m => m.id);
                lastMessageCount = currentMessageCount;
                
                // Update messages without flickering - only append new ones
                const messagesContainer = document.getElementById('chatMessages');
                if (messagesContainer) {
                    const existingIds = Array.from(messagesContainer.querySelectorAll('[data-message-id]'))
                        .map(el => parseInt(el.getAttribute('data-message-id')));
                    
                    // Find new messages
                    const newMessages = data.messages.filter(msg => !existingIds.includes(msg.id));
                    
                    // Only add new messages if any
                    if (newMessages.length > 0) {
                        newMessages.forEach(msg => {
                            const messageClass = msg.sender_type === 'user' ? 'admin-chat-message-left' : 'admin-chat-message-right';
                            const imageHtml = msg.image ? `<div class="admin-chat-message-image"><img src="${escapeHtml(msg.image)}" alt="Attachment" onerror="this.style.display='none';" loading="lazy" onclick="viewImage('${escapeHtml(msg.image)}')" style="cursor: pointer;"></div>` : '';
                            const textHtml = msg.message ? `<div class="admin-chat-message-text">${formatMessageText(msg.message)}</div>` : '';
                            const actionsHtml = msg.sender_type === 'admin' ? `
                                <div class="admin-chat-message-actions">
                                    <button class="admin-chat-action-btn" onclick="editMessage(${msg.id}, '${escapeHtml(msg.message || '')}', '${escapeHtml(msg.image || '')}')" title="Edit">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                        </svg>
                                    </button>
                                    <button class="admin-chat-action-btn" onclick="deleteMessage(${msg.id})" title="Delete">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <polyline points="3 6 5 6 21 6"></polyline>
                                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                        </svg>
                                    </button>
                                </div>
                            ` : '';
                            const messageHtml = `
                                <div class="admin-chat-message ${messageClass}" data-message-id="${msg.id}" data-sender-type="${msg.sender_type}">
                                    <div class="admin-chat-message-content">
                                        ${imageHtml}
                                        ${textHtml}
                                        <div class="admin-chat-message-time">${escapeHtml(msg.time)}</div>
                                        ${actionsHtml}
                                    </div>
                                </div>
                            `;
                            
                            // Remove chatEnd div, add new message, add chatEnd back
                            const chatEnd = document.getElementById('chatEnd');
                            if (chatEnd) {
                                chatEnd.insertAdjacentHTML('beforebegin', messageHtml);
                            } else {
                                messagesContainer.insertAdjacentHTML('beforeend', messageHtml);
                            }
                        });
                        
                        // Scroll to bottom if user was at bottom
                        if (isUserAtBottom) {
                            scrollToBottom(true);
                        }
                    }
                }
            }
        }
    })
    .catch(error => {
        console.error('Error checking for new messages:', error);
    });
}

// Image view and save functionality
function viewImage(imageUrl) {
    // Create lightbox modal
    const modal = document.createElement('div');
    modal.className = 'admin-image-lightbox';
    modal.innerHTML = `
        <div class="admin-image-lightbox-content">
            <button class="admin-image-lightbox-close" onclick="this.closest('.admin-image-lightbox').remove()">&times;</button>
            <img src="${escapeHtml(imageUrl)}" alt="Image" class="admin-image-lightbox-img">
            <div class="admin-image-lightbox-actions">
                <button class="admin-image-lightbox-btn" onclick="saveImage('${escapeHtml(imageUrl)}')">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                        <polyline points="7 10 12 15 17 10"></polyline>
                        <line x1="12" y1="15" x2="12" y2="3"></line>
                    </svg>
                    ${escapeHtml((window.__adminSupport && window.__adminSupport.save_image) ? window.__adminSupport.save_image : 'Save Image')}
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
    
    // Close on background click
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.remove();
        }
    });
    
    // Close on Escape key
    const escapeHandler = function(e) {
        if (e.key === 'Escape' && modal.parentNode) {
            modal.remove();
            document.removeEventListener('keydown', escapeHandler);
        }
    };
    document.addEventListener('keydown', escapeHandler);
}

function saveImage(imageUrl) {
    const link = document.createElement('a');
    link.href = imageUrl;
    link.download = imageUrl.split('/').pop() || 'image.jpg';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Edit message functionality
function editMessage(messageId, currentMessage, currentImage) {
    // Create edit modal
    const modal = document.createElement('div');
    modal.className = 'admin-edit-modal';
    const t = window.__adminSupport || {};
    modal.innerHTML = `
        <div class="admin-edit-modal-content">
            <div class="admin-edit-modal-header">
                <h3>${escapeHtml(t.edit_message || 'Edit Message')}</h3>
                <button class="admin-edit-modal-close" onclick="this.closest('.admin-edit-modal').remove()">&times;</button>
            </div>
            <form id="editMessageForm" onsubmit="saveEditedMessage(event, ${messageId})">
                <div class="admin-edit-modal-body">
                    <div class="form-group">
                        <label>${escapeHtml(t.message || 'Message')}</label>
                        <textarea id="editMessageText" class="form-control" rows="4" maxlength="5000">${escapeHtml(currentMessage || '')}</textarea>
                    </div>
                    ${currentImage ? `
                        <div class="form-group">
                            <label>${escapeHtml(t.current_image || 'Current Image')}</label>
                            <img src="${escapeHtml(currentImage)}" alt="Current" style="max-width: 200px; border-radius: 8px; margin-top: 8px;">
                        </div>
                    ` : ''}
                    <div class="form-group">
                        <label>${escapeHtml(t.replace_image || 'Replace Image (optional)')}</label>
                        <input type="file" id="editMessageImage" accept="image/*" class="form-control">
                    </div>
                </div>
                <div class="admin-edit-modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.admin-edit-modal').remove()">${escapeHtml(t.cancel || 'Cancel')}</button>
                    <button type="submit" class="btn btn-primary">${escapeHtml(t.save_changes || 'Save Changes')}</button>
                </div>
            </form>
        </div>
    `;
    document.body.appendChild(modal);
    
    // Close on background click
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.remove();
        }
    });
    
    // Close on Escape key
    const escapeHandler = function(e) {
        if (e.key === 'Escape' && modal.parentNode) {
            modal.remove();
            document.removeEventListener('keydown', escapeHandler);
        }
    };
    document.addEventListener('keydown', escapeHandler);
}

function saveEditedMessage(e, messageId) {
    e.preventDefault();
    
    const formData = new FormData();
    const messageText = document.getElementById('editMessageText').value.trim();
    const imageInput = document.getElementById('editMessageImage');
    
    if (messageText) {
        formData.append('message', messageText);
    }
    
    if (imageInput.files && imageInput.files[0]) {
        formData.append('image', imageInput.files[0]);
    }
    
    // Ensure at least message or image is provided
    if (!messageText && !imageInput.files[0]) {
        alert('Please provide a message or image');
        return;
    }
    
    formData.append('_token', document.querySelector('input[name="_token"]').value);
    formData.append('_method', 'PUT');
    
    fetch(supportRoutes.updateMessage(messageId), {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload messages
            if (currentTicketId) {
                loadTicket(currentTicketId);
            }
            // Close modal
            document.querySelector('.admin-edit-modal').remove();
        } else {
            alert(data.message || 'Failed to update message');
        }
    })
    .catch(error => {
        console.error('Error updating message:', error);
        alert('Failed to update message. Please try again.');
    });
}

// Delete message – show in-app confirm modal (no browser confirm)
function deleteMessage(messageId) {
    const modal = document.createElement('div');
    modal.className = 'admin-edit-modal admin-delete-confirm-modal';
    modal.setAttribute('role', 'dialog');
    modal.setAttribute('aria-labelledby', 'admin-delete-confirm-title');
    const t = window.__adminSupport || {};
    modal.innerHTML = `
        <div class="admin-edit-modal-content admin-delete-confirm-content">
            <div class="admin-edit-modal-header">
                <h3 id="admin-delete-confirm-title">${escapeHtml(t.delete_message || 'Delete message')}</h3>
                <button type="button" class="admin-edit-modal-close" aria-label="Close" onclick="this.closest('.admin-delete-confirm-modal').remove()">&times;</button>
            </div>
            <div class="admin-delete-confirm-body">
                <p>${escapeHtml(t.delete_message_confirm || 'Are you sure you want to delete this message? This action cannot be undone.')}</p>
            </div>
            <div class="admin-edit-modal-footer">
                <button type="button" class="btn btn-secondary" data-action="cancel">${escapeHtml(t.cancel || 'Cancel')}</button>
                <button type="button" class="btn btn-danger" data-action="delete">${escapeHtml(t.delete || 'Delete')}</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);

    const closeModal = () => modal.remove();

    modal.querySelector('[data-action="cancel"]').addEventListener('click', closeModal);
    modal.querySelector('.admin-edit-modal-close').addEventListener('click', closeModal);
    modal.addEventListener('click', function(e) {
        if (e.target === modal) closeModal();
    });

    const escapeHandler = function(e) {
        if (e.key === 'Escape' && modal.parentNode) {
            closeModal();
            document.removeEventListener('keydown', escapeHandler);
        }
    };
    document.addEventListener('keydown', escapeHandler);

    modal.querySelector('[data-action="delete"]').addEventListener('click', function() {
        const btn = this;
        btn.disabled = true;
        btn.textContent = (window.__adminSupport && window.__adminSupport.deleting) ? window.__adminSupport.deleting : 'Deleting...';
        const formData = new FormData();
        formData.append('_token', document.querySelector('input[name="_token"]').value);
        formData.append('_method', 'DELETE');
        fetch(supportRoutes.deleteMessage(messageId), {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value
            }
        })
        .then(response => response.json())
        .then(data => {
            closeModal();
            document.removeEventListener('keydown', escapeHandler);
            if (data.success) {
                const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
                if (messageElement) messageElement.remove();
            } else {
                alert(data.message || 'Failed to delete message');
            }
        })
        .catch(error => {
            console.error('Error deleting message:', error);
            alert('Failed to delete message. Please try again.');
            btn.disabled = false;
            btn.textContent = (window.__adminSupport && window.__adminSupport.delete) ? window.__adminSupport.delete : 'Delete';
        });
    });
}
</script>

<style>
/* Image Lightbox Styles */
.admin-image-lightbox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.9);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.admin-image-lightbox-content {
    position: relative;
    max-width: 90%;
    max-height: 90%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.admin-image-lightbox-close {
    position: absolute;
    top: -40px;
    right: 0;
    background: none;
    border: none;
    color: white;
    font-size: 32px;
    cursor: pointer;
    padding: 0;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.2s;
}

.admin-image-lightbox-close:hover {
    background: rgba(255, 255, 255, 0.2);
}

.admin-image-lightbox-img {
    max-width: 100%;
    max-height: 80vh;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}

.admin-image-lightbox-actions {
    margin-top: 20px;
}

.admin-image-lightbox-btn {
    background: var(--primary);
    color: var(--bg);
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.2s;
}

.admin-image-lightbox-btn:hover {
    background: var(--primary-hover, #00B8E6);
    transform: translateY(-2px);
}

/* Edit Modal Styles */
.admin-edit-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.admin-edit-modal-content {
    background: var(--card);
    border-radius: 12px;
    width: 100%;
    max-width: 600px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

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

.admin-edit-modal-header h3 {
    margin: 0;
    color: var(--text);
    font-size: 18px;
}

.admin-edit-modal-close {
    background: none;
    border: none;
    color: var(--text);
    font-size: 28px;
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.2s;
}

.admin-edit-modal-close:hover {
    background: var(--border);
}

.admin-edit-modal-body {
    padding: 20px;
}

.admin-edit-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px;
    border-top: 1px solid var(--border);
}

/* Message Actions Styles */
.admin-chat-message-actions {
    display: flex;
    gap: 6px;
    margin-top: 8px;
    align-items: center;
}

/* Always show actions for admin messages (right side) - always visible */
.admin-chat-message-right .admin-chat-message-actions {
    opacity: 1;
    display: flex;
}

/* Hide actions for user messages (left side) */
.admin-chat-message-left .admin-chat-message-actions {
    display: none;
}

.admin-chat-action-btn {
    background: rgba(255, 255, 255, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: var(--text);
    width: 32px;
    height: 32px;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    transition: all 0.2s;
    flex-shrink: 0;
}

.admin-chat-action-btn:hover {
    background: rgba(255, 255, 255, 0.25);
    border-color: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.admin-chat-action-btn:active {
    transform: scale(0.95);
}

.admin-chat-action-btn svg {
    width: 16px;
    height: 16px;
    stroke: currentColor;
}

/* Form Group Styles */
.admin-edit-modal-body .form-group {
    margin-bottom: 20px;
}

.admin-edit-modal-body .form-group label {
    display: block;
    margin-bottom: 8px;
    color: var(--text);
    font-size: 14px;
    font-weight: 500;
}

.admin-edit-modal-body .form-control {
    width: 100%;
    padding: 10px 14px;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text);
    font-size: 14px;
    font-family: inherit;
}

.admin-edit-modal-body .form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.1);
}

.admin-edit-modal-body textarea.form-control {
    resize: vertical;
    min-height: 100px;
}

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

.btn-primary {
    background: var(--primary);
    color: var(--bg);
}

.btn-primary:hover {
    background: var(--primary-hover, #00B8E6);
    transform: translateY(-1px);
}

.btn-secondary {
    background: var(--border);
    color: var(--text);
}

.btn-secondary:hover {
    background: rgba(255, 255, 255, 0.1);
}

/* Delete confirm modal */
.admin-delete-confirm-body {
    padding: 20px;
}
.admin-delete-confirm-body p {
    margin: 0;
    color: var(--text);
    font-size: 15px;
    line-height: 1.5;
}
.btn-danger {
    background: #dc3545;
    color: #fff;
}
.btn-danger:hover {
    background: #c82333;
    color: #fff;
    transform: translateY(-1px);
}
.btn-danger:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
}
</style>
</div>
</div>
<?php $__env->stopSection(); ?>


<?php echo $__env->make('admin.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/quanruqw/public_html/backend/resources/views/admin/support/chat.blade.php ENDPATH**/ ?>