// ── Session Control – Professional UI ──────────────────────────────
let currentSessionSettings = {
    session_timeout: 30,
    session_lifetime: 24,
    max_concurrent: 5,
    jwt_secret: '',
    php_session_name: ''
};

async function renderSession() {
    if (!window.securitySettings?.db_auth_enabled) {
        const container = document.getElementById('securityPageContainer');
        if (container) container.innerHTML = '<div class="alert alert-warning">Database authentication is not enabled. Please enable it in the Settings tab first.</div>';
        return;
    }
    const container = document.getElementById('securityPageContainer');
    if (!container) return;
    container.innerHTML = '<div class="text-center py-5"><div class="spinner-border"></div></div>';

    try {
        const settingsRes = await fetch(`${baseUrl}/project/${projectSlug}/security/session-settings`);
        const settingsData = await settingsRes.json();
        if (settingsData.success) {
            currentSessionSettings = { ...currentSessionSettings, ...settingsData.settings };
        }
        await loadActiveSessions();
    } catch (e) {
        console.error(e);
        container.innerHTML = `<div class="alert alert-danger">Failed to load session data: ${e.message}</div>`;
    }
}

async function loadActiveSessions() {
    const container = document.getElementById('securityPageContainer');
    if (!container) return;

    const sessionsRes = await fetch(`${baseUrl}/project/${projectSlug}/security/active-sessions`);
    const sessionsData = await sessionsRes.json();
    if (!sessionsData.success) throw new Error(sessionsData.message);
    const sessions = sessionsData.sessions || [];
    renderSessionUI(sessions);
}

function generateRandomString(length = 32) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

