let instance;
const instanceKey = 'data_392994';

class AppData {

    _data = {};

    constructor(key) {
        if (key !== instanceKey) {
            throw new Error('Cannot instantiate like this');
        }
        try {
            this._data = JSON.parse(jQuery('#frontend-data').html());
            // console.log('AppData initialized with data:', this._data);
            
        } catch (error) {
            console.error('Error in AppData constructor:', error);
        }
    }

    get(key) {
        if (this._data[key] === undefined) {
            return null;
        }
        return this._data[key];
    }

    set(key, value) {
        this._data[key] = value;
    }

    getLabel(key) {
        const langs = this.get('fe_labels');
        return langs[key] ? langs[key] : '';
    }

    getMetaByKey(key, defaultValue = null) {
        const user_data = this.get('user_data');
        if (!user_data) {
            return defaultValue;
        }
        if (!user_data?.meta) {
            return defaultValue;
        }
        
        return user_data.meta?.[key] ?? defaultValue;
    }

    setMetaByKey(key, value) {
        let user_data = this.get('user_data');
        if (!user_data) {
            user_data = {};
        }
        user_data[key] = value;
        this.set('user_data', user_data);
    }

    logData() {
        console.log('data', this._data);
    }

    static getInstance() {
        if (!instance) {
            instance = new AppData(instanceKey);
        }
        return instance;
    }
}
export default AppData;