const API_BASE = '/api';

let users = [];
let selectedFile = null;
let currentUserId = null;

const usersGrid = document.getElementById('usersGrid');
const btnAddUser = document.getElementById('btnAddUser');

const modalCreateUser = document.getElementById('modalCreateUser');
const closeCreateModal = document.getElementById('closeCreateModal');
const cancelCreate = document.getElementById('cancelCreate');
const createUserForm = document.getElementById('createUserForm');

const modalUserActions = document.getElementById('modalUserActions');
const closeActionsModal = document.getElementById('closeActionsModal');
const actionsModalTitle = document.getElementById('actionsModalTitle');

const modalEditUser = document.getElementById('modalEditUser');
const closeEditModal = document.getElementById('closeEditModal');
const cancelEdit = document.getElementById('cancelEdit');
const editUserForm = document.getElementById('editUserForm');

const modalAniList = document.getElementById('modalAniList');
const closeAniListModal = document.getElementById('closeAniListModal');
const aniListContent = document.getElementById('aniListContent');

const toastContainer = document.getElementById('userToastContainer');

const params = new URLSearchParams(window.location.search);
const anilistStatus = params.get("anilist");

if (anilistStatus === "success") {
    showUserToast("✅ AniList connected successfully!");
}

if (anilistStatus === "error") {
    showUserToast("❌ Failed to connect AniList");
}

document.addEventListener('DOMContentLoaded', () => {
    loadUsers();
    attachEventListeners();
});

function showUserToast(message, type = 'info') {
    if (!toastContainer) return;

    const toast = document.createElement('div');
    toast.className = `wb-toast ${type}`;
    toast.textContent = message;

    toastContainer.prepend(toast);

    setTimeout(() => toast.classList.add('show'), 10);

    setTimeout(() => {
        toast.classList.remove('show');
        toast.addEventListener('transitionend', () => toast.remove());
    }, 4000);
}

function attachEventListeners() {
    if (btnAddUser) btnAddUser.addEventListener('click', openCreateModal);

    if (closeCreateModal) closeCreateModal.addEventListener('click', closeModal);
    if (cancelCreate) cancelCreate.addEventListener('click', closeModal);
    if (closeAniListModal) closeAniListModal.addEventListener('click', closeModal);
    if (closeActionsModal) closeActionsModal.addEventListener('click', closeModal);
    if (closeEditModal) closeEditModal.addEventListener('click', closeModal);
    if (cancelEdit) cancelEdit.addEventListener('click', closeModal);

    if (createUserForm) createUserForm.addEventListener('submit', handleCreateUser);
    if (editUserForm) editUserForm.addEventListener('submit', handleEditUser);

    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-overlay')) closeModal();
        });
    });
}

function initAvatarUpload(uploadAreaId, fileInputId, previewId) {
    const uploadArea = document.getElementById(uploadAreaId);
    const fileInput = document.getElementById(fileInputId);
    const preview = document.getElementById(previewId);

    if (!uploadArea || !fileInput) return;

    uploadArea.addEventListener('click', () => fileInput.click());

    fileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) handleFileSelect(file, previewId);
    });

    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
            handleFileSelect(file, previewId);
        }
    });
}

function handleFileSelect(file, previewId) {
    if (!file.type.startsWith('image/')) {
        showUserToast('Please select an image file', 'error');
        return;
    }

    if (file.size > 5 * 1024 * 1024) {
        showUserToast('Image size must be less than 5MB', 'error');
        return;
    }

    selectedFile = file;

    const reader = new FileReader();
    reader.onload = (e) => {
        const preview = document.getElementById(previewId);
        if (preview) preview.innerHTML = `<img src="${e.target.result}" alt="Avatar preview">`;
    };
    reader.readAsDataURL(file);
}

function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = (err) => reject(err);
        reader.readAsDataURL(file);
    });
}

function togglePasswordVisibility(inputId, buttonElement) {
    const input = document.getElementById(inputId);
    if (!input) return;

    if (input.type === 'password') {
        input.type = 'text';
        buttonElement.innerHTML = `
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                <line x1="1" y1="1" x2="23" y2="23"></line>
            </svg>
        `;
    } else {
        input.type = 'password';
        buttonElement.innerHTML = `
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                <circle cx="12" cy="12" r="3"></circle>
            </svg>
        `;
    }
}

