/**
 * GuestProfileManager
 * Persistensi data identitas guest customer di localStorage.
 * Tidak terhubung ke sistem login apapun.
 *
 * Keys yang disimpan (satu object JSON):
 *   name, phone, address, deliveryAreaId, customerNotes
 */

const STORAGE_KEY = 'titipin_guest_profile';

const GuestProfile = {
    /**
     * Simpan data profil guest ke localStorage.
     * @param {object} data - { name, phone, address, deliveryAreaId, customerNotes }
     */
    save(data) {
        try {
            const existing = this.load();
            const merged = { ...existing, ...data };
            // Hapus key yang nilainya kosong/null agar tidak menimpa dengan kosong
            Object.keys(merged).forEach(k => {
                if (merged[k] === null || merged[k] === undefined || merged[k] === '') {
                    delete merged[k];
                }
            });
            localStorage.setItem(STORAGE_KEY, JSON.stringify(merged));
        } catch (e) {
            // localStorage tidak tersedia (private mode) — abaikan
        }
    },

    /**
     * Ambil data profil guest dari localStorage.
     * @returns {object} - data tersimpan, atau {} jika kosong
     */
    load() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            return raw ? JSON.parse(raw) : {};
        } catch (e) {
            return {};
        }
    },

    /**
     * Hapus seluruh data profil guest dari localStorage.
     */
    clear() {
        try {
            localStorage.removeItem(STORAGE_KEY);
        } catch (e) {
            // abaikan
        }
    },

    /**
     * Cek apakah ada data tersimpan.
     * @returns {boolean}
     */
    hasData() {
        const data = this.load();
        return Object.keys(data).length > 0;
    },
};

// Expose ke window agar bisa diakses dari inline script dan Livewire
window.GuestProfile = GuestProfile;

export default GuestProfile;
