// Define the mapping from Sitecore button names to Slate options
const SITECORE_TO_SLATE_MAPPING = {
    // Text formatting marks
    Bold: { type: "mark", id: "bold" },
    Italic: { type: "mark", id: "italic" },
    Underline: { type: "mark", id: "underline" },
    StrikeThrough: { type: "mark", id: "strikethrough" },
    Subscript: { type: "mark", id: "subscript" },
    Superscript: { type: "mark", id: "superscript" },
    // Custom headline marks
    Extrabold: { type: "mark", id: "extrabold" },
    // Alignment options
    JustifyLeft: { type: "alignment", id: "left" },
    JustifyCenter: { type: "alignment", id: "center" },
    JustifyRight: { type: "alignment", id: "right" },
    JustifyFull: { type: "alignment", id: "justify" },
    JustifyNone: { type: "alignment", id: "left" }, // Default to left
    // Block formats
    InsertOrderedList: { type: "list", id: "ordered-list" },
    InsertUnorderedList: { type: "list", id: "unordered-list" },
    Indent: null,
    Outdent: null,
    FormatBlock: { type: "block", id: "paragraph" },
    // Additional block format options that might come from Sitecore
    Paragraph: { type: "block", id: "paragraph" },
    PlainText: { type: "block", id: "no-tag" },
    plaintext: { type: "block", id: "no-tag" }, // Handle lowercase version from option headers
    NoTag: { type: "block", id: "no-tag" },
    Heading1: { type: "block", id: "heading-1" },
    Heading2: { type: "block", id: "heading-2" },
    Heading3: { type: "block", id: "heading-3" },
    Heading4: { type: "block", id: "heading-4" },
    Heading5: { type: "block", id: "heading-5" },
    Heading6: { type: "block", id: "heading-6" },
    // Links
    InsertSitecoreLink: { type: "link", id: "link" }, // Internal/External link
    InsertCustomLink: null, // Basic external link
    Unlink: null,
    // Line breaks - handled by Shift+Enter, not as a button
    ManualLineBreak: null, // Handled by keyboard shortcut
    // Colors (future enhancement - not implemented yet)
    ForeColor: null, // { type: 'color', id: 'text-color' },
    BackColor: null, // { type: 'color', id: 'background-color' },
    // Typography (future enhancement - not implemented yet)
    FontName: null, // { type: 'font', id: 'font-family' },
    FontSize: null, // { type: 'font', id: 'font-size' },
    // Special UI elements
    Divider: { type: "divider", id: "divider" },
    Print: null,
    FindAndReplace: null,
    Cut: null,
    Copy: null,
    Paste: null,
    PasteFromWord: null,
    PasteFromWordNoFontsNoSizes: null,
    PastePlainText: null,
    PasteAsHtml: null,
    FormatStripper: null,
    Undo: null,
    Redo: null,
    InsertSitecoreMedia: null,
    LinkManager: null,
    InsertTable: null,
    InsertFormElement: null,
    InsertParagraph: null,
    InsertDate: null,
    InsertTime: null,
    InsertSymbol: null,
    InsertSnippet: null,
    InsertHorizontalRule: null, //{ type: 'insertion', id: 'horizontal-rule' },
    ToggleTableBorder: null,
    ModuleManager: null,
    AjaxSpellCheck: null,
    XhtmlValidator: null,
    Help: null,
    ApplyClass: null,
    SelectAll: null,
    AbsolutePosition: null,
    MediaManager: null,
    FlashManager: null,
    Zoom: null,
    // Schott SXA
    AddMAsset: null,
    InsertContentToken: null,
};
/**
 * Cleans up dividers in an options array by removing consecutive dividers and dividers at start/end
 */
function cleanupDividers(options) {
    if (options.length === 0)
        return options;
    const cleaned = [];
    for (let i = 0; i < options.length; i++) {
        const option = options[i];
        if (!option)
            continue;
        // Skip dividers at the start
        if (option.type === "divider" && cleaned.length === 0) {
            continue;
        }
        // Skip consecutive dividers
        const lastOption = cleaned[cleaned.length - 1];
        if (option.type === "divider" &&
            cleaned.length > 0 &&
            lastOption &&
            lastOption.type === "divider") {
            continue;
        }
        cleaned.push(option);
    }
    // Remove divider at the end if present
    const lastOption = cleaned[cleaned.length - 1];
    if (cleaned.length > 0 && lastOption && lastOption.type === "divider") {
        cleaned.pop();
    }
    return cleaned;
}
/**
 * Maps a Sitecore rich text profile to a Slate editor profile
 */