async function loadUsers() {
    try {
        const res = await fetch(`${API_BASE}/users`);
        if (!res.ok) throw new Error('Failed to fetch users');
        const data = await res.json();
        users = data.users || [];
        renderUsers();
    } catch (err) {
        console.error('Error loading users:', err);
        showEmptyState();
    }
}

function renderUsers() {
    if (!usersGrid) return;

    if (users.length === 0) {
        showEmptyState();
        return;
    }

    usersGrid.innerHTML = '';
    users.forEach(user => {
        const userCard = createUserCard(user);
        usersGrid.appendChild(userCard);
    });
}

function createUserCard(user) {
    const card = document.createElement('div');
    card.className = 'user-card';

    if (user.has_password) {
        card.classList.add('has-password');
    }

    card.addEventListener('click', (e) => {
        if (!e.target.closest('.user-config-btn')) {
            loginUser(user.id, user.has_password);
        }
    });

    const avatarContent = user.profile_picture_url
        ? `<img src="${user.profile_picture_url}" alt="${user.username}">`
        : `<div class="user-avatar-placeholder">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                    <circle cx="12" cy="7" r="4"></circle>
                </svg>
           </div>`;

    card.innerHTML = `
        <div class="user-avatar">${avatarContent}</div>
        <div class="user-info">
            <div class="user-name">${user.username}</div>
        </div>
        <button class="user-config-btn" title="Manage User" data-user-id="${user.id}">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="3"></circle>
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0-.33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1.51-1V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
            </svg>
        </button>
    `;

    const configBtn = card.querySelector('.user-config-btn');
    configBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        openUserActionsModal(user.id);
    });

    return card;
}

function showEmptyState() {
    if (!usersGrid) return;
    usersGrid.innerHTML = `
        <div class="empty-state" style="grid-column: 1/-1;">
            <svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                <circle cx="9" cy="7" r="4"></circle>
                <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
            </svg>
            <h2 class="empty-title">No Users Yet</h2>
            <p class="empty-text">Create your first profile to get started</p>
        </div>
    `;
}

