/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import { vehicleQuotationElements } from "./vehicle-quotation/element-mapper";
import { vehicleQuotationInputsValidation } from "./vehicle-quotation/validations";
import { formLanguageChange, formErrorHandler, formLoadingHandler, formSuccessHandler, formDidLoadHandler, formGetFormHandler, handleFormSubmit, formStructureRenderedHandler, getMarketingValues, } from "../../features/form-hook/index";
import { sharedFormLocalesSchema } from "../../features/multi-lingual/index";
import getLanguageFromUrl from "../../global/lib/get-language-from-url";
import cn from "../../global/lib/cn";
import { LoaderIcon } from "../../global/assets/loader-icon";
export class VehicleQuotationForm {
    constructor() {
        this.locale = { sharedFormLocales: sharedFormLocalesSchema.getDefault() };
        this.isLoading = false;
        this.structureRendered = false;
        this.isDev = false;
        this.isMobileForm = false;
    }
    async changeLanguage(newLanguage) {
        await formLanguageChange(this, newLanguage);
    }
    setIsLoading(isLoading) {
        formLoadingHandler(this, isLoading);
    }
    setErrorCallback(error) {
        formErrorHandler(this, error);
    }
    setSuccessCallback(data) {
        formSuccessHandler(this, data);
    }
    async componentWillLoad() {
        if (!this.language)
            this.language = getLanguageFromUrl();
    }
    async formSubmit(formValues) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2;
        try {
            this.setIsLoading(true);
            const nameContactedVehicles = (_b = (_a = this.structure) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.nameContactedVehicles;
            const marketingValues = getMarketingValues(this.structure);
            let payload = Object.assign({ name: formValues.name, phone: formValues.phone, companyBranchId: formValues.dealer, cityId: formValues === null || formValues === void 0 ? void 0 : formValues.city, vehicleQuotationType: (_d = (_c = this.structure) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.quotationType, preferredContactTime: (formValues === null || formValues === void 0 ? void 0 : formValues.contactTime) || 'NotSpecified', preferredPaymentMethod: (formValues === null || formValues === void 0 ? void 0 : formValues.paymentType) || 'Flexible' }, marketingValues);
            if (nameContactedVehicles) {
                payload.vehicle = ((_e = this['vehicleList'].find(vehicle => vehicle.value === formValues.vehicle)) === null || _e === void 0 ? void 0 : _e.label) || '';
                if ((formValues === null || formValues === void 0 ? void 0 : formValues.ownVehicle) === 'yes') {
                    const currentBrand = ((_f = this['currentVehicleBrandList'].find(brand => brand.value === formValues.currentVehicleBrand)) === null || _f === void 0 ? void 0 : _f.meta) || false;
                    let currentModel;
                    if (currentBrand)
                        currentModel = currentBrand.Models.find(model => `${model.ID}` === formValues.currentVehicleModel) || false;
                    payload.currentOrTradeInVehicle = `${(currentBrand === null || currentBrand === void 0 ? void 0 : currentBrand.Name) || this.locale.Other} - ${(currentModel === null || currentModel === void 0 ? void 0 : currentModel.Name) || this.locale.Other}`;
                }
            }
            else {
                payload.vehicle = formValues.vehicle;
                payload.additionalData = {
                    DoYouOwnAVehicle: (formValues === null || formValues === void 0 ? void 0 : formValues.ownVehicle) === 'yes',
                };
                if ((formValues === null || formValues === void 0 ? void 0 : formValues.ownVehicle) === 'yes') {
                    payload.additionalData.yourCurrentVehicle = (formValues === null || formValues === void 0 ? void 0 : formValues.currentVehicleBrand) || this.locale.Other;
                    payload.additionalData.vehicleModel = (formValues === null || formValues === void 0 ? void 0 : formValues.currentVehicleModel) || this.locale.Other;
                }
            }
            const headers = {
                'Brand': (_h = (_g = this.structure) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.brandId,
                'Accept-Language': this.localeLanguage || 'en',
                'Content-Type': 'application/json',
            };
            let requestEndpoint = '';
            if (this.isMobileForm) {
                const token = await this.getMobileToken();
                if (token.toLowerCase().startsWith('bearer')) {
                    headers['Authorization'] = token;
                    requestEndpoint = (_k = (_j = this.structure) === null || _j === void 0 ? void 0 : _j.data) === null || _k === void 0 ? void 0 : _k.requestAppUrl;
                }
                else {
                    headers['verification-token'] = token;
                    requestEndpoint = (_m = (_l = this.structure) === null || _l === void 0 ? void 0 : _l.data) === null || _m === void 0 ? void 0 : _m.requestAppCheckUrl;
                }
            }
            else {
                requestEndpoint = (_p = (_o = this.structure) === null || _o === void 0 ? void 0 : _o.data) === null || _p === void 0 ? void 0 : _p.requestUrl;
                const token = await grecaptcha.execute((_r = (_q = this.structure) === null || _q === void 0 ? void 0 : _q.data) === null || _r === void 0 ? void 0 : _r.recaptchaKey, { action: 'submit' });
                headers['Recaptcha-Token'] = token;
            }
            if (this.isDev)
                requestEndpoint = requestEndpoint.replaceAll('production=true', 'production=false');
            if ((_t = (_s = this.structure) === null || _s === void 0 ? void 0 : _s.data) === null || _t === void 0 ? void 0 : _t.extraPayload)
                payload = Object.assign(Object.assign({}, payload), (_v = (_u = this.structure) === null || _u === void 0 ? void 0 : _u.data) === null || _v === void 0 ? void 0 : _v.extraPayload);
            const response = await fetch(requestEndpoint, {
                headers,
                method: 'POST',
                body: JSON.stringify(payload),
            });
            if (response === null || response === void 0 ? void 0 : response.ok) {
                const result = await (response === null || response === void 0 ? void 0 : response.json().catch(() => ({})));
                const eventHolder = (_x = (_w = this.structure) === null || _w === void 0 ? void 0 : _w.data) === null || _x === void 0 ? void 0 : _x.pushAnalyticsEventTo;
                if (eventHolder) {
                    window[eventHolder] = window[eventHolder] || [];
                    window[eventHolder].push({
                        event: 'get_a_quote',
                        phone: formValues.phone,
                        fullname: formValues.name,
                        dealer: (_y = this['dealerList'].find(d => d.value === formValues.dealer)) === null || _y === void 0 ? void 0 : _y.label,
                        vehicle: (_z = this['vehicleList'].find(v => v.value === formValues.vehicle)) === null || _z === void 0 ? void 0 : _z.label,
                    });
                }
                this.setSuccessCallback(result);
                setTimeout(() => {
                    this.form.reset();
                    this.form.rerender({ rerenderForm: true, rerenderAll: true });
                }, 100);
            }
            else {
                const contentType = response.headers.get('content-type') || '';
                const errorText = contentType.includes('application/json') ? ((_2 = (_1 = (_0 = (await response.json().catch(() => ({})))) === null || _0 === void 0 ? void 0 : _0.message) === null || _1 === void 0 ? void 0 : _1.body) !== null && _2 !== void 0 ? _2 : '') : await response.text().catch(() => '');
                throw new Error(errorText);
            }
        }
        catch (error) {
            console.error(error);
            this.setErrorCallback(error);
        }
        finally {
            this.setIsLoading(false);
        }
    }
    // #endregion
    // #region Component Logic
    async componentDidLoad() {
        await formDidLoadHandler(this, vehicleQuotationInputsValidation);
    }
    async getForm() {
        return await formGetFormHandler(this);
    }
    async submit() {
        await handleFormSubmit(this);
    }
    async structureChanged(isRendered) {
        await formStructureRenderedHandler(this, isRendered);
    }
    // #endregion
    render() {
        var _a, _b;
        return (h(Host, { key: 'fdc919a8b52675e1dd598408cc7f056d992c1517', translate: "no" }, h("div", { key: 'd11a5531f061e778038eedea7cca02b0ad834332', part: `shift-form vehicle-quotation-${(_b = (_a = this.structure) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.theme}` }, h("div", { key: 'abac151f3be810dbd850b63e7c692afe4e5f14fe', part: "form-container", class: "relative min-h-[150px]" }, h("div", { key: 'e6dcec2bd78ddef371e3adb5f249b4c3e7e8587c', part: "form-loader-container", class: cn('form-loader-container absolute top-0 left-0 w-full h-full pointer-events-none flex justify-center items-center transition-opacity duration-500', {
                'opacity-0': this.structureRendered,
            }) }, h(LoaderIcon, { key: '155668175e0735e2314ce55b586bd82df4a3c2df', part: "form-loader-icon", class: "img" })), h("flexible-container", { key: '61dea530ef1a00cd09a2b2871262573e8b1248a3', onlyForMounting: true, isOpened: this.structureRendered }, !!this.form && (h("form-structure", { key: '572c108a4d67e1443ca9f90585fa3339a5ffaea5', form: this.form, fields: this.fields, formId: this.formId, formLocale: this.locale, structure: this.structure, isLoading: this.isLoading, language: this.localeLanguage, errorMessage: this.errorMessage, formElementMapper: vehicleQuotationElements, successMessage: this.locale['Form submitted successfully.'] }, h("slot", { key: '8e0b1e969144912d4ce5c87edb8d7ede708be3e0' }))))))));
    }
    static get is() { return "vehicle-quotation-form"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["vehicle-quotation/themes.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["vehicle-quotation/themes.css"]
        };
    }
    static get properties() {
        return {
            "language": {
                "type": "string",
                "attribute": "language",
                "mutable": true,
                "complexType": {
                    "original": "LanguageKeys",
                    "resolved": "\"ar\" | \"en\" | \"ku\" | \"ru\"",
                    "references": {
                        "LanguageKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::LanguageKeys"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true
            },
            "gistId": {
                "type": "string",
                "attribute": "gist-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "extraHeader": {
                "type": "unknown",
                "attribute": "extra-header",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "extraPayload": {
                "type": "unknown",
                "attribute": "extra-payload",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "structureUrl": {
                "type": "string",
                "attribute": "structure-url",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "loadingChanges": {
                "type": "unknown",
                "attribute": "loading-changes",
                "mutable": false,
                "complexType": {
                    "original": "(loading: boolean) => void",
                    "resolved": "(loading: boolean) => void",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "errorCallback": {
                "type": "unknown",
                "attribute": "error-callback",
                "mutable": false,
                "complexType": {
                    "original": "(error: any, message: string) => Promise<void | boolean>",
                    "resolved": "(error: any, message: string) => Promise<boolean | void>",
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "successCallback": {
                "type": "unknown",
                "attribute": "success-callback",
                "mutable": false,
                "complexType": {
                    "original": "(data: any, message?: string) => Promise<void | boolean>",
                    "resolved": "(data: any, message?: string) => Promise<boolean | void>",
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "structure": {
                "type": "unknown",
                "attribute": "structure",
                "mutable": true,
                "complexType": {
                    "original": "FormElementStructure<vehicleQuotationElementNames> | undefined",
                    "resolved": "{ steps?: Record<LanguageKeys, Step>[]; data?: Record<string, any>; requiredContext?: Record<string, boolean>; } & { id?: string; step?: number; type?: string; class?: string; staticValue?: any; isHidden?: boolean; isDisabled?: boolean; children?: (OptionalKeys<{ vehicle: string; name: string; dealer: string; city: string; paymentType: string; contactTime: string; ownVehicle: string; currentVehicleBrand: string; currentVehicleModel: string; }> | AdditionalFields | FormElementStructureComponents<OptionalKeys<{ vehicle: string; name: string; dealer: string; city: string; paymentType: string; contactTime: string; ownVehicle: string; currentVehicleBrand: string; currentVehicleModel: string; }> | AdditionalFields>)[]; } & { tag: string; name?: OptionalKeys<{ vehicle: string; name: string; dealer: string; city: string; paymentType: string; contactTime: string; ownVehicle: string; currentVehicleBrand: string; currentVehicleModel: string; }> | AdditionalFields; } | { steps?: Record<LanguageKeys, Step>[]; data?: Record<string, any>; requiredContext?: Record<string, boolean>; } & { id?: string; step?: number; type?: string; class?: string; staticValue?: any; isHidden?: boolean; isDisabled?: boolean; children?: (OptionalKeys<{ vehicle: string; name: string; dealer: string; city: string; paymentType: string; contactTime: string; ownVehicle: string; currentVehicleBrand: string; currentVehicleModel: string; }> | AdditionalFields | FormElementStructureComponents<OptionalKeys<{ vehicle: string; name: string; dealer: string; city: string; paymentType: string; contactTime: string; ownVehicle: string; currentVehicleBrand: string; currentVehicleModel: string; }> | AdditionalFields>)[]; } & { tag?: string; name: OptionalKeys<{ vehicle: string; name: string; dealer: string; city: string; paymentType: string; contactTime: string; ownVehicle: string; currentVehicleBrand: string; currentVehicleModel: string; }> | AdditionalFields; }",
                    "references": {
                        "FormElementStructure": {
                            "location": "import",
                            "path": "~features/form-hook",
                            "id": "src/features/form-hook/index.ts::FormElementStructure"
                        },
                        "vehicleQuotationElementNames": {
                            "location": "import",
                            "path": "./vehicle-quotation/element-mapper",
                            "id": "src/components/forms/vehicle-quotation/element-mapper.tsx::vehicleQuotationElementNames"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "fields": {
                "type": "unknown",
                "attribute": "fields",
                "mutable": true,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "formReadyCallback": {
                "type": "unknown",
                "attribute": "form-ready-callback",
                "mutable": false,
                "complexType": {
                    "original": "() => void",
                    "resolved": "() => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "formId": {
                "type": "string",
                "attribute": "form-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isDev": {
                "type": "boolean",
                "attribute": "is-dev",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "disableScrollToTop": {
                "type": "boolean",
                "attribute": "disable-scroll-to-top",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isMobileForm": {
                "type": "boolean",
                "attribute": "is-mobile-form",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "getMobileToken": {
                "type": "unknown",
                "attribute": "get-mobile-token",
                "mutable": false,
                "complexType": {
                    "original": "() => string",
                    "resolved": "() => string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get states() {
        return {
            "locale": {},
            "errorMessage": {},
            "isLoading": {},
            "localeLanguage": {},
            "structureRendered": {},
            "form": {}
        };
    }
    static get methods() {
        return {
            "getForm": {
                "complexType": {
                    "signature": "() => Promise<FormHook<any>>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "FormHook": {
                            "location": "import",
                            "path": "~features/form-hook",
                            "id": "src/features/form-hook/index.ts::FormHook"
                        }
                    },
                    "return": "Promise<FormHook<any>>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "submit": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "changeLanguage"
            }, {
                "propName": "structureRendered",
                "methodName": "structureChanged"
            }];
    }
}