export function mapSitecoreProfileToSlate(sitecoreProfile, optionFolders = []) {
    const groups = [];
    const specialButtons = {
        alignment: new Set(),
        block: new Set(),
    };
    const unsupportedButtons = new Set();
    // Track whether we've processed Paragraphs options
    let hasParagraphsButton = false;
    sitecoreProfile.forEach((toolbar, toolbarIndex) => {
        const rowGroups = [];
        const rawOptions = [];
        toolbar.buttons.forEach((button) => {
            // Handle special "Paragraphs" button
            if (button.name === "Paragraphs") {
                hasParagraphsButton = true;
                const paragraphsFolder = optionFolders.find((folder) => folder.name === "Paragraphs");
                if (paragraphsFolder && paragraphsFolder.options.length > 0) {
                    const paragraphOptions = paragraphsFolder.options
                        .map((option) => {
                        // Try to find mapping for the header (first try as-is, then lowercase)
                        const mappedOption = SITECORE_TO_SLATE_MAPPING[option.header] ||
                            SITECORE_TO_SLATE_MAPPING[option.header.toLowerCase()];
                        return mappedOption
                            ? { type: mappedOption.type, id: mappedOption.id }
                            : null;
                    })
                        .filter((option) => option !== null);
                    if (paragraphOptions.length > 0) {
                        // Add paragraphs dropdown to the row
                        rowGroups.push({
                            id: `paragraphs-${toolbarIndex}`,
                            label: "Format",
                            display: "dropdown",
                            showIconsOnly: false,
                            options: paragraphOptions,
                            row: toolbarIndex,
                        });
                    }
                }
                return; // Skip normal processing for Paragraphs button
            }
            const mappedOption = SITECORE_TO_SLATE_MAPPING[button.name];
            if (mappedOption) {
                if (mappedOption.type === "alignment") {
                    specialButtons.alignment.add(mappedOption.id);
                }
                else if (mappedOption.type === "block") {
                    specialButtons.block.add(mappedOption.id);
                }
                else {
                    rawOptions.push(mappedOption);
                }
            }
            else if (!SITECORE_TO_SLATE_MAPPING.hasOwnProperty(button.name)) {
                unsupportedButtons.add(button.name);
            }
        });
        const cleanedOptions = cleanupDividers(rawOptions);
        // Add buttons group if there are any buttons
        if (cleanedOptions.length > 0) {
            rowGroups.push({
                id: `toolbar-${toolbarIndex}`,
                label: `Toolbar ${toolbarIndex + 1}`,
                display: "buttons",
                showIconsOnly: true,
                options: cleanedOptions,
                row: toolbarIndex,
            });
        }
        // Add all groups for this toolbar row
        groups.push(...rowGroups);
    });
    // Process Paragraphs options even if there was no Paragraphs button
    if (!hasParagraphsButton) {
        const paragraphsFolder = optionFolders.find((folder) => folder.name === "Paragraphs");
        if (paragraphsFolder && paragraphsFolder.options.length > 0) {
            paragraphsFolder.options.forEach((option) => {
                // Try to find mapping for the header (first try as-is, then lowercase)
                const mappedOption = SITECORE_TO_SLATE_MAPPING[option.header] ||
                    SITECORE_TO_SLATE_MAPPING[option.header.toLowerCase()];
                if (mappedOption && mappedOption.type === "block") {
                    specialButtons.block.add(mappedOption.id);
                }
            });
        }
    }
    // Create dropdown groups for special button types
    const dropdownGroups = [
        {
            condition: specialButtons.block.size > 0,
            id: "format-group",
            label: "",
            showIconsOnly: false,
            order: [
                "paragraph",
                "no-tag",
                "heading-1",
                "heading-2",
                "heading-3",
                "heading-4",
                "heading-5",
                "heading-6",
            ],
            buttons: specialButtons.block,
            type: "block",
            prepend: true,
        },
        {
            condition: specialButtons.alignment.size > 0,
            id: "alignment-group",
            label: "",
            showIconsOnly: true,
            order: ["left", "center", "right", "justify"],
            buttons: specialButtons.alignment,
            type: "alignment",
            prepend: false,
        },
    ];
    dropdownGroups.forEach((group) => {
        if (group.condition) {
            const options = group.order
                .filter((item) => group.buttons.has(item))
                .map((item) => ({ type: group.type, id: item }));
            const groupConfig = {
                id: group.id,
                label: group.label,
                display: "dropdown",
                showIconsOnly: group.showIconsOnly,
                options: options,
                row: group.prepend ? -1 : 1000, // Put prepend groups first, append groups last
            };
            if (group.prepend) {
                groups.unshift(groupConfig);
            }
            else {
                groups.push(groupConfig);
            }
        }
    });
    if (unsupportedButtons.size > 0) {
        console.warn("Unsupported Sitecore buttons found:", Array.from(unsupportedButtons).join(", "));
    }
    return {
        toolbar: {
            groups: groups,
        },
    };
}
/**
 * Maps a Sitecore profile JSON string to a Slate editor profile
 */
