/**
 * Utility functions for common operations
 */
const Helpers = {
    /**
     * Debounces a function
     * @param {Function} func - The function to debounce
     * @param {number} wait - The wait time in milliseconds
     * @returns {Function} The debounced function
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    /**
     * Formats a date string
     * @param {string|Date} date - The date to format
     * @returns {string} The formatted date string
     */
    formatDate(date) {
        if (!date) return '';
        const d = new Date(date);
        return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
    },

    /**
     * Truncates a string to a specified length
     * @param {string} str - The string to truncate
     * @param {number} length - The maximum length
     * @returns {string} The truncated string
     */
    truncate(str, length) {
        if (!str) return '';
        return str.length > length ? str.substring(0, length) + '...' : str;
    },

    /**
     * Shows a notification message
     * @param {string} message - The message to show
     * @param {string} type - The type of notification (success, error, warning, info)
     */
    showNotification(message, type = 'info') {
        const typeIcons = {
            success: 'bi bi-check-circle',
            error: 'bi bi-exclamation-circle',
            warning: 'bi bi-exclamation-triangle',
            info: 'bi bi-info-circle'
        };
        const icon = typeIcons[type] || typeIcons.info;
        console.log(`[${type.toUpperCase()}] ${message}`);
        try {
            const root = document.getElementById('app') && document.getElementById('app').__vue__;
            if (root && root.$root) {
                root.$root.$emit('show-toast', { icon: icon, text: message });
            }
        } catch (e) {
            /* toast optional */
        }
    },

    /**
     * Custom source: disambiguation hints for shared business ids (EN/AR bilingual files).
     * @param {object} node - Tree / selected content node
     * @returns {{ technicalNodeId: string, templateName: string, sourceFile: string }}
     */
    getCustomNodeResolveHints(node) {
        const empty = { technicalNodeId: '', templateName: '', sourceFile: '' };
        if (!node) return empty;
        const id = node.id != null ? String(node.id) : (node.Id != null ? String(node.Id) : '');
        let technical = '';
        const full = node.fullUrl != null ? String(node.fullUrl) : (node.FullUrl != null ? String(node.FullUrl) : '');
        if (full && (full !== id || full.indexOf('j|') === 0)) {
            technical = full;
        }
        const fields = node.fields || node.Fields;
        if (!technical && fields && fields.length) {
            for (let i = 0; i < fields.length; i++) {
                const f = fields[i];
                const name = (f.name || f.Name || '').toLowerCase();
                if (name === '__chameleontreenodeid') {
                    const v = f.value != null ? String(f.value) : (f.Value != null ? String(f.Value) : '');
                    if (v) {
                        technical = v;
                        break;
                    }
                }
            }
        }
        const templateName = node.templateName != null ? String(node.templateName)
            : (node.TemplateName != null ? String(node.TemplateName)
                : (node.template != null ? String(node.template)
                    : (node.Template != null ? String(node.Template)
                        : (node.contentType != null ? String(node.contentType)
                            : (node.ContentType != null ? String(node.ContentType) : '')))));
        let sourceFile = '';
        if (technical && technical.indexOf('j|') === 0) {
            const rest = technical.substring(2);
            const sep = rest.indexOf('|');
            if (sep > 0) sourceFile = rest.substring(0, sep);
        }
        return { technicalNodeId: technical, templateName: templateName, sourceFile: sourceFile };
    },

    /** @deprecated Use getCustomNodeResolveHints */
    getCustomTechnicalNodeId(node) {
        return this.getCustomNodeResolveHints(node).technicalNodeId;
    },

    /**
     * Builds GetNodeFields URL with Custom bilingual disambiguation (technical id, template, file).
     */
    buildGetNodeFieldsUrl(nodeId, platformType, connectionId, node) {
        let url = '/api/ContentTree/GetNodeFields?id=' + encodeURIComponent(nodeId)
            + '&platformType=' + encodeURIComponent(platformType)
            + '&connectionId=' + encodeURIComponent(connectionId);
        const hints = this.getCustomNodeResolveHints(node);
        if (hints.technicalNodeId) {
            url += '&technicalNodeId=' + encodeURIComponent(hints.technicalNodeId);
        }
        if (hints.templateName) {
            url += '&templateName=' + encodeURIComponent(hints.templateName);
        }
        if (hints.sourceFile) {
            url += '&sourceFile=' + encodeURIComponent(hints.sourceFile);
        }
        return url;
    }
}; 