'use strict';

var Feature = require('../../../../../../../../motion-dom@12.38.0/node_modules/motion-dom/dist/es/render/Feature.js');
var resolveDynamicVariants = require('../../../../../../../../motion-dom@12.38.0/node_modules/motion-dom/dist/es/render/utils/resolve-dynamic-variants.js');

let id = 0;
class ExitAnimationFeature extends Feature.Feature {
    constructor() {
        super(...arguments);
        this.id = id++;
        this.isExitComplete = false;
    }
    update() {
        if (!this.node.presenceContext)
            return;
        const { isPresent, onExitComplete } = this.node.presenceContext;
        const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};
        if (!this.node.animationState || isPresent === prevIsPresent) {
            return;
        }
        if (isPresent && prevIsPresent === false) {
            /**
             * When re-entering, if the exit animation already completed
             * (element is at rest), reset to initial values so the enter
             * animation replays from the correct position.
             */
            if (this.isExitComplete) {
                const { initial, custom } = this.node.getProps();
                if (typeof initial === "string") {
                    const resolved = resolveDynamicVariants.resolveVariant(this.node, initial, custom);
                    if (resolved) {
                        const { transition, transitionEnd, ...target } = resolved;
                        for (const key in target) {
                            this.node
                                .getValue(key)
                                ?.jump(target[key]);
                        }
                    }
                }
                this.node.animationState.reset();
                this.node.animationState.animateChanges();
            }
            else {
                this.node.animationState.setActive("exit", false);
            }
            this.isExitComplete = false;
            return;
        }
        const exitAnimation = this.node.animationState.setActive("exit", !isPresent);
        if (onExitComplete && !isPresent) {
            exitAnimation.then(() => {
                this.isExitComplete = true;
                onExitComplete(this.id);
            });
        }
    }
    mount() {
        const { register, onExitComplete } = this.node.presenceContext || {};
        if (onExitComplete) {
            onExitComplete(this.id);
        }
        if (register) {
            this.unmount = register(this.id);
        }
    }
    unmount() { }
}

exports.ExitAnimationFeature = ExitAnimationFeature;
