/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { F as FormHook } from './get-language-from-url-DvR7LGV5.js';
import './types-BDhR4pDq.js';
import { b as getSharedFormLocal } from './get-local-language-CE9dtbnG.js';
import { d as dateFnsExports } from './loader-icon-DM4Vm5gX.js';

function parseLooseJson(loose) {
    try {
        let s = loose.trim();
        // 1) remove trailing commas before } or ]
        s = s.replace(/,\s*([}\]])/g, '$1');
        // 2) quote unquoted keys: { tag: 'div' } -> { "tag": 'div' }
        s = s.replace(/([{,]\s*)([A-Za-z_]\w*)\s*:/g, '$1"$2":');
        // 3) turn 'single-quoted' strings into "double-quoted"
        s = s.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, (_, inner) => {
            // escape any double-quotes already inside
            return `"${inner.replace(/"/g, '\\"')}"`;
        });
        return JSON.parse(s);
    }
    catch (err) {
        console.error('Failed to parse loose JSON content:', err.message);
        return null;
    }
}

const gistLoader = async (gistId) => {
    try {
        const res = await fetch(`https://api.github.com/gists/${gistId}`, {
            headers: { Accept: 'application/vnd.github+json' },
        });
        if (!res.ok) {
            throw new Error(`GitHub API error: ${res.status} ${res.statusText}`);
        }
        const gist = await res.json();
        const jsonFile = Object.values(gist.files).find((file) => file === null || file === void 0 ? void 0 : file.filename.endsWith('.json'));
        if (!jsonFile)
            throw new Error('No JSON file found in this gist');
        const resStructure = parseLooseJson(jsonFile === null || jsonFile === void 0 ? void 0 : jsonFile.content);
        return resStructure;
    }
    catch (err) {
        console.error('Error fetching gist JSON:', err.message);
    }
    return undefined;
};

async function fetchJson(url) {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
}

