<?php
$userEdit = $editUser ?? null;
$isEdit = !empty($userEdit);
$formAction = $isEdit ? '/admin/users/' . (int)$userEdit['id'] . '/update' : '/admin/users/store';
$stats = $stats ?? ['favorites' => 0, 'likes' => 0, 'comments' => 0, 'history' => 0];
$recentComments = $recentComments ?? [];
$recentFavorites = $recentFavorites ?? [];
$isSelf = $isEdit && (int)($userEdit['id'] ?? 0) === Auth::id();
$userRole = $userEdit['role'] ?? 'user';
$isActive = !empty($userEdit['is_active']);
$avatarColors = ['admin' => 'bg-red-500', 'moderator' => 'bg-yellow-500', 'user' => 'bg-blue-500'];
$avatarBg = $avatarColors[$userRole] ?? 'bg-blue-500';
$roleBadgeColors = ['admin' => 'bg-red-100 text-red-800', 'moderator' => 'bg-yellow-100 text-yellow-800', 'user' => 'bg-blue-100 text-blue-800'];
$roleBadge = $roleBadgeColors[$userRole] ?? 'bg-blue-100 text-blue-800';
$memberSince = !empty($userEdit['created_at']) ? date('M Y', strtotime($userEdit['created_at'])) : 'N/A';
$initial = mb_strtoupper(mb_substr($userEdit['username'] ?? 'U', 0, 1));
?>

<?php if ($isEdit): ?>

<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
    <div class="flex flex-col sm:flex-row sm:items-center gap-4">
        
        <div class="w-16 h-16 rounded-full <?= $avatarBg ?> flex items-center justify-center text-white text-2xl font-bold shrink-0">
            <?= htmlspecialchars($initial) ?>
        </div>
        
        <div class="flex-1 min-w-0">
            <div class="flex flex-wrap items-center gap-2 mb-1">
                <h2 class="text-xl font-bold text-gray-900"><?= htmlspecialchars($userEdit['username'] ?? '') ?></h2>
                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold <?= $roleBadge ?>"><?= ucfirst(htmlspecialchars($userRole)) ?></span>
                <span id="activeBadge" class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold <?= $isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                    <?= $isActive ? 'Active' : 'Inactive' ?>
                </span>
            </div>
            <p class="text-sm text-gray-500">Member since <?= htmlspecialchars($memberSince) ?> &middot; User #<?= (int)$userEdit['id'] ?></p>
        </div>
        
        <div class="flex flex-wrap items-center gap-2 shrink-0">
            <button type="button" id="btnSetPassword" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 text-blue-700 text-xs font-medium rounded-lg border border-blue-200 hover:bg-blue-100 transition-colors">
                <i class="fa-solid fa-key text-[10px]"></i> Set Password
            </button>
            <button type="button" id="btnToggleActive" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors <?= $isActive ? 'bg-yellow-50 text-yellow-700 border-yellow-200 hover:bg-yellow-100' : 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100' ?>" data-user-id="<?= (int)$userEdit['id'] ?>" data-active="<?= $isActive ? '1' : '0' ?>">
                <i class="fa-solid <?= $isActive ? 'fa-ban' : 'fa-check' ?> text-[10px]"></i>
                <span><?= $isActive ? 'Deactivate' : 'Activate' ?></span>
            </button>
            <?php if (!$isSelf): ?>
            <form method="POST" action="/admin/users/<?= (int)$userEdit['id'] ?>/delete" class="inline" onsubmit="return confirm('Are you sure you want to delete this user? This action cannot be undone.');">
                <?= Router::csrfField() ?>
                <button type="submit" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-red-50 text-red-700 text-xs font-medium rounded-lg border border-red-200 hover:bg-red-100 transition-colors">
                    <i class="fa-solid fa-trash text-[10px]"></i> Delete
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>

    
    <div id="passwordPanel" class="hidden mt-4 pt-4 border-t border-gray-200">
        <form method="POST" action="<?= htmlspecialchars($formAction) ?>" class="flex flex-col sm:flex-row items-end gap-3">
            <?= Router::csrfField() ?>
            <input type="hidden" name="username" value="<?= htmlspecialchars($userEdit['username'] ?? '') ?>">
            <input type="hidden" name="email" value="<?= htmlspecialchars($userEdit['email'] ?? '') ?>">
            <input type="hidden" name="role" value="<?= htmlspecialchars($userRole) ?>">
            <input type="hidden" name="bio" value="<?= htmlspecialchars($userEdit['bio'] ?? '') ?>">
            <input type="hidden" name="is_active" value="<?= $isActive ? '1' : '0' ?>">
            <div class="flex-1 w-full sm:w-auto">
                <label class="block text-xs font-medium text-gray-700 mb-1">New Password</label>
                <input type="password" name="password" required minlength="6" placeholder="Enter new password" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
            </div>
            <div class="flex-1 w-full sm:w-auto">
                <label class="block text-xs font-medium text-gray-700 mb-1">Confirm Password</label>
                <input type="password" id="confirmPassword" required minlength="6" placeholder="Confirm new password" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
            </div>
            <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors whitespace-nowrap">
                <i class="fa-solid fa-save text-xs"></i> Save Password
            </button>
        </form>
    </div>
