import {
  require_lodash
} from "./chunk-GABLRWPI.js";
import {
  InstancePresenceRecordType,
  computed,
  createPresenceStateDerivation,
  createTLStore,
  defaultShapeUtils,
  defaultUserPreferences,
  getUserPreferences,
  react,
  setUserPreferences
} from "./chunk-HZMZCFKT.js";
import "./chunk-VXJXQW5O.js";
import "./chunk-7RVXTONK.js";
import "./chunk-FGBSNFAB.js";
import "./chunk-A4L6H3JD.js";
import "./chunk-SBOC772F.js";
import "./chunk-ADRVA6BL.js";
import "./chunk-3II6XBGW.js";
import "./chunk-7QCPQX5P.js";
import "./chunk-2NJBJH53.js";
import "./chunk-AB6ZV2XR.js";
import "./chunk-GUCB4VV7.js";
import "./chunk-QMZ62V7Z.js";
import "./chunk-N5TPNWD3.js";
import {
  Nn,
  Vn
} from "./chunk-KUXEU2ZE.js";
import "./chunk-EK5KU4LC.js";
import "./chunk-M2BG764J.js";
import {
  require_react
} from "./chunk-PWIQPVSF.js";
import {
  __toESM
} from "./chunk-5WWUZCGV.js";

// node_modules/.deno/automerge-tldraw@0.1.5/node_modules/automerge-tldraw/dist/default_store.js
var DEFAULT_STORE = {
  store: {
    "document:document": {
      gridSize: 10,
      name: "",
      meta: {},
      id: "document:document",
      typeName: "document"
    },
    "pointer:pointer": {
      id: "pointer:pointer",
      typeName: "pointer",
      x: 0,
      y: 0,
      lastActivityTimestamp: 0,
      meta: {}
    },
    "page:page": {
      meta: {},
      id: "page:page",
      name: "Page 1",
      index: "a1",
      typeName: "page"
    },
    "camera:page:page": {
      x: 0,
      y: 0,
      z: 1,
      meta: {},
      id: "camera:page:page",
      typeName: "camera"
    },
    "instance_page_state:page:page": {
      editingShapeId: null,
      croppingShapeId: null,
      selectedShapeIds: [],
      hoveredShapeId: null,
      erasingShapeIds: [],
      hintingShapeIds: [],
      focusedGroupId: null,
      meta: {},
      id: "instance_page_state:page:page",
      pageId: "page:page",
      typeName: "instance_page_state"
    },
    "instance:instance": {
      followingUserId: null,
      opacityForNextShape: 1,
      stylesForNextShape: {},
      brush: null,
      scribble: null,
      cursor: {
        type: "default",
        rotation: 0
      },
      isFocusMode: false,
      exportBackground: true,
      isDebugMode: false,
      isToolLocked: false,
      screenBounds: {
        x: 0,
        y: 0,
        w: 720,
        h: 400
      },
      zoomBrush: null,
      isGridMode: false,
      isPenMode: false,
      chatMessage: "",
      isChatting: false,
      highlightedUserIds: [],
      canMoveCamera: true,
      isFocused: true,
      devicePixelRatio: 2,
      isCoarsePointer: false,
      isHoveringCanvas: false,
      openMenus: [],
      isChangingStyle: false,
      isReadonly: false,
      meta: {},
      id: "instance:instance",
      currentPageId: "page:page",
      typeName: "instance"
    }
  },
  schema: {
    schemaVersion: 1,
    storeVersion: 4,
    recordVersions: {
      asset: {
        version: 1,
        subTypeKey: "type",
        subTypeVersions: {
          image: 2,
          video: 2,
          bookmark: 0
        }
      },
      camera: {
        version: 1
      },
      document: {
        version: 2
      },
      instance: {
        version: 21
      },
      instance_page_state: {
        version: 5
      },
      page: {
        version: 1
      },
      shape: {
        version: 3,
        subTypeKey: "type",
        subTypeVersions: {
          group: 0,
          text: 1,
          bookmark: 1,
          draw: 1,
          geo: 7,
          note: 4,
          line: 1,
          frame: 0,
          arrow: 1,
          highlight: 0,
          embed: 4,
          image: 2,
          video: 1
        }
      },
      instance_presence: {
        version: 5
      },
      pointer: {
        version: 1
      }
    }
  }
};

