/**
 * @license MIT
 * Snippet Manager for TinyMCE 6 & 7
 * Developed by Gerits Aurélien (https://www.gerits-aurelien.be)
 * Copyright (c) 2026, Magix CMS.
 * Version 1.0
 */
tinymce.PluginManager.requireLangPack("snippets");
tinymce.PluginManager.add('snippets', function (editor, url) {

    const _ = (text) => editor.translate(text);

    const openSnippetModal = () => {
        const endpoint = editor.getParam('snippets_url');
        if (!endpoint) {
            editor.notificationManager.open({
                text: _('Error: snippets_url not configured.'),
                type: 'error'
            });
            return;
        }

        editor.setProgressState(true);

        fetch(endpoint)
            .then(response => response.json())
            .then(allSnippets => {
                editor.setProgressState(false);

                // UID unique pour gérer les doublons de noms
                const snippetsWithId = allSnippets.map((s, i) => ({
                    ...s,
                    uid: s.id ? s.id.toString() : `snip-${i}`
                }));

                let currentFiltered = snippetsWithId;

                const loadPreview = (snippet) => {
                    const iframe = document.getElementById('snippet-preview-iframe');
                    if (!iframe || !snippet) return;

                    fetch(snippet.url).then(res => res.text()).then(html => {
                        const doc = iframe.contentDocument || iframe.contentWindow.document;
                        doc.documentElement.innerHTML = "";

                        const contentCss = editor.getParam('content_css');
                        let cssLinks = '';
                        if (contentCss) {
                            const cssFiles = Array.isArray(contentCss) ? contentCss : contentCss.split(',');
                            cssFiles.forEach(file => {
                                if(file.trim() !== "") cssLinks += `<link rel="stylesheet" href="${file.trim()}">`;
                            });
                        }

                        doc.head.innerHTML = `${cssLinks}<style>body{padding:15px;background:#fff;margin:0;font-family:sans-serif;}img{max-width:100%;height:auto;}</style>`;
                        doc.body.innerHTML = html;
                    });
                };

                const getDialogConfig = (items) => ({
                    title: _('Snippet Library'),
                    size: 'large',
                    body: {
                        type: 'panel',
                        items: [
                            {
                                type: 'input',
                                name: 'searchQuery',
                                label: _('Search (Title or Description)'),
                                placeholder: _('Filter snippets...')
                            },
                            {
                                type: 'selectbox',
                                name: 'snippetUid',
                                label: _('Found snippets ({0})').replace('{0}', items.length),
                                items: items.map(item => ({
                                    text: item.description ? `${item.title} (${item.description})` : item.title,
                                    value: item.uid
                                }))
                            },
                            {
                                type: 'htmlpanel',
                                html: '<div style="border:1px solid #ddd; background:#fff; border-radius:3px; overflow:hidden;"><iframe id="snippet-preview-iframe" style="width:100%; height:380px; border:none; display:block;"></iframe></div>'
                            }
                        ]
                    },
                    buttons: [
                        { type: 'cancel', text: _('Cancel') },
                        { type: 'submit', text: _('Insert'), primary: true }
                    ],
                    onChange: (api, details) => {
                        const data = api.getData();

                        if (details.name === 'searchQuery') {
                            const query = data.searchQuery.toLowerCase();
                            currentFiltered = snippetsWithId.filter(s =>
                                s.title.toLowerCase().includes(query) ||
                                (s.description && s.description.toLowerCase().includes(query))
                            );

                            api.redial(getDialogConfig(currentFiltered));
                            api.setData({ searchQuery: data.searchQuery });

                            if (currentFiltered.length > 0) {
                                loadPreview(currentFiltered[0]);
                            } else {
                                const iframe = document.getElementById('snippet-preview-iframe');
                                if (iframe) {
                                    const doc = iframe.contentDocument || iframe.contentWindow.document;
                                    doc.body.innerHTML = `<div style="padding:20px;text-align:center;color:#666;"><em>${_('No matching snippets found.')}</em></div>`;
                                }
                            }
                        }

                        if (details.name === 'snippetUid') {
                            const selected = currentFiltered.find(s => s.uid === data.snippetUid);
                            if (selected) loadPreview(selected);
                        }
                    },
                    onSubmit: (api) => {
                        const iframe = document.getElementById('snippet-preview-iframe');
                        if (iframe) {
                            const doc = iframe.contentDocument || iframe.contentWindow.document;
                            editor.insertContent(doc.body.innerHTML);
                        }
                        api.close();
                    }
                });

                editor.windowManager.open(getDialogConfig(snippetsWithId));
                if (snippetsWithId.length > 0) loadPreview(snippetsWithId[0]);
            })
            .catch(err => {
                editor.setProgressState(false);
                console.error("Snippets error:", err);
            });
    };

    // Raccourcis et Enregistrement
    editor.addShortcut('meta+shift+s', _('Open Snippets'), openSnippetModal);

    editor.ui.registry.addButton('snippets', {
        icon: 'template',
        tooltip: _('Insert snippet'),
        onAction: openSnippetModal
    });

    editor.ui.registry.addMenuItem('snippets', {
        text: _('Snippet...'),
        icon: 'template',
        shortcut: 'Meta+Shift+S',
        onAction: openSnippetModal
    });

    return {
        getMetadata: () => ({
            name: "Snippet Manager Pro",
            url: "https://www.gerits-aurelien.be",
            author: "Gerits Aurélien",
            version: "1.1.2"
        })
    };
});