"use strict";
// messages.ts
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
function getMyMessages() {
    return __awaiter(this, void 0, void 0, function* () {
        const res = yield fetch('/api/messages/my', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });
        if (!res.ok)
            throw new Error('Failed to load messages');
        return yield res.json();
    });
}
function formatDate(dateStr) {
    const date = new Date(dateStr);
    return date.toLocaleString(undefined, {
        year: 'numeric', month: 'short', day: 'numeric',
        hour: '2-digit', minute: '2-digit'
    });
}
function createMessageCard(msg) {
    var _a;
    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 = (_a = msg.content) !== null && _a !== void 0 ? _a : '';
    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;
}
function deleteMessage(messageId) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!confirm('Are you sure you want to delete this message?'))
            return;
        const res = yield 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();
    });
}
function loadMessages() {
    return __awaiter(this, void 0, void 0, function* () {
        const container = document.getElementById('messagesContainer');
        if (!container)
            return;
        try {
            const messages = yield getMyMessages();
            container.innerHTML = '';
            if (messages.length === 0) {
                container.innerHTML = `<p class="no-messages">No messages to display.</p>`;
                return;
            }
            messages.forEach((msg) => {
                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();
});
