<?php $pageTitle = t('members'); ?>

<div class="page-header">
    <div class="page-header-left">
        <a href="/project/<?= $project['id'] ?>" class="btn btn-ghost btn-sm">← <?= Helper::e($project['name']) ?></a>
        <h1 class="page-title"><?= t('members') ?></h1>
    </div>
</div>

<?php if ($success): ?>
<div class="alert alert-success"><?= Helper::e($success) ?></div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<div class="alert alert-error"><?php foreach ($errors as $e): ?><div><?= Helper::e($e) ?></div><?php endforeach; ?></div>
<?php endif; ?>

<div class="settings-grid">

<!-- ── Left column: lists ────────────────────────────────────── -->
<div class="settings-col">

    <!-- Registered members -->
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('members') ?></h2></div>
        <div class="card-body p-0">
            <table class="data-table">
                <thead>
                    <tr>
                        <th><?= t('username') ?></th>
                        <th><?= t('email') ?></th>
                        <th><?= t('member_role') ?></th>
                        <th><?= t('last_login') ?></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($members as $member): ?>
                <tr>
                    <td>
                        <div class="user-cell">
                            <?= Helper::avatar(['username' => $member['username'], 'avatar' => $member['avatar'], 'id' => $member['user_id']], 28) ?>
                            <?= Helper::e($member['username']) ?>
                        </div>
                    </td>
                    <td><?= Helper::e($member['email']) ?></td>
                    <td>
                        <form method="POST" class="inline-role-form">
                            <?= Helper::csrf() ?>
                            <input type="hidden" name="action" value="update_role">
                            <input type="hidden" name="member_id" value="<?= $member['id'] ?>">
                            <select name="role" class="form-select form-select-sm" data-auto-submit>
                                <option value="owner"   <?= $member['role'] === 'owner'   ? 'selected' : '' ?>><?= t('role_owner') ?></option>
                                <option value="manager" <?= $member['role'] === 'manager' ? 'selected' : '' ?>><?= t('role_manager') ?></option>
                                <option value="member"  <?= $member['role'] === 'member'  ? 'selected' : '' ?>><?= t('role_member') ?></option>
                                <option value="guest"   <?= $member['role'] === 'guest'   ? 'selected' : '' ?>><?= t('role_guest') ?></option>
                            </select>
                        </form>
                    </td>
                    <td><?= $member['last_login'] ? Helper::formatDateTime($member['last_login']) : t('never') ?></td>
                    <td>
                        <form method="POST" data-confirm="<?= Helper::e(t('confirm_delete')) ?>">
                            <?= Helper::csrf() ?>
                            <input type="hidden" name="action" value="remove_member">
                            <input type="hidden" name="member_id" value="<?= $member['id'] ?>">
                            <button type="submit" class="icon-btn-sm danger">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- External participants list -->
    <?php if (!empty($externals)): ?>
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('external_participants') ?></h2></div>
        <div class="card-body p-0">
            <table class="data-table">
                <thead>
                    <tr>
                        <th><?= t('username') ?></th>
                        <th><?= t('email') ?></th>
                        <th><?= t('ext_portal_link') ?></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($externals as $ext): ?>
                <tr>
                    <td>
                        <span class="avatar-initials avatar-ext" style="width:28px;height:28px;font-size:11px;display:inline-flex;align-items:center;justify-content:center;margin-right:6px"><?= Helper::e(mb_strtoupper(mb_substr($ext['name'],0,1))) ?></span>
                        <?= Helper::e($ext['name']) ?>
                    </td>
                    <td><?= Helper::e($ext['email']) ?></td>
                    <td>
                        <a href="/ext/<?= $ext['token'] ?>" class="link-sm" target="_blank" style="font-size:12px;word-break:break-all">/ext/<?= substr($ext['token'],0,12) ?>…</a>
                    </td>
                    <td>
                        <form method="POST" data-confirm="<?= Helper::e(t('confirm_delete')) ?>">
                            <?= Helper::csrf() ?>
                            <input type="hidden" name="action" value="remove_external">
                            <input type="hidden" name="external_id" value="<?= $ext['id'] ?>">
                            <button type="submit" class="icon-btn-sm danger">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- Dummy assignees list -->
    <?php if (!empty($dummies)): ?>
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('dummy_assignees') ?></h2></div>
        <div class="card-body">
            <div class="assignee-member-list">
                <?php foreach ($dummies as $d): ?>
                <div style="display:flex;align-items:center;gap:8px;padding:4px 0">
                    <span class="avatar-initials avatar-ext" style="width:28px;height:28px;font-size:11px;display:inline-flex;align-items:center;justify-content:center"><?= Helper::e(mb_strtoupper(mb_substr($d['name'],0,1))) ?></span>
                    <span style="flex:1"><?= Helper::e($d['name']) ?></span>
                    <form method="POST" data-confirm="<?= Helper::e(t('confirm_delete')) ?>">
                        <?= Helper::csrf() ?>
                        <input type="hidden" name="action" value="remove_external">
                        <input type="hidden" name="external_id" value="<?= $d['id'] ?>">
                        <button type="submit" class="icon-btn-sm danger">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
                        </button>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /settings-col left -->

