'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-d685a739.js');
const index$1 = require('./index-4f00f593.js');
const index$2 = require('./index-889ce6c6.js');
const navigation_service = require('./navigation.service-23bf9ce2.js');
const manageBenefits_service = require('./manage-benefits.service-f45b4602.js');
const scheduleArray = require('./scheduleArray-0ba3d6f8.js');
const activeRouter = require('./active-router-3742ead6.js');
require('./Option-98dab0b8.js');
require('./iframe-a50670af.js');
require('./datorama-akita-bb801820.js');
require('./delay-e91dba76.js');
require('./filter-c38164e6.js');
require('./api-client-00edc9b6.js');
require('./promise-f77cab90.js');
require('./benefits.api-a4bd9804.js');

const EditBenefitPage = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.benefitId = index$1.none;
    this.showDeleteConfirmDialog = false;
    this.showCancelConfirmDialog = false;
    this.isLoading = false;
    this.isValidationDisplayed = false;
    this.stateSubscription = new scheduleArray.Subscription();
  }
  async componentWillLoad() {
    await this.initialiseAsync();
  }
  disconnectedCallback() {
    this.stateSubscription.unsubscribe();
  }
  render() {
    return (index.h(index.Host, { class: "w-100" }, index.h("ap-ben-ui-container", { class: "w-100 d-none" }, index.h("div", { class: "row my-5" }, index.h("div", { class: "uiid-new-edit-delete-benefit-page col-12" }, index.h("h3", null, this.editMode === 'add' ? 'New Benefit' : 'Edit Benefit'), index.h("ap-ben-edit-benefit-form", { class: "d-block mt-4 mb-3", disabled: this.isLoading, isValidationDisplayed: this.isValidationDisplayed }), this.renderActionBar()))), this.showDeleteConfirmDialog && this.renderDeleteConfirmDialog(), this.showCancelConfirmDialog && this.renderCancelConfirmDialog()));
  }
  renderActionBar() {
    return (index.h("div", { class: "row" }, index.h("div", { class: "col-12 d-flex" }, index.h("button", { hidden: this.editMode === 'add', class: "uiid-delete-benefit-item btn btn-outline-danger", onClick: (_) => {
        this.showDeleteConfirmDialog = true;
      } }, "Delete"), index.h("div", { class: "ml-auto" }, index.h("button", { class: "btn btn-light mr-3", onClick: (_) => this.onCancelClicked() }, "Cancel"), index.h("button", { class: "uiid-publish-benefit btn btn-primary", onClick: (_) => this.publishBenefit(), disabled: this.isLoading }, "Publish")))));
  }
  renderDeleteConfirmDialog() {
    return (index.h("ap-ben-modal-section", { show: this.showDeleteConfirmDialog, showHeader: true, modalTitle: "Delete benefit", onModalClosed: (_) => {
        this.showDeleteConfirmDialog = false;
      } }, index.h("ap-ben-confirm-dialog", { acceptText: "Delete", declineText: "Cancel", dialogStyle: "danger", onAccepted: async (_) => {
        await this.deleteBenefitAsync();
        this.showDeleteConfirmDialog = false;
      }, onDeclined: (_) => {
        this.showDeleteConfirmDialog = false;
      } }, index.h("p", null, index.h("strong", null, "\"", index$2.getOrError(this.selectedBenefit).title.value, "\""), " will be permanently deleted from your benefits. Are you sure you want to delete it?"))));
  }
  renderCancelConfirmDialog() {
    return (index.h("ap-ben-modal-section", { show: this.showCancelConfirmDialog, showHeader: true, modalTitle: "Unsaved changes", onModalClosed: (_) => {
        this.showCancelConfirmDialog = false;
      } }, index.h("ap-ben-confirm-dialog", { acceptText: "Publish", declineText: "Discard", dialogStyle: "warning", onAccepted: async (_) => {
        this.showCancelConfirmDialog = false;
        await this.publishBenefit();
      }, onDeclined: (_) => {
        this.showCancelConfirmDialog = false;
        this.navigateToManageBenefits();
      } }, this.editMode === 'add' ? ('Do you want to save your new benefit?') : (index.h("p", null, index.h("strong", null, "\"", index$2.getOrError(this.selectedBenefit).title.value, "\""), " has been modified. Do you want to publish your changes?")))));
  }
  async initialiseAsync() {
    this.stateSubscription.add(manageBenefits_service.editBenefitQuery.isLoading$.subscribe((isLoading) => (this.isLoading = isLoading)));
    this.stateSubscription.add(manageBenefits_service.editBenefitQuery.selectedBenefit$.subscribe((selectedBenefit) => (this.selectedBenefit = selectedBenefit)));
    this.stateSubscription.add(manageBenefits_service.editBenefitQuery.draftBenefit$.subscribe((draftBenefit) => (this.draftBenefit = draftBenefit)));
    if (index$1.isSome(this.benefitId)) {
      this.editMode = 'edit';
      manageBenefits_service.editBenefitService.loadExistingBenefitForEditingAsync(this.benefitId.value);
    }
    else {
      manageBenefits_service.editBenefitService.createDraftBenefit();
      this.editMode = 'add';
    }
  }
  navigateToManageBenefits() {
    manageBenefits_service.editBenefitService.clearDraftBenefit();
    navigation_service.navigationService.navigateInternally(navigation_service.ManagePageRouteName);
  }
  async publishBenefit() {
    if (!index$2.getOrError(this.draftBenefit).isValid) {
      this.isValidationDisplayed = true;
      return;
    }
    if (index$2.getOrError(this.draftBenefit).isDirty) {
      await manageBenefits_service.editBenefitService.publishDraftBenefitAsync();
    }
    this.navigateToManageBenefits();
  }
  async onCancelClicked() {
    if (!index$2.getOrError(this.draftBenefit).isDirty) {
      this.navigateToManageBenefits();
      return;
    }
    this.showCancelConfirmDialog = true;
  }
  async deleteBenefitAsync() {
    await manageBenefits_service.editBenefitService.deleteSelectedBenefitAsync();
    this.navigateToManageBenefits();
  }
};

