import { HostInputFormComponent } from "./host-input-form.js";
/** Mount the real form inline in the terminal host. */
export function mountHostInputForm(ui, request, delegate) {
    let done;
    let settled = false;
    let closedBeforeMount = false;
    let workingHidden = true;
    ui.setWorkingVisible?.(false);
    const restoreWorking = () => {
        if (!workingHidden)
            return;
        workingHidden = false;
        ui.setWorkingVisible?.(true);
    };
    const finish = (notify) => {
        if (settled)
            return;
        settled = true;
        try {
            notify?.();
        }
        finally {
            try {
                done?.(undefined);
            }
            finally {
                restoreWorking();
            }
        }
    };
    const factory = (tui, theme, keybindings, complete) => {
        done = complete;
        if (closedBeforeMount)
            complete(undefined);
        return new HostInputFormComponent(tui, theme, keybindings, request, {
            onSubmit: (values) => finish(() => delegate.onSubmit(values)),
            onCancel: () => finish(() => delegate.onCancel()),
        });
    };
    try {
        void Promise.resolve(ui.custom(factory, { overlay: false })).catch(() => {
            finish(() => delegate.onCancel());
        }).finally(() => {
            if (settled)
                restoreWorking();
            else
                finish(() => delegate.onCancel());
        });
    }
    catch {
        finish(() => delegate.onCancel());
    }
    return {
        close: () => {
            if (settled)
                return;
            if (!done)
                closedBeforeMount = true;
            finish();
        },
    };
}
/** Non-isolated implementation of the public capability. */
export function openLocalHostInputForm(ui, request) {
    return new Promise((resolve) => {
        let settled = false;
        const settle = (values) => {
            if (settled)
                return;
            settled = true;
            resolve(values);
        };
        mountHostInputForm(ui, request, {
            onSubmit: (values) => settle(values),
            onCancel: () => settle(undefined),
        });
    });
}
//# sourceMappingURL=host-input-form-mount.js.map