function toLabel(path) {
  const seg = path.split(".").pop() ?? path;
  return seg.replace(/([A-Z])/g, " $1").trim().toLowerCase();
}
function createSettingsStore(initial, toastStore, activityStore) {
  const current = { ...initial };
  const pending = /* @__PURE__ */ new Map();
  const listeners = /* @__PURE__ */ new Set();
  const queues = /* @__PURE__ */ new Map();
  const notify = () => {
    for (const fn of listeners) fn();
  };
  async function commitOne(path) {
    if (!pending.has(path)) return;
    const value = pending.get(path);
    const prev = queues.get(path) ?? Promise.resolve();
    const next = prev.then(async () => {
      const { persistKey } = await import("../actions/write-config.js");
      const endActivity = activityStore?.begin("save:" + path);
      try {
        await persistKey(path, value);
        if (pending.get(path) === value) {
          pending.delete(path);
        }
        notify();
        toastStore?.push({
          message: `Saved \xB7 ${toLabel(path)}`,
          severity: "ok",
          ttl: 3e3,
          group: "save"
        });
      } catch (err) {
        toastStore?.push({
          message: `Save failed: ${toLabel(path)}`,
          severity: "err",
          ttl: 5e3,
          group: "save-error"
        });
        throw err;
      } finally {
        endActivity?.();
      }
    });
    queues.set(path, next);
    try {
      await next;
    } finally {
      if (queues.get(path) === next) queues.delete(path);
    }
  }
  return {
    getCurrent: () => ({ ...current }),
    getPending: () => Object.fromEntries(pending),
    isDirty: () => pending.size > 0,
    dirtyKeys: () => [...pending.keys()],
    set(key, value) {
      const cur = current[key];
      const same = JSON.stringify(cur) === JSON.stringify(value);
      if (same) pending.delete(key);
      else pending.set(key, value);
      notify();
    },
    discard() {
      pending.clear();
      notify();
    },
    commit() {
      if (pending.size === 0) return;
      for (const [k, v] of pending) current[k] = v;
      pending.clear();
      notify();
    },
    subscribe(fn) {
      listeners.add(fn);
      return () => {
        listeners.delete(fn);
      };
    },
    commitOne,
    async blur(path) {
      if (pending.has(path)) await commitOne(path);
    }
  };
}
export {
  createSettingsStore
};
//# sourceMappingURL=settings-store.js.map