<?php
$team = $team ?? [];
$members = $members ?? [];
$servers = $servers ?? [];
$availableServers = $availableServers ?? [];
?>

<div class="page-header">
    <div class="page-header-left">
        <div class="back-link">
            <a href="/teams"><i class="fas fa-arrow-left"></i> Back to Teams</a>
        </div>
        <h1 class="page-title"><?= htmlspecialchars($team['name'] ?? '') ?></h1>
        <p class="page-subtitle"><?= htmlspecialchars($team['description'] ?? '') ?></p>
    </div>
    <div class="page-header-right">
        <button class="btn btn-secondary" onclick="editTeam()">
            <i class="fas fa-edit"></i> Edit
        </button>
        <button class="btn btn-danger" onclick="deleteTeam()">
            <i class="fas fa-trash"></i> Delete
        </button>
    </div>
</div>

<div class="dashboard-grid">
    <div class="dashboard-card">
        <div class="card-header">
            <h2><i class="fas fa-users"></i> Members</h2>
            <span class="badge badge-info"><?= count($members) ?></span>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="membersList">
                        <?php foreach ($members as $member): ?>
                            <tr>
                                <td>
                                    <strong><?= htmlspecialchars($member['username']) ?></strong>
                                    <br><small class="text-muted"><?= htmlspecialchars($member['email']) ?></small>
                                </td>
                                <td>
                                    <button class="btn btn-xs btn-danger"
                                            onclick="removeMember(<?= $member['user_id'] ?>, '<?= htmlspecialchars(addslashes($member['username'])) ?>')">
                                        <i class="fas fa-user-minus"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="autocomplete-wrapper" style="margin-top:1rem">
                <label class="form-label">Add Member</label>
                <div class="autocomplete" id="userAutocomplete">
                    <input type="text" class="form-input autocomplete-input"
                           id="addUserInput" placeholder="Search users..."
                           autocomplete="off">
                    <div class="autocomplete-dropdown" id="userDropdown"></div>
                </div>
                <small class="form-hint">Type at least 2 characters to search users.</small>
            </div>
        </div>
    </div>

    <div class="dashboard-card">
        <div class="card-header">
            <h2><i class="fas fa-server"></i> Servers</h2>
            <span class="badge badge-primary"><?= count($servers) ?></span>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Server</th>
                            <th>Role</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($servers as $s): ?>
                            <tr>
                                <td>
                                    <a href="/servers/<?= $s['server_id'] ?>">
                                        <?= htmlspecialchars($s['server_name']) ?>
                                    </a>
                                </td>
                                <td>
                                    <select class="form-select form-select-sm role-select"
                                            onchange="updateServerRole(<?= $s['server_id'] ?>, this.value)"
                                            style="width:auto">
                                        <option value="viewer" <?= $s['role'] === 'viewer' ? 'selected' : '' ?>>Viewer</option>
                                        <option value="manager" <?= $s['role'] === 'manager' ? 'selected' : '' ?>>Manager</option>
                                    </select>
                                </td>
                                <td>
                                    <button class="btn btn-xs btn-danger"
                                            onclick="removeServer(<?= $s['server_id'] ?>, '<?= htmlspecialchars(addslashes($s['server_name'])) ?>')">
                                        <i class="fas fa-unlink"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if (!empty($availableServers)): ?>
            <form class="form-inline" style="margin-top:1rem;display:flex;gap:0.5rem;align-items:end" onsubmit="addServer(event)">
                <input type="hidden" name="_csrf_token" value="<?= $this->csrfToken() ?>">
                <div class="form-group" style="flex:1;margin-bottom:0">
                    <select id="addServerId" class="form-select" required>
                        <option value="">Assign server...</option>
                        <?php foreach ($availableServers as $s): ?>
                            <option value="<?= $s['id'] ?>">
                                <?= htmlspecialchars($s['name']) ?> (<?= htmlspecialchars($s['ip_address']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" style="margin-bottom:0">
                    <select id="addServerRole" class="form-select" required>
                        <option value="viewer">Viewer</option>
                        <option value="manager">Manager</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary btn-sm">
                    <i class="fas fa-plus"></i> Assign
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<form id="postForm" method="POST" style="display:none">
    <input type="hidden" name="_csrf_token" value="<?= $this->csrfToken() ?>">
</form>

<script>
function getCsrfToken() {
    return document.querySelector('meta[name="csrf-token"]')?.content || '';
}

function editTeam() {
    const name = prompt('Team name:', '<?= htmlspecialchars(addslashes($team['name'] ?? '')) ?>');
    if (!name) return;
    const desc = prompt('Description:', '<?= htmlspecialchars(addslashes($team['description'] ?? '')) ?>');

    const form = new FormData();
    form.append('name', name);
    form.append('description', desc || '');
    form.append('_csrf_token', getCsrfToken());

    fetch('/teams/<?= $team['id'] ?>/update', {
        method: 'POST',
        headers: { 'X-CSRF-Token': getCsrfToken() },
        body: form,
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) { showToast('success', res.message); location.reload(); }
        else { showToast('error', res.message); }
    });
}

function deleteTeam() {
    if (!confirm('Delete this team? Members will lose access to assigned servers.')) return;
    document.getElementById('postForm').action = '/teams/<?= $team['id'] ?>/delete';
    document.getElementById('postForm').submit();
}

/* ───── Autocomplete para usuarios ───── */
let searchTimeout = null;
let selectedUserId = null;

document.getElementById('addUserInput').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    const q = this.value.trim();
    selectedUserId = null;

    if (q.length < 2) {
        document.getElementById('userDropdown').classList.remove('active');
        return;
    }

    searchTimeout = setTimeout(function() {
        fetch('/teams/search-users?q=' + encodeURIComponent(q), {
            headers: { 'X-CSRF-Token': getCsrfToken() }
        })
        .then(r => r.json())
        .then(data => {
            const dropdown = document.getElementById('userDropdown');
            dropdown.innerHTML = '';
            if (data.users && data.users.length > 0) {
                data.users.forEach(function(u) {
                    const item = document.createElement('div');
                    item.className = 'autocomplete-item';
                    item.innerHTML = '<strong>' + escapeHtml(u.username) + '</strong> <small>' + escapeHtml(u.email) + '</small>';
                    item.dataset.id = u.id;
                    item.dataset.username = u.username;
                    item.addEventListener('click', function() {
                        selectUser(u.id, u.username);
                    });
                    dropdown.appendChild(item);
                });
                dropdown.classList.add('active');
            } else {
                dropdown.innerHTML = '<div class="autocomplete-empty">No users found</div>';
                dropdown.classList.add('active');
            }
        })
        .catch(function() {
            document.getElementById('userDropdown').classList.remove('active');
        });
    }, 300);
});

