<?php $base = array_filter(['token' => $token]); ?>
<main class="container py-4 py-md-5">
    <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4">
        <div>
            <span class="badge text-bg-warning text-dark rounded-pill px-3 py-2 mb-2"><?= e(internal_actor_label($actorType)) ?></span>
            <h1 class="h3 fw-bold text-cfc-dark mb-1"><i class="bi bi-chat-dots"></i> Mensagens do painel</h1>
            <p class="text-muted mb-0">Seu número de mensagem é <strong class="text-dark fs-5"><?= e($actor['internal_code'] ?? '---------') ?></strong>.</p>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a class="btn btn-success rounded-pill" href="<?= e(url('portal/contacts', $base)) ?>"><i class="bi bi-person-lines-fill"></i> Contatos</a>
            <a class="btn btn-outline-primary rounded-pill" href="<?= e($actorType === 'admin' ? url('admin/dashboard') : ($actorType === 'student' ? url('dashboard') : ($actorType === 'professional' ? url('professional/panel', $base) : url('beginner/panel')))) ?>"><i class="bi bi-arrow-left"></i> Voltar ao painel</a>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-xl-4">
            <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
                <h2 class="h5 fw-bold mb-3"><i class="bi bi-send"></i> Iniciar nova conversa</h2>
                <form method="post" action="<?= e(url('portal/messages/send')) ?>" enctype="multipart/form-data" class="row g-3" data-audio-message-form data-audio-chunk-url="<?= e(url('portal/messages/audio-chunk')) ?>" data-audio-finalize-url="<?= e(url('portal/messages/audio-finalize')) ?>">
                    <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>">
                    <div class="col-12"><label class="form-label">Número do destinatário</label><input name="recipient_code" inputmode="numeric" maxlength="9" pattern="\d{9}" class="form-control form-control-lg" placeholder="000000000" required><small class="text-muted">Use o código de 9 dígitos do aluno, instrutor, administração ou grupo.</small></div>
                    <div class="col-12"><label class="form-label">Mensagem</label><textarea name="message_body" rows="3" maxlength="10000" class="form-control" placeholder="Digite uma mensagem ou envie um áudio"></textarea></div>
                    <div class="col-12" data-audio-recorder>
                        <input type="file" name="message_audio" class="d-none" accept="audio/*,.webm,.ogg,.mp3,.m4a,.wav,.aac" data-audio-input>
                        <div class="audio-recorder-controls d-grid gap-2">
                            <button type="button" class="btn btn-outline-danger rounded-pill" data-audio-record><i class="bi bi-mic-fill"></i> Gravar na hora</button>
                            <button type="button" class="btn btn-danger rounded-pill d-none" data-audio-stop><i class="bi bi-stop-fill"></i> Parar gravação</button>
                            <button type="button" class="btn btn-outline-secondary rounded-pill" data-audio-choose><i class="bi bi-paperclip"></i> Escolher áudio</button>
                            <button type="button" class="btn btn-outline-dark rounded-pill d-none" data-audio-clear><i class="bi bi-x-circle"></i> Remover áudio</button>
                        </div>
                        <div class="audio-recorder-status small text-muted mt-2" data-audio-status>Nenhum áudio selecionado.</div><audio class="w-100 mt-2 d-none" controls data-audio-preview></audio>
                    </div>
                    <div class="col-12"><button class="btn btn-primary rounded-pill w-100"><i class="bi bi-send-check"></i> Enviar e abrir conversa</button></div>
                </form>
                <a class="btn btn-outline-success rounded-pill w-100 mt-3" href="<?= e(url('portal/contacts', $base)) ?>"><i class="bi bi-search"></i> Procurar contato pelo nome</a>
            </div></div>

            <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-center gap-2 mb-3"><h2 class="h5 fw-bold mb-0"><i class="bi bi-star"></i> Contatos salvos</h2><span class="badge text-bg-light border"><?= count($savedContacts ?? []) ?></span></div>
                <?php if (empty($savedContacts)): ?><div class="alert alert-light border rounded-4 mb-0">Nenhum contato salvo. Abra a área de contatos para adicionar.</div><?php else: ?>
                    <div class="d-grid gap-2">
                        <?php foreach ($savedContacts as $contact): ?>
                            <a class="btn btn-outline-primary text-start rounded-4 p-3" href="<?= e(url('portal/messages/direct', array_merge($base, ['contact_type' => $contact['actor_type'], 'contact_id' => (int)$contact['id']]))) ?>">
                                <strong class="d-block"><?= e(short_person_name($contact['name'])) ?></strong>
                                <small><?= e(internal_actor_label($contact['actor_type'])) ?> · <?= e($contact['internal_code'] ?? '---------') ?></small>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div></div>

            <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4">
                <h2 class="h5 fw-bold mb-3"><i class="bi bi-people"></i> Grupos teóricos</h2>
                <?php if (empty($groups)): ?><div class="alert alert-light border rounded-4 mb-0">Nenhuma turma teórica vinculada ao seu cadastro.</div><?php endif; ?>
                <div class="d-grid gap-2">
                    <?php foreach ($groups as $group): ?>
                        <a class="btn btn-outline-success text-start rounded-4 p-3" href="<?= e(url('portal/messages/group', array_merge($base, ['id' => (int)$group['id']]))) ?>">
                            <strong class="d-block"><?= e($group['name']) ?></strong>
                            <small>Código do grupo: <?= e($group['group_code']) ?></small>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div></div>
        </div>

        <div class="col-xl-8">
            <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-center gap-2 mb-3">
                    <div><h2 class="h5 fw-bold mb-1"><i class="bi bi-folder2-open"></i> Conversas diretas</h2><p class="text-muted small mb-0">Cada pessoa possui uma pasta separada. Abra a pasta para continuar enviando mensagens sem digitar o número novamente.</p></div>
                    <span class="badge text-bg-danger"><?= (int)($unreadMessages ?? 0) ?> nova(s)</span>
                </div>
                <?php if (empty($conversationFolders)): ?><div class="alert alert-light border rounded-4">Nenhuma conversa direta ainda.</div><?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($conversationFolders as $folder): ?>
                            <div class="col-12 col-md-6">
                                <a class="text-decoration-none" href="<?= e(url('portal/messages/direct', array_merge($base, ['contact_type' => $folder['contact_type'], 'contact_id' => (int)$folder['contact_id']]))) ?>">
                                    <div class="border rounded-4 p-3 h-100 conversation-folder-card">
                                        <div class="d-flex justify-content-between gap-2 align-items-start mb-2">
                                            <div><strong class="d-block text-dark"><?= e(short_person_name($folder['contact_name'])) ?></strong><small class="text-muted"><?= e(internal_actor_label($folder['contact_type'])) ?> · <?= e($folder['contact_code'] ?: '---------') ?></small></div>
                                            <?php if (!empty($folder['unread_count'])): ?><span class="badge text-bg-danger rounded-pill"><?= (int)$folder['unread_count'] ?></span><?php endif; ?>
                                        </div>
                                        <p class="small text-muted mb-2 text-truncate"><?= !empty($folder['last_is_mine']) ? 'Você: ' : '' ?><?= e($folder['last_message']) ?></p>
                                        <small class="text-muted"><?= e(date('d/m/Y H:i', strtotime($folder['last_at']))) ?></small>
                                    </div>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div></div>
        </div>
    </div>

    <?php if ($actorType === 'admin'): ?>
        <div class="card border-0 shadow-soft rounded-4 mt-4"><div class="card-body p-4">
            <h2 class="h5 fw-bold mb-1"><i class="bi bi-shield-check"></i> Administração das mensagens</h2>
            <p class="text-muted">A administração pode acompanhar as mensagens recentes e apagar qualquer mensagem para todos.</p>
            <?php if (empty($adminMessages)): ?><div class="alert alert-light border rounded-4 mb-0">Nenhuma mensagem registrada.</div><?php else: ?>
                <div class="table-responsive"><table class="table align-middle">
                    <thead><tr><th>Data</th><th>Remetente</th><th>Destino</th><th>Mensagem</th><th class="text-end">Ação</th></tr></thead>
                    <tbody><?php foreach ($adminMessages as $message): ?><tr>
                        <td class="text-nowrap"><?= e(date('d/m/Y H:i', strtotime($message['created_at']))) ?></td>
                        <td><?= e(short_person_name($message['sender_name'])) ?><small class="d-block text-muted"><?= e(internal_actor_label($message['sender_type'])) ?></small></td>
                        <td><?= e($message['destination_name']) ?><small class="d-block text-muted"><?= $message['conversation_type'] === 'group' ? 'Grupo teórico' : 'Mensagem direta' ?></small></td>
                        <td style="min-width:280px"><?php if(trim((string)$message['message_body'])!==''): ?><?= nl2br(e($message['message_body'])) ?><?php elseif(!empty($message['attachment_path'])): ?><span class="badge text-bg-info"><i class="bi bi-mic-fill"></i> Áudio/arquivo</span><?php endif; ?></td>
                        <td class="text-end"><form method="post" action="<?= e(url('portal/messages/delete')) ?>" onsubmit="return confirm('Apagar esta mensagem para todos?');"><?= CSRF::input() ?><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>"><input type="hidden" name="delete_mode" value="all"><button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash3"></i> Apagar</button></form></td>
                    </tr><?php endforeach; ?></tbody>
                </table></div>
            <?php endif; ?>
        </div></div>
    <?php endif; ?>
</main>
