/**
 * Persistent settings via Tauri store plugin.
 * Stores key-value data in a JSON file managed by the Tauri backend.
 * Falls back to in-memory Map when running in browser (dev mode).
 */
import { Store } from "@tauri-apps/plugin-store"

let _store: Store | null = null
const memoryStore = new Map<string, unknown>()

function isTauri(): boolean {
  return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window
}

async function getStore(): Promise<Store> {
  if (!_store) {
    _store = isTauri() ? await Store.load("settings.json") : null
  }
  return _store as Store
}

export function useSettings() {
  async function get<T>(key: string): Promise<T | undefined> {
    if (isTauri()) {
      const store = await getStore()
      return await store.get<T>(key)
    }
    return memoryStore.get(key) as T | undefined
  }

  async function set<T>(key: string, value: T): Promise<void> {
    if (isTauri()) {
      const store = await getStore()
      await store.set(key, value)
      await store.save()
      return
    }
    memoryStore.set(key, value)
  }

  return { get, set }
}