function renderSessionUI(sessions) {
    const container = document.getElementById('securityPageContainer');
    if (!container) return;

    const html = `
        <div class="row g-3">
            <!-- Left column: Session behaviour -->
            <div class="col-md-6">
                <div class="card shadow-sm h-100">
                    <div class="card-header bg-primary text-white py-2">
                        <i class="bi bi-clock-history me-2"></i> Session Behaviour
                        <button class="btn btn-sm btn-outline-light float-end" id="showSessionTips" title="Tips"><i class="bi bi-question-circle"></i></button>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label small fw-semibold">Session Timeout (minutes of inactivity)</label>
                            <input type="number" id="sessionTimeout" class="form-control form-control-sm" value="${currentSessionSettings.session_timeout}" min="1" max="480">
                            <div class="form-text text-muted">After this idle time, the user is automatically logged out.</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-semibold">Session Lifetime (hours)</label>
                            <input type="number" id="sessionLifetime" class="form-control form-control-sm" value="${currentSessionSettings.session_lifetime}" min="1" max="720">
                            <div class="form-text text-muted">Maximum total duration of a session, regardless of activity.</div>
                        </div>
                        <div class="mb-2">
                            <label class="form-label small fw-semibold">Max Concurrent Sessions per User</label>
                            <input type="number" id="maxConcurrent" class="form-control form-control-sm" value="${currentSessionSettings.max_concurrent}" min="0" max="50">
                            <div class="form-text text-muted">0 = unlimited. Oldest sessions are terminated when limit is exceeded.</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right column: Cross‑Project SSO -->
            <div class="col-md-6">
                <div class="card shadow-sm h-100">
                    <div class="card-header bg-primary text-white py-2">
                        <i class="bi bi-share me-2"></i> Single Sign‑On (Cross‑Project)
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label small fw-semibold">JWT Secret Key</label>
                            <div class="input-group input-group-sm">
                                <input type="text" id="jwtSecret" class="form-control" value="${escapeHtml(currentSessionSettings.jwt_secret || '')}" placeholder="Auto‑generated if empty">
                                <button class="btn btn-outline-secondary" type="button" id="generateJwtSecret"><i class="bi bi-arrow-repeat"></i> Generate</button>
                            </div>
                            <div class="form-text text-muted"><span class="badge bg-secondary">Planned</span> Stored for upcoming cross‑project single sign‑on (JWT‑based). Not enforced yet — a shared secret does not federate sign‑in today.</div>
                        </div>
                        <div class="mb-2">
                            <label class="form-label small fw-semibold">PHP Session Name</label>
                            <div class="input-group input-group-sm">
                                <input type="text" id="phpSessionName" class="form-control" value="${escapeHtml(currentSessionSettings.php_session_name || '')}" placeholder="Randomized by default">
                                <button class="btn btn-outline-secondary" type="button" id="generateSessionName"><i class="bi bi-arrow-repeat"></i> Generate</button>
                            </div>
                            <div class="form-text text-muted">Needed when sharing session data with other PHP applications on the same server. Avoid reusing the same name across unrelated projects.<br>
                            <span class="small text-muted">Note: Some frameworks add a prefix (e.g., 'p') – your actual session name would be <code>p${currentSessionSettings.php_session_name || '...'}</code>.</span></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Active Sessions (full width) -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white py-2 d-flex justify-content-between align-items-center">
                        <span><i class="bi bi-window-sidebar me-2"></i> Active Sessions</span>
                        <button class="btn btn-sm btn-outline-light" id="refreshSessions"><i class="bi bi-arrow-repeat"></i> Refresh</button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered small mb-0">
                                <thead class="table-light">
                                    <tr><th>User</th><th>IP Address</th><th>User Agent</th><th>Last Activity</th><th style="width:80px">Action</th></tr>
                                </thead>
                                <tbody id="sessionsTableBody">
                                    ${sessions.map(sess => `
                                        <tr>
                                            <td>${escapeHtml(sess.username || sess.user_id)}</td>
                                            <td>${escapeHtml(sess.ip_address || '-')}</td>
                                            <td>${escapeHtml((sess.user_agent || '').substring(0, 50))}${(sess.user_agent || '').length > 50 ? '…' : ''}</td>
                                            <td>${escapeHtml(sess.last_activity)}</td>
                                            <td><button class="btn btn-sm btn-outline-danger kill-session-btn" data-id="${sess.id}" title="Terminate session"><i class="bi bi-x-circle"></i></button></td>
                                        </tr>
                                    `).join('')}
                                    ${sessions.length === 0 ? '<tr><td colspan="5" class="text-center text-muted py-3">No active sessions</td>' : ''}
                                </tbody>
                            </table>
                        </div>
                        <div class="p-2 text-end border-top">
                            <button class="btn btn-sm btn-danger" id="killAllSessions"><i class="bi bi-trash"></i> Kill All Sessions</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Global Save button -->
        <div class="row mt-3">
            <div class="col-12 text-end">
                <button class="btn btn-primary" id="saveAllSessionSettings"><i class="bi bi-save"></i> Save All Settings</button>
            </div>
        </div>

        <!-- Tips Modal (expanded) -->
        <div class="modal fade" id="sessionTipsModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-info text-white">
                        <h5 class="modal-title"><i class="bi bi-lightbulb"></i> Session Control Tips</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <h6>⏱️ Session Behaviour <span class="badge bg-success">Live in the app</span></h6>
                        <p>These are <strong>enforced in the generated app</strong> — <em>rebuild to publish a change</em>.<br>
                        <strong>Timeout</strong> – signs out inactive users after the specified idle minutes.<br>
                        <strong>Lifetime</strong> – forces sign-out after the total hours, regardless of activity.<br>
                        <strong>Concurrent Sessions</strong> – caps simultaneous sessions per user; a new sign-in past the cap evicts that user&rsquo;s oldest session. <em>0 = unlimited.</em><br>
                        Both timeouts fail <strong>open</strong> (a storage hiccup never locks a user out of their own app).</p>
                        <h6>🍪 PHP Session Name <span class="badge bg-success">Live in the app</span></h6>
                        <p>Defines the built app&rsquo;s session cookie name (applied at boot). Useful when sharing session data between PHP apps on the same domain. Must start with a letter; avoid identical names for unrelated projects.</p>
                        <h6>🔐 Single Sign‑On (Cross‑Project) <span class="badge bg-secondary">Planned</span></h6>
                        <p>The JWT secret is stored for future cross-project SSO, but token exchange is <strong>not wired yet</strong> — a shared secret does not currently federate sign-in between projects.</p>
                        <h6>📱 Active Sessions <span class="badge bg-success">Live in the app</span></h6>
                        <p>Lists real sign-ins from the built app (<code>user_sessions</code>). <strong>Terminate</strong> a session or <strong>Kill All</strong> to sign those users out on their next request. Note: killing all sessions also ends your own app session.</p>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    container.innerHTML = html;

    // Event handlers
    document.getElementById('generateJwtSecret')?.addEventListener('click', () => {
        document.getElementById('jwtSecret').value = generateRandomString(32);
    });
    document.getElementById('generateSessionName')?.addEventListener('click', () => {
        document.getElementById('phpSessionName').value = generateRandomString(24);
    });
    document.getElementById('saveAllSessionSettings')?.addEventListener('click', async () => {
        const newSettings = {
            session_timeout: parseInt(document.getElementById('sessionTimeout').value) || 30,
            session_lifetime: parseInt(document.getElementById('sessionLifetime').value) || 24,
            max_concurrent: parseInt(document.getElementById('maxConcurrent').value) || 0,
            jwt_secret: document.getElementById('jwtSecret').value.trim(),
            php_session_name: document.getElementById('phpSessionName').value.trim()
        };
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/security/session-settings`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ settings: newSettings })
            });
            const data = await res.json();
            if (data.success) {
                pp.dialog.toast('success', data.message);
                currentSessionSettings = newSettings;
                loadActiveSessions(); // refresh in case of session invalidation
            } else {
                pp.dialog.alert('Error', data.message, 'error');
            }
        } catch (e) {
            pp.dialog.toast('error', 'Network error');
        }
    });
    document.getElementById('refreshSessions')?.addEventListener('click', () => loadActiveSessions());
    document.querySelectorAll('.kill-session-btn').forEach(btn => {
        btn.addEventListener('click', async () => {
            const sessionId = btn.dataset.id;
            if (await pp.dialog.confirm('Terminate session?', 'The user will be logged out immediately.')) {
                const res = await fetch(`${baseUrl}/project/${projectSlug}/security/sessions/${sessionId}`, { method: 'DELETE' });
                const data = await res.json();
                if (data.success) {
                    pp.dialog.toast('success', data.message);
                    loadActiveSessions();
                } else {
                    pp.dialog.alert('Error', data.message, 'error');
                }
            }
        });
    });
    document.getElementById('killAllSessions')?.addEventListener('click', async () => {
        if (await pp.dialog.confirm('Kill ALL sessions?', 'This will log out every user, including yourself. Continue?')) {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/security/sessions/all`, { method: 'DELETE' });
            const data = await res.json();
            if (data.success) {
                pp.dialog.toast('success', data.message);
                loadActiveSessions();
            } else {
                pp.dialog.alert('Error', data.message, 'error');
            }
        }
    });
    document.getElementById('showSessionTips')?.addEventListener('click', () => {
        const modal = new bootstrap.Modal(document.getElementById('sessionTipsModal'));
        modal.show();
    });

    // ── Auto‑save listeners ─────────────────────────────────────────
    attachAutoSaveListeners(container);
}

window.renderSession = renderSession;