import EdenCheckbox from "../common/eden-checkbox.js";
function isMetadataMatchesPath(paths, currentPath) {
    if (!paths || paths.length === 0)
        return true;
    return paths.some((path) => {
        const pathStartsWith = path.endsWith("*");
        const pathEndsWith = path.startsWith("*");
        const cleanPath = path.replace(/\*/g, "");
        if (pathStartsWith && pathEndsWith) {
            return currentPath.includes(cleanPath);
        }
        if (pathStartsWith) {
            return currentPath.startsWith(cleanPath);
        }
        if (pathEndsWith) {
            return currentPath.endsWith(cleanPath);
        }
        return currentPath === path;
    });
}
export function filterMetadataByPath(pagesMetadata, currentPath) {
    if (!pagesMetadata)
        return [];
    return pagesMetadata.filter((item) => isMetadataMatchesPath(item.paths, currentPath));
}
export function ensureStructureLangEntry(entryData, currentLang) {
    if (entryData[currentLang])
        return entryData;
    return {
        ...entryData,
        [currentLang]: {
            seo: {},
        },
    };
}
export function formatStructureMetadata(fields, pagesMetadata = []) {
    return Array.from(fields).reduce((acc, field) => {
        const matchingItem = pagesMetadata.find((item) => item.code === field.name);
        if (!matchingItem)
            return acc;
        const { code } = matchingItem;
        if (field instanceof EdenCheckbox) {
            return { ...acc, [code]: field.checked };
        }
        return { ...acc, [code]: field.value };
    }, {});
}
export function initializeStructureMetadata(fields, pagesMetadata = [], metadata) {
    const metadataFields = Array.from(fields);
    if (!pagesMetadata)
        return;
    metadataFields.forEach((field) => {
        if (!metadata) {
            field.setAttribute("checked", "false");
            field.setAttribute("value", "");
            return;
        }
        const item = pagesMetadata.find((meta) => meta.code === field.name);
        if (!item || !field.name)
            return;
        const value = metadata[field.name];
        if (value === undefined) {
            field.setAttribute("checked", "false");
            field.setAttribute("value", "");
            return;
        }
        if (item.type === "checkbox") {
            field.setAttribute("checked", String(value ?? false));
            return;
        }
        field.setAttribute("value", String(value ?? ""));
    });
}
export function isExternalUrl(value) {
    return /^((http|https):\/\/)/.test(value);
}
export function normalizePathBeforeSave(value) {
    return value === "/" ? value : value.replace(/\/$/, "");
}
export function normalizeStructurePathInput(value) {
    return value
        .toLowerCase()
        .normalize("NFD")
        .replace(/^\s+|\s+$/g, "")
        .replace(/[^a-z0-9 \- /]/g, "")
        .replace(/\s+/g, "-")
        .replace(/-+/g, "-");
}
