(function (root, factory) {
  const api = factory();
  if (typeof module === 'object' && module.exports) module.exports = api;
  else root.createPlanTodayPreview = api;
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
  'use strict';

  return function createPlanTodayPreview({
    planner,
    identity,
    getScroll = () => 0,
    setScroll = () => {},
    onOpen = () => {},
    onClose = () => {},
  }) {
    let current = null;

    function open(item, trigger = null) {
      if (!item || !identity?.(item) || !planner?.snapshot().open) return false;
      current = { item, trigger, scroll:Number(getScroll()) || 0 };
      onOpen(item, trigger);
      return true;
    }

    function setDependencies({ available, dependencies } = {}) {
      if (!current) return false;
      current.dependencies_available = available === true;
      current.dependencies = Array.isArray(dependencies) ? dependencies.filter(item => item?.state === 'open') : [];
      current.requires_override = !current.dependencies_available || current.dependencies.length > 0;
      return true;
    }

    function close({ add = false, override = false } = {}) {
      if (!current) return 'closed';
      if (add && current.requires_override && !override) {
        return current.dependencies_available ? 'blocked' : 'dependencies-unavailable';
      }
      const { item, trigger, scroll } = current;
      let result = 'returned';
      if (add) {
        const id = identity(item);
        result = planner.snapshot().ids.includes(id) ? 'already-added' : planner.toggle(item);
      }
      current = null;
      setScroll(scroll);
      onClose(item, trigger);
      return result;
    }

    function snapshot() {
      if (!current) return { open:false };
      const state = { open:true, item:current.item, trigger:current.trigger, scroll:current.scroll };
      if (Object.prototype.hasOwnProperty.call(current, 'dependencies_available')) {
        state.dependencies_available = current.dependencies_available;
        state.dependencies = current.dependencies;
        state.requires_override = current.requires_override;
      }
      return state;
    }

    return { open, close, setDependencies, snapshot };
  };
});