function openCreateModal() {
    modalCreateUser.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h2>Create New User</h2>
                <button class="modal-close" onclick="closeModal()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <form id="createUserFormDynamic">
                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" id="username" name="username" required maxlength="20" placeholder="Enter your name">
                </div>
                
                <div class="form-group">
                    <label for="createPassword">
                        Password <span class="optional-label">(Optional)</span>
                    </label>
                    <div class="password-toggle-wrapper">
                        <input type="password" id="createPassword" name="password" placeholder="Leave empty for no password">
                        <button type="button" class="password-toggle-btn" onclick="togglePasswordVisibility('createPassword', this)">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                <circle cx="12" cy="12" r="3"></circle>
                            </svg>
                        </button>
                    </div>
                </div>

                <div class="form-group">
                    <label>Profile Picture</label>
                    <div class="avatar-upload-area" id="avatarUploadArea">
                        <div class="avatar-preview" id="avatarPreview">
                            <svg class="avatar-preview-placeholder" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                        </div>
                        <p class="avatar-upload-text">Click to upload or drag and drop</p>
                        <p class="avatar-upload-hint">PNG, JPG up to 5MB</p>
                    </div>
                    <input type="file" id="avatarInput" accept="image/*">
                </div>

                <div class="modal-actions">
                    <button type="button" class="btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn-primary">Create User</button>
                </div>
            </form>
        </div>
    `;

    modalCreateUser.classList.add('active');

    initAvatarUpload('avatarUploadArea', 'avatarInput', 'avatarPreview');

    document.getElementById('createUserFormDynamic').addEventListener('submit', handleCreateUser);
    document.getElementById('username').focus();

    selectedFile = null;
}

function closeModal() {
    modalCreateUser.classList.remove('active');
    modalAniList.classList.remove('active');
    modalUserActions.classList.remove('active');
    modalEditUser.classList.remove('active');
    selectedFile = null;
}

async function handleCreateUser(e) {
    e.preventDefault();

    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('createPassword').value.trim();

    if (!username) {
        showUserToast('Please enter a username', 'error');
        return;
    }

    const submitBtn = e.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.textContent = 'Creating...';

    try {
        let profilePictureUrl = null;
        if (selectedFile) profilePictureUrl = await fileToBase64(selectedFile);

        const body = { username };
        if (profilePictureUrl) body.profilePictureUrl = profilePictureUrl;
        if (password) body.password = password;

        const res = await fetch(`${API_BASE}/users`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });

        if (!res.ok) {
            const error = await res.json();
            throw new Error(error.error || 'Error creating user');
        }

        closeModal();
        await loadUsers();
        showUserToast(`User ${username} created successfully!`, 'success');
    } catch (err) {
        console.error(err);
        showUserToast(err.message || 'Error creating user', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Create User';
    }
}

function openUserActionsModal(userId) {
    currentUserId = userId;
    const user = users.find(u => u.id === userId);
    if (!user) return;

    modalAniList.classList.remove('active');
    modalEditUser.classList.remove('active');

    actionsModalTitle.textContent = `Manage ${user.username}`;

    const content = document.getElementById('actionsModalContent');
    if (!content) return;

    content.innerHTML = `
        <div class="manage-actions-modal">
            <button class="btn-action edit" onclick="openEditModal(${user.id})">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>
                </svg>
                Edit Profile
            </button>
            <button class="btn-action password" onclick="openPasswordModal(${user.id})">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
                ${user.has_password ? 'Change Password' : 'Add Password'}
            </button>
            <button class="btn-action anilist" onclick="openAniListModal(${user.id})">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/>
                </svg>
                AniList Integration
            </button>
            <button class="btn-action delete" onclick="handleDeleteConfirmation(${user.id})">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 4H8l-7 8 7 8h13a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"></path>
                    <line x1="18" y1="9" x2="12" y2="15"></line>
                    <line x1="12" y1="9" x2="18" y2="15"></line>
                </svg>
                Delete Profile
            </button>
            <button class="btn-action cancel" onclick="closeModal()">
                Cancel
            </button>
        </div>
    `;

    modalUserActions.classList.add('active');
}

window.openEditModal = function(userId) {
    currentUserId = userId;
    modalUserActions.classList.remove('active');
    const user = users.find(u => u.id === userId);
    if (!user) return;

    modalEditUser.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h2>Edit Profile</h2>
                <button class="modal-close" onclick="closeModal()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <form id="editUserFormDynamic">
                <div class="form-group">
                    <label for="editUsername">Username</label>
                    <input type="text" id="editUsername" name="username" required maxlength="20" value="${user.username}">
                </div>
                
                <div class="form-group">
                    <label>Profile Picture</label>
                    <div class="avatar-upload-area" id="editAvatarUploadArea">
                        <div class="avatar-preview" id="editAvatarPreview">
                            ${user.profile_picture_url
        ? `<img src="${user.profile_picture_url}" alt="Avatar">`
        : `<svg class="avatar-preview-placeholder" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                    <circle cx="12" cy="7" r="4"></circle>
                                   </svg>`
    }
                        </div>
                        <p class="avatar-upload-text">Click to upload or drag and drop</p>
                        <p class="avatar-upload-hint">PNG, JPG up to 5MB</p>
                    </div>
                    <input type="file" id="editAvatarInput" accept="image/*">
                </div>

                <div class="modal-actions">
                    <button type="button" class="btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    `;

    modalEditUser.classList.add('active');

    initAvatarUpload('editAvatarUploadArea', 'editAvatarInput', 'editAvatarPreview');

    selectedFile = null;

    document.getElementById('editUserFormDynamic').addEventListener('submit', handleEditUser);
};

