// messages.ts

async function getMyMessages() {
    const res = await fetch('/api/messages/my', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    });
    if (!res.ok) throw new Error('Failed to load messages');
    return await res.json();
}

function formatDate(dateStr: string): string {
    const date = new Date(dateStr);
    return date.toLocaleString(undefined, {
        year: 'numeric', month: 'short', day: 'numeric',
        hour: '2-digit', minute: '2-digit'
    });
}

function createMessageCard(msg: any) {
    const card = document.createElement('div');
    card.className = 'messages-card';

    const sender = msg.isMsgFromVolunteer
        ? `Volunteer #${msg.volunteerId}`
        : `Organization #${msg.organizationId}`;

    // Safely inject content as HTML because it contains links
    const contentHtml = msg.content ?? '';

    card.innerHTML = `
    <button class="delete-btn" title="Delete message" data-id="${msg.messageId}">&times;</button>
    <div class="message-header">${sender}</div>
    <div class="message-date">${formatDate(msg.isoDate)}</div>
    <div class="message-content">${contentHtml}</div>
    <small><em>Regarding Event #${msg.eventType}</em></small>
  `;

    return card;
}

async function deleteMessage(messageId: number) {
    if (!confirm('Are you sure you want to delete this message?')) return;

    const res = await fetch(`/api/messages/${messageId}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' }
    });

    if (!res.ok) {
        alert('Failed to delete message.');
        return;
    }

    // Reload messages after delete
    loadMessages();
}

async function loadMessages() {
    const container = document.getElementById('messagesContainer');
    if (!container) return;

    try {
        const messages = await getMyMessages();

        container.innerHTML = '';
        if (messages.length === 0) {
            container.innerHTML = `<p class="no-messages">No messages to display.</p>`;
            return;
        }

        messages.forEach((msg: any) => {
            const card = createMessageCard(msg);
            container.appendChild(card);
        });

        // Attach delete handlers
        container.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const idStr = btn.getAttribute('data-id');
                if (idStr) deleteMessage(parseInt(idStr));
            });
        });

    } catch (err) {
        container.innerHTML = `<p class="no-messages text-danger">Failed to load messages.</p>`;
        console.error(err);
    }
}

document.addEventListener('DOMContentLoaded', () => {
    loadMessages();
});
