/**
 * erp-wizards.js — ویجت ERP اصلی (بدون سفارش خدمات میدانی)
 */
;(function (global) {
    'use strict';

    const ROUTES = [
        { key: 'erp_support', icon: '⚙️', title: 'پشتیبانی ERP' },
        { key: 'report_bug', icon: '🐛', title: 'گزارش خطا' },
        { key: 'training', icon: '📚', title: 'آموزش سیستم' },
    ];

    const FIELDS = {
        _default: [
            { key: 'name', label: 'نام *', type: 'text', required: true },
            { key: 'complaint_text', label: 'پیام *', type: 'textarea', required: true },
        ],
    };

    function esc(s) { return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;'); }
    function fieldHtml(f) {
        const id = `cw-w-${f.key}`;
        const req = f.required ? ' required' : '';
        if (f.type === 'textarea') return `<label class="cw-wiz-lbl">${esc(f.label)}</label><textarea class="cw-visitor-input" id="${id}" data-key="${f.key}" rows="3"${req}></textarea>`;
        return `<label class="cw-wiz-lbl">${esc(f.label)}</label><input class="cw-visitor-input" id="${id}" data-key="${f.key}" type="${f.type || 'text'}"${req}>`;
    }
    async function fetchFields() { return FIELDS._default; }
    function collectPayload(root, serviceType) {
        const payload = { service_type: serviceType, source_portal: 'erp' };
        root.querySelectorAll('[data-key]').forEach(el => { payload[el.dataset.key] = el.value?.trim?.() ?? el.value; });
        return payload;
    }

    global.SvcWizards = {
        ROUTES, fetchFields, fieldHtml, collectPayload,
        async renderWizard(container, serviceType, serviceTitle, serviceIcon, onBack, onSubmit) {
            const fields = await fetchFields(serviceType);
            container.innerHTML = `
                <button class="cw-back-btn" id="cw-wiz-back">◀ بازگشت</button>
                <div class="cw-section-title">${serviceIcon || '⚙️'} ${esc(serviceTitle)}</div>
                <div id="cw-wiz-fields">${fields.map(fieldHtml).join('')}</div>
                <button class="cw-start-btn" id="cw-w-submit">✅ ارسال</button>`;
            container.querySelector('#cw-wiz-back')?.addEventListener('click', onBack);
            container.querySelector('#cw-w-submit')?.addEventListener('click', () => onSubmit(collectPayload(container, serviceType)));
        },
    };
})(typeof window !== 'undefined' ? window : globalThis);