document.addEventListener('click', function(e) {
    if (!e.target.closest('.autocomplete')) {
        document.getElementById('userDropdown').classList.remove('active');
    }
});

function selectUser(id, username) {
    selectedUserId = id;
    document.getElementById('addUserInput').value = username;
    document.getElementById('userDropdown').classList.remove('active');

    // Auto-add the user
    const form = new FormData();
    form.append('user_id', id);
    form.append('_csrf_token', getCsrfToken());

    fetch('/teams/<?= $team['id'] ?>/add-user', {
        method: 'POST',
        headers: { 'X-CSRF-Token': getCsrfToken() },
        body: form,
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            showToast('success', username + ' added to team');
            location.reload();
        } else {
            showToast('error', res.message);
            document.getElementById('addUserInput').value = '';
        }
    });
}

/* ───── Funciones existentes ───── */
function removeMember(userId, username) {
    if (!confirm('Remove "' + username + '" from this team?')) return;

    const form = new FormData();
    form.append('user_id', userId);
    form.append('_csrf_token', getCsrfToken());

    fetch('/teams/<?= $team['id'] ?>/remove-user', {
        method: 'POST',
        headers: { 'X-CSRF-Token': getCsrfToken() },
        body: form,
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) { showToast('success', res.message); location.reload(); }
        else { showToast('error', res.message); }
    });
}

function addServer(e) {
    e.preventDefault();
    const serverId = document.getElementById('addServerId').value;
    const role = document.getElementById('addServerRole').value;
    if (!serverId) return;

    const form = new FormData();
    form.append('server_id', serverId);
    form.append('role', role);
    form.append('_csrf_token', getCsrfToken());

    fetch('/teams/<?= $team['id'] ?>/add-server', {
        method: 'POST',
        headers: { 'X-CSRF-Token': getCsrfToken() },
        body: form,
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) { showToast('success', res.message); location.reload(); }
        else { showToast('error', res.message); }
    });
}

function removeServer(serverId, name) {
    if (!confirm('Remove "' + name + '" from this team?')) return;

    const form = new FormData();
    form.append('server_id', serverId);
    form.append('_csrf_token', getCsrfToken());

    fetch('/teams/<?= $team['id'] ?>/remove-server', {
        method: 'POST',
        headers: { 'X-CSRF-Token': getCsrfToken() },
        body: form,
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) { showToast('success', res.message); location.reload(); }
        else { showToast('error', res.message); }
    });
}

function updateServerRole(serverId, role) {
    const form = new FormData();
    form.append('server_id', serverId);
    form.append('role', role);
    form.append('_csrf_token', getCsrfToken());

    fetch('/teams/<?= $team['id'] ?>/update-server-role', {
        method: 'POST',
        headers: { 'X-CSRF-Token': getCsrfToken() },
        body: form,
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) { showToast('success', 'Role updated to ' + role); }
        else { showToast('error', res.message); }
    });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
</script>
