class SecureTabManager {
    constructor() {
        this.securedTabs = ['identity', 'users', 'email'];
        this.unlocked = new Set();
        this.sessionTokens = {};
        this.init();
    }

    init() {
        this.createPasswordModal();
        this.attachTabListeners();
        this.lockSecuredTabs();
        this.checkExistingSessions();
    }

    async checkExistingSessions() {
        for (const tabName of this.securedTabs) {
            const token = localStorage.getItem(`secure_session_${tabName}`);
            if (token) {
                const isValid = await this.verifySession(token, tabName);
                if (isValid) {
                    this.unlockTab(tabName);
                    this.sessionTokens[tabName] = token;
                } else {
                    localStorage.removeItem(`secure_session_${tabName}`);
                }
            }
        }
    }

    createPasswordModal() {
        const modal = document.createElement('div');
        modal.id = 'password-modal';
        modal.className = 'hidden fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50';
        modal.innerHTML = `
            <div class="bg-white dark:bg-gray-800 rounded-lg w-full max-w-md mx-4 shadow-xl border border-red-200 dark:border-red-700">
                <div class="p-6">
                    <div class="flex items-center space-x-3 mb-6">
                        <div class="w-12 h-12 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center">
                            <i class="fas fa-lock text-red-600 dark:text-red-400 text-xl"></i>
                        </div>
                        <div>
                            <h2 class="text-xl font-bold text-red-600 dark:text-red-400">Restricted Access</h2>
                            <p class="text-sm text-gray-600 dark:text-gray-400">Security verification required</p>
                        </div>
                    </div>
                    
                    <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 rounded-lg p-4 mb-6">
                        <div class="flex items-start space-x-2">
                            <i class="fas fa-exclamation-triangle text-red-500 mt-0.5"></i>
                            <div class="text-sm text-red-700 dark:text-red-300">
                                <p class="font-medium mb-1">Warning</p>
                                <p>This section contains sensitive information. A security password is required for access.</p>
                            </div>
                        </div>
                    </div>

                    <form id="password-form" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">
                                Security Password (12 characters)
                            </label>
                            <input type="password" id="security-password" maxlength="12" 
                                   class="w-full px-4 py-3 rounded-lg bg-gray-100 dark:bg-gray-700 
                                          border-2 border-gray-200 dark:border-gray-600
                                          focus:outline-none focus:border-red-500 dark:focus:border-red-400
                                          font-mono text-center tracking-widest"
                                   placeholder="••••••••••••">
                        </div>
                        
                        <div class="text-xs text-gray-500 dark:text-gray-400 text-center">
                            <p>Attempts remaining: <span id="attempts-left">3</span></p>
                        </div>

                        <div id="error-message" class="hidden text-red-500 text-sm text-center"></div>

                        <div class="flex justify-end space-x-3 pt-4">
                            <button type="button" id="cancel-password"
                                    class="px-4 py-2 border border-gray-200 dark:border-gray-600 
                                           rounded-lg text-gray-700 dark:text-gray-300 
                                           hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                                Cancel
                            </button>
                            <button type="submit" id="unlock-button"
                                    class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white 
                                           rounded-lg transition-colors flex items-center space-x-2">
                                <i class="fas fa-unlock"></i>
                                <span>Unlock</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        document.getElementById('password-form').addEventListener('submit', (e) => {
            e.preventDefault();
            this.verifyPassword();
        });

        document.getElementById('cancel-password').addEventListener('click', () => {
            this.hidePasswordModal();
        });
    }

    attachTabListeners() {
        this.securedTabs.forEach(tabName => {
            const tab = document.querySelector(`.${tabName}-tab`);
            if (tab) {
                tab.onclick = (e) => {
                    e.preventDefault();
                    if (this.unlocked.has(tabName)) {
                        this.showTab(tabName);
                    } else {
                        this.currentTab = tabName;
                        this.showPasswordModal();
                    }
                };
            }
        });
    }

    lockSecuredTabs() {
        this.securedTabs.forEach(tabName => {
            const content = document.getElementById(`${tabName}-content`);
            if (content) {
                content.classList.add('hidden');
                this.createLockedPlaceholder(tabName);
            }
        });
    }

    createLockedPlaceholder(tabName) {
        const content = document.getElementById(`${tabName}-content`);
        if (!content) return;

        const placeholder = document.createElement('div');
        placeholder.id = `${tabName}-locked`;
        placeholder.className = 'tab-content flex items-center justify-center min-h-[400px]';
        placeholder.innerHTML = `
            <div class="text-center">
                <div class="w-24 h-24 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center mx-auto mb-6">
                    <i class="fas fa-lock text-red-600 dark:text-red-400 text-3xl"></i>
                </div>
                <h3 class="text-xl font-bold text-red-600 dark:text-red-400 mb-2">Restricted Access</h3>
                <p class="text-gray-600 dark:text-gray-400 mb-6">
                    This section is protected by a security password.
                </p>
                <button class="unlock-btn px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors flex items-center space-x-2 mx-auto"
                        data-tab="${tabName}">
                    <i class="fas fa-unlock"></i>
                    <span>Unlock Access</span>
                </button>
            </div>
        `;

        content.parentNode.insertBefore(placeholder, content.nextSibling);

        placeholder.querySelector('.unlock-btn').addEventListener('click', () => {
            this.currentTab = tabName;
            this.showPasswordModal();
        });
    }

    showPasswordModal() {
        document.getElementById('password-modal').classList.remove('hidden');
        document.getElementById('security-password').focus();
        this.hideError();
    }

    hidePasswordModal() {
        document.getElementById('password-modal').classList.add('hidden');
        document.getElementById('security-password').value = '';
        this.hideError();
    }

    showError(message) {
        const errorDiv = document.getElementById('error-message');
        errorDiv.textContent = message;
        errorDiv.classList.remove('hidden');
    }

    hideError() {
        const errorDiv = document.getElementById('error-message');
        errorDiv.classList.add('hidden');
    }

    async verifyPassword() {
        const passwordInput = document.getElementById('security-password');
        const unlockButton = document.getElementById('unlock-button');
        const password = passwordInput.value;

        if (password.length !== 12) {
            this.showError('Password must be exactly 12 characters');
            return;
        }

        unlockButton.disabled = true;
        unlockButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span>Verifying...</span>';

        try {
            const response = await fetch('secure_auth.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'verify_password',
                    password: password,
                    tabName: this.currentTab
                })
            });

            const data = await response.json();

            if (data.success) {
                localStorage.setItem(`secure_session_${this.currentTab}`, data.sessionToken);
                this.sessionTokens[this.currentTab] = data.sessionToken;
                this.unlockTab(this.currentTab);
                this.hidePasswordModal();
            } else {
                this.showError(data.message);
                if (data.remainingAttempts !== undefined) {
                    document.getElementById('attempts-left').textContent = data.remainingAttempts;
                }
                if (data.lockout) {
                    setTimeout(() => {
                        document.getElementById('attempts-left').textContent = '3';
                    }, 300000);
                }
            }
        } catch (error) {
            this.showError('Network error. Please try again.');
        }

        unlockButton.disabled = false;
        unlockButton.innerHTML = '<i class="fas fa-unlock"></i> <span>Unlock</span>';
        passwordInput.value = '';
    }

    async verifySession(sessionToken, tabName) {
        try {
            const response = await fetch('secure_auth.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'verify_session',
                    sessionToken: sessionToken,
                    tabName: tabName
                })
            });

            const data = await response.json();
            return data.success;
        } catch (error) {
            return false;
        }
    }

    unlockTab(tabName) {
        this.unlocked.add(tabName);
        
        const placeholder = document.getElementById(`${tabName}-locked`);
        if (placeholder) {
            placeholder.classList.add('hidden');
        }

        const content = document.getElementById(`${tabName}-content`);
        if (content) {
            content.classList.remove('hidden');
        }

        this.showTab(tabName);
        this.addUnlockIndicator(tabName);
    }

    addUnlockIndicator(tabName) {
        const tab = document.querySelector(`.${tabName}-tab`);
        if (tab && !tab.querySelector('.unlock-indicator')) {
            const indicator = document.createElement('i');
            indicator.className = 'fas fa-unlock unlock-indicator text-green-500 ml-1 text-xs';
            tab.appendChild(indicator);
        }
    }

    showTab(tabName) {
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });

        document.querySelectorAll('[data-tab]').forEach(tab => {
            tab.classList.remove('border-black', 'dark:border-white');
            tab.classList.add('border-transparent');
        });

        const content = document.getElementById(`${tabName}-content`);
        if (content) {
            content.classList.remove('hidden');
        }

        const tab = document.querySelector(`.${tabName}-tab`);
        if (tab) {
            tab.classList.add('border-black', 'dark:border-white');
            tab.classList.remove('border-transparent');
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    window.secureTabManager = new SecureTabManager();
});