const manageBenefitsPageCss = "manage-page .benefits-zero-state{height:32rem}";

const ManageBenefitsPage = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.showDisabledBenefits = false;
    this.storeSubscription = new scheduleArray.Subscription();
  }
  componentWillLoad() {
    manageBenefits_service.manageBenefitsService.loadPageStateAsync();
    this.storeSubscription.add(manageBenefits_service.manageBenefitsQuery.manageBenefitsPageState$.subscribe((pageState) => (this.pageState = pageState)));
    this.storeSubscription.add(manageBenefits_service.manageBenefitsQuery.isLoading$.subscribe((isLoading) => (this.isLoading = isLoading)));
  }
  disconnectedCallback() {
    this.storeSubscription.unsubscribe();
  }
  render() {
    if (this.isLoading) {
      return (index.h(index.Host, { class: "w-100 text-center mt-5" }, index.h("ap-ben-ui-container", { class: "w-100 d-none" }, index.h("fl-loading-indicator", null))));
    }
    return (index.h(index.Host, { class: "w-100" }, index.h("ap-ben-ui-container", { class: "w-100 d-none" }, this.managedBenefitHeader(), index.h("div", { class: "uiid-manage-benefit-body row bg-white border-left border-right border-bottom mb-5 mx-0 rounded no-gutters" }, index.h("div", { class: "col-12" }, this.pageState.enabledBenefits.length === 0 ? (index.h("ap-ben-empty-benefits", { onNewBenefitButtonClicked: () => this.addBenefit() })) : (this.ActiveBenefitsSection()), this.ToggleInactiveBenefitsRow(), this.showDisabledBenefits && this.InactiveBenefitsSection())))));
  }
  ActiveBenefitsSection() {
    return [
      index.h("ap-ben-manage-benefits-header-row", { class: "d-none d-md-block" }),
      this.pageState.enabledBenefits.map((b) => (index.h("ap-ben-managed-benefit-item", { benefit: b, onEditBenefitButtonClicked: (event) => this.editBenefit(event.detail) })))
    ];
  }
  ToggleInactiveBenefitsRow() {
    return (index.h("div", { class: "col-12 py-3 border-top d-flex justify-content-center" }, index.h("button", { class: "uiid-show-inactive-benefit-item btn btn-link", onClick: (_) => this.onToggleInactiveBenefits() }, index.h("h6", { class: "m-0" }, this.showDisabledBenefits
      ? `Hide inactive benefits (${this.pageState.disabledBenefits.length})`
      : `Show inactive (${this.pageState.disabledBenefits.length})`))));
  }
  InactiveBenefitsSection() {
    if (this.pageState.disabledBenefits.length === 0) {
      return [
        index.h("div", { class: "row border-top py-3 px-3 d-flex align-items-center no-gutters" }, index.h("div", { class: "col-12 my-1 d-flex justify-content-center" }, index.h("span", { class: "text-muted" }, "No inactive benefits.")))
      ];
    }
    return this.pageState.disabledBenefits.map((b) => (index.h("ap-ben-managed-benefit-item", { benefit: b, onEditBenefitButtonClicked: (event) => this.editBenefit(event.detail) })));
  }
  managedBenefitHeader() {
    return (index.h("div", { class: "uiid-manage-benefit-header row mb-3 mt-5" }, index.h("div", { class: "col-12 col-sm-6" }, index.h("h3", null, "Manage Benefits")), index.h("div", { class: "col-12 col-sm-6 d-flex justify-content-end align-items-center" }, index.h("fl-button", { class: "uiid-new-benefit-button", onClick: (_) => this.addBenefit() }, index.h("ap-ben-icon", { class: "mr-2", iconPrefix: "far", iconId: "plus" }), "New benefit"))));
  }
  onToggleInactiveBenefits() {
    this.showDisabledBenefits = !this.showDisabledBenefits;
  }
  addBenefit() {
    navigation_service.navigationService.navigateInternally(navigation_service.AddBenefitPageRouteName);
  }
  editBenefit(benefit) {
    navigation_service.navigationService.navigateInternally(`${navigation_service.EditBenefitPageRouteName}/${benefit.id}`);
  }
};
ManageBenefitsPage.style = manageBenefitsPageCss;

