<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Account Settings</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/@simplewebauthn/browser/dist/bundle/index.umd.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"
          rel="stylesheet">
    <style>
        :root {
            --bg-start-dark: hsla(252, 40%, 29%, 1);
            --bg-end-dark: hsla(270, 77%, 71%, 1);
        }
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(90deg, var(--bg-start-dark), var(--bg-end-dark));
            background-size: 400% 400%;
            animation: gradientAnimation 15s ease infinite;
        }
        @keyframes gradientAnimation {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        .bg-card {
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            background-color: rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.15);
        }
        .form-input {
            background-color: rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.15);
        }
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        #confirm-modal {
            transition: opacity 0.3s ease;
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-200">

<div class="relative min-h-screen lg:flex">

    <div class="lg:hidden flex justify-between items-center p-4">
        <h1 class="text-2xl font-bold text-white">AuthTuna</h1>
        <button id="menu-toggle-button" class="text-white focus:outline-none">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path>
            </svg>
        </button>
    </div>

    <aside id="sidebar"
           class="w-64 bg-card p-6 flex-col justify-between fixed inset-y-0 left-0 z-30 transform -translate-x-full transition-transform duration-300 ease-in-out lg:relative lg:translate-x-0 lg:flex">
        <div>
            <h1 class="text-2xl font-bold text-white mb-8 hidden lg:block">AuthTuna</h1>
            <nav class="space-y-4">
                <a href="{{ url_for('ui_dashboard') }}"
                   class="flex items-center p-2 text-base font-normal text-gray-300 rounded-lg hover:bg-white/5">
                    <span class="ml-3">Dashboard</span>
                </a>
                <a href="{{ url_for('ui_profile') }}"
                   class="flex items-center p-2 text-base font-normal text-gray-300 rounded-lg hover:bg-white/5">
                    <span class="ml-3">Profile</span>
                </a>
                <a href="{{ url_for('ui_settings') }}"
                   class="flex items-center p-2 text-base font-normal text-white rounded-lg bg-white/10">
                    <span class="ml-3">Settings</span>
                </a>
            </nav>
        </div>
        <div>
            <a href="/auth/logout"
               class="flex items-center p-2 text-base font-normal text-gray-300 rounded-lg hover:bg-white/5">
                <span class="ml-3">Logout</span>
            </a>
        </div>
    </aside>

    <main class="flex-1 p-6 lg:p-10 overflow-y-auto">
        <h1 class="text-3xl font-bold text-white">Account Settings</h1>
        <p class="text-gray-400 mb-8">Manage your account security.</p>

        <div class="max-w-4xl space-y-8">
            <div class="bg-card p-6 md:p-8 rounded-lg shadow-lg">
                <h2 class="text-2xl font-semibold text-white mb-6">Change Password</h2>
                <form id="password-form" class="space-y-6">
                    <div>
                        <label for="current-password" class="block text-sm font-medium text-gray-300 mb-2">Current Password</label>
                        <input type="password" id="current-password" required autocomplete="current-password"
                               class="form-input w-full text-white p-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="new-password" class="block text-sm font-medium text-gray-300 mb-2">New Password</label>
                        <input type="password" id="new-password" required autocomplete="new-password"
                               class="form-input w-full text-white p-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="confirm-password" class="block text-sm font-medium text-gray-300 mb-2">Confirm New Password</label>
                        <input type="password" id="confirm-password" required autocomplete="new-password"
                               class="form-input w-full text-white p-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    </div>
                    <button type="submit"
                            class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg transition-colors">
                        Update Password
                    </button>
                </form>
                <div id="password-message-box" class="mt-4 text-center text-sm font-medium"></div>
            </div>

            <div class="bg-card p-6 md:p-8 rounded-lg shadow-lg">
                <h2 class="text-2xl font-semibold text-white mb-4">Two-Factor Authentication (2FA)</h2>
                {% if user.mfa_enabled %}
                <p class="text-green-400 mb-4">2FA is currently <strong>enabled</strong> on your account.</p>
                <button id="disable-mfa-button"
                        class="bg-red-600 hover:bg-red-700 text-white font-bold py-3 px-4 rounded-lg transition-colors">
                    Disable Two-Factor Authentication
                </button>
                {% else %}
                <p class="text-gray-400 mb-4">Protect your account with an extra layer of security using an authenticator app.</p>
                <a href="/mfa/setup"
                   class="inline-block bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg transition-colors">
                    Setup Two-Factor Authentication
                </a>
                {% endif %}
                <div id="mfa-message-box" class="mt-4 text-center text-sm font-medium"></div>
            </div>

            <div class="bg-card p-6 md:p-8 rounded-lg shadow-lg">
                <h2 class="text-2xl font-semibold text-white mb-4">Passkeys</h2>
                <p class="text-gray-400 mb-4">Add a passkey for a fast and secure passwordless login experience.</p>

                <div id="passkey-list" class="space-y-2">
                    </div>

                <button id="add-passkey-button"
                        class="mt-4 bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg">
                    Add a New Passkey
                </button>
                <div id="passkey-message-box" class="mt-4 text-center text-sm font-medium"></div>
            </div>

            <div class="bg-card p-6 md:p-8 rounded-lg shadow-lg">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4">
                    <div>
                        <h2 class="text-2xl font-semibold text-white">Active Sessions</h2>
                        <p class="text-gray-400 mt-1">This is a list of devices that have logged into your account.</p>
                    </div>
                    <button id="terminate-all-button"
                            class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg text-sm mt-4 sm:mt-0 w-full sm:w-auto">
                        Terminate All Others
                    </button>
                </div>
                <div id="sessions-list" class="space-y-4">
                    </div>
                <div id="sessions-message-box" class="mt-4 text-center text-sm font-medium"></div>
            </div>
        </div>
    </main>
