<?= $this->extend('layouts/enterprise') ?>

<?= $this->section('styles') ?>
<link rel="stylesheet" href="<?= base_url('assets/css/messaging.css') ?>">
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Messages',
    'workspaceCrumbCurrent' => 'Inbox',
    'workspaceTitle'        => 'Messages',
    'workspaceDesc'         => 'Direct messages, the public channel, and team groups.',
    'workspaceAction'       => ! empty($isAdmin) ? [
        'href'  => base_url('messages/groups'),
        'label' => 'Manage Groups',
        'icon'  => 'fa-solid fa-users-gear',
    ] : null,
]) ?>

<div class="msg-shell enterprise-data-panel">
    <aside class="msg-sidebar">
        <div class="msg-sidebar__head">
            <h2 class="msg-sidebar__title">Conversations</h2>
            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#msgNewDmModal">
                <i class="fa-solid fa-pen-to-square me-1"></i>New
            </button>
        </div>
        <div class="msg-sidebar__list" id="msgConversationList">
            <?php if (empty($conversations)): ?>
                <p class="msg-empty">No conversations yet.</p>
            <?php else: ?>
                <?php foreach ($conversations as $c): ?>
                    <?php
                    $title = $c['type'] === 'direct'
                        ? ($c['peer_name'] ?? 'Direct message')
                        : ($c['name'] ?? 'Conversation');
                    $icon = match ($c['type']) {
                        'public' => 'fa-bullhorn',
                        'group'  => 'fa-users',
                        default  => 'fa-user',
                    };
                    $preview = $c['last_message'] ?? 'No messages yet';
                    $unread  = (int) ($c['unread_count'] ?? 0);
                    $isActive = (int) $c['id'] === (int) $activeId;
                    ?>
                    <a
                        href="<?= base_url('messages?c=' . $c['id']) ?>"
                        class="msg-conv<?= $isActive ? ' is-active' : '' ?>"
                    >
                        <span class="msg-conv__icon msg-conv__icon--<?= esc($c['type']) ?>">
                            <i class="fa-solid <?= $icon ?>"></i>
                        </span>
                        <span class="msg-conv__body">
                            <span class="msg-conv__top">
                                <span class="msg-conv__name"><?= esc($title) ?></span>
                                <?php if ($unread > 0 && ! $isActive): ?>
                                    <span class="msg-conv__badge"><?= $unread > 99 ? '99+' : $unread ?></span>
                                <?php endif; ?>
                            </span>
                            <span class="msg-conv__preview"><?= esc(character_limiter($preview, 48)) ?></span>
                        </span>
                    </a>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </aside>

    <section class="msg-thread" id="msgThread" data-conversation-id="<?= (int) $activeId ?>" data-user-id="<?= (int) ($currentUser['id'] ?? 0) ?>">
        <?php if (! $active): ?>
            <div class="msg-thread__empty">
                <i class="fa-regular fa-comments"></i>
                <p>Select a conversation or start a new direct message.</p>
            </div>
        <?php else: ?>
            <header class="msg-thread__head">
                <div>
                    <h2 class="msg-thread__title"><?= esc($activeTitle) ?></h2>
                    <p class="msg-thread__meta">
                        <?php if ($active['type'] === 'public'): ?>
                            Public channel · everyone can post
                        <?php elseif ($active['type'] === 'group'): ?>
                            Group · <?= count($members) ?> member<?= count($members) === 1 ? '' : 's' ?>
                            <?php if (! empty($isAdmin)): ?>
                                · <a href="<?= base_url('messages/groups/' . $active['id'] . '/edit') ?>">Edit</a>
                            <?php endif; ?>
                        <?php else: ?>
                            Direct message
                        <?php endif; ?>
                    </p>
                </div>
            </header>

            <div class="msg-thread__messages" id="msgMessages">
                <?php
                $lastId = 0;
                foreach ($thread as $m):
                    $lastId = (int) $m['id'];
                    $mine = (int) $m['sender_id'] === (int) ($currentUser['id'] ?? 0);
                    $senderName = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                    if ($senderName === '') {
                        $senderName = $m['username'] ?? 'User';
                    }
                ?>
                    <div class="msg-bubble<?= $mine ? ' msg-bubble--mine' : '' ?>" data-message-id="<?= (int) $m['id'] ?>">
                        <?php if (! $mine): ?>
                            <div class="msg-bubble__sender"><?= esc($senderName) ?></div>
                        <?php endif; ?>
                        <div class="msg-bubble__body"><?= nl2br(esc($m['body'])) ?></div>
                        <div class="msg-bubble__time"><?= esc(date('M j, g:i A', strtotime($m['created_at']))) ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <form
                class="msg-composer"
                id="msgComposer"
                method="post"
                action="<?= base_url('messages/' . $active['id'] . '/send') ?>"
                data-last-id="<?= $lastId ?>"
            >
                <?= csrf_field() ?>
                <textarea
                    name="body"
                    id="msgBody"
                    class="form-control"
                    rows="2"
                    placeholder="Write a message…"
                    required
                    maxlength="5000"
                ></textarea>
                <button type="submit" class="btn btn-primary msg-composer__send">
                    <i class="fa-solid fa-paper-plane"></i>
                    <span>Send</span>
                </button>
            </form>
        <?php endif; ?>
    </section>
</div>

<!-- New DM modal -->
<div class="modal fade" id="msgNewDmModal" tabindex="-1" aria-labelledby="msgNewDmModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form method="post" action="<?= base_url('messages/direct') ?>" class="modal-content">
            <?= csrf_field() ?>
            <div class="modal-header">
                <h5 class="modal-title" id="msgNewDmModalLabel">New direct message</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <label class="enterprise-field-label" for="peer_user_id">Send to</label>
                <select name="peer_user_id" id="peer_user_id" class="form-select" required>
                    <option value="">Select a user…</option>
                    <?php foreach ($users as $u): ?>
                        <option value="<?= (int) $u['id'] ?>">
                            <?= esc(trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')) ?: $u['username']) ?>
                            (<?= esc($u['username'] ?? '') ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Start chat</button>
            </div>
        </form>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="<?= base_url('assets/js/messaging.js') ?>"></script>
<?= $this->endSection() ?>