const getConfirmation = (win, message, callback) => (callback(win.confirm(message)));
const isModifiedEvent = (ev) => (ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey);
/**
 * Returns true if the HTML5 history API is supported. Taken from Modernizr.
 *
 * https://github.com/Modernizr/Modernizr/blob/master/LICENSE
 * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
 * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586
 */
const supportsHistory = (win) => {
    const ua = win.navigator.userAgent;
    if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
        ua.indexOf('Mobile Safari') !== -1 &&
        ua.indexOf('Chrome') === -1 &&
        ua.indexOf('Windows Phone') === -1) {
        return false;
    }
    return win.history && 'pushState' in win.history;
};
/**
 * Returns true if browser fires popstate on hash change.
 * IE10 and IE11 do not.
 */
const supportsPopStateOnHashChange = (nav) => (nav.userAgent.indexOf('Trident') === -1);
/**
 * Returns false if using go(n) with hash history causes a full page reload.
 */
const supportsGoWithoutReloadUsingHash = (nav) => (nav.userAgent.indexOf('Firefox') === -1);
const isExtraneousPopstateEvent = (nav, event) => (event.state === undefined &&
    nav.userAgent.indexOf('CriOS') === -1);
const storageAvailable = (win, type) => {
    const storage = win[type];
    const x = '__storage_test__';
    try {
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch (e) {
        return e instanceof DOMException && (
        // everything except Firefox
        e.code === 22 ||
            // Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            // Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already stored
            storage.length !== 0;
    }
};

const getUrl = (url, root) => {
  // Don't allow double slashes
  if (url.charAt(0) == '/' && root.charAt(root.length - 1) == '/') {
    return root.slice(0, root.length - 1) + url;
  }
  return root + url;
};
const RouteLink = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.unsubscribe = () => { return; };
    this.activeClass = 'link-active';
    this.exact = false;
    this.strict = true;
    /**
      *  Custom tag to use instead of an anchor
      */
    this.custom = 'a';
    this.match = null;
  }
  componentWillLoad() {
    this.computeMatch();
  }
  // Identify if the current route is a match.
  computeMatch() {
    if (this.location) {
      this.match = manageBenefits_service.matchPath(this.location.pathname, {
        path: this.urlMatch || this.url,
        exact: this.exact,
        strict: this.strict
      });
    }
  }
  handleClick(e) {
    if (isModifiedEvent(e) || !this.history || !this.url || !this.root) {
      return;
    }
    e.preventDefault();
    return this.history.push(getUrl(this.url, this.root));
  }
  // Get the URL for this route link without the root from the router
  render() {
    let anchorAttributes = {
      class: {
        [this.activeClass]: this.match !== null,
      },
      onClick: this.handleClick.bind(this)
    };
    if (this.anchorClass) {
      anchorAttributes.class[this.anchorClass] = true;
    }
    if (this.custom === 'a') {
      anchorAttributes = Object.assign({}, anchorAttributes, { href: this.url, title: this.anchorTitle, role: this.anchorRole, tabindex: this.anchorTabIndex, 'aria-haspopup': this.ariaHaspopup, id: this.anchorId, 'aria-posinset': this.ariaPosinset, 'aria-setsize': this.ariaSetsize, 'aria-label': this.ariaLabel });
    }
    return (index.h(this.custom, Object.assign({}, anchorAttributes), index.h("slot", null)));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "location": ["computeMatch"]
  }; }
};
activeRouter.ActiveRouter.injectProps(RouteLink, [
  'history',
  'location',
  'root'
]);

