const encode = (data) => {
    try {
        // If the data is an object, convert it to a JSON string
        const stringValue = typeof data === 'object' ? JSON.stringify(data) : data;
        // Encode the string value in UTF-8 before converting to Base64
        return btoa(unescape(encodeURIComponent(stringValue)));
    }
    catch (error) {
        console.error('Error encoding data:', error);
        throw new Error('Encoding failed');
    }
};
const decode = (data) => {
    try {
        // Decode from Base64 and decode the UTF-8 string
        const decodedString = decodeURIComponent(escape(atob(data)));
        // Try parsing the string as JSON; if it fails, return the string as-is
        try {
            return JSON.parse(decodedString);
        }
        catch {
            return decodedString;
        }
    }
    catch (error) {
        console.error('Error decoding data:', error);
        throw new Error('Decoding failed');
    }
};
const openIndexedDB = () => {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('fireflink', 1);
        request.onupgradeneeded = (event) => {
            const db = event.target.result;
            // Create object store if it doesn't exist
            if (!db.objectStoreNames.contains('keyValueStore')) {
                db.createObjectStore('keyValueStore', { keyPath: 'key' });
            }
        };
        request.onsuccess = (event) => resolve(event.target.result);
        request.onerror = (event) => {
            console.error('Error opening IndexedDB:', event.target.error);
            reject('Error opening IndexedDB');
        };
    });
};
const withTransaction = (storeName, mode, callback) => {
    return new Promise(async (resolve, reject) => {
        try {
            const db = await openIndexedDB();
            const transaction = db.transaction(storeName, mode);
            const store = transaction.objectStore(storeName);
            if (!store) {
                reject(`Object store "${storeName}" not found.`);
                return;
            }
            const result = await callback(store);
            transaction.oncomplete = () => resolve(result);
            transaction.onerror = (e) => {
                console.error('Transaction error:', e);
                reject('Transaction failed');
            };
        }
        catch (error) {
            console.error('Error in transaction:', error);
            reject(`Transaction error: ${error}`);
        }
    });
};
export const setStoreValue = async (key, value) => {
    if (!key || value === undefined) {
        throw new Error('Key and value must be provided');
    }
    await withTransaction('keyValueStore', 'readwrite', (store) => {
        const encodedValue = encode(value);
        const request = store.put({ key, value: encodedValue });
        return new Promise((resolve, reject) => {
            request.onsuccess = () => resolve();
            request.onerror = (e) => {
                console.error('Failed to save data:', e);
                reject('Failed to save data');
            };
        });
    });
};
export const getStoreValue = async (key) => {
    if (!key) {
        throw new Error('Key must be provided');
    }
    return await withTransaction('keyValueStore', 'readonly', (store) => {
        const request = store.get(key);
        return new Promise((resolve, reject) => {
            request.onsuccess = (event) => {
                const result = event.target.result;
                if (result && result.value) {
                    try {
                        resolve(decode(result.value));
                    }
                    catch (decodeError) {
                        console.error('Error decoding data:', decodeError);
                        reject('Error decoding retrieved data');
                    }
                }
                else {
                    resolve(null);
                }
            };
            request.onerror = (e) => {
                console.error('Failed to retrieve data:', e);
                reject('Failed to retrieve data');
            };
        });
    });
};
export const deleteStoreValue = async (key) => {
    if (!key) {
        throw new Error('Key must be provided');
    }
    await withTransaction('keyValueStore', 'readwrite', (store) => {
        const request = store.delete(key);
        return new Promise((resolve, reject) => {
            request.onsuccess = () => resolve();
            request.onerror = (e) => {
                console.error('Failed to delete data:', e);
                reject('Failed to delete data');
            };
        });
    });
};
export const clearStore = async () => {
    await withTransaction('keyValueStore', 'readwrite', (store) => {
        const request = store.clear();
        return new Promise((resolve, reject) => {
            request.onsuccess = () => resolve();
            request.onerror = (e) => {
                console.error('Failed to clear data:', e);
                reject('Failed to clear data');
            };
        });
    });
};
//# sourceMappingURL=indexDB%20copy.js.map