import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { c as checkPkgVersion } from './check-pkg-version.js';
import { D as DisputeManagementClickActions, b as makeUpdateDisputeResponse, c as makeCreateDisputeEvidence, m as makeSubmitDisputeResponse, a as DisputeService } from './event-types3.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { C as ComponentErrorSeverity, a as ComponentErrorCodes } from './Plaid.js';
import { L as heading4 } from './parts.js';
import { B as Button } from './button.js';
import { d as defineCustomElement$f } from './additional-statement2.js';
import { d as defineCustomElement$e } from './cancellation-policy2.js';
import { d as defineCustomElement$d } from './custom-popper2.js';
import { d as defineCustomElement$c } from './customer-details2.js';
import { d as defineCustomElement$b } from './duplicate-charge2.js';
import { d as defineCustomElement$a } from './electronic-evidence2.js';
import { d as defineCustomElement$9 } from './form-control-date2.js';
import { d as defineCustomElement$8 } from './form-control-file-v22.js';
import { d as defineCustomElement$7 } from './form-control-help-text3.js';
import { d as defineCustomElement$6 } from './form-control-text2.js';
import { d as defineCustomElement$5 } from './form-control-textarea2.js';
import { d as defineCustomElement$4 } from './form-control-tooltip2.js';
import { d as defineCustomElement$3 } from './product-or-service2.js';
import { d as defineCustomElement$2 } from './refund-policy2.js';
import { d as defineCustomElement$1 } from './shipping-details2.js';

