{% extends "admin/index.html" %}

{% block content %}
<div class="container-fluid mt-5">
    <div class="row">
        <div class="col-md-12">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">
                        <i class="mdi mdi-video-camera"></i> Recording Studio
                    </h4>
                </div>
                <div class="card-body">

                    <!-- Recorder Selection -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card border-left-primary">
                                <div class="card-body text-center">
                                    <h5>Playwright</h5>
                                    <p class="text-muted small">Async, headless, full network interception</p>
                                    <button class="btn btn-primary btn-sm" onclick="selectRecorder('playwright')">
                                        <i class="mdi mdi-play"></i> Use Playwright
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card border-left-info">
                                <div class="card-body text-center">
                                    <h5>Selenium</h5>
                                    <p class="text-muted small">Chrome/Firefox, headless mode, form auto-fill</p>
                                    <button class="btn btn-info btn-sm" onclick="selectRecorder('selenium')">
                                        <i class="mdi mdi-play"></i> Use Selenium
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Configuration Panel -->
                    <div id="configPanel" style="display:none;" class="mt-4 p-4 bg-light rounded">
                        <h5>Recording Configuration</h5>
                        <form id="recordingForm" onsubmit="startRecording(event)">
                            <div class="form-group">
                                <label for="recordingType">Recorder Type</label>
                                <input type="hidden" id="recordingType" name="type" value="">
                            </div>

                            <div class="form-group">
                                <label for="targetUrl">Target URL</label>
                                <input type="url" class="form-control form-control-sm" id="targetUrl" name="url" 
                                       placeholder="https://example.com/login" required>
                            </div>

                            <!-- Selenium-specific options -->
                            <div id="seleniumOptions" style="display:none;">
                                <div class="form-group">
                                    <label for="browser">Browser</label>
                                    <select class="form-control form-control-sm" id="browser" name="browser">
                                        <option value="chrome">Chrome (Recommended)</option>
                                        <option value="firefox">Firefox</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>
                                    <input type="checkbox" id="headless" name="headless" value="true" checked>
                                    Run in Headless Mode
                                </label>
                                <small class="d-block text-muted">Recommended for background recording</small>
                            </div>

                            <button type="submit" class="btn btn-success btn-sm">
                                <i class="mdi mdi-record"></i> Start Recording
                            </button>
                        </form>
                    </div>

                    <!-- Status Panel -->
                    <div id="statusPanel" style="display:none;" class="mt-4">
                        <div class="alert alert-info">
                            <i class="mdi mdi-loading mdi-spin"></i>
                            <span id="statusText">Recording in progress...</span>
                        </div>
                        <div id="sessionDetails" class="mt-3 p-3 bg-white rounded border">
                            <h6>Session Details</h6>
                            <dl class="row">
                                <dt class="col-sm-4">Recorder Type:</dt>
                                <dd class="col-sm-8" id="detailRecorder"></dd>

                                <dt class="col-sm-4">Target URL:</dt>
                                <dd class="col-sm-8" id="detailUrl"></dd>

                                <dt class="col-sm-4">Headless:</dt>
                                <dd class="col-sm-8" id="detailHeadless"></dd>

                                <dt class="col-sm-4">Forms Detected:</dt>
                                <dd class="col-sm-8" id="detailForms">-</dd>

                                <dt class="col-sm-4">Cookies Captured:</dt>
                                <dd class="col-sm-8" id="detailCookies">-</dd>
                            </dl>
                        </div>

                        <!-- Live Log Panel -->
                        <div id="liveLogPanel" class="mt-4">
                            <h6><i class="mdi mdi-file-document-outline"></i> Live Activity Log</h6>
                            <div id="liveLog" style="height: 300px; overflow-y: auto; background: #1a1a1a; color: #0f0; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 0.85em; border: 1px solid #444;">
                                <small class="text-muted">[*] Initializing recorder...</small>
                            </div>
                            <div class="mt-2">
                                <button class="btn btn-sm btn-outline-secondary" onclick="clearLiveLog()">Clear Log</button>
                                <button class="btn btn-sm btn-outline-info" onclick="pauseAutoScroll()">Pause</button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <!-- Advanced Options Card -->
    <div class="row mt-5">
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="mdi mdi-tune"></i> Stealth Options</h6>
                </div>
                <div class="card-body small">
                    <label>
                        <input type="checkbox" id="useStealthPayload" checked>
                        Inject Stealth Evasion (perfection.js)
                    </label>
                    <p class="text-muted mt-2">Evades detection by spoofing navigator properties and fingerprints</p>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="mdi mdi-shield-account"></i> CAPTCHA Solving</h6>
                </div>
                <div class="card-body small">
                    <select class="form-control form-control-sm" id="captchaSolver">
                        <option value="none">Disabled</option>
                        <option value="2captcha">2Captcha API</option>
                        <option value="anticaptcha">Anti-Captcha API</option>
                        <option value="manual">Manual Solving</option>
                    </select>
                    <p class="text-muted mt-2">Auto-detect and solve CAPTCHA on page</p>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="mdi mdi-network"></i> Attack Payloads</h6>
                </div>
                <div class="card-body small">
                    <button class="btn btn-sm btn-outline-danger btn-block mb-2" data-toggle="tooltip" 
                            title="Tab hijacking payload">
                        <i class="mdi mdi-tab-duplicate"></i> Tab Jacking
                    </button>
                    <button class="btn btn-sm btn-outline-warning btn-block" data-toggle="tooltip"
                            title="File upload injection payload">
                        <i class="mdi mdi-cloud-upload"></i> File Upload
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Mock Server Card -->
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-dark text-white">
                    <h6 class="mb-0"><i class="mdi mdi-server"></i> Mock Authentication Server</h6>
                </div>
                <div class="card-body">
                    <p>Test recordings against realistic authentication flows (OAuth 2.0, SSO, 2FA).</p>
                    <button class="btn btn-dark btn-sm" onclick="startMockServer()">
                        <i class="mdi mdi-power"></i> Start Mock Server (Port 5001)
                    </button>
                    <div id="mockServerStatus" class="mt-3" style="display:none;">
                        <div class="alert alert-success">
                            Mock server running at <code>http://localhost:5001</code>
                        </div>
                        <h6>Available Endpoints:</h6>
                        <ul>
                            <li><code>/login</code> - Simple login form</li>
                            <li><code>/oauth/authorize</code> - OAuth 2.0 flow</li>
                            <li><code>/sso/login</code> - SSO/SAML endpoint</li>
                            <li><code>/2fa/request</code> - 2FA OTP request</li>
                            <li><code>/api/users</code> - Mock user database</li>
                            <li><code>/api/sessions</code> - Session tracking</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<style>
    .border-left-primary {
        border-left: 4px solid #007bff;
    }
    .border-left-info {
        border-left: 4px solid #17a2b8;
    }