async function handleEditUser(e) {
    e.preventDefault();

    const user = users.find(u => u.id === currentUserId);
    if (!user) return;

    const username = document.getElementById('editUsername').value.trim();
    if (!username) {
        showUserToast('Please enter a username', 'error');
        return;
    }

    const submitBtn = e.target.querySelector('.btn-primary');
    submitBtn.disabled = true;
    submitBtn.textContent = 'Saving...';

    try {
        let profilePictureUrl;
        if (selectedFile) profilePictureUrl = await fileToBase64(selectedFile);

        const updates = { username };
        if (profilePictureUrl !== undefined) updates.profilePictureUrl = profilePictureUrl;

        const res = await fetch(`${API_BASE}/users/${currentUserId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(updates)
        });

        if (!res.ok) {
            const error = await res.json();
            throw new Error(error.error || 'Error updating user');
        }

        closeModal();
        await loadUsers();
        showUserToast('Profile updated successfully!', 'success');
    } catch (err) {
        console.error(err);
        showUserToast(err.message || 'Error updating user', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = 'Save Changes';
    }
}

window.openPasswordModal = function(userId) {
    currentUserId = userId;
    modalUserActions.classList.remove('active');
    const user = users.find(u => u.id === userId);
    if (!user) return;

    modalAniList.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h2>${user.has_password ? 'Change Password' : 'Add Password'}</h2>
                <button class="modal-close" onclick="closeModal()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <div class="password-modal-content">
                ${user.has_password ? `
                    <div class="password-info">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="16" x2="12" y2="12"></line>
                            <line x1="12" y1="8" x2="12.01" y2="8"></line>
                        </svg>
                        <span>This profile is currently password protected</span>
                    </div>
                ` : ''}
                
                <form id="passwordForm">
                    ${user.has_password ? `
                        <div class="form-group">
                            <label for="currentPassword">Current Password</label>
                            <div class="password-toggle-wrapper">
                                <input type="password" id="currentPassword" required placeholder="Enter current password">
                                <button type="button" class="password-toggle-btn" onclick="togglePasswordVisibility('currentPassword', this)">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                        <circle cx="12" cy="12" r="3"></circle>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    ` : ''}
                    
                    <div class="form-group">
                        <label for="newPassword">New Password ${user.has_password ? '' : '<span class="optional-label">(Optional)</span>'}</label>
                        <div class="password-toggle-wrapper">
                            <input type="password" id="newPassword" ${user.has_password ? '' : ''} placeholder="Enter new password">
                            <button type="button" class="password-toggle-btn" onclick="togglePasswordVisibility('newPassword', this)">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn-secondary" onclick="closeModal()">Cancel</button>
                        ${user.has_password ? `
                            <button type="button" class="btn-disconnect" onclick="handleRemovePassword()">
                                Remove Password
                            </button>
                        ` : ''}
                        <button type="submit" class="btn-primary">
                            ${user.has_password ? 'Update' : 'Set'} Password
                        </button>
                    </div>
                </form>
            </div>
        </div>
    `;

    modalAniList.classList.add('active');

    document.getElementById('passwordForm').addEventListener('submit', handlePasswordSubmit);
};

async function handlePasswordSubmit(e) {
    e.preventDefault();

    const user = users.find(u => u.id === currentUserId);
    if (!user) return;

    const currentPassword = user.has_password ? document.getElementById('currentPassword').value : null;
    const newPassword = document.getElementById('newPassword').value;

    if (!newPassword && !user.has_password) {
        showUserToast('Please enter a password', 'error');
        return;
    }

    const submitBtn = e.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.textContent = 'Updating...';

    try {
        const body = { newPassword: newPassword || null };
        if (currentPassword) body.currentPassword = currentPassword;

        const res = await fetch(`${API_BASE}/users/${currentUserId}/password`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });

        if (!res.ok) {
            const error = await res.json();
            throw new Error(error.error || 'Error updating password');
        }

        closeModal();
        await loadUsers();
        showUserToast('Password updated successfully!', 'success');
    } catch (err) {
        console.error(err);
        showUserToast(err.message || 'Error updating password', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = user.has_password ? 'Update Password' : 'Set Password';
    }
}

window.handleRemovePassword = async function() {
    if (!confirm('Are you sure you want to remove the password protection from this profile?')) return;

    try {
        const currentPassword = document.getElementById('currentPassword').value;

        if (!currentPassword) {
            showUserToast('Please enter your current password', 'error');
            return;
        }

        const res = await fetch(`${API_BASE}/users/${currentUserId}/password`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ currentPassword, newPassword: null })
        });

        if (!res.ok) {
            const error = await res.json();
            throw new Error(error.error || 'Error removing password');
        }

        closeModal();
        await loadUsers();
        showUserToast('Password removed successfully!', 'success');
    } catch (err) {
        console.error(err);
        showUserToast(err.message || 'Error removing password', 'error');
    }
};