</div>


<div class="flex flex-col lg:flex-row gap-6">

    
    <div class="lg:w-1/3 flex flex-col gap-6">

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <h3 class="text-sm font-semibold text-gray-900 mb-3"><i class="fa-solid fa-chart-bar text-gray-400 mr-1.5"></i> Activity Stats</h3>
            <div class="grid grid-cols-2 gap-3">
                <div class="bg-red-50 rounded-lg p-3 text-center">
                    <i class="fa-solid fa-heart text-red-500 text-lg mb-1"></i>
                    <div class="text-xl font-bold text-gray-900"><?= number_format($stats['favorites']) ?></div>
                    <div class="text-[11px] text-gray-500">Favorites</div>
                </div>
                <div class="bg-blue-50 rounded-lg p-3 text-center">
                    <i class="fa-solid fa-thumbs-up text-blue-500 text-lg mb-1"></i>
                    <div class="text-xl font-bold text-gray-900"><?= number_format($stats['likes']) ?></div>
                    <div class="text-[11px] text-gray-500">Liked</div>
                </div>
                <div class="bg-amber-50 rounded-lg p-3 text-center">
                    <i class="fa-solid fa-comment text-amber-500 text-lg mb-1"></i>
                    <div class="text-xl font-bold text-gray-900"><?= number_format($stats['comments']) ?></div>
                    <div class="text-[11px] text-gray-500">Comments</div>
                </div>
                <div class="bg-purple-50 rounded-lg p-3 text-center">
                    <i class="fa-solid fa-clock-rotate-left text-purple-500 text-lg mb-1"></i>
                    <div class="text-xl font-bold text-gray-900"><?= number_format($stats['history']) ?></div>
                    <div class="text-[11px] text-gray-500">History</div>
                </div>
            </div>
        </div>

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <h3 class="text-sm font-semibold text-gray-900 mb-3"><i class="fa-solid fa-shield-halved text-gray-400 mr-1.5"></i> Security</h3>
            <div class="space-y-3">
                
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-2 text-sm text-gray-700">
                        <i class="fa-solid fa-lock text-gray-400 text-xs"></i>
                        <span>Password</span>
                    </div>
                    <span class="text-xs text-gray-400">&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;</span>
                </div>
                
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-2 text-sm text-gray-700">
                        <i class="fa-solid fa-mobile-screen text-gray-400 text-xs"></i>
                        <span>2FA</span>
                    </div>
                    <?php if (!empty($userEdit['totp_secret'])): ?>
                        <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-green-100 text-green-800">Enabled</span>
                    <?php else: ?>
                        <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-gray-100 text-gray-600">Not enabled</span>
                    <?php endif; ?>
                </div>
                
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-2 text-sm text-gray-700">
                        <i class="fa-solid fa-circle-user text-gray-400 text-xs"></i>
                        <span>Status</span>
                    </div>
                    <span id="securityStatus" class="flex items-center gap-1.5 text-xs font-medium <?= $isActive ? 'text-green-700' : 'text-red-700' ?>">
                        <span class="w-2 h-2 rounded-full <?= $isActive ? 'bg-green-500' : 'bg-red-500' ?>"></span>
                        <?= $isActive ? 'Active' : 'Inactive' ?>
                    </span>
                </div>
            </div>
        </div>

    </div>

    
    <div class="lg:w-2/3 flex flex-col gap-6">

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <h3 class="text-sm font-semibold text-gray-900 mb-3"><i class="fa-solid fa-user-pen text-gray-400 mr-1.5"></i> Account Details</h3>
            <form method="POST" action="<?= htmlspecialchars($formAction) ?>" id="userEditForm">
                <?= Router::csrfField() ?>
                <input type="hidden" name="is_active" value="<?= $isActive ? '1' : '0' ?>">

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="username" class="block text-xs font-medium text-gray-700 mb-1">Username</label>
                        <input type="text" id="username" name="username" value="<?= htmlspecialchars($userEdit['username'] ?? '') ?>" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                    </div>
                    <div>
                        <label for="email" class="block text-xs font-medium text-gray-700 mb-1">Email</label>
                        <input type="email" id="email" name="email" value="<?= htmlspecialchars($userEdit['email'] ?? '') ?>" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                    </div>
                </div>

                <div class="mt-4">
                    <label for="role" class="block text-xs font-medium text-gray-700 mb-1">Role</label>
                    <?php if ($isSelf): ?>
                        <input type="hidden" name="role" value="<?= htmlspecialchars($userRole) ?>">
                        <div class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-gray-50 text-gray-500 cursor-not-allowed flex items-center gap-2">
                            <i class="fa-solid fa-lock text-gray-400 text-xs"></i>
                            <?= ucfirst(htmlspecialchars($userRole)) ?>
                        </div>
                        <p class="mt-1 text-xs text-gray-400">You cannot change your own role.</p>
                    <?php else: ?>
                        <select id="role" name="role" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                            <option value="user" <?= $userRole === 'user' ? 'selected' : '' ?>>User</option>
                            <option value="moderator" <?= $userRole === 'moderator' ? 'selected' : '' ?>>Moderator</option>
                            <option value="admin" <?= $userRole === 'admin' ? 'selected' : '' ?>>Administrator</option>
                        </select>
                    <?php endif; ?>
                </div>

                <div class="mt-4">
                    <label for="bio" class="block text-xs font-medium text-gray-700 mb-1">Bio</label>
                    <textarea id="bio" name="bio" rows="2" maxlength="500" placeholder="Short bio..."
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none resize-none"><?= htmlspecialchars($userEdit['bio'] ?? '') ?></textarea>
                    <p class="mt-1 text-xs text-gray-400">Max 500 characters.</p>
                </div>

                
                <div class="flex flex-col sm:flex-row gap-2 sm:gap-3 mt-6 pt-4 border-t border-gray-200">
                    <button type="submit" class="w-full sm:w-auto inline-flex items-center justify-center gap-1.5 px-5 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">
                        <i class="fa-solid fa-save text-xs"></i> Save Changes
                    </button>
                    <a href="/admin/users" class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">Cancel</a>
                </div>
            </form>
        </div>

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <h3 class="text-sm font-semibold text-gray-900 mb-3"><i class="fa-solid fa-comments text-gray-400 mr-1.5"></i> Recent Comments</h3>
            <?php if (!empty($recentComments)): ?>
                <div class="space-y-3">
                    <?php foreach ($recentComments as $rc): ?>
                        <div class="flex flex-col sm:flex-row sm:items-start gap-2 py-2 border-b border-gray-100 last:border-0">
                            <div class="flex-1 min-w-0">
                                <p class="text-sm text-gray-700 leading-snug">
                                    "<?= htmlspecialchars(mb_strimwidth($rc['body'] ?? '', 0, 80, '...')) ?>"
                                    <?php if (!empty($rc['video_title'])): ?>
                                        <span class="text-gray-400">on</span>
                                        <a href="/admin/videos/<?= (int)$rc['video_id'] ?>/edit" class="text-blue-600 hover:text-blue-800 font-medium"><?= htmlspecialchars(mb_strimwidth($rc['video_title'], 0, 40, '...')) ?></a>
                                    <?php endif; ?>
                                </p>
                                <div class="flex flex-wrap items-center gap-2 mt-1">
                                    <span class="text-[11px] text-gray-400"><?= htmlspecialchars(date('M j, Y', strtotime($rc['created_at']))) ?></span>
                                    <?php
                                    $statusColors = ['approved' => 'bg-green-100 text-green-800', 'pending' => 'bg-yellow-100 text-yellow-800', 'spam' => 'bg-red-100 text-red-800'];
                                    $stClass = $statusColors[$rc['status'] ?? ''] ?? 'bg-gray-100 text-gray-600';
                                    ?>
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium <?= $stClass ?>"><?= ucfirst(htmlspecialchars($rc['status'] ?? 'unknown')) ?></span>
                                    <?php if (($rc['status'] ?? '') === 'pending'): ?>
                                        <form method="POST" action="/admin/comments/<?= (int)$rc['id'] ?>/approve" class="inline">
                                            <?= Router::csrfField() ?>
                                            <button type="submit" class="text-[11px] text-green-600 hover:text-green-800 font-medium">Approve</button>
                                        </form>
                                        <form method="POST" action="/admin/comments/<?= (int)$rc['id'] ?>/delete" class="inline">
                                            <?= Router::csrfField() ?>
                                            <button type="submit" class="text-[11px] text-red-600 hover:text-red-800 font-medium">Delete</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="mt-3 pt-2 border-t border-gray-100">
                    <a href="/admin/comments?q=<?= urlencode($userEdit['username'] ?? '') ?>" class="text-xs text-blue-600 hover:text-blue-800 font-medium">View all comments &rarr;</a>
                </div>
            <?php else: ?>
                <p class="text-sm text-gray-400 py-2">This user hasn't posted any comments yet.</p>
            <?php endif; ?>
        </div>

        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <h3 class="text-sm font-semibold text-gray-900 mb-3"><i class="fa-solid fa-heart text-gray-400 mr-1.5"></i> Recent Favorites</h3>
            <?php if (!empty($recentFavorites)): ?>
                <div class="flex flex-wrap gap-2">
                    <?php foreach ($recentFavorites as $fav): ?>
                        <?php
                        $thumbUrl = '';
                        if (!empty($fav['thumbnail'])) {
                            $thumbUrl = htmlspecialchars($fav['thumbnail']);
                        }
                        ?>
                        <a href="/admin/videos/<?= (int)$fav['id'] ?>/edit" title="<?= htmlspecialchars($fav['title'] ?? '') ?>" class="block w-24 h-16 rounded-lg overflow-hidden border border-gray-200 hover:border-blue-400 transition-colors bg-gray-100 shrink-0">
                            <?php if ($thumbUrl): ?>
                                <img src="<?= $thumbUrl ?>" alt="<?= htmlspecialchars($fav['title'] ?? '') ?>" class="w-full h-full object-cover">
                            <?php else: ?>
                                <div class="w-full h-full flex items-center justify-center text-gray-400"><i class="fa-solid fa-film"></i></div>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="text-sm text-gray-400 py-2">No favorites yet.</p>
            <?php endif; ?>
        </div>

    </div>
