<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>404 - Page Not Found</title>
    
    <!-- Security Headers -->
    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <meta name="googlebot" content="noindex, nofollow">
    <meta name="bingbot" content="noindex, nofollow">
    
    <!-- Prevent caching -->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    
    <!-- Security headers -->
    <meta http-equiv="X-Content-Type-Options" content="nosniff">
    <meta http-equiv="X-Frame-Options" content="DENY">
    <meta http-equiv="X-XSS-Protection" content="1; mode=block">
    <meta http-equiv="Referrer-Policy" content="no-referrer">
    <meta http-equiv="Permissions-Policy" content="camera=(), microphone=(), geolocation=()">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 2.5rem;
        }

        .header p {
            color: #7f8c8d;
            font-size: 1.1rem;
        }

        .auth-section {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 40px;
            margin-bottom: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .login-btn {
            background: #4285f4;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

        .login-btn:hover {
            background: #3367d6;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(66, 133, 244, 0.3);
        }

        .logout-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: #c82333;
        }

        .user-info {
            background: #e8f5e8;
            border: 1px solid #4caf50;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .dashboard {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            display: none;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 1rem;
            opacity: 0.9;
        }

        .submissions-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .table-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #dee2e6;
        }

        .table-header h3 {
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .table-controls {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-input {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1rem;
            min-width: 250px;
        }

        .filter-select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1rem;
            background: white;
        }

        .refresh-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .refresh-btn:hover {
            background: #218838;
        }

        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }

        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
            position: sticky;
            top: 0;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-new {
            background: #d4edda;
            color: #155724;
        }

        .status-processed {
            background: #cce5ff;
            color: #004085;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
            border: 1px solid #f5c6cb;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
            border: 1px solid #c3e6cb;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #dee2e6;
        }

        .close {
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }

        .close:hover {
            color: #000;
        }

        .detail-item {
            margin-bottom: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 6px;
        }

        .detail-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .detail-value {
            color: #495057;
            word-break: break-word;
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .table-controls {
                flex-direction: column;
                align-items: stretch;
            }
            
            .search-input {
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Fake 404 Page (shown to unauthorized users) -->
        <div class="header" id="fake404" style="display: block;">
            <h1>404 - Page Not Found</h1>
            <p>The page you are looking for does not exist.</p>
            <div style="margin-top: 30px;">
                <a href="/" style="color: #667eea; text-decoration: none; font-weight: 500;">← Back to Home</a>
            </div>
        </div>

        <!-- Real Admin Header (hidden until authenticated) -->
        <div class="header" id="realHeader" style="display: none;">
            <h1>🔐 Admin Dashboard</h1>
            <p>Su Seguro de Vida - Form Submissions Management</p>
        </div>

        <!-- Authentication Section -->
        <div class="auth-section" id="authSection">
            <h2>Secure Access Required</h2>
            <p style="margin: 20px 0; color: #6c757d;">Please sign in with your Google account to access the admin dashboard.</p>
            <button class="login-btn" id="loginBtn">
                <span>🔑</span>
                Sign in with Google
            </button>
        </div>

        <!-- User Info (shown after login) -->
        <div class="user-info" id="userInfo" style="display: none;">
            <div>
                <strong>Welcome, <span id="userName"></span>!</strong>
                <span style="margin-left: 10px; color: #6c757d;">Signed in as: <span id="userEmail"></span></span>
            </div>
            <button class="logout-btn" id="logoutBtn">Sign Out</button>
        </div>

        <!-- Dashboard (shown after authentication) -->
        <div class="dashboard" id="dashboard">
            <!-- Statistics -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-number" id="totalSubmissions">0</div>
                    <div class="stat-label">Total Submissions</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="newSubmissions">0</div>
                    <div class="stat-label">New Submissions</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="todaySubmissions">0</div>
                    <div class="stat-label">Today's Submissions</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="thisWeekSubmissions">0</div>
                    <div class="stat-label">This Week</div>
                </div>
            </div>

            <!-- Submissions Table -->
            <div class="submissions-table">
                <div class="table-header">
                    <h3>📋 Form Submissions</h3>
                    <div class="table-controls">
                        <input type="text" class="search-input" id="searchInput" placeholder="Search submissions...">
                        <select class="filter-select" id="statusFilter">
                            <option value="all">All Status</option>
                            <option value="new">New</option>
                            <option value="processed">Processed</option>
                        </select>
                        <button class="refresh-btn" id="refreshBtn">🔄 Refresh</button>
                    </div>
                </div>
                <div class="table-container">
                    <div class="loading" id="loadingIndicator">Loading submissions...</div>
                    <table id="submissionsTable" style="display: none;">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Submitted</th>
                                <th>Status</th>
                                <th>Source</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="submissionsTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Submission Detail Modal -->
    <div class="modal" id="detailModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📄 Submission Details</h3>
                <span class="close" id="closeModal">&times;</span>
            </div>
            <div id="modalContent">
                <!-- Content will be populated dynamically -->
            </div>
        </div>
    </div>

    <!-- Firebase SDK -->
    <script type="module">
        // Import Firebase modules
        import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js';
        import { getFirestore, collection, query, orderBy, onSnapshot, where, getDocs } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js';
        import { getAuth, signInWithPopup, GoogleAuthProvider, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js';

        // Firebase configuration
        const firebaseConfig = {
            apiKey: "AIzaSyDZMm5LAKQFJX9zSbiFVBFT0bD1jr7Lqow",
            authDomain: "suseguro-d0e84.firebaseapp.com",
            projectId: "suseguro-d0e84",
            storageBucket: "suseguro-d0e84.firebasestorage.app",
            messagingSenderId: "979621711541",
            appId: "1:979621711541:web:5b0e8cffc300f09463f8fc"
        };

        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        const db = getFirestore(app);
        const auth = getAuth(app);
        const provider = new GoogleAuthProvider();

        // DOM elements
        const fake404 = document.getElementById('fake404');
        const realHeader = document.getElementById('realHeader');
        const authSection = document.getElementById('authSection');
        const userInfo = document.getElementById('userInfo');
        const dashboard = document.getElementById('dashboard');
        const loginBtn = document.getElementById('loginBtn');
        const logoutBtn = document.getElementById('logoutBtn');
        const userName = document.getElementById('userName');
        const userEmail = document.getElementById('userEmail');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const submissionsTable = document.getElementById('submissionsTable');
        const submissionsTableBody = document.getElementById('submissionsTableBody');
        const searchInput = document.getElementById('searchInput');
        const statusFilter = document.getElementById('statusFilter');
        const refreshBtn = document.getElementById('refreshBtn');
        const detailModal = document.getElementById('detailModal');
        const closeModal = document.getElementById('closeModal');
        const modalContent = document.getElementById('modalContent');

        // Statistics elements
        const totalSubmissions = document.getElementById('totalSubmissions');
        const newSubmissions = document.getElementById('newSubmissions');
        const todaySubmissions = document.getElementById('todaySubmissions');
        const thisWeekSubmissions = document.getElementById('thisWeekSubmissions');

        // Global variables
        let allSubmissions = [];
        let filteredSubmissions = [];

        // Authentication functions
        async function signInWithGoogle() {
            try {
                const result = await signInWithPopup(auth, provider);
                console.log('Signed in successfully:', result.user);
            } catch (error) {
                console.error('Sign-in error:', error);
                alert('Sign-in failed. Please try again.');
            }
        }

        async function signOutUser() {
            try {
                await signOut(auth);
                console.log('Signed out successfully');
            } catch (error) {
                console.error('Sign-out error:', error);
            }
        }

        // Auth state listener
        onAuthStateChanged(auth, (user) => {
            if (user) {
                // User is signed in - show real admin interface
                fake404.style.display = 'none';
                realHeader.style.display = 'block';
                authSection.style.display = 'none';
                userInfo.style.display = 'block';
                dashboard.style.display = 'block';
                
                userName.textContent = user.displayName || 'User';
                userEmail.textContent = user.email;
                
                // Load submissions
                loadSubmissions();
            } else {
                // User is signed out - show fake 404 page
                fake404.style.display = 'block';
                realHeader.style.display = 'none';
                authSection.style.display = 'none';
                userInfo.style.display = 'none';
                dashboard.style.display = 'none';
            }
        });

        // Load submissions from Firestore
        function loadSubmissions() {
            loadingIndicator.style.display = 'block';
            submissionsTable.style.display = 'none';

            const submissionsRef = collection(db, 'formSubmissions');
            const q = query(submissionsRef, orderBy('submittedAt', 'desc'));

            onSnapshot(q, (snapshot) => {
                allSubmissions = [];
                snapshot.forEach((doc) => {
                    const data = doc.data();
                    allSubmissions.push({
                        id: doc.id,
                        ...data,
                        submittedAt: data.submittedAt?.toDate() || new Date()
                    });
                });

                updateStatistics();
                applyFilters();
                loadingIndicator.style.display = 'none';
                submissionsTable.style.display = 'table';
            }, (error) => {
                console.error('Error loading submissions:', error);
                loadingIndicator.innerHTML = '<div class="error">Error loading submissions. Please try again.</div>';
            });
        }

        // Update statistics
        function updateStatistics() {
            const now = new Date();
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

            const newCount = allSubmissions.filter(sub => sub.status === 'new').length;
            const todayCount = allSubmissions.filter(sub => sub.submittedAt >= today).length;
            const weekCount = allSubmissions.filter(sub => sub.submittedAt >= weekAgo).length;

            totalSubmissions.textContent = allSubmissions.length;
            newSubmissions.textContent = newCount;
            todaySubmissions.textContent = todayCount;
            thisWeekSubmissions.textContent = weekCount;
        }

        // Apply filters
        function applyFilters() {
            const searchTerm = searchInput.value.toLowerCase();
            const statusFilterValue = statusFilter.value;

            filteredSubmissions = allSubmissions.filter(submission => {
                const matchesSearch = 
                    submission.name.toLowerCase().includes(searchTerm) ||
                    submission.email.toLowerCase().includes(searchTerm) ||
                    submission.phone.includes(searchTerm);

                const matchesStatus = 
                    statusFilterValue === 'all' || 
                    submission.status === statusFilterValue;

                return matchesSearch && matchesStatus;
            });

            renderSubmissions();
        }

        // Render submissions table
        function renderSubmissions() {
            submissionsTableBody.innerHTML = '';

            if (filteredSubmissions.length === 0) {
                submissionsTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 40px; color: #6c757d;">No submissions found</td></tr>';
                return;
            }

            filteredSubmissions.forEach(submission => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${submission.name}</td>
                    <td>${submission.email}</td>
                    <td>${submission.phone}</td>
                    <td>${formatDate(submission.submittedAt)}</td>
                    <td><span class="status-badge status-${submission.status}">${submission.status}</span></td>
                    <td>${submission.source || 'Website'}</td>
                    <td>
                        <button onclick="viewDetails('${submission.id}')" style="background: #007bff; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 0.9rem;">View</button>
                    </td>
                `;
                submissionsTableBody.appendChild(row);
            });
        }

        // View submission details
        window.viewDetails = function(submissionId) {
            const submission = allSubmissions.find(sub => sub.id === submissionId);
            if (!submission) return;

            modalContent.innerHTML = `
                <div class="detail-item">
                    <div class="detail-label">Name</div>
                    <div class="detail-value">${submission.name}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Email</div>
                    <div class="detail-value">${submission.email}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Phone</div>
                    <div class="detail-value">${submission.phone}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Submitted At</div>
                    <div class="detail-value">${formatDateTime(submission.submittedAt)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Status</div>
                    <div class="detail-value"><span class="status-badge status-${submission.status}">${submission.status}</span></div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Source</div>
                    <div class="detail-value">${submission.source || 'Website'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">User Agent</div>
                    <div class="detail-value">${submission.userAgent || 'N/A'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">IP Address</div>
                    <div class="detail-value">${submission.ipAddress || 'N/A'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Language</div>
                    <div class="detail-value">${submission.language || 'N/A'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Timezone</div>
                    <div class="detail-value">${submission.timezone || 'N/A'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Referrer</div>
                    <div class="detail-value">${submission.referrer || 'Direct'}</div>
                </div>
            `;

            detailModal.style.display = 'block';
        };

        // Utility functions
        function formatDate(date) {
            return new Intl.DateTimeFormat('en-US', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            }).format(date);
        }

        function formatDateTime(date) {
            return new Intl.DateTimeFormat('en-US', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            }).format(date);
        }

        // Event listeners
        loginBtn.addEventListener('click', signInWithGoogle);
        logoutBtn.addEventListener('click', signOutUser);
        searchInput.addEventListener('input', applyFilters);
        statusFilter.addEventListener('change', applyFilters);
        refreshBtn.addEventListener('click', loadSubmissions);
        closeModal.addEventListener('click', () => {
            detailModal.style.display = 'none';
        });

        // Close modal when clicking outside
        window.addEventListener('click', (event) => {
            if (event.target === detailModal) {
                detailModal.style.display = 'none';
            }
        });
    </script>
</body>
</html>
