<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - LocalLendables</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        .conversation-card {
            border-left: 4px solid #007bff;
            transition: all 0.3s ease;
            border-radius: 8px;
        }
        
        .conversation-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            transform: translateY(-1px);
        }
        
        .conversation-card.deactivated {
            border-left-color: #dc3545;
            opacity: 0.7;
        }
        
        .compact-message-card {
            max-height: 150px;
            overflow-y: auto;
        }
        
        .message-preview {
            background-color: #f8f9fa;
            border-radius: 8px;
            font-size: 0.9em;
        }
        
        .audio-indicator {
            color: #6c757d;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .admin-actions-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }
        
        .cleanup-btn {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
        }
        
        .cleanup-btn:hover {
            background: rgba(255,255,255,0.3);
            color: white;
        }
    </style>
</head>

<body class="bg-light">
    <div class="container-fluid py-4">
        <!-- Header -->
        <div class="row mb-4">
            <div class="col-md-8">
                <h1 class="h3 mb-0"><i class="fas fa-shield-alt me-2"></i>Admin Dashboard</h1>
                <p class="text-muted mb-0">Manage chat conversations and member activity</p>
            </div>
            <div class="col-md-4 text-end">
                <div class="btn-group" role="group">
                    <a href="/admin/member-import" class="btn btn-outline-success">
                        <i class="fas fa-users me-1"></i>Import Members
                    </a>
                    <a href="/admin/site-config" class="btn btn-outline-primary">
                        <i class="fas fa-cog me-1"></i>Site Config
                    </a>
                    <button type="button" class="btn btn-outline-danger" onclick="cleanupEmptyConversations()">
                        <i class="fas fa-broom me-1"></i>Cleanup Empty Chats
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="cleanupDuplicateRequests()">
                        <i class="fas fa-copy me-1"></i>Remove Duplicates
                    </button>
                </div>
            </div>
        </div>

        <!-- Stats Overview -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h3 class="mb-1">{{ conversations|length }}</h3>
                        <small>Total Conversations</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h3 class="mb-1">{{ activeConversations }}</h3>
                        <small>Active Conversations</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h3 class="mb-1">{{ totalMessages }}</h3>
                        <small>Total Messages</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h3 class="mb-1">{{ uniqueItems }}</h3>
                        <small>Items Discussed</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Navigation Tabs -->
        <div class="row mb-4">
            <div class="col-12">
                <ul class="nav nav-tabs" id="adminTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="conversations-tab" data-bs-toggle="tab" data-bs-target="#conversations" type="button" role="tab">
                            <i class="fas fa-comments me-2"></i>Conversations
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="content-tab" data-bs-toggle="tab" data-bs-target="#content" type="button" role="tab">
                            <i class="fas fa-edit me-2"></i>Content Management
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="/admin/site-config">
                            <i class="fas fa-cog me-2"></i>Site Configuration
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="/admin/static-pages">
                            <i class="fas fa-file-alt me-2"></i>Static Pages
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="/admin/alpha-feedback">
                            <i class="fas fa-star me-2"></i>Alpha Feedback
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="/admin/email">
                            <i class="fas fa-envelope me-2 text-primary"></i>Email Notifications
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Tab Content -->
        <div class="tab-content" id="adminTabContent">
            <!-- Conversations Tab -->
            <div class="tab-pane fade show active" id="conversations" role="tabpanel">
                <!-- Filters -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-3">
                                        <label class="form-label">Filter by Item:</label>
                                        <select class="form-select" id="itemFilter">
                                            <option value="">All Items</option>
                                    {% for item in items %}
                                    <option value="{{ item.id }}">{{ item.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Filter by Member:</label>
                                <select class="form-select" id="memberFilter">
                                    <option value="">All Members</option>
                                    {% for member in members %}
                                    <option value="{{ member.id }}">{{ member.showName ?: (member.firstName ~ ' ' ~ member.lastName) }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Status:</label>
                                <select class="form-select" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="active">Active</option>
                                    <option value="inactive">Deactivated</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">&nbsp;</label>
                                <button class="btn btn-primary d-block" onclick="applyFilters()">
                                    <i class="fas fa-filter me-1"></i>Apply Filters
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Conversations List -->
        <div class="row">
            <div class="col-12">
                <div id="conversationsList">
                    {% for conversation in conversations %}
                    <div class="conversation-card card mb-2{% if not conversation.isActive %} deactivated{% endif %}" 
                         data-item-id="{{ conversation.itemId }}" 
                         data-members="{{ conversation.ownerId }},{{ conversation.borrowerId }}"
                         data-status="{% if conversation.isActive %}active{% else %}inactive{% endif %}">
                        
                        <!-- Compact Card Header with WHO TO WHOM format -->
                        <div class="card-body p-3">
                            <div class="row align-items-center">
                                <!-- Participants & Item (Left side) -->
                                <div class="col-md-6">
                                    <div class="d-flex align-items-center mb-1">
                                        <i class="fas fa-exchange-alt me-2 text-primary"></i>
                                        <strong class="text-primary">{{ conversation.ownerName }}</strong>
                                        <i class="fas fa-arrow-right mx-2 text-muted"></i>
                                        <strong class="text-info">{{ conversation.borrowerName }}</strong>
                                    </div>
                                    <div class="text-muted small">
                                        <i class="fas fa-box me-1"></i>{{ conversation.itemName }}
                                    </div>
                                </div>
                                
                                <!-- Date & Messages (Center) -->
                                <div class="col-md-3">
                                    <div class="small text-muted">
                                        {% if conversation.lastMessageAt %}
                                            {{ conversation.lastMessageAt|date('M j, g:i A') }}
                                        {% else %}
                                            No messages yet
                                        {% endif %}
                                    </div>
                                    <div class="small">
                                        <span class="badge bg-secondary">{{ conversation.messageCount }} msg{% if conversation.messageCount != 1 %}s{% endif %}</span>
                                        {% if not conversation.isActive %}
                                            <span class="badge bg-danger ms-1">Inactive</span>
                                        {% endif %}
                                    </div>
                                </div>
                                
                                <!-- Actions (Right side) -->
                                <div class="col-md-3 text-end">
                                    <button class="btn btn-sm btn-outline-info" onclick="viewConversation({{ conversation.conversationId }})">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Recent Messages (Compact) -->
                            {% if conversation.recentMessages and conversation.recentMessages|length > 0 %}
                                <hr class="my-2">
                                <div class="recent-messages">
                                    {% for message in conversation.recentMessages %}
                                        {% if loop.index <= 2 %}
                                        <div class="small mb-1" id="message-{{ message.id }}">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="flex-grow-1">
                                                    <strong class="text-secondary">{{ message.senderName }}:</strong>
                                                    {% if message.audioPath %}
                                                        <span class="text-muted">
                                                            <i class="fas fa-microphone me-1"></i>
                                                            {% if message.transcription %}
                                                                {{ message.transcription[:80] }}{% if message.transcription|length > 80 %}...{% endif %}
                                                            {% else %}
                                                                Audio message
                                                            {% endif %}
                                                        </span>
                                                    {% else %}
                                                        <span class="text-muted">{{ message.content[:80] }}{% if message.content|length > 80 %}...{% endif %}</span>
                                                    {% endif %}
                                                </div>
                                                <div class="d-flex align-items-center">
                                                    <small class="text-muted me-2">{{ message.createdAt|date('M j') }}</small>
                                                    <button class="btn btn-sm btn-outline-danger p-1" 
                                                            onclick="deleteMessage({{ message.id }}, {{ conversation.conversationId }})"
                                                            title="Delete Message">
                                                        <i class="fas fa-trash fa-xs"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        {% endif %}
                                    {% endfor %}
                                </div>
                            {% else %}
                                <hr class="my-2">
                                <div class="text-muted text-center small">
                                    <i class="fas fa-comments fa-2x mb-2"></i>
                                    <p class="mb-0">No messages in this conversation yet</p>
                                </div>
                            {% endif %}
                            
                            <!-- Timeline -->
                            <div class="text-muted small border-top pt-2 mt-2">
                                <i class="fas fa-clock me-1"></i>Started: {{ conversation.createdAt|date('M j, Y g:i A') }}
                                {% if conversation.lastMessageAt %}
                                    • Last message: {{ conversation.lastMessageAt|date('M j, Y g:i A') }}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% else %}
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-comments fa-3x mb-3"></i>
                        <h5>No conversations found</h5>
                        <p>Chat conversations will appear here as members communicate about items.</p>
                    </div>
                    {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Content Management Tab -->
            <div class="tab-pane fade" id="content" role="tabpanel">
                <!-- Content Management Header -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card border-0 bg-light">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <h4 class="mb-2">
                                            <i class="fas fa-edit me-2 text-primary"></i>Content Management System
                                        </h4>
                                        <p class="text-muted mb-0">
                                            Manage editable text blocks throughout the LocalLendables platform. Control messaging, 
                                            privacy notices, and user guidance content with version tracking and role-based permissions.
                                        </p>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <button class="btn btn-primary btn-lg" onclick="showCreateContentModal()">
                                            <i class="fas fa-plus me-2"></i>Add Content Block
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Content Blocks List -->
                <div class="row" id="contentBlocksList">
                    <div class="col-12">
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-3 text-muted">Loading content blocks...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Content Block Edit Modal -->
    <div class="modal fade" id="contentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="contentModalTitle">Edit Content Block</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="contentForm">
                        <input type="hidden" id="contentId" name="id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="contentIdentifier" class="form-label">Identifier</label>
                                    <input type="text" class="form-control" id="contentIdentifier" name="identifier" required>
                                    <div class="form-text">Unique key for this content block</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="contentTitle" class="form-label">Title</label>
                                    <input type="text" class="form-control" id="contentTitle" name="title" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="contentParentPage" class="form-label">Parent Page</label>
                                    <input type="text" class="form-control" id="contentParentPage" name="parentPage" required>
                                    <div class="form-text">e.g., edit-profile, homepage</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="contentSection" class="form-label">Section</label>
                                    <input type="text" class="form-control" id="contentSection" name="section">
                                    <div class="form-text">Optional section identifier</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="contentEditPermission" class="form-label">Edit Permission</label>
                                    <select class="form-select" id="contentEditPermission" name="editPermission" required>
                                        <option value="admin">Admin Only</option>
                                        <option value="manager">Manager+</option>
                                        <option value="owner">Owner+</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="contentType" class="form-label">Content Type</label>
                                    <select class="form-select" id="contentType" name="contentType">
                                        <option value="text">Text</option>
                                        <option value="html">HTML</option>
                                        <option value="markdown">Markdown</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="contentSortOrder" class="form-label">Sort Order</label>
                                    <input type="number" class="form-control" id="contentSortOrder" name="sortOrder" value="0">
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="contentContent" class="form-label">Content</label>
                            <textarea class="form-control" id="contentContent" name="content" rows="8" required></textarea>
                            <div class="form-text">The actual content that will be displayed to users</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveContentBlock()">Save Changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Initialize tabs
        document.addEventListener('DOMContentLoaded', function() {
            loadContentBlocks();
        });

        // Content Management Functions
        async function loadContentBlocks() {
            try {
                const response = await fetch('/api/admin/content');
                const blocks = await response.json();
                
                const container = document.getElementById('contentBlocksList');
                
                if (blocks.length === 0) {
                    container.innerHTML = `
                        <div class="col-12">
                            <div class="text-center py-5">
                                <i class="fas fa-file-text fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">No content blocks found</h5>
                                <p class="text-muted">Create your first content block to get started</p>
                            </div>
                        </div>
                    `;
                    return;
                }
                
                const groupedBlocks = blocks.reduce((acc, block) => {
                    if (!acc[block.parentPage]) acc[block.parentPage] = [];
                    acc[block.parentPage].push(block);
                    return acc;
                }, {});
                
                let html = '';
                Object.entries(groupedBlocks).forEach(([page, pageBlocks]) => {
                    html += `
                        <div class="col-12 mb-4">
                            <h5 class="text-primary mb-3">
                                <i class="fas fa-file me-2"></i>${page}
                                <span class="badge bg-secondary ms-2">${pageBlocks.length}</span>
                            </h5>
                            <div class="row">
                    `;
                    
                    pageBlocks.forEach(block => {
                        const permissionColor = block.editPermission === 'admin' ? 'danger' : 
                                              block.editPermission === 'manager' ? 'warning' : 'success';
                        
                        html += `
                            <div class="col-md-6 mb-3">
                                <div class="card h-100">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="card-title mb-0">${block.title}</h6>
                                            <span class="badge bg-${permissionColor}">${block.editPermission}</span>
                                        </div>
                                        <p class="text-muted small mb-2">${block.identifier}</p>
                                        <p class="card-text text-truncate" style="max-height: 3rem; overflow: hidden;">
                                            ${block.content}
                                        </p>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <small class="text-muted">v${block.version}</small>
                                            <div>
                                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editContentBlock(${block.id})">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-outline-info" onclick="viewContentHistory(${block.id})">
                                                    <i class="fas fa-history"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    html += `
                            </div>
                        </div>
                    `;
                });
                
                container.innerHTML = html;
            } catch (error) {
                console.error('Error loading content blocks:', error);
                document.getElementById('contentBlocksList').innerHTML = `
                    <div class="col-12">
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading content blocks
                        </div>
                    </div>
                `;
            }
        }

        function showCreateContentModal() {
            document.getElementById('contentForm').reset();
            document.getElementById('contentId').value = '';
            document.getElementById('contentModalTitle').textContent = 'Create Content Block';
            new bootstrap.Modal(document.getElementById('contentModal')).show();
        }

        async function editContentBlock(id) {
            try {
                const response = await fetch('/api/admin/content');
                const blocks = await response.json();
                const block = blocks.find(b => b.id === id);
                
                if (!block) {
                    alert('Content block not found');
                    return;
                }
                
                document.getElementById('contentId').value = block.id;
                document.getElementById('contentIdentifier').value = block.identifier;
                document.getElementById('contentTitle').value = block.title;
                document.getElementById('contentParentPage').value = block.parentPage;
                document.getElementById('contentSection').value = block.section || '';
                document.getElementById('contentEditPermission').value = block.editPermission;
                document.getElementById('contentType').value = block.contentType;
                document.getElementById('contentSortOrder').value = block.sortOrder;
                document.getElementById('contentContent').value = block.content;
                
                document.getElementById('contentModalTitle').textContent = 'Edit Content Block';
                new bootstrap.Modal(document.getElementById('contentModal')).show();
            } catch (error) {
                console.error('Error loading content block:', error);
                alert('Error loading content block');
            }
        }

        async function saveContentBlock() {
            const form = document.getElementById('contentForm');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());
            
            const id = data.id;
            const url = id ? `/api/admin/content/${id}` : '/api/admin/content';
            const method = id ? 'PUT' : 'POST';
            
            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('contentModal')).hide();
                    loadContentBlocks();
                } else {
                    const error = await response.json();
                    alert('Error saving content block: ' + error.error);
                }
            } catch (error) {
                console.error('Error saving content block:', error);
                alert('Error saving content block');
            }
        }

        async function viewContentHistory(id) {
            try {
                const response = await fetch(`/api/admin/content/${id}/history`);
                const history = await response.json();
                
                let historyHtml = '<div class="list-group">';
                history.forEach(entry => {
                    historyHtml += `
                        <div class="list-group-item">
                            <div class="d-flex justify-content-between">
                                <h6 class="mb-1">Version ${entry.version}</h6>
                                <small>${new Date(entry.editedAt).toLocaleString()}</small>
                            </div>
                            <p class="mb-1">${entry.changeReason || 'No reason provided'}</p>
                            <small>Edited by User ID: ${entry.editedBy}</small>
                        </div>
                    `;
                });
                historyHtml += '</div>';
                
                // Show in a simple alert for now
                const modal = document.createElement('div');
                modal.innerHTML = `
                    <div class="modal fade" tabindex="-1">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">Content History</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">${historyHtml}</div>
                            </div>
                        </div>
                    </div>
                `;
                document.body.appendChild(modal);
                new bootstrap.Modal(modal.querySelector('.modal')).show();
            } catch (error) {
                console.error('Error loading content history:', error);
                alert('Error loading content history');
            }
        }

        // Conversation filtering functions (existing code)
        function applyFilters() {
            const itemFilter = document.getElementById('itemFilter').value;
            const memberFilter = document.getElementById('memberFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            
            const conversations = document.querySelectorAll('.conversation-card');
            
            conversations.forEach(conv => {
                let show = true;
                
                // Item filter
                if (itemFilter && conv.dataset.itemId !== itemFilter) {
                    show = false;
                }
                
                // Member filter
                if (memberFilter && !conv.dataset.members.includes(memberFilter)) {
                    show = false;
                }
                
                // Status filter
                if (statusFilter && conv.dataset.status !== statusFilter) {
                    show = false;
                }
                
                conv.style.display = show ? 'block' : 'none';
            });
        }
        
        async function deleteMessage(messageId, conversationId) {
            if (!confirm('Are you sure you want to delete this message? This action cannot be undone.')) {
                return;
            }
            
            try {
                const response = await fetch(`/admin/api/messages/${messageId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    // Remove the message from the DOM
                    const messageElement = document.getElementById(`message-${messageId}`);
                    if (messageElement) {
                        messageElement.remove();
                    }
                    
                    // Show success notification
                    const notification = document.createElement('div');
                    notification.className = 'alert alert-success alert-dismissible fade show position-fixed';
                    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
                    notification.innerHTML = `
                        <i class="fas fa-check-circle me-2"></i>Message deleted successfully
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.body.appendChild(notification);
                    
                    // Auto-remove notification after 3 seconds
                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.remove();
                        }
                    }, 3000);
                } else {
                    throw new Error('Failed to delete message');
                }
            } catch (error) {
                console.error('Error deleting message:', error);
                alert('Error deleting message. Please try again.');
            }
        }
        
        async function toggleConversation(conversationId, activate) {
            const action = activate ? 'reactivate' : 'deactivate';
            
            try {
                const response = await fetch(`/admin/api/conversations/${conversationId}/${action}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    location.reload(); // Refresh to show updated status
                } else {
                    alert('Failed to ' + action + ' conversation');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Error occurred while updating conversation');
            }
        }
        
        function viewConversation(conversationId) {
            // Placeholder function for viewing conversation details
            alert(`Viewing conversation ${conversationId} - Feature coming soon!`);
        }
        
        // Cleanup empty conversations
        async function cleanupEmptyConversations() {
            if (!confirm('Are you sure you want to delete all empty conversations? This action cannot be undone.')) {
                return;
            }

            try {
                // First get count
                const countResponse = await fetch('/api/admin/empty-conversations/count');
                const countData = await countResponse.json();
                
                if (countData.count === 0) {
                    alert('No empty conversations found to delete.');
                    return;
                }

                // Delete empty conversations
                const deleteResponse = await fetch('/api/admin/empty-conversations', {
                    method: 'DELETE'
                });
                
                const result = await deleteResponse.json();
                
                if (result.success) {
                    alert(`Successfully deleted ${result.deletedCount} empty conversations.`);
                    // Reload the page to refresh conversation list
                    window.location.reload();
                } else {
                    alert('Failed to delete conversations: ' + (result.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('Error cleaning up conversations:', error);
                alert('Error occurred while cleaning up conversations');
            }
        }

        // Cleanup duplicate borrow requests
        async function cleanupDuplicateRequests() {
            try {
                // First get duplicate count
                const duplicatesResponse = await fetch('/api/admin/duplicate-requests');
                const duplicatesData = await duplicatesResponse.json();
                
                if (duplicatesData.duplicates.length === 0) {
                    alert('No duplicate borrow requests found.');
                    return;
                }

                const totalDuplicates = duplicatesData.duplicates.reduce((sum, dup) => sum + (dup.duplicate_count - 1), 0);
                
                if (!confirm(`Found ${duplicatesData.duplicates.length} items with duplicates (${totalDuplicates} extra requests). This will keep the most recent request for each item and delete the rest. Continue?`)) {
                    return;
                }

                // Delete duplicates
                const deleteResponse = await fetch('/api/admin/duplicate-requests', {
                    method: 'DELETE'
                });
                
                const result = await deleteResponse.json();
                
                if (result.success) {
                    alert(`Successfully deleted ${result.deletedCount} duplicate borrow requests.`);
                    // Optionally reload the page to refresh data
                    window.location.reload();
                } else {
                    alert('Failed to delete duplicates: ' + (result.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('Error cleaning up duplicates:', error);
                alert('Error occurred while cleaning up duplicates');
            }
        }

        // Auto-apply filters when changed
        document.getElementById('itemFilter').addEventListener('change', applyFilters);
        document.getElementById('memberFilter').addEventListener('change', applyFilters);
        document.getElementById('statusFilter').addEventListener('change', applyFilters);
    </script>
</body>
</html>