import tinymce from 'tinymce';

import 'tinymce/icons/default';
import 'tinymce/themes/silver';
import 'tinymce/models/dom';

import 'tinymce/plugins/advlist';
import 'tinymce/plugins/autolink';
import 'tinymce/plugins/charmap';
import 'tinymce/plugins/code';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/table';
import 'tinymce/plugins/wordcount';

import 'tinymce/skins/ui/oxide/skin.min.css';
// content CSS belongs in the editor iframe (via content_style / content_css),
// not as a global page stylesheet.

const SELECTOR = 'textarea.js-tinymce';

function initHelpArticleEditors(): void {
    const targets = document.querySelectorAll(SELECTOR);
    if (targets.length === 0) {
        return;
    }

    void tinymce.init({
        selector: SELECTOR,
        height: 480,
        menubar: false,
        branding: false,
        promotion: false,
        skin: false,
        content_css: false,
        plugins: 'advlist autolink lists link charmap table code wordcount',
        toolbar:
            'undo redo | blocks | bold italic underline | alignleft aligncenter alignright | ' +
            'bullist numlist outdent indent | link table | removeformat | code',
        block_formats: 'Paragraph=p; Heading 2=h2; Heading 3=h3; Heading 4=h4',
        valid_elements:
            'p,br,strong/b,em/i,u,ul,ol,li,h2,h3,h4,blockquote,pre,code,table,thead,tbody,tr,th,td,' +
            'a[href|title|target|rel],img[src|alt|title|width|height|loading|class],hr,div[class|id],span[class],figure,figcaption',
        extended_valid_elements: 'div[class|id],span[class]',
        convert_urls: false,
        relative_urls: false,
        entity_encoding: 'raw',
        content_style:
            'body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; font-size: 15px; line-height: 1.55; }' +
            'h2,h3,h4 { font-weight: 600; }' +
            'img { max-width: 100%; height: auto; }',
        setup: (editor) => {
            editor.on('change input undo redo', () => {
                editor.save();
            });
        },
    });

    document.querySelectorAll('form').forEach((form) => {
        form.addEventListener('submit', () => {
            tinymce.triggerSave();
        });
    });
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initHelpArticleEditors);
} else {
    initHelpArticleEditors();
}