// node_modules/.deno/automerge-tldraw@0.1.5/node_modules/automerge-tldraw/dist/useAutomergeStore.js
var import_react = __toESM(require_react());

// node_modules/.deno/automerge-tldraw@0.1.5/node_modules/automerge-tldraw/dist/AutomergeToTLStore.js
function applyAutomergePatchesToTLStore(patches, store) {
  const toRemove = [];
  const updatedObjects = {};
  patches.forEach((patch) => {
    if (!isStorePatch(patch))
      return;
    const id = pathToId(patch.path);
    const record = updatedObjects[id] || JSON.parse(JSON.stringify(store.get(id) || {}));
    switch (patch.action) {
      case "insert": {
        updatedObjects[id] = applyInsertToObject(patch, record);
        break;
      }
      case "put":
        updatedObjects[id] = applyPutToObject(patch, record);
        break;
      case "update": {
        updatedObjects[id] = applyUpdateToObject(patch, record);
        break;
      }
      case "splice": {
        updatedObjects[id] = applySpliceToObject(patch, record);
        break;
      }
      case "del": {
        const id2 = pathToId(patch.path);
        toRemove.push(id2);
        break;
      }
      default: {
        console.log("Unsupported patch:", patch);
      }
    }
  });
  const toPut = Object.values(updatedObjects);
  console.log({ patches, toPut });
  store.mergeRemoteChanges(() => {
    if (toRemove.length)
      store.remove(toRemove);
    if (toPut.length)
      store.put(toPut);
  });
}
var isStorePatch = (patch) => {
  return patch.path[0] === "store" && patch.path.length > 1;
};
var pathToId = (path) => {
  return path[1];
};
var applyInsertToObject = (patch, object) => {
  const { path, values } = patch;
  let current = object;
  const insertionPoint = path[path.length - 1];
  const pathEnd = path[path.length - 2];
  const parts = path.slice(2, -2);
  for (const part of parts) {
    if (current[part] === void 0) {
      throw new Error("NO WAY");
    }
    current = current[part];
  }
  const clone = current[pathEnd].slice(0);
  clone.splice(insertionPoint, 0, ...values);
  current[pathEnd] = clone;
  return object;
};
var applyPutToObject = (patch, object) => {
  const { path, value } = patch;
  let current = object;
  if (path.length === 2) {
    return object;
  }
  const parts = path.slice(2, -2);
  const property = path[path.length - 1];
  const target = path[path.length - 2];
  if (path.length === 3) {
    return { ...object, [property]: value };
  }
  for (const part of parts) {
    current = current[part];
  }
  current[target] = { ...current[target], [property]: value };
  return object;
};
var applyUpdateToObject = (patch, object) => {
  const { path, value } = patch;
  let current = object;
  const parts = path.slice(2, -1);
  const pathEnd = path[path.length - 1];
  for (const part of parts) {
    if (current[part] === void 0) {
      throw new Error("NO WAY");
    }
    current = current[part];
  }
  current[pathEnd] = value;
  return object;
};
var applySpliceToObject = (patch, object) => {
  const { path, value } = patch;
  let current = object;
  const insertionPoint = path[path.length - 1];
  const pathEnd = path[path.length - 2];
  const parts = path.slice(2, -2);
  for (const part of parts) {
    if (current[part] === void 0) {
      throw new Error("NO WAY");
    }
    current = current[part];
  }
  if (insertionPoint !== 0) {
    throw new Error("Splices are not supported yet");
  }
  current[pathEnd] = value;
  return object;
};

// node_modules/.deno/automerge-tldraw@0.1.5/node_modules/automerge-tldraw/dist/TLStoreToAutomerge.js
var import_lodash = __toESM(require_lodash());
function applyTLStoreChangesToAutomerge(doc, changes) {
  Object.values(changes.added).forEach((record) => {
    doc.store[record.id] = record;
  });
  Object.values(changes.updated).forEach(([_2, record]) => {
    deepCompareAndUpdate(doc.store[record.id], record);
  });
  Object.values(changes.removed).forEach((record) => {
    delete doc.store[record.id];
  });
}
function deepCompareAndUpdate(objectA, objectB) {
  if (import_lodash.default.isArray(objectB)) {
    if (!import_lodash.default.isArray(objectA)) {
      objectA = objectB.slice();
    } else {
      for (let i = 0; i < objectB.length; i++) {
        if (i >= objectA.length) {
          objectA.push(objectB[i]);
        } else {
          if (import_lodash.default.isObject(objectB[i]) || import_lodash.default.isArray(objectB[i])) {
            deepCompareAndUpdate(objectA[i], objectB[i]);
          } else if (objectA[i] !== objectB[i]) {
            objectA[i] = objectB[i];
          }
        }
      }
      if (objectA.length > objectB.length) {
        objectA.splice(objectB.length);
      }
    }
  } else if (import_lodash.default.isObject(objectB)) {
    import_lodash.default.forIn(objectB, (value, key) => {
      if (objectA[key] === void 0) {
        objectA[key] = value;
      } else {
        if (import_lodash.default.isObject(value) || import_lodash.default.isArray(value)) {
          deepCompareAndUpdate(objectA[key], value);
        } else if (objectA[key] !== value) {
          objectA[key] = value;
        }
      }
    });
    import_lodash.default.forIn(objectA, (_2, key) => {
      if (objectB[key] === void 0) {
        delete objectA[key];
      }
    });
  }
}

