<?php
session_start();
require_once '../config/db.php';

// Check if authorized role is logged in
$allowedRoles = ['AC', 'AAC', 'NROI', 'PPSA'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], $allowedRoles)) {
    header("Location: ../index.php");
    exit;
}

$firstName = $_SESSION['name'] ?? 'Officer';
$role = $_SESSION['user_role'];
$userId = $_SESSION['user_id'];
$isSpecialRole = in_array(strtoupper($role), ['PPSA', 'NROI']);

if ($isSpecialRole) {
    header("Location: dashboard.php");
    exit;
}

// Fetch Officer Area from Database
$stmt = $pdo->prepare("SELECT area FROM users WHERE id = ?");
$stmt->execute([$userId]);
$area = $stmt->fetchColumn();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo $role; ?> Dashboard | Notifications | NROI Portal
    </title>
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <link rel="stylesheet" href="../assets/css/loader.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/dashboard.css">
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
    <style>
        .notifications-wrapper {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 200px);
            min-height: 500px;
        }

        .notif-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }

        .notif-tabs {
            display: flex;
            gap: 15px;
        }

        .notif-tab {
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.9rem;
            color: #64748b;
            transition: all 0.2s;
        }

        .notif-tab.active {
            background: #2563eb;
            color: #fff;
        }

        .notif-body {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .notif-list {
            width: 350px;
            border-right: 1px solid #e2e8f0;
            overflow-y: auto;
            background: #fff;
        }

        .notif-item {
            padding: 15px 20px;
            border-bottom: 1px solid #f1f5f9;
            cursor: pointer;
            transition: background 0.2s;
        }

        .notif-item:hover {
            background: #f8fafc;
        }

        .notif-item.unread {
            background: #eff6ff;
            border-left: 4px solid #2563eb;
        }

        .notif-item.active {
            background: #f1f5f9;
            border-left: 4px solid #1e293b;
        }

        .notif-item-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }

        .notif-name {
            font-weight: 700;
            color: #1e293b;
            font-size: 0.95rem;
        }

        .notif-date {
            font-size: 0.75rem;
            color: #94a3b8;
        }

        .notif-subject {
            font-weight: 600;
            color: #334155;
            font-size: 0.85rem;
            margin-bottom: 3px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .notif-body-preview {
            font-size: 0.8rem;
            color: #64748b;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .notif-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #fcfcfc;
        }

        .notif-thread {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .thread-message {
            margin-bottom: 20px;
            display: flex;
            flex-direction: column;
        }

        .thread-message.me {
            align-items: flex-end;
        }

        .thread-message.other {
            align-items: flex-start;
        }

        .thread-bubble {
            max-width: 75%;
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 0.9rem;
            line-height: 1.5;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        }

        .thread-message.me .thread-bubble {
            background: #2563eb;
            color: #fff;
            border-bottom-right-radius: 2px;
        }

        .thread-message.other .thread-bubble {
            background: #fff;
            color: #1e293b;
            border: 1px solid #e2e8f0;
            border-bottom-left-radius: 2px;
        }

        .thread-info {
            font-size: 0.7rem;
            color: #94a3b8;
            margin-top: 4px;
            margin-bottom: 2px;
        }

        .notif-reply-box {
            padding: 15px 20px;
            border-top: 1px solid #e2e8f0;
            background: #fff;
            display: flex;
            gap: 10px;
        }

        .reply-input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #cbd5e1;
            border-radius: 20px;
            outline: none;
            font-family: 'Inter', sans-serif;
            font-size: 0.9rem;
        }

        .reply-input:focus {
            border-color: #2563eb;
        }

        .btn-send {
            background: #2563eb;
            color: #fff;
            border: none;
            border-radius: 20px;
            padding: 0 20px;
            cursor: pointer;
            font-weight: 600;
            transition: background 0.2s;
        }

        .btn-send:hover {
            background: #1d4ed8;
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        /* Modal specific */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(15, 23, 42, 0.6);
            backdrop-filter: blur(4px);
            z-index: 9999;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 20px;
            width: 90%;
            max-width: 550px;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            font-size: 0.85rem;
            color: #475569;
        }

        .form-input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #cbd5e1;
            border-radius: 8px;
            font-family: inherit;
            font-size: 0.9rem;
            color: #1e293b;
            box-sizing: border-box;
        }

        .radio-group {
            display: flex;
            gap: 15px;
            margin-bottom: 10px;
        }
    </style>
