/**
 * melk-form-renderer.js — رندر فیلدهای پویا از بانک فرم
 */
export function renderFormField(f, esc, districts = []) {
    const req = f.required ? ' required' : '';
    const dir = f.dir ? ` dir="${f.dir}"` : '';
    const ph = f.placeholder ? ` placeholder="${esc(f.placeholder)}"` : '';
    const min = f.min !== undefined ? ` min="${f.min}"` : '';
    const max = f.max !== undefined ? ` max="${f.max}"` : '';
    const key = esc(f.key);
    const ref = `data-field="${key}"`;

    if (f.type === 'district_select') {
        const opts = districts.map(d => `<option value="${d.id}">${esc(d.name)}</option>`).join('');
        return `<label class="em-dyn-field">${esc(f.label)}<select class="red-sel" ${ref}${req}><option value="">انتخاب منطقه</option>${opts}</select></label>`;
    }
    if (f.type === 'neighborhood_select') {
        return `<label class="em-dyn-field">${esc(f.label)}<select class="red-sel" ${ref} data-neigh-for-district><option value="">ابتدا منطقه را انتخاب کنید</option></select></label>`;
    }
    if (f.type === 'textarea') {
        const rows = f.rows || 3;
        return `<label class="em-dyn-field em-dyn-field--full">${esc(f.label)}<textarea class="red-inp" ${ref} rows="${rows}"${req}${ph}></textarea></label>`;
    }
    if (f.type === 'select') {
        const opts = f.options || {};
        const entries = Array.isArray(opts) ? opts.map(v => [v, v]) : Object.entries(opts);
        return `<label class="em-dyn-field">${esc(f.label)}<select class="red-sel" ${ref}${req}>${entries.map(([k, v]) => `<option value="${esc(k)}">${esc(v)}</option>`).join('')}</select></label>`;
    }
    if (f.type === 'multiselect') {
        const opts = f.options || {};
        const entries = Object.entries(opts);
        return `<div class="em-dyn-field em-dyn-field--full"><span class="em-dyn-lbl">${esc(f.label)}</span><div class="em-vis-roles">${entries.map(([k, v]) =>
            `<label><input type="checkbox" data-field="${key}" value="${esc(k)}"> ${esc(v)}</label>`).join('')}</div></div>`;
    }
    const type = f.type === 'number' ? 'number' : (f.type === 'tel' ? 'tel' : 'text');
    return `<label class="em-dyn-field">${esc(f.label)}<input class="red-inp" type="${type}" ${ref}${dir}${req}${ph}${min}${max}></label>`;
}

export function renderFormSections(sections, esc, districts = []) {
    return sections.map(sec => `
        <div class="em-form-section" data-section="${esc(sec.key)}">
            <h4>${esc(sec.title)}</h4>
            <div class="em-ext-grid2 em-dyn-grid">${sec.fields.map(f => renderFormField(f, esc, districts)).join('')}</div>
        </div>
    `).join('');
}

export function collectFormData(container) {
    const data = {};
    container.querySelectorAll('[data-field]').forEach(el => {
        const key = el.dataset.field;
        if (el.type === 'checkbox') {
            if (!data[key]) data[key] = [];
            if (el.checked) data[key].push(el.value);
        } else if (el.tagName === 'SELECT' || el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
            if (el.type !== 'checkbox') data[key] = el.value;
        }
    });
    return data;
}

export function validateRequired(container, sections) {
    const missing = [];
    const fields = [];
    sections.forEach(s => fields.push(...s.fields));
    fields.forEach(f => {
        if (!f.required) return;
        const el = container.querySelector(`[data-field="${f.key}"]`);
        if (!el) return;
        if (f.type === 'multiselect') {
            const checked = container.querySelectorAll(`[data-field="${f.key}"]:checked`);
            if (!checked.length) missing.push(f.label);
        } else if (!String(el.value || '').trim()) {
            missing.push(f.label);
        }
    });
    return missing;
}