</div>

<?php else: ?>

<div class="bg-white rounded-lg shadow-sm border border-gray-200">
    <div class="p-6">
        <form method="POST" action="<?= htmlspecialchars($formAction) ?>">
            <?= Router::csrfField() ?>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
                    <input type="text" id="username" name="username" value="" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                </div>

                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                    <input type="email" id="email" name="email" value="" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                <div>
                    <label for="role" class="block text-sm font-medium text-gray-700 mb-1">Role</label>
                    <select id="role" name="role"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                        <option value="user" selected>User</option>
                        <option value="moderator">Moderator</option>
                        <option value="admin">Administrator</option>
                    </select>
                </div>

                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                    <input type="password" id="password" name="password" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                </div>
            </div>

            <div class="flex items-center gap-2 mt-4">
                <input type="checkbox" id="is_active" name="is_active" value="1" class="w-4 h-4" checked>
                <label for="is_active" class="text-sm text-gray-700">Active account</label>
            </div>

            <div class="flex flex-col sm:flex-row gap-2 sm:gap-3 mt-6 pt-4 border-t border-gray-200">
                <button type="submit" class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700">Create User</button>
                <a href="/admin/users" class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50">Cancel</a>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($isEdit): ?>
<script>
(function(){
    
    var btnPwd = document.getElementById('btnSetPassword');
    var pwdPanel = document.getElementById('passwordPanel');
    if (btnPwd && pwdPanel) {
        btnPwd.addEventListener('click', function() {
            pwdPanel.classList.toggle('hidden');
            if (!pwdPanel.classList.contains('hidden')) {
                pwdPanel.querySelector('input[type=password]').focus();
            }
        });
    }

    
    var btnToggle = document.getElementById('btnToggleActive');
    if (btnToggle) {
        btnToggle.addEventListener('click', function() {
            var userId = this.getAttribute('data-user-id');
            var csrf = '<?= Router::csrfToken() ?>';
            var btn = this;
            var formData = new FormData();
            formData.append('csrf_token', csrf);
            fetch('/admin/users/' + userId + '/toggle-active', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (!data.success) return;
                var isNowActive = data.is_active === 1;
                btn.setAttribute('data-active', isNowActive ? '1' : '0');

                
                var icon = btn.querySelector('i');
                var label = btn.querySelector('span');
                if (isNowActive) {
                    btn.className = 'inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors bg-yellow-50 text-yellow-700 border-yellow-200 hover:bg-yellow-100';
                    icon.className = 'fa-solid fa-ban text-[10px]';
                    label.textContent = 'Deactivate';
                } else {
                    btn.className = 'inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors bg-green-50 text-green-700 border-green-200 hover:bg-green-100';
                    icon.className = 'fa-solid fa-check text-[10px]';
                    label.textContent = 'Activate';
                }

                
                var badge = document.getElementById('activeBadge');
                if (badge) {
                    badge.className = 'inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold ' + (isNowActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800');
                    badge.textContent = isNowActive ? 'Active' : 'Inactive';
                }

                
                var secStatus = document.getElementById('securityStatus');
                if (secStatus) {
                    secStatus.className = 'flex items-center gap-1.5 text-xs font-medium ' + (isNowActive ? 'text-green-700' : 'text-red-700');
                    secStatus.innerHTML = '<span class="w-2 h-2 rounded-full ' + (isNowActive ? 'bg-green-500' : 'bg-red-500') + '"></span>' + (isNowActive ? 'Active' : 'Inactive');
                }

                
                var hiddenActive = document.querySelector('#userEditForm input[name="is_active"]');
                if (hiddenActive) {
                    hiddenActive.value = isNowActive ? '1' : '0';
                }
            })
            .catch(function(err) { alert('Failed to toggle status. Please try again.'); });
        });
    }
})();
</script>
<?php endif; ?>