const getUniqueId = () => {
  return ((Math.random() * 10e16).toString().match(/.{4}/g) || []).join('-');
};
const getMatch = (pathname, url, exact) => {
  return manageBenefits_service.matchPath(pathname, {
    path: url,
    exact: exact,
    strict: true
  });
};
const isHTMLStencilRouteElement = (elm) => {
  return elm.tagName === 'STENCIL-ROUTE';
};
const RouteSwitch = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.group = getUniqueId();
    this.subscribers = [];
    this.queue = index.getContext(this, "queue");
  }
  componentWillLoad() {
    if (this.location != null) {
      this.regenerateSubscribers(this.location);
    }
  }
  async regenerateSubscribers(newLocation) {
    if (newLocation == null) {
      return;
    }
    let newActiveIndex = -1;
    this.subscribers = Array.prototype.slice.call(this.el.children)
      .filter(isHTMLStencilRouteElement)
      .map((childElement, index) => {
      const match = getMatch(newLocation.pathname, childElement.url, childElement.exact);
      if (match && newActiveIndex === -1) {
        newActiveIndex = index;
      }
      return {
        el: childElement,
        match: match
      };
    });
    if (newActiveIndex === -1) {
      return;
    }
    // Check if this actually changes which child is active
    // then just pass the new match down if the active route isn't changing.
    if (this.activeIndex === newActiveIndex) {
      this.subscribers[newActiveIndex].el.match = this.subscribers[newActiveIndex].match;
      return;
    }
    this.activeIndex = newActiveIndex;
    // Set all props on the new active route then wait until it says that it
    // is completed
    const activeChild = this.subscribers[this.activeIndex];
    if (this.scrollTopOffset) {
      activeChild.el.scrollTopOffset = this.scrollTopOffset;
    }
    activeChild.el.group = this.group;
    activeChild.el.match = activeChild.match;
    activeChild.el.componentUpdated = (routeViewUpdatedOptions) => {
      // After the new active route has completed then update visibility of routes
      this.queue.write(() => {
        this.subscribers.forEach((child, index) => {
          child.el.componentUpdated = undefined;
          if (index === this.activeIndex) {
            return child.el.style.display = '';
          }
          if (this.scrollTopOffset) {
            child.el.scrollTopOffset = this.scrollTopOffset;
          }
          child.el.group = this.group;
          child.el.match = null;
          child.el.style.display = 'none';
        });
      });
      if (this.routeViewsUpdated) {
        this.routeViewsUpdated(Object.assign({ scrollTopOffset: this.scrollTopOffset }, routeViewUpdatedOptions));
      }
    };
  }
  render() {
    return (index.h("slot", null));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "location": ["regenerateSubscribers"]
  }; }
};
activeRouter.ActiveRouter.injectProps(RouteSwitch, [
  'location',
  'routeViewsUpdated'
]);

const warning = (value, ...args) => {
    if (!value) {
        console.warn(...args);
    }
};

// Adapted from the https://github.com/ReactTraining/history and converted to TypeScript
const createTransitionManager = () => {
    let prompt;
    let listeners = [];
    const setPrompt = (nextPrompt) => {
        warning(prompt == null, 'A history supports only one prompt at a time');
        prompt = nextPrompt;
        return () => {
            if (prompt === nextPrompt) {
                prompt = null;
            }
        };
    };
    const confirmTransitionTo = (location, action, getUserConfirmation, callback) => {
        // TODO: If another transition starts while we're still confirming
        // the previous one, we may end up in a weird state. Figure out the
        // best way to handle this.
        if (prompt != null) {
            const result = typeof prompt === 'function' ? prompt(location, action) : prompt;
            if (typeof result === 'string') {
                if (typeof getUserConfirmation === 'function') {
                    getUserConfirmation(result, callback);
                }
                else {
                    warning(false, 'A history needs a getUserConfirmation function in order to use a prompt message');
                    callback(true);
                }
            }
            else {
                // Return false from a transition hook to cancel the transition.
                callback(result !== false);
            }
        }
        else {
            callback(true);
        }
    };
    const appendListener = (fn) => {
        let isActive = true;
        const listener = (...args) => {
            if (isActive) {
                fn(...args);
            }
        };
        listeners.push(listener);
        return () => {
            isActive = false;
            listeners = listeners.filter(item => item !== listener);
        };
    };
    const notifyListeners = (...args) => {
        listeners.forEach(listener => listener(...args));
    };
    return {
        setPrompt,
        confirmTransitionTo,
        appendListener,
        notifyListeners
    };
};

