function createDraftFilingSession({list}) {
  let orderedIds = [];
  let currentId = '';
  let reviewTrigger = null;

  function visibleIds() {
    const available = new Set(list().map(item => item.id));
    orderedIds = orderedIds.filter(id => available.has(id));
    for (const item of list()) {
      if (!orderedIds.includes(item.id)) orderedIds.push(item.id);
    }
    return orderedIds;
  }

  function state() {
    const ids = visibleIds();
    if (!ids.length) {
      currentId = '';
      return null;
    }
    if (!ids.includes(currentId)) currentId = ids[0];
    const index = ids.indexOf(currentId);
    return {id:currentId, position:index + 1, total:ids.length, remaining:ids.length - index - 1};
  }

  function start(id) {
    orderedIds = list().map(item => item.id);
    if (!orderedIds.includes(id)) throw new Error('This capture is no longer available.');
    currentId = id;
    return state();
  }

  function move(offset) {
    const ids = visibleIds();
    if (!ids.length) return state();
    const index = Math.max(0, ids.indexOf(currentId));
    currentId = ids[(index + offset + ids.length) % ids.length];
    return state();
  }

  function removeCurrentAndNext(removedId) {
    const previousIds = orderedIds.slice();
    const removedIndex = Math.max(0, previousIds.indexOf(removedId));
    orderedIds = previousIds.filter(id => id !== removedId);
    const ids = visibleIds();
    if (!ids.length) return state();
    currentId = ids[Math.min(removedIndex, ids.length - 1)];
    return state();
  }

  const session = {start, current:state, next:()=>move(1), previous:()=>move(-1), removeCurrentAndNext};
  session.attach = (qs, dependencies) => {
    const openCapture = async (captureId, trigger = null) => {
      const resumed = await dependencies.captures.resume(captureId, dependencies.getLogin());
      const issueCapture = dependencies.capture?.() || dependencies.issueCapture;
      issueCapture.saveDraft(resumed);
      dependencies.setResumedId(captureId);
      await dependencies.openSheet(false);
      const evidence = resumed.attachments || resumed.attachment;
      dependencies.attachment[evidence ? 'restore' : 'clear'](evidence);
      dependencies.setFilingMode(true);
      session.render();
      if (trigger) {
        await dependencies.review(resumed);
        reviewTrigger = trigger;
        const submitter = resumed.completionIntent === 'create-and-start' ?
          qs('#create-and-start-issue') : qs('#submit-new-issue');
        const disabled = submitter.disabled;
        submitter.disabled = false;
        qs('#create-issue-form').requestSubmit(submitter);
        submitter.disabled = disabled;
      }
    };
    return Object.assign(session, {
    nextCapture() { const state = session.current(); return state ? openCapture(state.id) : null; },
    reviewCapture(captureId, trigger) {
      session.start(captureId);
      return openCapture(captureId, trigger);
    },
    open(captureId, trigger = null) {
      session.start(captureId);
      return openCapture(captureId, trigger);
    },
    takeTrigger() {
      const trigger = reviewTrigger;
      reviewTrigger = null;
      return trigger;
    },
    render() {
      const state = session.current();
      qs('#draft-filing-session').hidden = !state;
      if (!state) return;
      qs('#draft-filing-progress').textContent = `Draft ${state.position} of ${state.total}`;
      qs('#draft-filing-remaining').textContent = state.remaining ? `${state.remaining} remaining` : 'Last Draft';
      qs('#previous-draft').disabled = qs('#skip-draft').disabled = state.total < 2;
      qs('#submit-new-issue').textContent = state.remaining ? 'File & next' : 'File final Draft';
    },
    bind() {
      [['#previous-draft','previous'],['#skip-draft','next']].forEach(([selector, method]) =>
        qs(selector).addEventListener('click', async () => {
          const state = session[method]();
          if (state) await openCapture(state.id);
        })
      );
    },
    async advance(completedId) {
      const state = session.removeCurrentAndNext(completedId);
      if (state) { await openCapture(state.id); return true; }
      qs('#draft-filing-session').hidden = true;
      qs('#submit-new-issue').textContent = 'Create & assign to me';
      return false;
    },
  });
  };
  return session;
}

if (typeof module !== 'undefined' && module.exports) module.exports = createDraftFilingSession;