export function mapSitecoreProfileJsonToSlate(profileJson) {
    // Add input validation
    if (!profileJson || typeof profileJson !== "string") {
        console.error("Invalid profile JSON input:", profileJson);
        return null;
    }
    if (profileJson.trim().length === 0) {
        console.error("Empty profile JSON string");
        return null;
    }
    try {
        const parsed = JSON.parse(profileJson);
        // Handle both formats: direct array or wrapped in toolbars property
        let sitecoreProfile;
        let optionFolders = [];
        if (Array.isArray(parsed)) {
            // Old format: direct array
            sitecoreProfile = parsed;
        }
        else if (parsed.toolbars && Array.isArray(parsed.toolbars)) {
            // New format: wrapped in toolbars property
            sitecoreProfile = parsed.toolbars;
            optionFolders = parsed.options || [];
        }
        else {
            console.error("Invalid Sitecore profile format:", parsed);
            return null;
        }
        // Validate the structure
        if (!sitecoreProfile.every((toolbar) => toolbar.buttons && Array.isArray(toolbar.buttons))) {
            console.error("Invalid toolbar structure in Sitecore profile");
            return null;
        }
        return mapSitecoreProfileToSlate(sitecoreProfile, optionFolders);
    }
    catch (error) {
        console.error("Failed to parse Sitecore profile JSON:", error);
        console.error("Raw profile JSON length:", profileJson.length);
        console.error("Raw profile JSON preview:", profileJson.substring(0, 200) + (profileJson.length > 200 ? "..." : ""));
        console.error("Raw profile JSON ending:", profileJson.length > 200
            ? "..." + profileJson.substring(profileJson.length - 200)
            : profileJson);
        // Try to determine if it's a truncation issue
        if (error instanceof SyntaxError &&
            error.message.includes("Unexpected end of JSON input")) {
            console.error("This appears to be a truncated JSON string. Check the caching implementation.");
        }
        return null;
    }
}
/**
 * Creates a debug profile with ALL available options for testing
 * - All text formatting marks (including custom ones)
 * - All block formats
 * - All list options
 * - All alignment options
 * - All link options
 * - Visual dividers for grouping
 */
export function getDebugProfile() {
    return {
        toolbar: {
            groups: [
                {
                    id: "all-marks",
                    label: "",
                    display: "buttons",
                    showIconsOnly: false,
                    options: [
                        { type: "mark", id: "bold" },
                        { type: "mark", id: "italic" },
                        { type: "mark", id: "underline" },
                        { type: "mark", id: "strikethrough" },
                        { type: "mark", id: "subscript" },
                        { type: "mark", id: "superscript" },
                        { type: "divider", id: "divider" },
                        { type: "mark", id: "extrabold" },
                    ],
                },
                {
                    id: "all-blocks",
                    label: "",
                    display: "dropdown",
                    showIconsOnly: false,
                    options: [
                        { type: "block", id: "no-tag" },
                        { type: "block", id: "paragraph" },
                        { type: "block", id: "heading-1" },
                        { type: "block", id: "heading-2" },
                        { type: "block", id: "heading-3" },
                        { type: "block", id: "heading-4" },
                        { type: "block", id: "heading-5" },
                        { type: "block", id: "heading-6" },
                    ],
                },
                {
                    id: "all-lists",
                    label: "",
                    display: "buttons",
                    showIconsOnly: false,
                    options: [
                        { type: "list", id: "unordered-list" },
                        { type: "list", id: "ordered-list" },
                    ],
                },
                {
                    id: "all-alignment",
                    label: "",
                    display: "dropdown",
                    showIconsOnly: false,
                    options: [
                        { type: "alignment", id: "left" },
                        { type: "alignment", id: "center" },
                        { type: "alignment", id: "right" },
                        { type: "alignment", id: "justify" },
                    ],
                },
                {
                    id: "all-links",
                    label: "",
                    display: "buttons",
                    showIconsOnly: false,
                    options: [{ type: "link", id: "link" }],
                },
            ],
        },
    };
}
//# sourceMappingURL=profileMapper.js.map