const createScrollHistory = (win, applicationScrollKey = 'scrollPositions') => {
    let scrollPositions = new Map();
    const set = (key, value) => {
        scrollPositions.set(key, value);
        if (storageAvailable(win, 'sessionStorage')) {
            const arrayData = [];
            scrollPositions.forEach((value, key) => {
                arrayData.push([key, value]);
            });
            win.sessionStorage.setItem('scrollPositions', JSON.stringify(arrayData));
        }
    };
    const get = (key) => {
        return scrollPositions.get(key);
    };
    const has = (key) => {
        return scrollPositions.has(key);
    };
    const capture = (key) => {
        set(key, [win.scrollX, win.scrollY]);
    };
    if (storageAvailable(win, 'sessionStorage')) {
        const scrollData = win.sessionStorage.getItem(applicationScrollKey);
        scrollPositions = scrollData ?
            new Map(JSON.parse(scrollData)) :
            scrollPositions;
    }
    if ('scrollRestoration' in win.history) {
        history.scrollRestoration = 'manual';
    }
    return {
        set,
        get,
        has,
        capture
    };
};

// Adapted from the https://github.com/ReactTraining/history and converted to TypeScript
const PopStateEvent = 'popstate';
const HashChangeEvent$1 = 'hashchange';
/**
 * Creates a history object that uses the HTML5 history API including
 * pushState, replaceState, and the popstate event.
 */
const createBrowserHistory = (win, props = {}) => {
    let forceNextPop = false;
    const globalHistory = win.history;
    const globalLocation = win.location;
    const globalNavigator = win.navigator;
    const canUseHistory = supportsHistory(win);
    const needsHashChangeListener = !supportsPopStateOnHashChange(globalNavigator);
    const scrollHistory = createScrollHistory(win);
    const forceRefresh = (props.forceRefresh != null) ? props.forceRefresh : false;
    const getUserConfirmation = (props.getUserConfirmation != null) ? props.getUserConfirmation : getConfirmation;
    const keyLength = (props.keyLength != null) ? props.keyLength : 6;
    const basename = props.basename ? manageBenefits_service.stripTrailingSlash(manageBenefits_service.addLeadingSlash(props.basename)) : '';
    const getHistoryState = () => {
        try {
            return win.history.state || {};
        }
        catch (e) {
            // IE 11 sometimes throws when accessing window.history.state
            // See https://github.com/ReactTraining/history/pull/289
            return {};
        }
    };
    const getDOMLocation = (historyState) => {
        historyState = historyState || {};
        const { key, state } = historyState;
        const { pathname, search, hash } = globalLocation;
        let path = pathname + search + hash;
        warning((!basename || manageBenefits_service.hasBasename(path, basename)), 'You are attempting to use a basename on a page whose URL path does not begin ' +
            'with the basename. Expected path "' + path + '" to begin with "' + basename + '".');
        if (basename) {
            path = manageBenefits_service.stripBasename(path, basename);
        }
        return manageBenefits_service.createLocation(path, state, key || manageBenefits_service.createKey(keyLength));
    };
    const transitionManager = createTransitionManager();
    const setState = (nextState) => {
        // Capture location for the view before changing history.
        scrollHistory.capture(history.location.key);
        Object.assign(history, nextState);
        // Set scroll position based on its previous storage value
        history.location.scrollPosition = scrollHistory.get(history.location.key);
        history.length = globalHistory.length;
        transitionManager.notifyListeners(history.location, history.action);
    };
    const handlePopState = (event) => {
        // Ignore extraneous popstate events in WebKit.
        if (!isExtraneousPopstateEvent(globalNavigator, event)) {
            handlePop(getDOMLocation(event.state));
        }
    };
    const handleHashChange = () => {
        handlePop(getDOMLocation(getHistoryState()));
    };
    const handlePop = (location) => {
        if (forceNextPop) {
            forceNextPop = false;
            setState();
        }
        else {
            const action = 'POP';
            transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
                if (ok) {
                    setState({ action, location });
                }
                else {
                    revertPop(location);
                }
            });
        }
    };
    const revertPop = (fromLocation) => {
        const toLocation = history.location;
        // TODO: We could probably make this more reliable by
        // keeping a list of keys we've seen in sessionStorage.
        // Instead, we just default to 0 for keys we don't know.
        let toIndex = allKeys.indexOf(toLocation.key);
        let fromIndex = allKeys.indexOf(fromLocation.key);
        if (toIndex === -1) {
            toIndex = 0;
        }
        if (fromIndex === -1) {
            fromIndex = 0;
        }
        const delta = toIndex - fromIndex;
        if (delta) {
            forceNextPop = true;
            go(delta);
        }
    };
    const initialLocation = getDOMLocation(getHistoryState());
    let allKeys = [initialLocation.key];
    let listenerCount = 0;
    let isBlocked = false;
    // Public interface
    const createHref = (location) => {
        return basename + manageBenefits_service.createPath(location);
    };
    const push = (path, state) => {
        warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' +
            'argument is a location-like object that already has state; it is ignored');
        const action = 'PUSH';
        const location = manageBenefits_service.createLocation(path, state, manageBenefits_service.createKey(keyLength), history.location);
        transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
            if (!ok) {
                return;
            }
            const href = createHref(location);
            const { key, state } = location;
            if (canUseHistory) {
                globalHistory.pushState({ key, state }, '', href);
                if (forceRefresh) {
                    globalLocation.href = href;
                }
                else {
                    const prevIndex = allKeys.indexOf(history.location.key);
                    const nextKeys = allKeys.slice(0, prevIndex === -1 ? 0 : prevIndex + 1);
                    nextKeys.push(location.key);
                    allKeys = nextKeys;
                    setState({ action, location });
                }
            }
            else {
                warning(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history');
                globalLocation.href = href;
            }
        });
    };
    const replace = (path, state) => {
        warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' +
            'argument is a location-like object that already has state; it is ignored');
        const action = 'REPLACE';
        const location = manageBenefits_service.createLocation(path, state, manageBenefits_service.createKey(keyLength), history.location);
        transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
            if (!ok) {
                return;
            }
            const href = createHref(location);
            const { key, state } = location;
            if (canUseHistory) {
                globalHistory.replaceState({ key, state }, '', href);
                if (forceRefresh) {
                    globalLocation.replace(href);
                }
                else {
                    const prevIndex = allKeys.indexOf(history.location.key);
                    if (prevIndex !== -1) {
                        allKeys[prevIndex] = location.key;
                    }
                    setState({ action, location });
                }
            }
            else {
                warning(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history');
                globalLocation.replace(href);
            }
        });
    };
    const go = (n) => {
        globalHistory.go(n);
    };
    const goBack = () => go(-1);
    const goForward = () => go(1);
    const checkDOMListeners = (delta) => {
        listenerCount += delta;
        if (listenerCount === 1) {
            win.addEventListener(PopStateEvent, handlePopState);
            if (needsHashChangeListener) {
                win.addEventListener(HashChangeEvent$1, handleHashChange);
            }
        }
        else if (listenerCount === 0) {
            win.removeEventListener(PopStateEvent, handlePopState);
            if (needsHashChangeListener) {
                win.removeEventListener(HashChangeEvent$1, handleHashChange);
            }
        }
    };
    const block = (prompt = '') => {
        const unblock = transitionManager.setPrompt(prompt);
        if (!isBlocked) {
            checkDOMListeners(1);
            isBlocked = true;
        }
        return () => {
            if (isBlocked) {
                isBlocked = false;
                checkDOMListeners(-1);
            }
            return unblock();
        };
    };
    const listen = (listener) => {
        const unlisten = transitionManager.appendListener(listener);
        checkDOMListeners(1);
        return () => {
            checkDOMListeners(-1);
            unlisten();
        };
    };
    const history = {
        length: globalHistory.length,
        action: 'POP',
        location: initialLocation,
        createHref,
        push,
        replace,
        go,
        goBack,
        goForward,
        block,
        listen,
        win: win
    };
    return history;
};

