/**
 * CKEditor 4 initialization for Viartas CMS
 *
 * Auto-initializes CKEditor on all textarea.cked elements.
 * Supports Laravel File Manager (LFM) for image browsing/upload.
 *
 * Two profiles, selectable via `data-ckeditor-profile` attribute on the textarea:
 *   - "admin"  (default) — full markup: iframes, tables, divs/spans/styles.
 *                          Pair with Purifier 'cms-admin' on the backend.
 *   - "strict" — restricted whitelist; no iframes/scripts/styles.
 *                Pair with Purifier 'cms-strict' on the backend.
 *
 * Other data attributes:
 *   data-toolbar="full|standard|basic"  (default depends on profile)
 *   data-height="300"
 *   data-locale="lt" (optional — used for translatable fields)
 */
(function() {
    'use strict';

    if (typeof CKEDITOR === 'undefined') {
        console.warn('CKEditor not loaded — skipping WYSIWYG initialization');
        return;
    }

    // Global CKEditor settings — apply regardless of profile.
    CKEDITOR.config.enterMode = CKEDITOR.ENTER_P;
    CKEDITOR.config.entities = false;
    CKEDITOR.config.entities_latin = false;
    CKEDITOR.config.entities_greek = false;
    CKEDITOR.config.youtube_related = false;
    CKEDITOR.config.youtube_controls = true;
    CKEDITOR.config.youtube_privacy = true;

    var csrfMeta = document.querySelector('meta[name="csrf-token"]');
    var csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';
    var lfmFallback = '/admin/laravel-filemanager';

    function lfmBase() {
        return (window.Viartas && window.Viartas.lfmUrl) || lfmFallback;
    }

    // Toolbar presets — shared by both profiles.
    var toolbars = {
        full: [
            { name: 'clipboard', groups: ['clipboard', 'undo'] },
            { name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
            { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align'] },
            { name: 'links' },
            { name: 'insert' },
            '/',
            { name: 'styles' },
            { name: 'colors' },
            { name: 'tools' },
            { name: 'document', groups: ['mode'] }
        ],
        standard: [
            { name: 'clipboard', groups: ['clipboard', 'undo'] },
            { name: 'basicstyles', groups: ['basicstyles'] },
            { name: 'paragraph', groups: ['list', 'align'] },
            { name: 'links' },
            { name: 'insert' }
        ],
        basic: [
            { name: 'basicstyles', groups: ['basicstyles'] },
            { name: 'paragraph', groups: ['list'] },
            { name: 'links' }
        ]
    };

    // Profile-specific overrides. Backend Purifier ('cms-strict' / 'cms-admin')
    // is the source of truth for what's actually persisted — these client-side
    // limits are the editor UX layer.
    var profiles = {
        strict: {
            extraAllowedContent:
                'p; h1; h2; h3; h4; h5; h6; ul; ol; li; strong; em;'
                + ' a[href|title|target|rel]; blockquote; code; pre;'
                + ' img[src|alt|title|width|height]',
            removePlugins: 'iframe',
            extraPlugins: 'image2,justify',
            defaultToolbar: 'standard'
        },
        admin: {
            extraAllowedContent: 'iframe[*]; div[*]; span[*]; img[*]{*}',
            removePlugins: '',
            extraPlugins: 'image2,justify,colorbutton,font,iframe,youtube',
            defaultToolbar: 'full'
        }
    };

    /**
     * Initialize CKEditor on a single textarea element.
     */
    function initEditor(el) {
        if (el.getAttribute('data-cked-initialized')) return;
        el.setAttribute('data-cked-initialized', 'true');

        var profileName = el.getAttribute('data-ckeditor-profile') || 'admin';
        var profile = profiles[profileName] || profiles.admin;

        var toolbar = el.getAttribute('data-toolbar') || profile.defaultToolbar;
        var height = parseInt(el.getAttribute('data-height')) || 300;
        var skin = 'n1theme,/vendor/ckeditor/skins/n1theme/';
        var lfm = lfmBase();

        var config = {
            skin: skin,
            height: height,
            language: document.documentElement.lang || 'lt',
            toolbarGroups: toolbars[toolbar] || toolbars[profile.defaultToolbar],
            removeButtons: 'Subscript,Superscript,About',
            format_tags: 'p;h1;h2;h3;h4;pre',
            pasteFromWordRemoveFontStyles: true,
            pasteFromWordRemoveStyles: true,
            extraAllowedContent: profile.extraAllowedContent,
            removePlugins: profile.removePlugins,
            extraPlugins: profile.extraPlugins,
            // LFM integration — URL injected via window.Viartas.lfmUrl.
            filebrowserBrowseUrl:        lfm + '?type=Files',
            filebrowserImageBrowseUrl:   lfm + '?type=Images',
            filebrowserUploadUrl:        lfm + '/upload?type=Files&_token=' + csrfToken,
            filebrowserImageUploadUrl:   lfm + '/upload?type=Images&_token=' + csrfToken
        };

        CKEDITOR.replace(el, config);
    }

    /**
     * Initialize all .cked textareas on page (skipping ones hidden by Alpine x-show).
     */
    function initAll() {
        document.querySelectorAll('textarea.cked').forEach(function(el) {
            var parent = el.closest('[x-show]');
            if (parent && parent.style.display === 'none') {
                return; // Will be initialized when locale switches.
            }
            initEditor(el);
        });
    }

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

    // Re-init when Alpine reveals previously hidden translatable editors.
    document.addEventListener('click', function(e) {
        var btn = e.target.closest('.lang-btn, .va-locale-btn');
        if (!btn) return;
        setTimeout(function() {
            document.querySelectorAll('textarea.cked:not([data-cked-initialized])').forEach(function(el) {
                var parent = el.closest('[x-show]');
                if (parent && parent.style.display !== 'none') {
                    initEditor(el);
                }
            });
        }, 100);
    });

    // Expose for manual init.
    window.ViartasCKEditor = {
        init: initEditor,
        initAll: initAll,
        profiles: profiles
    };

})();