</head>

<body class="dashboard-body">
    <?php include '../includes/loader.php'; ?>

    <!-- Sidebar Navigation -->
    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">
                <?php
                if ($role === 'AC')
                    echo 'A.C';
                elseif ($role === 'AAC')
                    echo 'A.A.C';
                else
                    echo $role;
                ?>
            </div>
        </div>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="dashboard.php" class="sidebar-link">
                    <i class="fas fa-th-large"></i> Overview
                </a>
            </li>
            <?php if (!$isSpecialRole): ?>
                <li class="sidebar-item">
                    <a href="notifications.php" class="sidebar-link active">
                        <i class="fas fa-bell"></i> Notifications
                    </a>
                </li>
                <?php if ($role === 'AC' || $role === 'AAC'): ?>
                    <li class="sidebar-item">
                        <a href="../api/users.php" class="sidebar-link">
                            <i class="fas fa-user-friends"></i> Accounts
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="../api/matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a href="../api/request.php" class="sidebar-link">
                            <i class="fas fa-inbox"></i> For Approval
                        </a>
                    </li>
                <?php else: ?>
                    <li class="sidebar-item">
                        <a href="../api/matches.php" class="sidebar-link">
                            <i class="fas fa-trophy"></i> Matches
                        </a>
                    </li>
                <?php endif; ?>
            <?php endif; ?>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </a>
            </li>
        </ul>

        <!-- Sidebar Profile -->
        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">
                    <?php echo strtoupper(substr($role, 0, 2)); ?>
                </div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">
                        <?php echo $firstName; ?>
                    </div>
                    <div class="sidebar-user-role">
                        <?php echo $role; ?> Account
                    </div>
                </div>
                <i class="fas fa-chevron-up" style="font-size: 0.7rem; color: #94a3b8;"></i>

                <div class="profile-dropdown" id="profileDropdown"
                    style="bottom: 100%; top: auto; right: 10px; left: 10px; width: auto; margin-bottom: 10px;">
                    <a href="profile.php" class="dropdown-item">
                        <i class="far fa-user-circle"></i> My Profile
                    </a>
                    <div style="height: 1px; background: rgba(0,0,0,0.05); margin: 5px 0;"></div>
                    <a href="../logout.php" class="dropdown-item logout">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </aside>

    <div class="main-layout">
        <main class="content-wrapper">
            <header class="welcome-header">
                <div class="header-brand-box">
                    <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="header-logo">
                    <div class="header-text">
                        <h2>NATIONAL RANGE OFFICERS INSTITUTE</h2>
                        <p>NOTIFICATIONS</p>
                    </div>
                </div>
            </header>

            <div class="notifications-wrapper">
                <div class="notif-header">
                    <div class="notif-tabs">
                        <div class="notif-tab active" id="tab-inbox" onclick="switchTab('inbox')">Inbox</div>
                        <div class="notif-tab" id="tab-sent" onclick="switchTab('sent')">Sent</div>
                    </div>
                    <button class="btn-primary" style="margin: 0; padding: 8px 16px; width: auto;"
                        onclick="openComposeModal()"><i class="fas fa-edit"></i> Compose</button>
                </div>

                <div class="notif-body">
                    <!-- Left Sidebar List -->
                    <div class="notif-list" id="notif-list">
                        <!-- Populated by JS -->
                    </div>

                    <!-- Right Content Area -->
                    <div class="notif-content" id="notif-content">
                        <div class="empty-state">
                            <i class="far fa-envelope-open"></i>
                            <p>Select a message to read</p>
                        </div>
                    </div>
                </div>
            </div>

        </main>
    </div>

    <!-- Compose Modal -->
    <div id="composeModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-top:0; margin-bottom: 20px;">Compose Message</h3>

            <div class="form-group">
                <label class="form-label">Subject</label>
                <input type="text" id="compose-subject" class="form-input" placeholder="Subject">
            </div>

            <div class="form-group">
                <label class="form-label">Message</label>
                <textarea id="compose-body" class="form-input" rows="4"
                    placeholder="Type your message here..."></textarea>
            </div>

            <?php if ($role === 'AC' || $role === 'AAC'): ?>
                <div class="form-group">
                    <label class="form-label">Send to</label>
                    <div class="radio-group">
                        <label><input type="radio" name="recipient_type" value="area_members" checked
                                onchange="toggleSpecificUserSelect()"> All Members in Area</label>
                        <label><input type="radio" name="recipient_type" value="specific_members"
                                onchange="toggleSpecificUserSelect()"> Specific Members</label>
                    </div>

                    <div id="specific-users-search-wrapper" style="display: none; margin-top: 10px;">
                        <input type="text" id="specific-users-search" class="form-input" placeholder="Search members..."
                            oninput="filterSpecificMembers()"
                            style="margin-bottom: 5px; padding: 8px 12px; font-size: 0.85rem;">
                    </div>
                    <div id="specific-users-wrapper"
                        style="display: none; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; max-height: 150px; overflow-y: auto;">
                        <!-- Checkboxes populated via JS -->
                    </div>
                </div>
            <?php else: ?>
                <input type="hidden" name="recipient_type" id="compose-recipient-type" value="ac_aac_same_area">
                <p style="font-size: 0.85rem; color: #64748b; margin-bottom: 15px;">Your message will be sent directly to
                    A.C/A.A.C in your area.</p>
            <?php endif; ?>

            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button type="button" onclick="closeModals()"
                    style="background: none; border: none; color: #64748b; cursor: pointer; font-weight: 600;">Cancel</button>
                <button type="button" class="btn-secondary" style="margin: 0; width: auto; padding: 10px 18px;"
                    onclick="sendMessage()">Send Message</button>
            </div>
        </div>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        const userId = <?php echo $userId; ?>;
        const userRole = "<?php echo $role; ?>";
        let currentTab = 'inbox';
        let notifications = [];
        let activeNotificationId = null;
        let activeRootId = null; // root_id of the currently open thread

        // Profile Dropdown Toggle
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');

        if (profileToggle && profileDropdown) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });
            document.addEventListener('click', (e) => {
                if (!profileToggle.contains(e.target) && !profileDropdown.contains(e.target)) {
                    profileDropdown.classList.remove('active');
                }
            });
        }

        function switchTab(tab) {
            currentTab = tab;
            document.getElementById('tab-inbox').classList.remove('active');
            document.getElementById('tab-sent').classList.remove('active');
            document.getElementById('tab-' + tab).classList.add('active');
            activeNotificationId = null;
            activeRootId = null;
            renderEmptyContent();
            fetchNotifications();
        }

        async function fetchNotifications() {
            const listEl = document.getElementById('notif-list');
            listEl.innerHTML = '<div style="padding:20px; text-align:center; color:#94a3b8;">Loading...</div>';

            try {
                const endpoint = currentTab === 'inbox'
                    ? `../api/get_notification_inbox.php?user_id=${userId}`
                    : `../api/get_notification_sent.php?user_id=${userId}`;

                const res = await fetch(endpoint);
                const json = await res.json();

                if (json.status === 'success') {
                    notifications = json.data || [];
                    renderList();
                } else {
                    listEl.innerHTML = '<div style="padding:20px; text-align:center; color:#ef4444;">Failed to load.</div>';
                }
            } catch (err) {
                listEl.innerHTML = '<div style="padding:20px; text-align:center; color:#ef4444;">Error occurred.</div>';
            }
        }

        function renderList() {
            const listEl = document.getElementById('notif-list');
            listEl.innerHTML = '';

            if (notifications.length === 0) {
                listEl.innerHTML = `
                    <div style="padding: 30px 20px; text-align: center; color: #94a3b8;">
                        <i class="fas fa-inbox" style="font-size: 2rem; margin-bottom: 10px; opacity: 0.5;"></i>
                        <p>No ${currentTab} messages found.</p>
                    </div>
                `;
                return;
            }

            notifications.forEach(n => {
                const isUnread = currentTab === 'inbox' && !n.read_at;
                const isActive = activeNotificationId === n.id;

                const timeStr = new Date(n.created_at).toLocaleDateString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });

                // Construct the name based on current tab
                let nameStr = currentTab === 'inbox'
                    ? (n.from_name || 'System')
                    : 'To: ' + (n.recipient_names || 'recipients');
                if (currentTab === 'inbox' && !nameStr) nameStr = 'System';

                const div = document.createElement('div');
                div.className = `notif-item ${isUnread ? 'unread' : ''} ${isActive ? 'active' : ''}`;
                div.onclick = () => openThread(n);

                div.innerHTML = `
                    <div class="notif-item-header">
                        <span class="notif-name">${nameStr}</span>
                        <span class="notif-date">${timeStr}</span>
                    </div>
                    <div class="notif-subject">${n.subject}</div>
                    <div class="notif-body-preview">${n.body}</div>
                `;
                listEl.appendChild(div);
            });
        }

        function renderEmptyContent() {
            document.getElementById('notif-content').innerHTML = `
                <div class="empty-state">
                    <i class="far fa-envelope-open"></i>
                    <p>Select a message to read</p>
                </div>
            `;
        }

        async function openThread(n) {
            activeNotificationId = n.id;
            // Store root_id for later use (thread fetching, re-renders after reply)
            activeRootId = n.root_id || n.id;
            renderList(); // Update active state

            const contentEl = document.getElementById('notif-content');
            contentEl.innerHTML = '<div class="empty-state"><p>Loading conversation...</p></div>';

            // Mark as read if inbox
            if (currentTab === 'inbox' && !n.read_at) {
                try {
                    await fetch('../api/mark_notification_read.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ user_id: userId, notification_id: n.id })
                    });
                    n.read_at = new Date().toISOString(); // local update
                } catch (e) { }
            }

            // Fetch full thread using root_id so we always start from the top of the conversation
            try {
                const threadMsgId = n.root_id || n.id;
                const res = await fetch(`../api/get_notification_details.php?user_id=${userId}&message_id=${threadMsgId}`);
                const json = await res.json();

                if (json.status === 'success') {
                    renderThreadDetails(n, json.thread);
                } else {
                    contentEl.innerHTML = '<div class="empty-state"><p>Error loading thread.</p></div>';
                }
            } catch (e) {
                contentEl.innerHTML = '<div class="empty-state"><p>Error loading thread.</p></div>';
            }
        }

        function renderThreadDetails(rootMessage, thread) {
            const contentEl = document.getElementById('notif-content');

            let html = `
                <div style="padding: 20px; border-bottom: 1px solid #e2e8f0; background: #fff;">
                    <h3 style="margin: 0 0 5px 0; color: #1e293b;">${rootMessage.subject}</h3>
                    <div style="font-size: 0.85rem; color: #64748b;">Conversation</div>
                </div>
                <div class="notif-thread" id="thread-scroll-container">
            `;

            thread.forEach(msg => {
                const isMe = parseInt(msg.from_user_id) === userId;
                const nameStrt = isMe ? 'You' : msg.from_name;
                const timeStrt = new Date(msg.created_at).toLocaleDateString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });

                html += `
                    <div class="thread-message ${isMe ? 'me' : 'other'}">
                        <div class="thread-info">${nameStrt} • ${timeStrt}</div>
                        <div class="thread-bubble">${msg.body.replace(/\\n/g, '<br>')}</div>
                    </div>
                `;
            });

            html += `</div>`;

            // Reply Box
            const canReply = rootMessage.can_reply == 1;
            if (canReply) {
                html += `
                    <div class="notif-reply-box">
                        <input type="text" id="reply-input" class="reply-input" placeholder="Type a reply...">
                        <button class="btn-send" onclick="sendReply(${rootMessage.id}, '${rootMessage.subject.replace(/'/g, "\\'")}')"><i class="fas fa-paper-plane"></i></button>
                    </div>
                `;
            } else {
                html += `
                    <div class="notif-reply-box" style="justify-content: center; color: #94a3b8; font-style: italic; background: #f8fafc;">
                        Replies are disabled for this message.
                    </div>
                `;
            }

            contentEl.innerHTML = html;

            // Scroll to bottom
            const scrollContainer = document.getElementById('thread-scroll-container');
            if (scrollContainer) scrollContainer.scrollTop = scrollContainer.scrollHeight;

            if (canReply) {
                const input = document.getElementById('reply-input');
                input.addEventListener('keypress', function (e) {
                    if (e.key === 'Enter') {
                        sendReply(rootMessage.id, rootMessage.subject);
                    }
                });
            }
        }

        async function sendReply(parentId, subject) {
            const input = document.getElementById('reply-input');
            const body = input.value.trim();
            if (!body) return;

            // Capture rootMessage NOW before any async operation that could change notifications[]
            const rootMessage = notifications.find(n => n.id === activeNotificationId);
            if (!rootMessage) return;

            input.disabled = true;

            // --- Optimistic UI: append the bubble immediately so the user sees it right away ---
            const scrollContainer = document.getElementById('thread-scroll-container');
            if (scrollContainer) {
                const now = new Date();
                const timeStr = now.toLocaleDateString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
                const tempDiv = document.createElement('div');
                tempDiv.className = 'thread-message me';
                tempDiv.id = 'optimistic-reply';
                tempDiv.innerHTML = `
                    <div class="thread-info">You • ${timeStr}</div>
                    <div class="thread-bubble" style="opacity:0.7;">${body.replace(/\n/g, '<br>')}</div>
                `;
                scrollContainer.appendChild(tempDiv);
                scrollContainer.scrollTop = scrollContainer.scrollHeight;
            }
            input.value = '';

            // Strip leading 'RE: ' prefixes to avoid stacking "RE: RE: RE: ..."
            const cleanSubject = subject.replace(/^(RE:\s*)+/i, '');

            const payload = {
                from_user_id: userId,
                parent_id: parentId,
                subject: 'RE: ' + cleanSubject,
                body: body
            };

            try {
                const res = await fetch('../api/create_notification.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                const json = await res.json();

                if (json.status === 'success') {
                    // Re-fetch the full thread to get the authoritative state (confirmed by server)
                    const threadMsgId = activeRootId || activeNotificationId;
                    const threadRes = await fetch(`../api/get_notification_details.php?user_id=${userId}&message_id=${threadMsgId}`);
                    const threadJson = await threadRes.json();
                    if (threadJson.status === 'success') {
                        // Re-render the thread using the already-captured rootMessage
                        renderThreadDetails(rootMessage, threadJson.thread);
                    }
                    // Silently refresh the left-panel list preview without touching the active thread
                    refreshListOnly();
                } else {
                    // Remove optimistic bubble on failure
                    const opt = document.getElementById('optimistic-reply');
                    if (opt) opt.remove();
                    alert('Error: ' + json.message);
                    input.value = body;
                    input.disabled = false;
                }
            } catch (e) {
                const opt = document.getElementById('optimistic-reply');
                if (opt) opt.remove();
                alert('Connection error');
                input.value = body;
                input.disabled = false;
            }
        }

        // Refresh only the left-panel notifications list without disturbing the open thread
        async function refreshListOnly() {
            try {
                const endpoint = currentTab === 'inbox'
                    ? `../api/get_notification_inbox.php?user_id=${userId}`
                    : `../api/get_notification_sent.php?user_id=${userId}`;
                const res = await fetch(endpoint);
                const json = await res.json();
                if (json.status === 'success') {
                    notifications = json.data || [];
                    renderList(); // Only updates the left panel
                }
            } catch (e) { /* silently ignore */ }
        }

        // --- Compose Modal Logic ---

        async function openComposeModal() {
            document.getElementById('compose-subject').value = '';
            document.getElementById('compose-body').value = '';

            if (userRole === 'AC' || userRole === 'AAC') {
                document.querySelector('input[name="recipient_type"][value="area_members"]').checked = true;
                toggleSpecificUserSelect();
            }

            document.getElementById('composeModal').classList.add('active');

            // Prefetch members if AC/AAC
            if (userRole === 'AC' || userRole === 'AAC') {
                const wrap = document.getElementById('specific-users-wrapper');
                wrap.innerHTML = '<div style="color:#64748b; font-size:0.85rem; text-align:center;">Loading members...</div>';
                try {
                    const res = await fetch(`../api/get_area_members.php?user_id=${userId}`);
                    const json = await res.json();
                    if (json.status === 'success') {
                        let html = '';
                        if (json.list.length === 0) {
                            html = '<div style="color:#64748b; font-size:0.85rem; text-align:center;">No members found in your area.</div>';
                        } else {
                            json.list.forEach(m => {
                                html += `<label style="display:block; margin-bottom:5px; font-size:0.9rem;"><input type="checkbox" class="specific-user-cb" value="${m.id}"> ${m.name} (${m.nroi_id})</label>`;
                            });
                        }
                        wrap.innerHTML = html;
                    } else {
                        wrap.innerHTML = '<div style="color:#ef4444; font-size:0.85rem;">Failed to load members.</div>';
                    }
                } catch (e) {
                    wrap.innerHTML = '<div style="color:#ef4444; font-size:0.85rem;">Failed to load members.</div>';
                }
            }
        }

        function toggleSpecificUserSelect() {
            const rad = document.querySelector('input[name="recipient_type"]:checked');
            const wrap = document.getElementById('specific-users-wrapper');
            const searchWrap = document.getElementById('specific-users-search-wrapper');
            if (rad && rad.value === 'specific_members') {
                wrap.style.display = 'block';
                if (searchWrap) searchWrap.style.display = 'block';
            } else {
                wrap.style.display = 'none';
                if (searchWrap) searchWrap.style.display = 'none';
            }
        }

        function filterSpecificMembers() {
            const input = document.getElementById('specific-users-search');
            const filter = input.value.toLowerCase();
            const wrap = document.getElementById('specific-users-wrapper');
            const labels = wrap.getElementsByTagName('label');

            for (let i = 0; i < labels.length; i++) {
                const text = labels[i].textContent || labels[i].innerText;
                if (text.toLowerCase().indexOf(filter) > -1) {
                    labels[i].style.display = 'block';
                } else {
                    labels[i].style.display = 'none';
                }
            }
        }

        function closeModals() {
            document.querySelectorAll('.modal').forEach(m => m.classList.remove('active'));
        }

        async function sendMessage() {
            const subj = document.getElementById('compose-subject').value.trim();
            const body = document.getElementById('compose-body').value.trim();

            if (!subj || !body) {
                alert('Please enter a subject and a message.');
                return;
            }

            let recipientType = '';
            let selectedIds = [];

            if (userRole === 'AC' || userRole === 'AAC') {
                recipientType = document.querySelector('input[name="recipient_type"]:checked').value;
                if (recipientType === 'specific_members') {
                    const cbs = document.querySelectorAll('.specific-user-cb:checked');
                    cbs.forEach(cb => selectedIds.push(cb.value));
                    if (selectedIds.length === 0) {
                        alert('Please select at least one member.');
                        return;
                    }
                }
            } else {
                recipientType = 'ac_aac_same_area';
            }

            const payload = {
                from_user_id: userId,
                subject: subj,
                body: body,
                recipient_type: recipientType,
                recipient_user_ids: selectedIds
            };

            const sendBtn = document.querySelector('#composeModal .btn-secondary');
            if (sendBtn) { sendBtn.disabled = true; sendBtn.textContent = 'Sending...'; }

            try {
                const res = await fetch('../api/create_notification.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                const json = await res.json();

                if (json.status === 'success') {
                    closeModals();
                    // Switch to sent tab immediately — fetchNotifications() inside will load new message
                    switchTab('sent');
                } else {
                    alert('Failed to send: ' + json.message);
                    if (sendBtn) { sendBtn.disabled = false; sendBtn.textContent = 'Send Message'; }
                }
            } catch (e) {
                alert('Connection error.');
                if (sendBtn) { sendBtn.disabled = false; sendBtn.textContent = 'Send Message'; }
            }
        }

        // Init
        fetchNotifications();
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>