window.handleDeleteConfirmation = function(userId) {
    const user = users.find(u => u.id === userId);
    if (!user) return;

    closeModal();

    if (user.has_password) {
        modalAniList.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content" style="max-width:400px;">
            <div class="modal-header">
                <h2>Confirm Deletion</h2>
                <button class="modal-close" onclick="closeModal()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>

            <form id="deleteWithPasswordForm">
                <p style="margin-bottom:1.25rem; color:var(--color-text-secondary)">
                    Enter your password to permanently delete
                    <b>${user.username}</b>
                </p>

                <div class="form-group">
                    <label for="deletePassword">Password</label>
                    <div class="password-toggle-wrapper">
                        <input
                            type="password"
                            id="deletePassword"
                            required
                            placeholder="Enter password"
                            autofocus
                        >
                        <button
                            type="button"
                            class="password-toggle-btn"
                            onclick="togglePasswordVisibility('deletePassword', this)"
                        >
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                <circle cx="12" cy="12" r="3"></circle>
                            </svg>
                        </button>
                    </div>
                </div>

                <div class="modal-actions">
                    <button type="button" class="btn-secondary" onclick="closeModal()">
                        Cancel
                    </button>
                    <button type="submit" class="btn-disconnect">
                        Delete Profile
                    </button>
                </div>
            </form>
        </div>
    `;
        modalAniList.classList.add('active');

        document
            .getElementById('deleteWithPasswordForm')
            .addEventListener('submit', e => {
                e.preventDefault();
                const password = document.getElementById('deletePassword').value;
                handleConfirmedDeleteUser(userId, password);
            });

        return;
    }

    showConfirmationModal(
        'Confirm Deletion',
        `Are you absolutely sure you want to delete profile ${user.username}?`,
        `handleConfirmedDeleteUser(${userId})`
    );
};

window.handleConfirmedDeleteUser = async function(userId, password = null) {
    closeModal();

    try {
        const options = { method: 'DELETE' };

        if (password) {
            options.headers = { 'Content-Type': 'application/json' };
            options.body = JSON.stringify({ password });
        }

        const res = await fetch(`${API_BASE}/users/${userId}`, options);

        if (!res.ok) {
            const error = await res.json();
            throw new Error(error.error);
        }

        await loadUsers();
        showUserToast('User deleted successfully!', 'success');
    } catch (err) {
        showUserToast(err.message || 'Error deleting user', 'error');
    }
};

function showConfirmationModal(title, message, confirmAction) {
    closeModal();

    modalAniList.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h2>${title}</h2>
                <button class="modal-close" onclick="closeModal()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <div style="text-align: center; padding: 1rem;">
                <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" style="opacity: 0.8; margin: 0 auto 1rem; display: block;">
                    <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
                    <line x1="12" y1="9" x2="12" y2="13"></line>
                    <line x1="12" y1="17" x2="12.01" y2="17"></line>
                </svg>
                <p style="color: var(--color-text-secondary); margin-bottom: 2rem; font-size: 1rem;">
                    ${message}
                </p>
                <div style="display: flex; gap: 1rem;">
                    <button class="btn-secondary" style="flex: 1;" onclick="closeModal()">
                        Cancel
                    </button>
                    <button class="btn-disconnect" style="flex: 1; background: #ef4444; color: white;" onclick="window.${confirmAction}">
                        Confirm Delete
                    </button>
                </div>
            </div>
        </div>
    `;

    modalAniList.classList.add('active');
}

function openAniListModal(userId) {
    currentUserId = userId;

    modalUserActions.classList.remove('active');
    modalEditUser.classList.remove('active');

    aniListContent.innerHTML = `<div style="text-align: center; padding: 2rem;">Loading integration status...</div>`;

    modalAniList.innerHTML = `
        <div class="modal-overlay"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h2>AniList Integration</h2>
                <button class="modal-close" onclick="closeModal()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <div id="aniListContent">
                <div style="text-align: center; padding: 2rem;">Loading integration status...</div>
            </div>
        </div>
    `;

    modalAniList.classList.add('active');

    getIntegrationStatus(userId).then(integration => {
        const content = document.getElementById('aniListContent');

        content.innerHTML = `
            <div class="anilist-status">
                ${integration.connected ? `
                    <div class="anilist-connected">
                        <div class="anilist-icon">
                            <img src="https://anilist.co/img/icons/icon.svg" alt="AniList" style="width:40px; height:40px;">
                        </div>
                        <div class="anilist-info">
                            <h3>Connected to AniList</h3>
                            <p>User ID: ${integration.anilistUserId}</p>
                            <p style="font-size: 0.75rem;">Expires: ${new Date(integration.expiresAt).toLocaleDateString()}</p>
                        </div>
                    </div>
                    <button class="btn-disconnect" onclick="handleDisconnectAniList()">
                        Disconnect AniList
                    </button>
                ` : `
                    <div style="text-align: center; padding: 1rem;">
                        <h3 style="margin-bottom: 0.5rem;">Connect with AniList</h3>
                        <p style="color: var(--color-text-secondary); margin-bottom: 1.5rem;">
                            Sync your anime list by logging in with AniList.
                        </p>
                        <div style="display:flex; justify-content:center;">
                            <button class="btn-connect" onclick="redirectToAniListLogin()">
                                Login with AniList
                            </button>
                        </div>
                        <p style="font-size:0.85rem; margin-top:1rem; color:var(--color-text-secondary)">
                            You will be redirected and then returned here.
                        </p>
                    </div>
                `}
            </div>
        `;
    }).catch(err => {
        console.error(err);
        const content = document.getElementById('aniListContent');
        content.innerHTML = `<div style="text-align:center;padding:1rem;color:var(--color-text-secondary)">Error loading integration status.</div>`;
    });
}

async function redirectToAniListLogin() {
    try {
        const res = await fetch(`/api/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ userId: currentUserId })
        });

        if (!res.ok) throw new Error('Login failed before AniList redirect');

        const data = await res.json();
        localStorage.setItem('token', data.token);

        const clientId = 32898;
        const redirectUri = encodeURIComponent(window.location.origin + '/api/anilist');
        const state = encodeURIComponent(currentUserId);

        window.location.href =
            `https://anilist.co/api/v2/oauth/authorize` +
            `?client_id=${clientId}` +
            `&response_type=code` +
            `&redirect_uri=${redirectUri}` +
            `&state=${state}`;

    } catch (err) {
        console.error(err);
        showUserToast('Error starting AniList login', 'error');
    }
}

async function getIntegrationStatus(userId) {
    try {
        const res = await fetch(`${API_BASE}/users/${userId}/integration`);
        if (!res.ok) {
            return { connected: false };
        }
        return await res.json();
    } catch (err) {
        console.error('getIntegrationStatus error', err);
        return { connected: false };
    }
}

window.handleDisconnectAniList = async function() {
    if (!confirm('Are you sure you want to disconnect AniList?')) return;

    try {
        const res = await fetch(`${API_BASE}/users/${currentUserId}/integration`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!res.ok) {
            const error = await res.json();
            throw new Error(error.error || 'Error disconnecting AniList');
        }

        showUserToast('AniList disconnected successfully', 'success');
        openAniListModal(currentUserId);
    } catch (err) {
        console.error(err);
        showUserToast('Error disconnecting AniList', 'error');
    }
};

async function loginUser(userId, hasPassword) {
    if (hasPassword) {
        // Mostrar modal de contraseña
        modalAniList.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h2>Enter Password</h2>
                    <button class="modal-close" onclick="closeModal()">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <line x1="18" y1="6" x2="6" y2="18"></line>
                            <line x1="6" y1="6" x2="18" y2="18"></line>
                        </svg>
                    </button>
                </div>
                <form id="loginPasswordForm">
                    <div class="form-group">
                        <label for="loginPassword">Password</label>
                        <div class="password-toggle-wrapper">
                            <input type="password" id="loginPassword" required placeholder="Enter your password" autofocus>
                            <button type="button" class="password-toggle-btn" onclick="togglePasswordVisibility('loginPassword', this)">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn-secondary" onclick="closeModal()">Cancel</button>
                        <button type="submit" class="btn-primary">Login</button>
                    </div>
                </form>
            </div>
        `;

        modalAniList.classList.add('active');

        document.getElementById('loginPasswordForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const password = document.getElementById('loginPassword').value;
            await performLogin(userId, password);
        });
    } else {
        await performLogin(userId);
    }
}

async function performLogin(userId, password = null) {
    try {
        const body = { userId };
        if (password) body.password = password;

        const res = await fetch(`${API_BASE}/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });

        if (!res.ok) {
            const err = await res.json().catch(() => ({}));
            throw new Error(err.error || 'Login failed');
        }

        const data = await res.json();
        localStorage.setItem('token', data.token);

        window.location.href = '/anime';
    } catch (err) {
        console.error('Login error', err);
        showUserToast(err.message || 'Login failed', 'error');
    }
}

window.openAniListModal = openAniListModal;
window.redirectToAniListLogin = redirectToAniListLogin;