// Adapted from the https://github.com/ReactTraining/history and converted to TypeScript
const HashChangeEvent = 'hashchange';
const HashPathCoders = {
    hashbang: {
        encodePath: (path) => path.charAt(0) === '!' ? path : '!/' + manageBenefits_service.stripLeadingSlash(path),
        decodePath: (path) => path.charAt(0) === '!' ? path.substr(1) : path
    },
    noslash: {
        encodePath: manageBenefits_service.stripLeadingSlash,
        decodePath: manageBenefits_service.addLeadingSlash
    },
    slash: {
        encodePath: manageBenefits_service.addLeadingSlash,
        decodePath: manageBenefits_service.addLeadingSlash
    }
};
const createHashHistory = (win, props = {}) => {
    let forceNextPop = false;
    let ignorePath = null;
    let listenerCount = 0;
    let isBlocked = false;
    const globalLocation = win.location;
    const globalHistory = win.history;
    const canGoWithoutReload = supportsGoWithoutReloadUsingHash(win.navigator);
    const keyLength = (props.keyLength != null) ? props.keyLength : 6;
    const { getUserConfirmation = getConfirmation, hashType = 'slash' } = props;
    const basename = props.basename ? manageBenefits_service.stripTrailingSlash(manageBenefits_service.addLeadingSlash(props.basename)) : '';
    const { encodePath, decodePath } = HashPathCoders[hashType];
    const getHashPath = () => {
        // We can't use window.location.hash here because it's not
        // consistent across browsers - Firefox will pre-decode it!
        const href = globalLocation.href;
        const hashIndex = href.indexOf('#');
        return hashIndex === -1 ? '' : href.substring(hashIndex + 1);
    };
    const pushHashPath = (path) => (globalLocation.hash = path);
    const replaceHashPath = (path) => {
        const hashIndex = globalLocation.href.indexOf('#');
        globalLocation.replace(globalLocation.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path);
    };
    const getDOMLocation = () => {
        let path = decodePath(getHashPath());
        warning((!basename || manageBenefits_service.hasBasename(path, basename)), 'You are attempting to use a basename on a page whose URL path does not begin ' +
            'with the basename. Expected path "' + path + '" to begin with "' + basename + '".');
        if (basename) {
            path = manageBenefits_service.stripBasename(path, basename);
        }
        return manageBenefits_service.createLocation(path, undefined, manageBenefits_service.createKey(keyLength));
    };
    const transitionManager = createTransitionManager();
    const setState = (nextState) => {
        Object.assign(history, nextState);
        history.length = globalHistory.length;
        transitionManager.notifyListeners(history.location, history.action);
    };
    const handleHashChange = () => {
        const path = getHashPath();
        const encodedPath = encodePath(path);
        if (path !== encodedPath) {
            // Ensure we always have a properly-encoded hash.
            replaceHashPath(encodedPath);
        }
        else {
            const location = getDOMLocation();
            const prevLocation = history.location;
            if (!forceNextPop && manageBenefits_service.locationsAreEqual(prevLocation, location)) {
                return; // A hashchange doesn't always == location change.
            }
            if (ignorePath === manageBenefits_service.createPath(location)) {
                return; // Ignore this change; we already setState in push/replace.
            }
            ignorePath = null;
            handlePop(location);
        }
    };
    const handlePop = (location) => {
        if (forceNextPop) {
            forceNextPop = false;
            setState();
        }
        else {
            const action = 'POP';
            transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
                if (ok) {
                    setState({ action, location });
                }
                else {
                    revertPop(location);
                }
            });
        }
    };
    const revertPop = (fromLocation) => {
        const toLocation = history.location;
        // TODO: We could probably make this more reliable by
        // keeping a list of paths we've seen in sessionStorage.
        // Instead, we just default to 0 for paths we don't know.
        let toIndex = allPaths.lastIndexOf(manageBenefits_service.createPath(toLocation));
        let fromIndex = allPaths.lastIndexOf(manageBenefits_service.createPath(fromLocation));
        if (toIndex === -1) {
            toIndex = 0;
        }
        if (fromIndex === -1) {
            fromIndex = 0;
        }
        const delta = toIndex - fromIndex;
        if (delta) {
            forceNextPop = true;
            go(delta);
        }
    };
    // Ensure the hash is encoded properly before doing anything else.
    const path = getHashPath();
    const encodedPath = encodePath(path);
    if (path !== encodedPath) {
        replaceHashPath(encodedPath);
    }
    const initialLocation = getDOMLocation();
    let allPaths = [manageBenefits_service.createPath(initialLocation)];
    // Public interface
    const createHref = (location) => ('#' + encodePath(basename + manageBenefits_service.createPath(location)));
    const push = (path, state) => {
        warning(state === undefined, 'Hash history cannot push state; it is ignored');
        const action = 'PUSH';
        const location = manageBenefits_service.createLocation(path, undefined, manageBenefits_service.createKey(keyLength), history.location);
        transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
            if (!ok) {
                return;
            }
            const path = manageBenefits_service.createPath(location);
            const encodedPath = encodePath(basename + path);
            const hashChanged = getHashPath() !== encodedPath;
            if (hashChanged) {
                // We cannot tell if a hashchange was caused by a PUSH, so we'd
                // rather setState here and ignore the hashchange. The caveat here
                // is that other hash histories in the page will consider it a POP.
                ignorePath = path;
                pushHashPath(encodedPath);
                const prevIndex = allPaths.lastIndexOf(manageBenefits_service.createPath(history.location));
                const nextPaths = allPaths.slice(0, prevIndex === -1 ? 0 : prevIndex + 1);
                nextPaths.push(path);
                allPaths = nextPaths;
                setState({ action, location });
            }
            else {
                warning(false, 'Hash history cannot PUSH the same path; a new entry will not be added to the history stack');
                setState();
            }
        });
    };
    const replace = (path, state) => {
        warning(state === undefined, 'Hash history cannot replace state; it is ignored');
        const action = 'REPLACE';
        const location = manageBenefits_service.createLocation(path, undefined, manageBenefits_service.createKey(keyLength), history.location);
        transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
            if (!ok) {
                return;
            }
            const path = manageBenefits_service.createPath(location);
            const encodedPath = encodePath(basename + path);
            const hashChanged = getHashPath() !== encodedPath;
            if (hashChanged) {
                // We cannot tell if a hashchange was caused by a REPLACE, so we'd
                // rather setState here and ignore the hashchange. The caveat here
                // is that other hash histories in the page will consider it a POP.
                ignorePath = path;
                replaceHashPath(encodedPath);
            }
            const prevIndex = allPaths.indexOf(manageBenefits_service.createPath(history.location));
            if (prevIndex !== -1) {
                allPaths[prevIndex] = path;
            }
            setState({ action, location });
        });
    };
    const go = (n) => {
        warning(canGoWithoutReload, 'Hash history go(n) causes a full page reload in this browser');
        globalHistory.go(n);
    };
    const goBack = () => go(-1);
    const goForward = () => go(1);
    const checkDOMListeners = (win, delta) => {
        listenerCount += delta;
        if (listenerCount === 1) {
            win.addEventListener(HashChangeEvent, handleHashChange);
        }
        else if (listenerCount === 0) {
            win.removeEventListener(HashChangeEvent, handleHashChange);
        }
    };
    const block = (prompt = '') => {
        const unblock = transitionManager.setPrompt(prompt);
        if (!isBlocked) {
            checkDOMListeners(win, 1);
            isBlocked = true;
        }
        return () => {
            if (isBlocked) {
                isBlocked = false;
                checkDOMListeners(win, -1);
            }
            return unblock();
        };
    };
    const listen = (listener) => {
        const unlisten = transitionManager.appendListener(listener);
        checkDOMListeners(win, 1);
        return () => {
            checkDOMListeners(win, -1);
            unlisten();
        };
    };
    const history = {
        length: globalHistory.length,
        action: 'POP',
        location: initialLocation,
        createHref,
        push,
        replace,
        go,
        goBack,
        goForward,
        block,
        listen,
        win: win
    };
    return history;
};

