/**
 * AES Encryption/Decryption utility for securing chat data
 * Uses Web Crypto API for secure client-side encryption
 */
class ChatEncryption {
    constructor() {
        this.algorithm = 'AES-GCM';
        this.keyLength = 256;
        this.ivLength = 12; // 96 bits for GCM
        this.tagLength = 128; // 128 bits for GCM
        this.textEncoder = new TextEncoder();
        this.textDecoder = new TextDecoder();
        this.cryptoKey = null;
        this.isInitialized = false;
        
        // Don't initialize automatically - let caller do it when ready
    }

    /**
     * Initialize or retrieve encryption key from localStorage
     */
    async initializeKey() {
        // Check if already initialized
        if (this.isInitialized) {
            return;
        }

        // Check if encryption is supported
        if (!ChatEncryption.isSupported()) {
            console.warn('Web Crypto API not supported in this environment');
            return;
        }

        try {
            // Try to get existing key from localStorage
            const storedKey = localStorage.getItem('askany_encryption_key');
            
            if (storedKey) {
                // Import existing key
                const keyData = this.base64ToArrayBuffer(storedKey);
                this.cryptoKey = await window.crypto.subtle.importKey(
                    'raw',
                    keyData,
                    { name: this.algorithm },
                    false,
                    ['encrypt', 'decrypt']
                );
            } else {
                // Generate new key
                await this.generateNewKey();
            }
            
            this.isInitialized = true;
        } catch (error) {
            console.warn('Encryption key initialization failed:', error);
            this.isInitialized = false;
        }
    }

    
}

// Expose the class globally for static method access
window.ChatEncryption = ChatEncryption;

// Create global instance only if supported
if (ChatEncryption.isSupported()) {
    window.chatEncryption = new ChatEncryption();
} else {
    // Create a dummy instance that does nothing
    window.chatEncryption = {
        initializeKey: async () => {},
        encrypt: async (text) => text,
        decrypt: async (text) => text,
        encryptObject: async (obj) => JSON.stringify(obj),
        decryptObject: async (str) => {
            try {
                return JSON.parse(str);
            } catch {
                return {};
            }
        }
    };
    console.warn('Chat encryption disabled: Web Crypto API not available');
}

// Export for module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ChatEncryption;
}