package com.tt.honeyDue.data

import kotlinx.browser.localStorage

/**
 * WasmJS implementation of PersistenceManager using browser localStorage.
 */
actual class PersistenceManager {
    actual fun save(key: String, value: String) {
        localStorage.setItem(key, value)
    }

    actual fun load(key: String): String? {
        return localStorage.getItem(key)
    }

    actual fun remove(key: String) {
        localStorage.removeItem(key)
    }

    actual fun clear() {
        // Remove all items with our prefix
        val keysToRemove = mutableListOf<String>()
        for (i in 0 until localStorage.length) {
            val key = localStorage.key(i) ?: continue
            if (key.startsWith("dm_")) {
                keysToRemove.add(key)
            }
        }
        keysToRemove.forEach { localStorage.removeItem(it) }
    }

    companion object {
        private val instance by lazy { PersistenceManager() }

        fun getInstance(): PersistenceManager = instance
    }
}
