import '../css/mtc_members_messaging.less';
import Vue from 'vue';
import Threads from './Threads.vue';

// Mount Vue to the container element

const threads = new Vue({
  el: '#members_messaging',      // the <div id="vue_environment"></div> in your template
  components: {
    'threads': Threads
  },
  template: '<threads></threads>' // render the component inside the div
});

const initReplyButton = () => {
    const btn = document.querySelector('button[name="reply"]');
    const textarea = wrapper.querySelector('textarea[name="text"]');
    if (!btn) return;

    btn.addEventListener('click', async () => {

        const text = tinymce.get(textarea.id).getContent({ format: 'html' }).trim();

        if (!text) {
            alert('Reply text cannot be empty.');
            return;
        }          
        
        const token = document.querySelector('meta[name="csrf-token"]').content;

        const pathParts = window.location.pathname.split('/');
        const threadUrl = pathParts[pathParts.length - 1];

        try {
            const res = await fetch('/admin/members/messaging/message', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': token,
                },
                body: JSON.stringify({
                    text: text,
                    url: threadUrl
                })
            });

            const data = await res.json();

            if (!data.success) {
                alert(data.message);
                return;
            }

            window.location.reload();
        } catch (err) {
            console.error('Error:', err);
        }
    });
}
    
const initTemplateDropdown = () => {
    const dropdown = document.querySelector('select[name="template-select"]');
    if (!dropdown) return;

    dropdown.addEventListener('change', async (e) => {
        const value = e.target.value;
        if (!value || value === '0') {
            const editor = tinymce.activeEditor;
            if (editor) editor.setContent('');
            return;
        }

        try {
            const res = await fetch(`/admin/members/messaging/template/${encodeURIComponent(value)}`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            if (!res.ok) throw new Error(`Failed to fetch template (HTTP ${res.status})`);

            const data = await res.json();

            if (data.text) {
                tinymce.activeEditor?.setContent(data.text);
            } else {
                console.warn('Template found but no text returned.');
                tinymce.activeEditor?.setContent('');
            }
        } catch (err) {
            console.error('Error fetching template:', err);
        }
    });
};

const initMessagingInteractions = () => {
    if (!window.csrfToken) {
        const csrfMatch = document.cookie.match(/XSRF-TOKEN=([^;]+)/);
        if (csrfMatch) {
            try {
                window.csrfToken = decodeURIComponent(csrfMatch[1]);
            } catch (error) {
                console.warn('Failed to decode XSRF token', error);
            }
        }
    }

    initReplyButton();
    initTemplateDropdown();
};

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initMessagingInteractions, { once: true });
} else {
    initMessagingInteractions();
}

const loadScript = (src) =>
    new Promise((resolve, reject) => {
        const existing = document.querySelector(`script[data-tiny-src="${src}"]`);
        if (existing) {
            if (existing.hasAttribute('data-loaded')) return resolve();
            existing.addEventListener('load', resolve, { once: true });
            existing.addEventListener('error', () => reject(new Error(`Failed to load ${src}`)), { once: true });
            return;
        }

        const tag = document.createElement('script');
        tag.src = src;
        tag.dataset.tinySrc = src;
        tag.onload = () => {
            tag.setAttribute('data-loaded', 'true');
            resolve();
        };
        tag.onerror = () => reject(new Error(`Failed to load ${src}`));
        document.head.appendChild(tag);
    });

const tinyMceSelectors = [
    'textarea.cmstinymce',
    'textarea.tinymce',
    'textarea.tinymce_simple_with_image',
    'textarea.simpletinymce',
    'textarea.linkOnlyTinyMce',
];

const hasTinyMceTarget = () => document.querySelector(tinyMceSelectors.join(', '));

const bootTinyMCE = async () => {
    const targetExists = hasTinyMceTarget();
    if (!targetExists) return;

    console.debug('bootTinyMCE: initialising TinyMCE', {
        readyState: document.readyState,
        targetExists,
    });

    try {
        await loadScript('/core/js/tinymce/tinymce.min.js');
        console.debug('bootTinyMCE: tinymce.min.js loaded');
        await loadScript('/core/js/tinymce/jquery.tinymce.min.js');
        console.debug('bootTinyMCE: jquery.tinymce.min.js loaded');
        await loadScript('/core/js/tinymce.js');
        console.debug('bootTinyMCE: tinymce.js loaded');
    } catch (error) {
        console.error('Failed to load TinyMCE assets:', error);
        return;
    }

    if (window.tinymce && !window.tinymce.baseURL) {
        window.tinymce.baseURL = '/core/js/tinymce';
    }

    window.openFilePicker = window.openFilePicker || function (callback) {
        window.insertMediaToTinyMCE = (url) => callback(url);
        window.open('/admin/media-manager/tinymce', 'Media Manager', 'width=950,height=650');
    };

    window.init_tinymce();
};

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', bootTinyMCE, { once: true });
} else {
    bootTinyMCE();
}