</div>

<div id="confirm-modal" class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center hidden opacity-0 z-50">
    <div class="bg-card rounded-lg shadow-xl p-8 max-w-sm w-full mx-4">
        <h3 id="modal-title" class="text-xl font-bold text-white mb-4">Are you sure?</h3>
        <p id="modal-body" class="text-gray-300 mb-6">This action cannot be undone.</p>
        <div class="flex justify-end space-x-4">
            <button id="modal-cancel-button" class="px-6 py-2 rounded-lg bg-gray-600 hover:bg-gray-700 text-white font-semibold transition-colors">
                Cancel
            </button>
            <button id="modal-confirm-button" class="px-6 py-2 rounded-lg bg-red-600 hover:bg-red-700 text-white font-semibold transition-colors">
                Confirm
            </button>
        </div>
    </div>
</div>

<script>
    // --- Mobile Menu Toggle ---
    const sidebar = document.getElementById('sidebar');
    const menuButton = document.getElementById('menu-toggle-button');

    function toggleMenu() {
        sidebar.classList.toggle('-translate-x-full');
    }

    menuButton.addEventListener('click', toggleMenu);

    // Close menu if clicking outside of it on mobile
    document.addEventListener('click', (event) => {
        const isClickInsideSidebar = sidebar.contains(event.target);
        const isClickOnMenuButton = menuButton.contains(event.target);

        if (!isClickInsideSidebar && !isClickOnMenuButton && !sidebar.classList.contains('-translate-x-full')) {
             if (window.innerWidth < 1024) { // 1024px is lg breakpoint
                toggleMenu();
             }
        }
    });

    // --- Utility Functions ---
    function showMessage(box, text, type) {
        const colorClass = type === 'success' ? 'text-green-400' : 'text-red-400';
        box.textContent = text;
        box.className = `mt-4 text-center text-sm font-medium ${colorClass}`;
        setTimeout(() => { box.textContent = ''; }, 5000);
    }

    // --- Confirmation Modal Logic ---
    const modal = document.getElementById('confirm-modal');
    let confirmCallback = null;
    document.getElementById('modal-cancel-button').addEventListener('click', () => {
        modal.classList.add('opacity-0');
        setTimeout(() => modal.classList.add('hidden'), 300);
    });
    document.getElementById('modal-confirm-button').addEventListener('click', () => {
        if (confirmCallback) confirmCallback();
        document.getElementById('modal-cancel-button').click();
    });
    function showModal(title, body, onConfirm) {
        document.getElementById('modal-title').textContent = title;
        document.getElementById('modal-body').textContent = body;
        confirmCallback = onConfirm;
        modal.classList.remove('hidden');
        setTimeout(() => modal.classList.remove('opacity-0'), 10);
    }

    // --- Password Change Logic ---
    document.getElementById('password-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const box = document.getElementById('password-message-box');
        const newPassword = document.getElementById('new-password').value;
        if (newPassword !== document.getElementById('confirm-password').value) {
            return showMessage(box, "New passwords do not match.", 'error');
        }
        try {
            const response = await fetch('/auth/change-password', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    current_password: document.getElementById('current-password').value,
                    new_password: newPassword
                })
            });
            const data = await response.json();
            showMessage(box, data.detail || data.message, response.ok ? 'success' : 'error');
            if (response.ok) e.target.reset();
        } catch (err) {
            showMessage(box, 'A network error occurred.', 'error');
        }
    });

    // --- MFA Logic ---
    const disableMfaButton = document.getElementById('disable-mfa-button');
    if (disableMfaButton) {
        disableMfaButton.addEventListener('click', () => {
            showModal('Disable Two-Factor Authentication?', 'This will reduce your account security. Are you sure?', async () => {
                const box = document.getElementById('mfa-message-box');
                try {
                    const response = await fetch('/mfa/disable', {method: 'POST'});
                    const data = await response.json();
                    showMessage(box, data.detail || data.message, response.ok ? 'success' : 'error');
                    if (response.ok) setTimeout(() => window.location.reload(), 2000);
                } catch (err) {
                    showMessage(box, 'A network error occurred.', 'error');
                }
            });
        });
    }

    // --- Passkey Logic ---
    const passkeyMessageBox = document.getElementById('passkey-message-box');
    const passkeyList = document.getElementById('passkey-list');

    async function loadPasskeys() {
        try {
            const response = await fetch('/passkeys/');
            if (!response.ok) throw new Error('Failed to load passkeys.');
            const passkeys = await response.json();
            passkeyList.innerHTML = passkeys.map(key => `
                <div class="bg-black/20 p-3 rounded-lg flex items-center justify-between border border-white/10">
                    <p class="font-semibold text-white truncate pr-2">${key.name}</p>
                    <button onclick="removePasskey('${key.id}')" class="text-red-400 hover:text-red-300 text-sm font-semibold flex-shrink-0">Remove</button>
                </div>
            `).join('') || '<p class="text-sm text-gray-400">No passkeys registered yet.</p>';
        } catch (error) {
            showMessage(passkeyMessageBox, error.message, 'error');
        }
    }

    async function removePasskey(credentialId) {
        showModal('Remove this Passkey?', 'You will no longer be able to use this passkey to sign in. This action cannot be undone.', async () => {
            try {
                const response = await fetch(`/passkeys/${credentialId}`, {method: 'DELETE'});
                if (response.ok) {
                    showMessage(passkeyMessageBox, 'Passkey removed successfully.', 'success');
                    loadPasskeys();
                } else {
                    const data = await response.json();
                    throw new Error(data.detail || 'Failed to remove passkey.');
                }
            } catch (error) {
                showMessage(passkeyMessageBox, error.message, 'error');
            }
        });
    }

    document.getElementById('add-passkey-button').addEventListener('click', async () => {
        const button = document.getElementById('add-passkey-button');
        button.disabled = true;
        try {
            const optionsResp = await fetch('/passkeys/register-options', { method: 'POST' });
            if (!optionsResp.ok) throw new Error('Could not get registration options.');
            const options = await optionsResp.json();
            const registrationResp = await SimpleWebAuthnBrowser.startRegistration(options);
            const nickname = prompt("Please enter a name for this passkey (e.g., 'My iPhone'):", `Passkey on ${new Date().toLocaleDateString()}`);
            if (!nickname) throw new Error("Registration cancelled.");
            const verificationResp = await fetch('/passkeys/register', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name: nickname, registration_response: registrationResp }),
            });
            if (!verificationResp.ok) throw new Error('Server verification failed.');
            showMessage(passkeyMessageBox, 'Passkey registered successfully!', 'success');
            loadPasskeys();
        } catch (err) {
            showMessage(passkeyMessageBox, err.message, 'error');
        } finally {
            button.disabled = false;
        }
    });

    // --- Active Sessions Logic ---
    const sessionsMessageBox = document.getElementById('sessions-message-box');
    const sessionsList = document.getElementById('sessions-list');

    async function loadSessions() {
        try {
            const response = await fetch('/ui/settings/sessions');
            if (!response.ok) throw new Error('Failed to load sessions.');
            const sessions = await response.json();
            document.getElementById('terminate-all-button').style.display = sessions.length > 1 ? 'inline-block' : 'none';
            sessionsList.innerHTML = sessions.map(session => `
                <div class="bg-black/20 p-4 rounded-lg flex flex-col sm:flex-row items-start sm:items-center justify-between border border-white/10 space-y-3 sm:space-y-0">
                    <div>
                        <p class="font-semibold text-white">${session.device}</p>
                        <p class="text-sm text-gray-400">${session.region} &bull; IP: ${session.last_ip}
                            ${session.is_current ? '<span class="text-green-400 font-semibold ml-2">(Current Session)</span>' : ''}
                        </p>
                        <p class="text-xs text-gray-500 mt-1">Last active: ${new Date(session.mtime * 1000).toLocaleString()}</p>
                    </div>
                    ${!session.is_current ? `<button onclick="terminateSession('${session.session_id}')" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg text-sm w-full sm:w-auto">Terminate</button>` : ''}
                </div>
            `).join('');
        } catch (error) {
            showMessage(sessionsMessageBox, error.message, 'error');
        }
    }

    function terminateSession(sessionId) {
        showModal('Terminate Session?', 'The user will be logged out on this device.', async () => {
            try {
                const response = await fetch(`/ui/settings/sessions/${sessionId}/terminate`, {method: 'POST'});
                if (!response.ok) throw new Error('Failed to terminate session.');
                showMessage(sessionsMessageBox, 'Session terminated.', 'success');
                loadSessions();
            } catch (error) {
                showMessage(sessionsMessageBox, error.message, 'error');
            }
        });
    }

    document.getElementById('terminate-all-button').addEventListener('click', () => {
        showModal('Terminate All Other Sessions?', 'This will log you out from all other devices.', async () => {
            try {
                const response = await fetch('/ui/settings/sessions/terminate-all', {method: 'POST'});
                if (!response.ok) throw new Error('Failed to terminate sessions.');
                showMessage(sessionsMessageBox, 'All other sessions terminated.', 'success');
                loadSessions();
            } catch (error) {
                showMessage(sessionsMessageBox, error.message, 'error');
            }
        });
    });

    // --- Initial Load ---
    document.addEventListener('DOMContentLoaded', () => {
        loadSessions();
        loadPasskeys();
    });
</script>
</body>
</html>