<!-- ── Right column: add forms ──────────────────────────────── -->
<div class="settings-col">

    <!-- Add registered member -->
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('add_member') ?></h2></div>
        <div class="card-body">
            <form method="POST" id="addMemberForm">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="add_member">
                <input type="hidden" name="user_id" id="memberUserId" required>
                <div class="form-group">
                    <label class="form-label"><?= t('select_user') ?></label>
                    <div style="position:relative">
                        <input type="text" id="memberSearch" class="form-input" autocomplete="off"
                               placeholder="<?= t('search') ?>…"
                               style="padding-right:32px">
                        <svg style="position:absolute;right:10px;top:50%;transform:translateY(-50%);pointer-events:none;opacity:.4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
                        <div id="memberDropdown" style="display:none;position:absolute;top:calc(100% + 3px);left:0;right:0;background:#fff;border:1px solid var(--border-color);border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.1);max-height:114px;overflow-y:auto;z-index:200"></div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('member_role') ?></label>
                    <select name="role" class="form-select">
                        <option value="member"><?= t('role_member') ?></option>
                        <option value="manager"><?= t('role_manager') ?></option>
                        <option value="owner"><?= t('role_owner') ?></option>
                        <option value="guest"><?= t('role_guest') ?></option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary"><?= t('add_member') ?></button>
            </form>
            <script nonce="<?= csp_nonce() ?>">
            (function () {
                // Server-side type-ahead. The full user directory is no longer shipped to the
                // page; matches are fetched on demand with a 2-character minimum (security-audit #24).
                const PROJECT_ID = <?= (int)$project['id'] ?>;
                const MIN_CHARS  = 2;
                const input    = document.getElementById('memberSearch');
                const hidden   = document.getElementById('memberUserId');
                const dropdown = document.getElementById('memberDropdown');
                let activeIdx  = -1;
                let lastResults = [];
                let debounceTimer = null;
                let inflightAbort = null;
                let reqSeq = 0;

                function setActive(idx) {
                    const items = dropdown.querySelectorAll('div');
                    items.forEach((el, i) => el.style.background = i === idx ? 'var(--bg-secondary, #f1f5f9)' : '');
                    activeIdx = idx;
                }

                function renderItems(matches) {
                    dropdown.replaceChildren();
                    activeIdx = -1;
                    lastResults = matches;
                    if (matches.length === 0) {
                        dropdown.style.display = 'none';
                        return;
                    }
                    matches.forEach((u, i) => {
                        const item = document.createElement('div');
                        item.dataset.id = u.id;
                        item.style.cssText = 'height:38px;box-sizing:border-box;padding:0 12px;cursor:pointer;display:flex;align-items:center;gap:10px;font-size:.875rem;flex-shrink:0';
                        const name = document.createElement('span');
                        name.style.cssText = 'flex:1;font-weight:500';
                        name.textContent = u.username;
                        const mail = document.createElement('span');
                        mail.style.cssText = 'color:var(--text-secondary);font-size:.78rem';
                        mail.textContent = u.email;
                        item.appendChild(name);
                        item.appendChild(mail);
                        item.addEventListener('mousedown', e => { e.preventDefault(); select(u); });
                        item.addEventListener('mouseover', () => setActive(i));
                        dropdown.appendChild(item);
                    });
                    dropdown.style.display = 'block';
                }

                function select(u) {
                    input.value  = u.username + ' (' + u.email + ')';
                    hidden.value = u.id;
                    dropdown.style.display = 'none';
                }

                async function search(q) {
                    if (q.length < MIN_CHARS) { renderItems([]); return; }
                    if (inflightAbort) inflightAbort.abort();
                    inflightAbort = new AbortController();
                    const seq = ++reqSeq;
                    const base = typeof BASE_URL !== 'undefined' ? BASE_URL : '';
                    const csrf = typeof CSRF_TOKEN !== 'undefined' ? CSRF_TOKEN : '';
                    try {
                        const res = await fetch(base + '/api/project/available-users', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ project_id: PROJECT_ID, q: q, csrf_token: csrf }),
                            signal: inflightAbort.signal,
                        });
                        if (!res.ok) { renderItems([]); return; }
                        const data = await res.json();
                        if (seq !== reqSeq) return; // stale response
                        renderItems(Array.isArray(data.users) ? data.users : []);
                    } catch (e) {
                        if (e.name !== 'AbortError') renderItems([]);
                    }
                }

                function scheduleSearch() {
                    clearTimeout(debounceTimer);
                    const q = input.value.trim();
                    debounceTimer = setTimeout(() => search(q), 200);
                }

                input.addEventListener('focus', scheduleSearch);
                input.addEventListener('input', () => { hidden.value = ''; scheduleSearch(); });
                input.addEventListener('keydown', e => {
                    const items = dropdown.querySelectorAll('div');
                    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(Math.min(activeIdx + 1, items.length - 1)); }
                    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(Math.max(activeIdx - 1, 0)); }
                    else if (e.key === 'Enter' && activeIdx >= 0) {
                        e.preventDefault();
                        const id = items[activeIdx].dataset.id;
                        const match = lastResults.find(u => String(u.id) === id);
                        if (match) select(match);
                    } else if (e.key === 'Escape') { dropdown.style.display = 'none'; }
                });
                document.addEventListener('click', e => { if (!input.contains(e.target) && !dropdown.contains(e.target)) dropdown.style.display = 'none'; });

                dropdown.addEventListener('wheel', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    let delta = e.deltaY;
                    if (e.deltaMode === 1) delta *= 38;
                    else if (e.deltaMode === 2) delta *= this.clientHeight;
                    this.scrollTop += delta;
                }, { passive: false });

                document.getElementById('addMemberForm').addEventListener('submit', function (e) {
                    if (!hidden.value) { e.preventDefault(); input.focus(); input.style.borderColor = 'var(--color-danger, #ef4444)'; }
                });
            })();
            </script>
        </div>
    </div>

    <!-- Add external participant -->
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('external_participants') ?></h2></div>
        <div class="card-body">
            <p class="form-hint" style="margin-bottom:12px"><?= t('external_participants_hint') ?></p>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="add_external">
                <div class="form-group">
                    <label class="form-label"><?= t('ext_name_placeholder') ?></label>
                    <input type="text" name="ext_name" class="form-input" placeholder="<?= t('ext_name_placeholder') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('ext_email_placeholder') ?></label>
                    <input type="email" name="ext_email" class="form-input" placeholder="<?= t('ext_email_placeholder') ?>">
                </div>
                <button type="submit" class="btn btn-primary"><?= t('add') ?></button>
            </form>
        </div>
    </div>

    <!-- Add dummy assignee -->
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('dummy_assignees') ?></h2></div>
        <div class="card-body">
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="add_dummy">
                <div class="form-group">
                    <label class="form-label"><?= t('username') ?></label>
                    <input type="text" name="dummy_name" class="form-input" placeholder="<?= t('external_name_placeholder') ?>">
                </div>
                <button type="submit" class="btn btn-primary"><?= t('add') ?></button>
            </form>
        </div>
    </div>

</div><!-- /settings-col right -->
</div><!-- /settings-grid -->
