/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { h } from './index-Bf4Ol6Qt.js';
import { L as LoaderIcon, d as dateFnsExports } from './loader-icon-DM4Vm5gX.js';
import { c as cn } from './cn-BK16Cn81.js';
import { C as CalendarDaysIcon } from './calendar-days-icon-Dz291Fau.js';
import { d as decodeTimeOffset } from './decode-time-offset-DFZOybyr.js';
import { g as getNestedValue } from './get-nested-value-D0IHkGuC.js';

const cachedImages = {};
const cacheImage = (form, imSrc, id) => {
    fetch(imSrc)
        .then(res => res.blob())
        .then(blob => {
        const reader = new FileReader();
        reader.onloadend = () => {
            cachedImages[id] = reader.result;
            form.rerender({ rerenderForm: true });
        };
        reader.readAsDataURL(blob);
    })
        .catch(e => {
        console.log(e);
        // fail silently, keep fallback
    });
};
let imageSrcBase64 = '';
const VehicleImageViewer = ({ form }) => {
    var _a, _b, _c, _d;
    form.addWatcher('vehicle');
    let vehicleId = form.getValue('vehicle');
    let openContainer = !!vehicleId;
    const selectedVehicle = (_a = form.context['vehicleList']) === null || _a === void 0 ? void 0 : _a.find(vehicle => vehicle.value === vehicleId);
    let imSrc;
    if (selectedVehicle) {
        imSrc = (_b = selectedVehicle === null || selectedVehicle === void 0 ? void 0 : selectedVehicle.meta) === null || _b === void 0 ? void 0 : _b.image;
        vehicleId = selectedVehicle.value;
    }
    else if (form.context['vehicleList'] && form.context['vehicleList'][0]) {
        imSrc = (_d = (_c = form.context['vehicleList'][0]) === null || _c === void 0 ? void 0 : _c.meta) === null || _d === void 0 ? void 0 : _d.image;
        vehicleId = form.context['vehicleList'][0].value;
    }
    let isLoading = false;
    if (cachedImages[vehicleId]) {
        imageSrcBase64 = cachedImages[vehicleId];
    }
    else if (form && imSrc && vehicleId) {
        cacheImage(form, imSrc, vehicleId);
        isLoading = true;
    }
    return (h("flexible-container", { isOpened: openContainer },
        h("div", { style: { 'min-height': '60px' }, part: "vehicle-image-wrapper", class: cn('vehicle-image-wrapper', { loading: isLoading }) },
            h("div", { part: cn('vehicle-image-loading-wrapper', { 'vehicle-image-active-loading-wrapper': isLoading }), class: cn('loading-wrapper vehicle-image-loading-wrapper', { 'vehicle-image-active-loading-wrapper': isLoading }) },
                h(LoaderIcon, { part: "vehicle-image-loader-icon", class: "img vehicle-image-loader-icon" })),
            h("img", { alt: "vehicle image", part: "vehicle-image", src: imageSrcBase64, style: { 'border-radius': '6px', 'transition': 'opacity 150ms cubic-bezier(0.4, 0, 0.2, 1);', 'opacity': isLoading ? '0' : '1' } }))));
};

const getObjectValue = (obj, path) => {
    if (typeof path === 'string')
        return getNestedValue(obj, path);
    return path.map(itemPath => getNestedValue(obj, itemPath)).find(value => value != null);
};
const populateItems = (data, setup, hasMeta) => {
    const options = [];
    const baseOptions = getObjectValue(data, setup.items);
    baseOptions.forEach(item => {
        const value = getObjectValue(item, setup['item-value']);
        const label = getObjectValue(item, setup['item-label']);
        const newItemObject = { value: (setup === null || setup === void 0 ? void 0 : setup.useNamedValue) ? label : value, label };
        newItemObject.meta = Object.assign({}, item);
        options.push(newItemObject);
    });
    return options;
};