</style>

<script>
let autoScrollEnabled = true;

function appendLog(message, type = 'info') {
    const liveLog = document.getElementById('liveLog');
    const timestamp = new Date().toLocaleTimeString();
    const prefix = {
        'info': '[*]',
        'success': '[+]',
        'warning': '[!]',
        'error': '[-]',
        'network': '[N]',
        'form': '[F]',
        'payload': '[P]',
        'cookie': '[C]'
    }[type] || '[*]';
    
    const colors = {
        'info': '#0f0',
        'success': '#0f0',
        'warning': '#ff0',
        'error': '#f00',
        'network': '#0ff',
        'form': '#f0f',
        'payload': '#f80',
        'cookie': '#0f8'
    }[type] || '#0f0';
    
    const logEntry = document.createElement('div');
    logEntry.style.color = colors;
    logEntry.innerHTML = `<small>${prefix} [${timestamp}] ${message}</small>`;
    liveLog.appendChild(logEntry);
    
    if (autoScrollEnabled) {
        liveLog.scrollTop = liveLog.scrollHeight;
    }
}

function clearLiveLog() {
    document.getElementById('liveLog').innerHTML = '<small class="text-muted">[*] Log cleared</small>';
}

function pauseAutoScroll() {
    autoScrollEnabled = !autoScrollEnabled;
    const btn = event.target;
    btn.textContent = autoScrollEnabled ? 'Pause' : 'Resume';
    btn.classList.toggle('btn-outline-info');
    btn.classList.toggle('btn-info');
}

