{# Reusable TinyMCE bootstrap. Pass `selector` and `allow_images` (bool) #}
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
    tinymce.init({
        selector: '{{ selector|default('#editor') }}',
        height: {{ height|default(380) }},
        menubar: {{ menubar|default(false) ? 'true' : 'false' }},
        plugins: 'lists link {% if allow_images|default(false) %}image media table code preview searchreplace{% endif %} autolink autoresize',
        toolbar: 'undo redo | blocks | bold italic underline | bullist numlist | link {% if allow_images|default(false) %}image media table | code preview{% endif %}',
        branding: false,
        promotion: false,
        skin: 'oxide',
        statusbar: false,
        relative_urls: false,
        remove_script_host: false,
        convert_urls: true,
        {% if allow_images|default(false) %}
        images_upload_url: '{{ app_url('/uploads/image') }}',
        images_upload_credentials: true,
        images_reuse_filename: true,
        automatic_uploads: true,
        paste_data_images: true,
        file_picker_types: 'image',
        images_upload_handler: function (blobInfo, progress) {
            return new Promise((resolve, reject) => {
                const fd = new FormData();
                fd.append('file', blobInfo.blob(), blobInfo.filename());
                fd.append('_csrf', '{{ csrf_token() }}');
                fetch('{{ app_url('/uploads/image') }}', {
                    method: 'POST',
                    body: fd,
                    credentials: 'same-origin',
                }).then(async r => {
                    if (!r.ok) {
                        const err = await r.json().catch(() => ({}));
                        return reject(err.error || 'Upload failed');
                    }
                    const data = await r.json();
                    resolve(data.location);
                }).catch(e => reject(String(e)));
            });
        },
        {% endif %}
        content_style: 'body { font-family: -apple-system, system-ui, Segoe UI, Roboto, sans-serif; font-size: 15px; line-height: 1.6; color: #1f2937; } p { margin: 0 0 12px; } img { max-width: 100%; height: auto; }',
    });
</script>
