<?php
$base = array_filter(['token' => $token]);
$conversationParams = array_merge($base, ['contact_type' => $contact['actor_type'], 'contact_id' => (int)$contact['id']]);
?>
<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-primary rounded-pill px-3 py-2 mb-2"><?= e(internal_actor_label($contact['actor_type'])) ?></span>
            <h1 class="h3 fw-bold text-cfc-dark mb-1"><i class="bi bi-folder2-open"></i> <?= e(short_person_name($contact['name'])) ?></h1>
            <p class="text-muted mb-0">Pasta individual · código <?= e($contact['internal_code'] ?? '---------') ?></p>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a class="btn btn-outline-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(url('portal/messages', $base)) ?>"><i class="bi bi-arrow-left"></i> Todas as conversas</a>
        </div>
    </div>

    <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
        <div class="message-action-hint"><i class="bi bi-hand-index-thumb"></i> Toque ou pressione uma mensagem para mostrar as opções de apagar.</div>
        <?php if (empty($messages)): ?><div class="alert alert-light border rounded-4">Nenhuma mensagem nesta conversa. Envie a primeira abaixo.</div><?php else: ?>
            <div class="message-timeline direct-conversation-timeline chat-scroll-panel" data-chat-scroll aria-label="Mensagens da conversa">
                <?php foreach ($messages as $message): ?>
                    <div class="internal-message <?= !empty($message['is_mine']) ? 'mine' : 'received' ?>" data-message-item tabindex="0" aria-expanded="false">
                        <div class="small text-muted mb-1"><?= !empty($message['is_mine']) ? 'Você' : e(short_person_name($contact['name'])) ?> · <?= e(date('d/m/Y H:i', strtotime($message['created_at']))) ?></div>
                        <?php $fileUrl = !empty($message['attachment_path']) ? url('portal/messages/file', array_merge($base, ['message_id'=>(int)$message['id']])) : ''; $mime = strtolower((string)($message['attachment_mime'] ?? '')); ?>
                        <div class="message-bubble">
                            <?php if(trim((string)($message['message_body']??''))!==''): ?><?= nl2br(e($message['message_body'])) ?><?php endif; ?>
                            <?php if($fileUrl!==''): ?>
                                <div class="audio-message-wrap mt-2"><audio controls preload="metadata" src="<?= e($fileUrl) ?>">Seu navegador não suporta áudio.</audio><small class="d-block opacity-75 mt-1"><i class="bi bi-mic-fill"></i> Mensagem de áudio</small></div>
                            <?php endif; ?>
                        </div>
                        <div class="message-actions d-flex flex-wrap gap-2 mt-2" data-message-actions>
                            <form method="post" action="<?= e(url('portal/messages/delete')) ?>" onsubmit="return confirm('Apagar esta mensagem apenas para você?');">
                                <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>"><input type="hidden" name="delete_mode" value="self"><input type="hidden" name="contact_type" value="<?= e($contact['actor_type']) ?>"><input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>"><button class="btn btn-sm btn-outline-secondary rounded-pill"><i class="bi bi-trash"></i> Apagar para mim</button>
                            </form>
                            <?php if (!empty($message['is_mine']) || $actorType === 'admin'): ?>
                                <form method="post" action="<?= e(url('portal/messages/delete')) ?>" onsubmit="return confirm('Apagar esta mensagem para todos?');">
                                    <?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>"><input type="hidden" name="delete_mode" value="all"><input type="hidden" name="contact_type" value="<?= e($contact['actor_type']) ?>"><input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash3"></i> Apagar para todos</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                <?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-reply"></i> Enviar outra mensagem</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) ?>"><input type="hidden" name="recipient_type" value="<?= e($contact['actor_type']) ?>"><input type="hidden" name="recipient_id" value="<?= (int)$contact['id'] ?>">
            <div class="col-12"><textarea name="message_body" rows="3" maxlength="10000" class="form-control" placeholder="Digite uma mensagem ou grave um áudio para <?= e(short_person_name($contact['name'])) ?>" autofocus></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">
                    <button type="button" class="btn btn-outline-danger rounded-pill" data-audio-record><i class="bi bi-mic-fill"></i> Gravar áudio</button>
                    <button type="button" class="btn btn-danger rounded-pill d-none" data-audio-stop><i class="bi bi-stop-fill"></i> Parar</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</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 px-5"><i class="bi bi-send-check"></i> Enviar mensagem</button></div>
        </form>
    </div></div>
</main>