const getFormMappers = (extraMappers = {}) => (Object.assign({ submit: ({ props }) => h("form-submit", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), inputPreview: ({ props }) => h("form-input-preview", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), fileUploader: ({ props }) => h("form-file", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), formStepper: ({ props, language }) => h("form-stepper", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name, language: language }, props)), back: ({ props }) => h("form-stepper-control", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), stepperSubmit: ({ props }) => h("form-stepper-submit", Object.assign({ key: (props === null || props === void 0 ? void 0 : props.step) || (props === null || props === void 0 ? void 0 : props.name) }, props)), name: ({ props }) => h("form-input", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), lastName: ({ props }) => h("form-input", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), email: ({ props }) => h("form-input", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name, type: "email" }, props)), message: ({ props }) => h("form-text-area", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), file: ({ props }) => h("form-file", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), vin: ({ props }) => h("form-vin-input", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props)), vehicleImage: ({ form }) => h(VehicleImageViewer, { form: form }), phone: ({ props, isLoading }) => h("form-phone-number", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name, isLoading: isLoading }, props)), vehicle: ({ language, props }) => {
        const fetcher = async ({ signal, context }) => {
            var _a, _b;
            const params = new URLSearchParams(window.location.search);
            let paramValue = (_a = (params.get(props === null || props === void 0 ? void 0 : props.vehicleIdQueryParam) || '')) === null || _a === void 0 ? void 0 : _a.toLowerCase();
            const vehicleEndpoint = props.vehicleApi;
            const response = await fetch(vehicleEndpoint, { signal, headers: { 'Accept-Language': language } });
            let options;
            let defaultIndex = -1;
            if (props === null || props === void 0 ? void 0 : props.dynamic) {
                const res = await response.json();
                options = populateItems(res, props);
                options.forEach((vehicle, idx) => {
                    var _a, _b;
                    if (!props.defaultValue && paramValue && (((_a = vehicle === null || vehicle === void 0 ? void 0 : vehicle.label) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === paramValue || ((_b = `${vehicle.value}`) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === paramValue))
                        defaultIndex = idx;
                });
            }
            else if (props === null || props === void 0 ? void 0 : props.vehiclesApiStrapiFormat) {
                const res = await response.json();
                options = res.data;
                options = options.map((vehicle, idx) => {
                    var _a, _b, _c, _d, _e;
                    if (!props.defaultValue && paramValue && (((_a = vehicle === null || vehicle === void 0 ? void 0 : vehicle.GradeName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === paramValue || ((_b = `${vehicle.id}`) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === paramValue))
                        defaultIndex = idx;
                    return {
                        label: vehicle.attributes.GradeName,
                        value: (props === null || props === void 0 ? void 0 : props.useNamedValue) ? `${(vehicle === null || vehicle === void 0 ? void 0 : vehicle.GradeName) || ((_c = vehicle === null || vehicle === void 0 ? void 0 : vehicle.attributes) === null || _c === void 0 ? void 0 : _c.GradeName)}` : `${vehicle.id}`,
                        meta: Object.assign(Object.assign({}, vehicle), { image: ((_d = vehicle === null || vehicle === void 0 ? void 0 : vehicle.Cover) === null || _d === void 0 ? void 0 : _d.url) || ((_e = vehicle.attributes.Cover.data.attributes) === null || _e === void 0 ? void 0 : _e.url) }),
                    };
                });
            }
            else {
                options = await response.json();
                options = options.map((vehicle, idx) => {
                    var _a, _b;
                    if (!props.defaultValue && paramValue && (((_a = vehicle === null || vehicle === void 0 ? void 0 : vehicle.Title) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === paramValue || ((_b = `${vehicle.ID}`) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === paramValue))
                        defaultIndex = idx;
                    return {
                        label: vehicle.Title,
                        value: (props === null || props === void 0 ? void 0 : props.useNamedValue) ? `${vehicle.Title}` : `${vehicle.ID}`,
                        meta: Object.assign(Object.assign({}, vehicle), { image: vehicle.Image }),
                    };
                });
            }
            if (!(props === null || props === void 0 ? void 0 : props.defaultValue)) {
                if (defaultIndex > -1)
                    context.defaultValue = (_b = options[defaultIndex]) === null || _b === void 0 ? void 0 : _b.value;
                else
                    context.defaultValue = '';
            }
            else
                context.defaultValue = props === null || props === void 0 ? void 0 : props.defaultValue;
            return options;
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { searchable: true, fetcher: fetcher, language: language }));
    }, companyBranchId: ({ language, props }) => {
        const fetcher = async ({ signal }) => {
            const dealerEndpoint = props === null || props === void 0 ? void 0 : props.branchApi;
            const response = await fetch(dealerEndpoint, { signal, headers: { 'Accept-Language': language } });
            const options = (await response.json()).map(dealer => ({
                label: dealer.Name,
                value: `${dealer.ID}`,
                meta: Object.assign({}, dealer),
            }));
            return options;
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { clearable: true, searchable: true, fetcher: fetcher, language: language }));
    }, vacancyId: ({ language, props }) => {
        const fetcher = async ({ signal }) => {
            const dealerEndpoint = props === null || props === void 0 ? void 0 : props.vacancyApi;
            const response = await fetch(dealerEndpoint, { signal, headers: { 'Accept-Language': language } });
            const options = (await response.json()).map(dealer => ({
                label: dealer.Title,
                value: `${dealer.ID}`,
                meta: Object.assign({}, dealer),
            }));
            return options;
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { clearable: true, searchable: true, fetcher: fetcher, language: language }));
    }, cityId: ({ language, props }) => {
        const fetcher = async ({ signal }) => {
            const dealerEndpoint = props === null || props === void 0 ? void 0 : props.cityApi;
            const response = await fetch(dealerEndpoint, { signal, headers: { 'Accept-Language': language } });
            const options = (await response.json()).map(dealer => ({
                label: dealer.Name,
                value: `${dealer.ID}`,
                meta: Object.assign({}, dealer),
            }));
            return options;
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { clearable: true, searchable: true, fetcher: fetcher, language: language }));
    }, date: ({ props }) => h("form-picker-input", Object.assign({ type: "date" }, props, { icon: h(CalendarDaysIcon, null) })), time: ({ language, props }) => {
        const fetcher = async () => {
            const options = [];
            if (Array.isArray(props.span) && Array.isArray(props.min) && Array.isArray(props.max) && props.format) {
                let tempDate = decodeTimeOffset({ offsets: props.min });
                let maxDate = decodeTimeOffset({ offsets: props.max });
                while (dateFnsExports.isBefore(tempDate, maxDate) || dateFnsExports.isEqual(tempDate, maxDate)) {
                    options.push({
                        value: dateFnsExports.format(tempDate, props.format),
                        label: dateFnsExports.format(tempDate, props.format),
                    });
                    tempDate = decodeTimeOffset({ offsets: props.span, date: tempDate });
                }
            }
            return options;
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { clearable: true, fetcher: fetcher, language: language }));
    }, year: ({ language, props }) => {
        const minYear = (props === null || props === void 0 ? void 0 : props.min) || new Date().getFullYear() - 20;
        const maxYear = (props === null || props === void 0 ? void 0 : props.max) || new Date().getFullYear();
        const options = [];
        for (let year = minYear; year <= maxYear; year++) {
            options.push({
                value: `${year}`,
                label: `${year}`,
            });
        }
        const fetcher = async ({ language }) => {
            var _a, _b, _c, _d, _e, _f, _g, _h;
            let parsedOptions = [...options];
            if (props === null || props === void 0 ? void 0 : props.firstOption) {
                parsedOptions = [{ label: ((_b = (_a = props === null || props === void 0 ? void 0 : props.firstOption) === null || _a === void 0 ? void 0 : _a.label) === null || _b === void 0 ? void 0 : _b[language]) || '', value: ((_d = (_c = props === null || props === void 0 ? void 0 : props.firstOption) === null || _c === void 0 ? void 0 : _c.value) === null || _d === void 0 ? void 0 : _d[language]) || '' }, ...parsedOptions];
            }
            if (props === null || props === void 0 ? void 0 : props.lastOption) {
                parsedOptions = [...parsedOptions, { label: ((_f = (_e = props === null || props === void 0 ? void 0 : props.lastOption) === null || _e === void 0 ? void 0 : _e.label) === null || _f === void 0 ? void 0 : _f[language]) || '', value: ((_h = (_g = props === null || props === void 0 ? void 0 : props.lastOption) === null || _g === void 0 ? void 0 : _g.value) === null || _h === void 0 ? void 0 : _h[language]) || '' }];
            }
            return parsedOptions;
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { clearable: true, fetcher: fetcher, language: language }));
    }, currentVehicleBrand: ({ form, language, props, locale }) => {
        const fetcher = async ({ signal }) => {
            var _a;
            const currentVehiclesEndpoint = (_a = form.context.structure) === null || _a === void 0 ? void 0 : _a.data.currentVehiclesApi;
            const response = await fetch(currentVehiclesEndpoint, { signal, headers: { 'Accept-Language': 'en' } });
            const options = (await response.json()).filter(vehicle => vehicle.name !== 'Other');
            return [
                ...options.map(vehicle => ({
                    label: vehicle.Name,
                    value: `${vehicle.ID}`,
                    meta: Object.assign({}, vehicle),
                })),
                {
                    value: 'Other',
                    label: locale.Other,
                },
            ];
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { searchable: true, fetcher: fetcher, language: language }));
    }, currentVehicleModel: ({ form, language, props, locale }) => {
        form.addWatcher('currentVehicleBrand');
        const currentVehicleBrand = form === null || form === void 0 ? void 0 : form.getValue('currentVehicleBrand');
        const fetcher = async ({}) => {
            var _a, _b;
            if (!currentVehicleBrand)
                return [];
            const selectedBrand = (_b = (_a = form.context['currentVehicleBrandList']) === null || _a === void 0 ? void 0 : _a.find(vehicle => vehicle.value === currentVehicleBrand)) === null || _b === void 0 ? void 0 : _b.meta;
            if (!selectedBrand)
                return [];
            return [
                ...selectedBrand === null || selectedBrand === void 0 ? void 0 : selectedBrand.Models.map(model => ({ label: model.Name, value: `${model.ID}` })),
                {
                    value: 'Other',
                    label: locale.Other,
                },
            ];
        };
        return (h("form-select", Object.assign({}, props, { searchable: true, key: props === null || props === void 0 ? void 0 : props.name, fetcher: fetcher, language: language, resetKey: currentVehicleBrand, fetcherKey: currentVehicleBrand, isRequired: currentVehicleBrand !== 'Other', isDisabled: !currentVehicleBrand || currentVehicleBrand === 'Other' })));
    }, ownVehicle: ({ language, props }) => {
        const fetcher = async ({}) => {
            var _a, _b, _c, _d;
            return [
                {
                    value: 'yes',
                    label: (_b = (_a = props === null || props === void 0 ? void 0 : props.localization) === null || _a === void 0 ? void 0 : _a[language]) === null || _b === void 0 ? void 0 : _b.yes,
                },
                {
                    value: 'no',
                    label: (_d = (_c = props === null || props === void 0 ? void 0 : props.localization) === null || _c === void 0 ? void 0 : _c[language]) === null || _d === void 0 ? void 0 : _d.no,
                },
            ];
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { fetcher: fetcher, language: language }));
    }, conditionalCurrentVehicleBrand: ({ form, language, props, locale }) => {
        form.addWatcher('ownVehicle');
        const ownVehicle = (form === null || form === void 0 ? void 0 : form.getValue('ownVehicle')) === 'yes';
        const fetcher = async ({ signal }) => {
            const currentVehiclesEndpoint = props === null || props === void 0 ? void 0 : props.brandApi;
            const response = await fetch(currentVehiclesEndpoint, { signal, headers: { 'Accept-Language': 'en' } });
            const options = (await response.json()).filter(vehicle => vehicle.name !== 'Other');
            return [
                ...options.map(vehicle => ({
                    label: vehicle.Name,
                    value: (props === null || props === void 0 ? void 0 : props.useNamedValue) ? vehicle.Name : `${vehicle.ID}`,
                    meta: Object.assign({}, vehicle),
                })),
                {
                    value: 'Other',
                    label: locale.Other,
                },
            ];
        };
        return h("form-select", Object.assign({ key: props === null || props === void 0 ? void 0 : props.name }, props, { searchable: true, fetcher: fetcher, language: language, resetKey: ownVehicle, isRequired: ownVehicle, isDisabled: !ownVehicle }));
    }, conditionalCurrentVehicleModel: ({ form, language, props, locale }) => {
        form.addWatcher('ownVehicle');
        form.addWatcher('conditionalCurrentVehicleBrand');
        const ownVehicle = (form === null || form === void 0 ? void 0 : form.getValue('ownVehicle')) === 'yes';
        const currentVehicleBrand = form === null || form === void 0 ? void 0 : form.getValue('conditionalCurrentVehicleBrand');
        const fetcher = async ({}) => {
            var _a, _b;
            if (!currentVehicleBrand)
                return [];
            const selectedBrand = (_b = (_a = form.context['conditionalCurrentVehicleBrandList']) === null || _a === void 0 ? void 0 : _a.find(vehicle => vehicle.value === currentVehicleBrand)) === null || _b === void 0 ? void 0 : _b.meta;
            if (!selectedBrand)
                return [];
            return [
                ...selectedBrand === null || selectedBrand === void 0 ? void 0 : selectedBrand.Models.map(model => ({ label: model.Name, value: (props === null || props === void 0 ? void 0 : props.useNamedValue) ? model.Name : `${model.ID}` })),
                {
                    value: 'Other',
                    label: locale.Other,
                },
            ];
        };
        return (h("form-select", Object.assign({}, props, { searchable: true, fetcher: fetcher, key: props === null || props === void 0 ? void 0 : props.name, language: language, resetKey: currentVehicleBrand, fetcherKey: currentVehicleBrand, isRequired: ownVehicle && currentVehicleBrand !== 'Other', isDisabled: !currentVehicleBrand || currentVehicleBrand === 'Other' })));
    } }, extraMappers));

export { getFormMappers as g };