const DisputeResponse = /*@__PURE__*/ proxyCustomElement(class DisputeResponse extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.clickEvent = createEvent(this, "click-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.stepCompleteEvent = createEvent(this, "complete-form-step-event", 7);
        this.submitEvent = createEvent(this, "submit-event", 7);
        this.errorMessage = null;
        this.disputeResponse = {};
        this.apiOrigin = "https://wc-proxy.justifi.ai";
        this.isLoading = false;
        this.documentList = [];
        this.documentErrors = {};
        this.currentStep = 0;
        this.componentStepMapping = [
            () => (h("product-or-service", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("customer-details", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("cancellation-policy", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("refund-policy", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("duplicate-charge", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("electronic-evidence", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("shipping-details", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (h("additional-statement", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
        ];
        this.saveData = async (formData, formStep) => {
            const hasFormData = Object.keys(formData).length;
            if (!hasFormData) {
                this.stepCompleteEvent.emit({ response: null, formStep: formStep });
                return;
            }
            if (this.isLastStep) {
                return this.submitDisputeResponse({
                    payload: formData,
                    onSuccess: (response) => {
                        this.submitEvent.emit({ response: response });
                        this.stepCompleteEvent.emit({ response: response, formStep: formStep });
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            errorCode: code,
                            message: error,
                            severity,
                        });
                    },
                });
            }
            else {
                return this.updateDisputeResponse({
                    payload: formData,
                    onSuccess: (response) => {
                        this.disputeResponse = Object.assign({}, response.data);
                        this.stepCompleteEvent.emit({ response: response, formStep: formStep });
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            errorCode: code,
                            message: error,
                            severity,
                        });
                    },
                });
            }
        };
        this.initializeMakePresignedURLs = async () => {
            const presignedUrlPromises = this.documentList.map((document) => {
                return this.getPresignedFileUrl(document);
            });
            return await Promise.all(presignedUrlPromises);
        };
        this.initializeFileUploads = async () => {
            const uploadDocumentPromises = this.documentList.map((document) => {
                return this.uploadDocument(document);
            });
            return Promise.all(uploadDocumentPromises);
        };
        this.getPresignedFileUrl = async (document) => {
            return this.createDisputeEvidence({
                payload: {
                    file_name: document.file_name,
                    file_type: document.file_type,
                    dispute_evidence_type: document.dispute_evidence_type,
                },
                onSuccess: (response) => {
                    document.presignedUrl = response.data.presigned_url;
                },
                onError: ({ error, code, severity }) => {
                    const errors = { [document.dispute_evidence_type]: error };
                    this.documentErrors = Object.assign(Object.assign({}, this.documentErrors), errors);
                    this.errorEvent.emit({
                        errorCode: code,
                        message: error,
                        severity,
                    });
                },
            });
        };
        this.uploadDocument = async (document) => {
            const fileData = await document.getFileString();
            if (!document.presignedUrl) {
                throw new Error('Presigned URL is not set');
            }
            const response = await fetch(document.presignedUrl, {
                method: 'PUT',
                body: fileData,
            });
            return response;
        };
        this.handleSubmit = async (formData, documentList, formStep) => {
            this.isLoading = true;
            if (documentList.length) {
                this.documentErrors = {};
                this.documentList = documentList;
                await this.initializeMakePresignedURLs();
                const hasPresigningErrors = Object.keys(this.documentErrors).length;
                if (hasPresigningErrors) {
                    this.isLoading = false;
                    throw new Error('Could not presign all documents');
                }
                await this.initializeFileUploads();
            }
            await this.saveData(formData, formStep);
            this.isLoading = false;
        };
        this.onCancel = () => {
            this.clickEvent.emit({ name: DisputeManagementClickActions.cancelDispute });
        };
        this.onBack = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: DisputeManagementClickActions.previousStep });
                await this.handleSubmit(formData, documentList, formStep);
                this.currentStep--;
            });
        };
        this.onNext = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: DisputeManagementClickActions.nextStep });
                await this.handleSubmit(formData, documentList, formStep);
                this.currentStep++;
            });
        };
        this.onSubmit = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: DisputeManagementClickActions.submit });
                const submitData = Object.assign(Object.assign({}, formData), { forfeit: false });
                await this.handleSubmit(submitData, documentList, formStep);
            });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.initializeDisputeServiceMethods();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    propChanged() {
        this.initializeDisputeServiceMethods();
    }
    initializeDisputeServiceMethods() {
        if (this.disputeId && this.authToken) {
            this.updateDisputeResponse = makeUpdateDisputeResponse({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new DisputeService(),
            });
            this.createDisputeEvidence = makeCreateDisputeEvidence({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new DisputeService(),
            });
            this.submitDisputeResponse = makeSubmitDisputeResponse({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new DisputeService(),
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    get currentStepComponent() {
        return this.componentStepMapping[this.currentStep]();
    }
    get isLastStep() {
        return this.currentStep === this.componentStepMapping.length - 1;
    }
    get isFirstStep() {
        return this.currentStep === 0;
    }
    render() {
        return (h("div", { key: '7f9c8d56cfb86cea73ab2f299b83ff0de28f5c3e', class: "dispute-response-root" }, h("div", { key: 'a805bf54df79453127557bf651c3d776a381241f', class: "row gy-3" }, h("div", { key: '2e6bc9cbe369e0ea5d200bc0934b4cad50f3c76f', class: "col-12" }, h("h1", { key: '9876e9c87c6dfb405e7bad46d64fdb40ad048142', class: "h4", part: heading4 }, "Counter dispute")), h("div", { key: '045028232da5331c7041ad222c4e98364674ace3', class: "col-12" }, this.currentStepComponent), h("div", { key: '0455c4856a44340ce25c1c4c8f776abb197f919f', class: "col-12" }, h("div", { key: '5b990cc1d41b3a7152d727c941e9758ed70f75a1', class: "d-flex gap-2 mt-4 justify-content-end" }, this.isFirstStep ? (h(Button, { variant: "secondary", onClick: () => this.onCancel(), disabled: this.isLoading, isLoading: this.isLoading }, "Cancel")) : (h(Button, { variant: "secondary", onClick: () => this.onBack(), disabled: this.isLoading, isLoading: this.isLoading }, "Back")), this.isLastStep ? (h(Button, { variant: "primary", onClick: () => this.onSubmit(), disabled: this.isLoading, isLoading: this.isLoading }, "Submit Counter Dispute")) : (h(Button, { variant: "primary", onClick: () => this.onNext(), disabled: this.isLoading, isLoading: this.isLoading }, "Next")))))));
    }
    static get watchers() { return {
        "disputeId": ["propChanged"],
        "authToken": ["propChanged"]
    }; }
}, [256, "dispute-response", {
        "authToken": [1, "auth-token"],
        "disputeId": [1, "dispute-id"],
        "disputeResponse": [8, "dispute-response"],
        "apiOrigin": [1, "api-origin"],
        "updateDisputeResponse": [32],
        "submitDisputeResponse": [32],
        "createDisputeEvidence": [32],
        "errorMessage": [32],
        "isLoading": [32],
        "documentList": [32],
        "documentErrors": [32],
        "currentStep": [32],
        "currentStepComponentRef": [32]
    }, undefined, {
        "disputeId": ["propChanged"],
        "authToken": ["propChanged"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["dispute-response", "additional-statement", "cancellation-policy", "custom-popper", "customer-details", "duplicate-charge", "electronic-evidence", "form-control-date", "form-control-file-v2", "form-control-help-text", "form-control-text", "form-control-textarea", "form-control-tooltip", "product-or-service", "refund-policy", "shipping-details"];
    components.forEach(tagName => { switch (tagName) {
        case "dispute-response":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, DisputeResponse);
            }
            break;
        case "additional-statement":
            if (!customElements.get(tagName)) {
                defineCustomElement$f();
            }
            break;
        case "cancellation-policy":
            if (!customElements.get(tagName)) {
                defineCustomElement$e();
            }
            break;
        case "custom-popper":
            if (!customElements.get(tagName)) {
                defineCustomElement$d();
            }
            break;
        case "customer-details":
            if (!customElements.get(tagName)) {
                defineCustomElement$c();
            }
            break;
        case "duplicate-charge":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "electronic-evidence":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "form-control-date":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "form-control-file-v2":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "form-control-help-text":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "form-control-text":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "form-control-textarea":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "form-control-tooltip":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "product-or-service":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "refund-policy":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "shipping-details":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}
defineCustomElement();

export { DisputeResponse as D, defineCustomElement as d };