// node_modules/.deno/automerge-tldraw@0.1.5/node_modules/automerge-tldraw/dist/useAutomergeStore.js
function useAutomergeStore({ handle, userId, shapeUtils = [] }) {
  const [store] = (0, import_react.useState)(() => {
    const store2 = createTLStore({
      shapeUtils: [...defaultShapeUtils, ...shapeUtils]
    });
    return store2;
  });
  const [storeWithStatus, setStoreWithStatus] = (0, import_react.useState)({
    status: "loading"
  });
  const [, updateLocalState] = Nn({
    handle,
    userId,
    initialState: {}
  });
  const [peerStates] = Vn({
    handle,
    localUserId: userId
  });
  (0, import_react.useEffect)(() => {
    const toRemove = [];
    const toPut = Object.values(peerStates).filter((record) => record && Object.keys(record).length !== 0);
    if (toRemove.length)
      store.remove(toRemove);
    if (toPut.length)
      store.put(toPut);
  }, [store, peerStates]);
  (0, import_react.useEffect)(() => {
    setUserPreferences({ id: userId });
    const userPreferences = computed("userPreferences", () => {
      const user = getUserPreferences();
      return {
        id: user.id,
        color: user.color ?? defaultUserPreferences.color,
        name: user.name ?? defaultUserPreferences.name
      };
    });
    const presenceId = InstancePresenceRecordType.createId(userId);
    const presenceDerivation = createPresenceStateDerivation(userPreferences, presenceId)(store);
    return react("when presence changes", () => {
      const presence = presenceDerivation.value;
      requestAnimationFrame(() => {
        updateLocalState(presence);
      });
    });
  }, [store, userId, updateLocalState]);
  (0, import_react.useEffect)(() => {
    const unsubs = [];
    let preventPatchApplications = false;
    function syncStoreChangesToAutomergeDoc({ changes }) {
      preventPatchApplications = true;
      handle.change((doc) => {
        applyTLStoreChangesToAutomerge(doc, changes);
      });
      preventPatchApplications = false;
    }
    unsubs.push(store.listen(syncStoreChangesToAutomergeDoc, {
      source: "user",
      scope: "document"
    }));
    const syncAutomergeDocChangesToStore = ({ patches }) => {
      if (preventPatchApplications)
        return;
      applyAutomergePatchesToTLStore(patches, store);
    };
    handle.on("change", syncAutomergeDocChangesToStore);
    unsubs.push(() => handle.off("change", syncAutomergeDocChangesToStore));
    handle.whenReady().then(() => {
      const doc = handle.docSync();
      if (!doc)
        throw new Error("Document not found");
      if (!doc.store)
        throw new Error("Document store not initialized");
      store.mergeRemoteChanges(() => {
        store.loadSnapshot({
          store: JSON.parse(JSON.stringify(doc.store)),
          schema: doc.schema
        });
      });
      setStoreWithStatus({
        store,
        status: "synced-remote",
        connectionStatus: "online"
      });
    });
    return () => {
      unsubs.forEach((fn) => fn());
      unsubs.length = 0;
    };
  }, [handle, store]);
  return storeWithStatus;
}

// node_modules/.deno/automerge-tldraw@0.1.5/node_modules/automerge-tldraw/dist/index.js
function init(doc) {
  Object.assign(doc, DEFAULT_STORE);
}
export {
  init,
  useAutomergeStore
};
//# sourceMappingURL=automerge-tldraw.js.map