function connectRecorderLogs(sessionId) {
    // Connect to WebSocket for live logs
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const socket = io(null, { secure: true });
    
    socket.on('recorder_log', (data) => {
        appendLog(data.message, data.type || 'info');
    });
    
    socket.on('form_detected', (data) => {
        document.getElementById('detailForms').textContent = data.count || '-';
        appendLog(`Form detected: ${data.form_name || 'Unknown'} with ${data.field_count || 0} fields`, 'form');
    });
    
    socket.on('cookie_captured', (data) => {
        document.getElementById('detailCookies').textContent = (parseInt(document.getElementById('detailCookies').textContent) || 0) + 1;
        appendLog(`Cookie captured: ${data.name}`, 'cookie');
    });
    
    socket.on('network_log', (data) => {
        appendLog(`${data.method} ${data.url.substring(0, 80)}... -> ${data.status}`, 'network');
    });
    
    socket.on('payload_injected', (data) => {
        appendLog(`Payload injected: ${data.payload_type} (${data.target})`, 'payload');
    });
    
    socket.on('recording_error', (data) => {
        appendLog(`Error: ${data.message}`, 'error');
    });
}

function selectRecorder(type) {
    document.getElementById('recordingType').value = type;
    document.getElementById('configPanel').style.display = 'block';
    
    // Show/hide browser options for Selenium
    const seleniumOpts = document.getElementById('seleniumOptions');
    if (type === 'selenium') {
        seleniumOpts.style.display = 'block';
    } else {
        seleniumOpts.style.display = 'none';
    }
}

function startRecording(event) {
    event.preventDefault();
    
    const form = new FormData(document.getElementById('recordingForm'));
    const data = {
        type: form.get('type'),
        url: form.get('url'),
        browser: form.get('browser') || 'chrome',
        headless: form.get('headless') === 'on' ? 'true' : 'false'
    };
    
    if (!data.url) {
        alert('Please enter target URL');
        return;
    }
    
    // Show status panel
    document.getElementById('configPanel').style.display = 'none';
    document.getElementById('statusPanel').style.display = 'block';
    clearLiveLog();
    
    // Update details
    document.getElementById('detailRecorder').textContent = data.type.toUpperCase();
    document.getElementById('detailUrl').innerHTML = '<code>' + data.url + '</code>';
    document.getElementById('detailHeadless').textContent = data.headless === 'true' ? 'Yes' : 'No';
    document.getElementById('detailForms').textContent = '-';
    document.getElementById('detailCookies').textContent = '-';
    
    appendLog(`Starting ${data.type} recorder for: ${data.url}`, 'info');
    appendLog(`Headless mode: ${data.headless === 'true' ? 'enabled' : 'disabled'}`, 'info');
    appendLog(`Browser: ${data.browser}`, 'info');
    
    // Connect to live logs
    connectRecorderLogs();
    
    // Send to backend
    fetch('/studio/recorder', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(response => {
        console.log('Recording response:', response);
        if (response.status === 'ok') {
            appendLog(`Recording completed successfully. Session ID: ${response.session_id || 'N/A'}`, 'success');
            document.getElementById('statusText').textContent = response.message || 'Recording completed';
        } else {
            appendLog(`Recording failed: ${response.message || 'Unknown error'}`, 'error');
            document.getElementById('statusText').innerHTML = '<span class="text-danger">Error: ' + (response.message || 'Unknown error') + '</span>';
        }
    })
    .catch(e => {
        console.error('Error:', e);
        appendLog(`Error: ${e.message}`, 'error');
        document.getElementById('statusText').innerHTML = '<span class="text-danger">Error: ' + e.message + '</span>';
    });
}

function startMockServer() {
    fetch('/mock-server/start', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({port: 5001})
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            document.getElementById('mockServerStatus').style.display = 'block';
        }
    })
    .catch(e => alert('Error: ' + e));
}
</script>
{% endblock %}