const formLanguageChange = async (formContext, newLanguage) => {
    var _a, _b, _c, _d, _e;
    const sharedLocales = await getSharedFormLocal(newLanguage);
    const LS = (_b = (_a = formContext.structure) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.localization;
    const structureLocalization = typeof LS === 'object' ? ((_d = (_c = LS === null || LS === void 0 ? void 0 : LS[newLanguage]) !== null && _c !== void 0 ? _c : LS === null || LS === void 0 ? void 0 : LS.en) !== null && _d !== void 0 ? _d : {}) : {};
    formContext.locale = Object.assign(Object.assign({}, structureLocalization), { sharedFormLocales: Object.assign(Object.assign({}, sharedLocales), structureLocalization === null || structureLocalization === void 0 ? void 0 : structureLocalization.sharedFormLocales) });
    formContext.localeLanguage = newLanguage;
    (_e = formContext.form) === null || _e === void 0 ? void 0 : _e.rerender({ rerenderAll: true });
};
const formErrorHandler = async (formContext, error) => {
    var _a, _b, _c;
    const message = error.message || ((_c = (_b = (_a = formContext.locale) === null || _a === void 0 ? void 0 : _a.sharedFormLocales) === null || _b === void 0 ? void 0 : _b.errors) === null || _c === void 0 ? void 0 : _c.wildCard) || '';
    let openDefaultDialog = true;
    if (formContext === null || formContext === void 0 ? void 0 : formContext.errorCallback)
        openDefaultDialog = !!(await formContext.errorCallback(error, message));
    if (openDefaultDialog)
        formContext.errorMessage = message;
};
const formLoadingHandler = async (formContext, isLoading) => {
    formContext.isLoading = isLoading;
    if (formContext.loadingChanges)
        formContext.loadingChanges(isLoading);
};
const formSuccessHandler = async (formContext, data) => {
    let openDefaultDialog = true;
    if (formContext.successCallback)
        openDefaultDialog = !!(await formContext.successCallback(data, formContext.locale['Form submitted successfully.'] || ''));
    if (openDefaultDialog)
        formContext.form.openDialog();
    if (!formContext.disableScrollToTop) {
        const formDom = formContext.el.shadowRoot || formContext.el;
        let targetElement = formDom instanceof ShadowRoot ? formDom.firstElementChild : formDom;
        const yOffset = -100;
        const y = targetElement.getBoundingClientRect().top + window.pageYOffset + yOffset;
        window.scrollTo({ top: Math.max(y, 0), behavior: 'smooth' });
    }
};
const formDidLoadHandler = async (formContext, validator) => {
    var _a, _b;
    if (!formContext.structure) {
        if (formContext.gistId) {
            const [newGistStructure] = await Promise.all([gistLoader(formContext.gistId), formContext.changeLanguage(formContext.language)]);
            formContext.structure = newGistStructure;
        }
        else if (formContext.structureUrl) {
            const [newGistStructure] = await Promise.all([fetchJson(formContext.structureUrl), formContext.changeLanguage(formContext.language)]);
            formContext.structure = newGistStructure;
        }
    }
    formContext.localeLanguage = formContext.language;
    await formContext.changeLanguage(formContext.language);
    if (!formContext.isMobileForm) {
        try {
            const key = (_b = (_a = formContext.structure) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.recaptchaKey;
            if (key) {
                const script = document.createElement('script');
                script.src = `https://www.google.com/recaptcha/api.js?render=${key}&hl=${formContext.language}`;
                script.async = true;
                script.defer = true;
                document.head.appendChild(script);
            }
        }
        catch (error) {
            console.log(error);
        }
    }
    formContext.form = new FormHook(formContext, validator);
};
const formGetFormHandler = async (formContext) => {
    if (formContext.form)
        return formContext.form;
};
const handleFormSubmit = async (formContext) => {
    if (formContext.form)
        return formContext.form.submit();
};
const formStructureRenderedHandler = async (formContext, isRendered) => {
    var _a;
    if (isRendered)
        (_a = formContext.formReadyCallback) === null || _a === void 0 ? void 0 : _a.call(formContext);
};
const marketingQueryParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
const getMarketingValues = (structure) => {
    var _a;
    if ((_a = structure === null || structure === void 0 ? void 0 : structure.data) === null || _a === void 0 ? void 0 : _a.disableUTMLog)
        return {};
    const params = new URLSearchParams(window.location.search);
    if (typeof params.get('disable_utm_log') === 'string' && params.get('disable_utm_log') === 'true')
        return {};
    const marketingValues = {};
    marketingQueryParams.forEach(param => {
        if (!!params.get(param))
            marketingValues[param] = params.get(param);
    });
    return marketingValues;
};
const onFormSubmit = async ({ context, formValues, middleware, afterSuccess }) => {
    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, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12;
    try {
        context.setIsLoading(true);
        Object.keys(formValues).forEach(key => {
            if (context[`${key}-format`]) {
                formValues[key] = context[`${key}-format`];
            }
        });
        const hasAdditionalData = !!((_b = (_a = context.structure) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.truncatedFields) && !!((_e = Object.keys((_d = (_c = context.structure) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.truncatedFields)) === null || _e === void 0 ? void 0 : _e.length);
        let additionalData = {};
        const marketingValues = getMarketingValues(context === null || context === void 0 ? void 0 : context.structure);
        let payload = Object.assign({}, formValues);
        if ((_g = (_f = context.structure) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.extraPayload)
            payload = Object.assign(Object.assign({}, payload), (_j = (_h = context.structure) === null || _h === void 0 ? void 0 : _h.data) === null || _j === void 0 ? void 0 : _j.extraPayload);
        if (hasAdditionalData)
            payload.additionalData = Object.assign({}, additionalData);
        if (!!(context === null || context === void 0 ? void 0 : context.extraPayload))
            payload = Object.assign(Object.assign({}, payload), context === null || context === void 0 ? void 0 : context.extraPayload);
        if (hasAdditionalData) {
            Object.entries((_l = (_k = context.structure) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.truncatedFields).forEach(([oldKey, truncateValue]) => {
                if (Array.isArray(truncateValue)) {
                    let constructNewValue = '';
                    truncateValue.forEach(key => {
                        constructNewValue += payload[key.toString()] || key.toString();
                    });
                    payload = Object.assign(Object.assign({}, payload), { [oldKey]: constructNewValue });
                }
                else if (typeof truncateValue === 'string' && truncateValue) {
                    if (oldKey.startsWith('parse date: ')) {
                        let tempKey = oldKey.replaceAll('parse date: ', '');
                        payload[tempKey] = dateFnsExports.parse(payload[tempKey], truncateValue, new Date());
                    }
                    else if (oldKey.startsWith('format date: ')) {
                        let tempKey = oldKey.replaceAll('format date: ', '');
                        payload[tempKey] = dateFnsExports.formatISO(payload[tempKey]);
                    }
                    else {
                        additionalData[truncateValue] = payload[oldKey];
                        delete payload[oldKey];
                    }
                }
            });
        }
        let header = {
            'Content-Type': 'application/json',
            'Brand': (_o = (_m = context.structure) === null || _m === void 0 ? void 0 : _m.data) === null || _o === void 0 ? void 0 : _o.brandId,
            'Accept-Language': context.localeLanguage || 'en',
        };
        if (!!(context === null || context === void 0 ? void 0 : context.extraHeader))
            header = Object.assign(Object.assign({}, header), context === null || context === void 0 ? void 0 : context.extraHeader);
        if (!!((_q = (_p = context.structure) === null || _p === void 0 ? void 0 : _p.data) === null || _q === void 0 ? void 0 : _q.extraHeader))
            header = Object.assign(Object.assign({}, header), (_s = (_r = context.structure) === null || _r === void 0 ? void 0 : _r.data) === null || _s === void 0 ? void 0 : _s.extraHeader);
        let requestEndpoint = '';
        if (context.isMobileForm) {
            const token = await context.getMobileToken();
            if (token.toLowerCase().startsWith('bearer')) {
                header['Authorization'] = token;
                requestEndpoint = (_u = (_t = context.structure) === null || _t === void 0 ? void 0 : _t.data) === null || _u === void 0 ? void 0 : _u.requestAppUrl;
            }
            else {
                header['verification-token'] = token;
                requestEndpoint = (_w = (_v = context.structure) === null || _v === void 0 ? void 0 : _v.data) === null || _w === void 0 ? void 0 : _w.requestAppCheckUrl;
            }
        }
        else {
            requestEndpoint = (_y = (_x = context.structure) === null || _x === void 0 ? void 0 : _x.data) === null || _y === void 0 ? void 0 : _y.requestUrl;
            if ((_0 = (_z = context.structure) === null || _z === void 0 ? void 0 : _z.data) === null || _0 === void 0 ? void 0 : _0.recaptchaKey) {
                const token = await grecaptcha.execute((_2 = (_1 = context.structure) === null || _1 === void 0 ? void 0 : _1.data) === null || _2 === void 0 ? void 0 : _2.recaptchaKey, { action: 'submit' });
                header['Recaptcha-Token'] = token;
            }
        }
        if (context.isDev)
            requestEndpoint = requestEndpoint.replaceAll('production=true', 'production=false');
        if (!requestEndpoint) {
            throw new Error('Request endpoint is not configured');
        }
        const method = ((_4 = (_3 = context.structure) === null || _3 === void 0 ? void 0 : _3.data) === null || _4 === void 0 ? void 0 : _4.requestMethod) || 'POST';
        if (['get', 'head'].includes(method.toLowerCase()))
            header = Object.assign(Object.assign({}, header), marketingValues);
        else
            payload = Object.assign(Object.assign({}, payload), marketingValues);
        if (middleware) {
            const middlewareRes = middleware(payload, header, requestEndpoint);
            payload = Object.assign({}, middlewareRes.payload);
            header = Object.assign({}, middlewareRes.header);
            requestEndpoint = middlewareRes.url;
        }
        Object.values(context.form.pendingRequests).forEach(async (req) => {
            try {
                await req();
            }
            catch (error) {
                console.error(error);
            }
        });
        const response = await fetch(requestEndpoint, Object.assign({ headers: header, method: ((_6 = (_5 = context.structure) === null || _5 === void 0 ? void 0 : _5.data) === null || _6 === void 0 ? void 0 : _6.requestMethod) || 'POST' }, (((_9 = (_8 = (_7 = context.structure) === null || _7 === void 0 ? void 0 : _7.data) === null || _8 === void 0 ? void 0 : _8.requestMethod) === null || _9 === void 0 ? void 0 : _9.toLowerCase()) === 'get' ? {} : { body: JSON.stringify(payload) })));
        if (response.ok) {
            const result = await response.json().catch(() => ({}));
            if (afterSuccess)
                await afterSuccess(payload, header);
            context.setSuccessCallback(result);
            setTimeout(() => {
                context.form.reset();
                context.form.rerender({ rerenderForm: true, rerenderAll: true });
            }, 100);
        }
        else {
            const contentType = response.headers.get('content-type') || '';
            const errorText = contentType.includes('application/json') ? ((_12 = (_11 = (_10 = (await response.json().catch(() => ({})))) === null || _10 === void 0 ? void 0 : _10.message) === null || _11 === void 0 ? void 0 : _11.body) !== null && _12 !== void 0 ? _12 : '') : await response.text().catch(() => '');
            throw new Error(errorText);
        }
    }
    catch (error) {
        console.error(error);
        context.setErrorCallback(error);
    }
    finally {
        context.setIsLoading(false);
    }
};
const functionHooks = {
    formLanguageChange,
    formErrorHandler,
    handleFormSubmit,
    formLoadingHandler,
    formSuccessHandler,
    formDidLoadHandler,
    formGetFormHandler,
    onFormSubmit,
    formStructureRenderedHandler,
};

export { formLanguageChange as a, formLoadingHandler as b, formErrorHandler as c, formSuccessHandler as d, formDidLoadHandler as e, functionHooks as f, getMarketingValues as g, formGetFormHandler as h, handleFormSubmit as i, formStructureRenderedHandler as j };
