<?php $base=array_filter(['token'=>$token]); ?>
<main class="container py-4 py-md-5">
    <div class="card border-0 shadow-soft rounded-4 overflow-hidden mb-4">
        <div class="row g-0 align-items-stretch">
            <div class="col-md-3 group-cover-wrap">
                <?php if(!empty($group['image_path'])): ?>
                    <img class="group-cover" src="<?= e(asset($group['image_path'])) ?>" alt="Imagem da turma">
                <?php else: ?>
                    <div class="group-cover-placeholder"><i class="bi bi-people-fill"></i></div>
                <?php endif; ?>
            </div>
            <div class="col-md-9"><div class="card-body p-4">
                <div class="d-flex flex-column flex-lg-row justify-content-between gap-3">
                    <div>
                        <span class="badge text-bg-success mb-2">Grupo teórico #<?= e($group['group_code']) ?></span>
                        <h1 class="h3 fw-bold mb-1"><?= e($group['name']) ?></h1>
                        <p class="text-muted mb-2"><?= e($group['description']??'') ?></p>
                        <div class="d-flex align-items-center gap-2 mt-2"><?php if(!empty($group['instructor_photo_path'])): ?><img src="<?= e(asset($group['instructor_photo_path'])) ?>" class="profile-avatar" alt="Foto de <?= e($group['instructor_name']??'Instrutor') ?>"><?php endif; ?><small>Instrutor: <strong><?= e(short_person_name($group['instructor_name']??'')) ?></strong></small></div>
                    </div>
                    <a class="btn btn-outline-primary rounded-pill align-self-start" href="<?= e(url('portal/messages',$base)) ?>"><i class="bi bi-arrow-left"></i> Voltar às mensagens</a>
                </div>
                <hr>
                <div class="d-flex flex-wrap gap-2"><span class="text-muted small me-1">Participantes:</span><?php foreach($members as $member): ?><span class="badge text-bg-light border text-dark"><?= e(short_person_name($member['name'])) ?></span><?php endforeach; ?></div>
            </div></div>
        </div>
    </div>

    <?php if(!empty($groupVideos)): ?>
        <section class="card border-0 shadow-soft rounded-4 mb-4">
            <div class="card-body p-4">
                <div class="d-flex align-items-center gap-2 mb-3">
                    <span class="action-icon text-bg-success"><i class="bi bi-play-btn"></i></span>
                    <div><h2 class="h5 fw-bold mb-0">Vídeos liberados para esta turma</h2><small class="text-muted"><?= count($groupVideos) ?> conteúdo(s) disponível(is)</small></div>
                </div>
                <div class="row g-4">
                    <?php foreach($groupVideos as $video): ?>
                        <div class="col-xl-6"><div class="card border rounded-4 overflow-hidden h-100">
                            <?php if(!empty($video['cover_path'])): ?><img src="<?= e(asset($video['cover_path'])) ?>" class="video-cover" alt="Capa da videoaula"><?php endif; ?>
                            <div class="card-body">
                                <h3 class="h6 fw-bold"><?= e($video['title']) ?></h3>
                                <?php if(!empty($video['description'])): ?><p class="text-muted small"><?= e($video['description']) ?></p><?php endif; ?>
                                <?php if(($video['source_type']??'')==='upload'): ?>
                                    <video class="w-100 rounded-4 bg-dark" controls preload="metadata" src="<?= e(url('portal/video-stream',array_merge($base,['id'=>(int)$video['id']]))) ?>"></video>
                                <?php else: ?>
                                    <?php $embed=video_embed_url($video['video_url']??''); ?>
                                    <?php if($embed!==''): ?><div class="ratio ratio-16x9"><iframe class="rounded-4" src="<?= e($embed) ?>" allowfullscreen loading="lazy"></iframe></div>
                                    <?php elseif(is_direct_video_url($video['video_url']??'')): ?><video class="w-100 rounded-4 bg-dark" controls preload="metadata" src="<?= e($video['video_url']) ?>"></video>
                                    <?php else: ?><a target="_blank" rel="noopener" class="btn btn-primary rounded-pill" href="<?= e($video['video_url']) ?>"><i class="bi bi-box-arrow-up-right"></i> Abrir vídeo</a><?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div></div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
    <?php endif; ?>

    <div class="card border-0 shadow-soft rounded-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>
        <div class="group-chat chat-scroll-panel mb-4" data-chat-scroll aria-label="Mensagens do grupo">
            <?php if(empty($messages)): ?><div class="alert alert-light border rounded-4">Ainda não há mensagens nesta turma.</div><?php endif; ?>
            <?php foreach($messages as $message): ?>
                <?php $fileUrl = !empty($message['attachment_path']) ? url('portal/messages/file', array_merge($base, ['message_id'=>(int)$message['id']])) : ''; ?>
                <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"><strong><?= e($message['sender_name']) ?></strong> · <?= e($message['sender_label']) ?> · <?= e(date('d/m/Y H:i',strtotime($message['created_at']))) ?></div>
                    <div class="message-bubble">
                        <?php if(trim((string)($message['message_body']??''))!==''): ?><div><?= nl2br(e($message['message_body'])) ?></div><?php endif; ?>
                        <?php if($fileUrl!==''): ?>
                            <?php $attachmentMime=strtolower((string)($message['attachment_mime']??'')); $attachmentName=strtolower((string)($message['attachment_name']??'')); $isAudio=str_starts_with($attachmentMime,'audio/')||in_array($attachmentMime,['video/webm','application/ogg'],true)||preg_match('/\.(webm|ogg|oga|mp3|m4a|wav|aac)$/',$attachmentName); ?>
                            <?php if(str_starts_with($attachmentMime,'image/')): ?>
                                <button type="button" class="group-image-preview-button mt-2" aria-label="Ampliar imagem enviada"><img class="group-message-image" src="<?= e($fileUrl) ?>" alt="<?= e($message['attachment_name']??'Imagem enviada') ?>" loading="lazy" draggable="false"></button>
                            <?php elseif($isAudio): ?>
                                <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 else: ?>
                                <a class="btn btn-light border rounded-pill mt-2" href="<?= e($fileUrl) ?>" target="_blank" rel="noopener"><i class="bi bi-file-earmark-pdf text-danger"></i> <?= e($message['attachment_name']??'Abrir PDF') ?></a>
                            <?php endif; ?>
                        <?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 apenas para você?');"><?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="group_id" value="<?= (int)$group['id'] ?>"><input type="hidden" name="message_id" value="<?= (int)$message['id'] ?>"><input type="hidden" name="delete_mode" value="self"><button class="btn btn-sm btn-outline-secondary rounded-pill">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 para todos do grupo?');"><?= CSRF::input() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="group_id" value="<?= (int)$group['id'] ?>"><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">Apagar para todos</button></form><?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <form method="post" action="<?= e(url('portal/messages/group-send',array_merge($base,['id'=>(int)$group['id']]))) ?>" enctype="multipart/form-data" class="row g-2" 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="group_id" value="<?= (int)$group['id'] ?>">
            <div class="col-12"><textarea name="message_body" rows="2" class="form-control" placeholder="Escreva uma mensagem para a turma..."></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>
            <?php if(in_array($actorType,['admin','professional'],true)): ?>
                <div class="col-md-9">
                    <label class="btn btn-outline-primary rounded-pill w-100 text-start mb-0"><i class="bi bi-paperclip"></i> Anexar imagem ou PDF <input type="file" name="group_attachment" class="visually-hidden" accept="image/jpeg,image/png,image/webp,image/gif,application/pdf,.pdf" onchange="this.parentElement.querySelector('.file-name').textContent=this.files[0]?this.files[0].name:'Nenhum arquivo selecionado'"><span class="file-name small ms-2 text-muted">Nenhum arquivo selecionado</span></label>
                    <small class="text-muted d-block mt-1">Até 25 MB. Disponível para o administrador e o instrutor responsável pela turma.</small>
                </div>
                <div class="col-md-3"><button class="btn btn-success rounded-4 w-100 h-100"><i class="bi bi-send"></i> Enviar</button></div>
            <?php else: ?>
                <div class="col-12"><button class="btn btn-success rounded-pill px-4"><i class="bi bi-send"></i> Enviar mensagem</button></div>
            <?php endif; ?>
        </form>
    </div></div>
</main>