const getLocation = (location, root) => {
  // Remove the root URL if found at beginning of string
  const pathname = location.pathname.indexOf(root) == 0 ?
    '/' + location.pathname.slice(root.length) :
    location.pathname;
  return Object.assign({}, location, { pathname });
};
const HISTORIES = {
  'browser': createBrowserHistory,
  'hash': createHashHistory
};
const Router = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.root = '/';
    this.historyType = 'browser';
    // A suffix to append to the page title whenever
    // it's updated through RouteTitle
    this.titleSuffix = '';
    this.routeViewsUpdated = (options = {}) => {
      if (this.history && options.scrollToId && this.historyType === 'browser') {
        const elm = this.history.win.document.getElementById(options.scrollToId);
        if (elm) {
          return elm.scrollIntoView();
        }
      }
      this.scrollTo(options.scrollTopOffset || this.scrollTopOffset);
    };
    this.isServer = index.getContext(this, "isServer");
    this.queue = index.getContext(this, "queue");
  }
  componentWillLoad() {
    this.history = HISTORIES[this.historyType](this.el.ownerDocument.defaultView);
    this.history.listen((location) => {
      location = getLocation(location, this.root);
      this.location = location;
    });
    this.location = getLocation(this.history.location, this.root);
  }
  scrollTo(scrollToLocation) {
    const history = this.history;
    if (scrollToLocation == null || this.isServer || !history) {
      return;
    }
    if (history.action === 'POP' && Array.isArray(history.location.scrollPosition)) {
      return this.queue.write(() => {
        if (history && history.location && Array.isArray(history.location.scrollPosition)) {
          history.win.scrollTo(history.location.scrollPosition[0], history.location.scrollPosition[1]);
        }
      });
    }
    // okay, the frame has passed. Go ahead and render now
    return this.queue.write(() => {
      history.win.scrollTo(0, scrollToLocation);
    });
  }
  render() {
    if (!this.location || !this.history) {
      return;
    }
    const state = {
      historyType: this.historyType,
      location: this.location,
      titleSuffix: this.titleSuffix,
      root: this.root,
      history: this.history,
      routeViewsUpdated: this.routeViewsUpdated
    };
    return (index.h(activeRouter.ActiveRouter.Provider, { state: state }, index.h("slot", null)));
  }
  get el() { return index.getElement(this); }
};

exports.ap_ben_edit_benefit_page = EditBenefitPage;
exports.ap_ben_manage_page = ManageBenefitsPage;
exports.stencil_route_link = RouteLink;
exports.stencil_route_switch = RouteSwitch;
exports.stencil_router = Router;
