/**
 * رندر مشترک جزئیات پرونده اقتصاد ملک — اعضا، فعالیت، یادداشت‌ها
 */

export const MELK_ROLE_LABELS = {
    agent: 'مشاور املاک', legal: 'وکیل حقوقی', municipality: 'کارشناس شهرداری', registry: 'کارشناس ثبت',
    appraisal: 'کارشناس رسمی', contractor: 'پیمانکار ساخت', finance: 'کارشناس مالی', other: 'سایر',
};

export const MELK_NOTE_TYPES = {
    note: 'یادداشت', action: 'اقدام', legal: 'حقوقی', municipality: 'شهرداری', registry: 'ثبت',
};

export function melkEsc(t) {
    return String(t ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

export function melkFmtDate(iso) {
    if (!iso) return '—';
    try {
        const d = new Date(iso.replace(' ', 'T'));
        if (Number.isNaN(d.getTime())) return iso;
        return d.toLocaleString('fa-IR', { dateStyle: 'medium', timeStyle: 'short' });
    } catch {
        return iso;
    }
}

export function melkInitial(name, login) {
    const src = (name || login || '?').trim();
    return src.charAt(0).toUpperCase();
}

export function melkRoleBadgeClass(role) {
    const map = {
        agent: 'agent', legal: 'legal', municipality: 'municipality', registry: 'registry',
        appraisal: 'appraisal', contractor: 'contractor', finance: 'finance',
    };
    return map[role] || 'other';
}

function renderMemberCard(p, esc, canEditFull) {
    const login = p.user_login ? `@${esc(p.user_login)}` : 'نام کاربری ثبت نشده';
    const notes = +p.note_count || 0;
    return `<article class="em-member-card" data-member-uid="${p.user_id}" title="کلیک کنید تا نظرات این عضو را ببینید">
        <div class="em-member-avatar em-member-avatar--${melkRoleBadgeClass(p.role_type)}">${esc(melkInitial(p.display_name || p.user_name, p.user_login))}</div>
        <div class="em-member-body">
            <div class="em-member-top">
                <div>
                    <div class="em-member-name">${esc(p.display_name || p.user_name)}</div>
                    <div class="em-member-login">${login}</div>
                </div>
                <span class="em-member-role em-member-role--${melkRoleBadgeClass(p.role_type)}">${esc(p.role_label || MELK_ROLE_LABELS[p.role_type] || p.role_type)}</span>
            </div>
            <div class="em-member-meta">
                <span class="em-member-join" title="نحوه پیوستن">🔗 ${esc(p.join_label || 'عضو پرونده')}</span>
                <span class="em-member-date" title="تاریخ پیوستن">📅 ${esc(melkFmtDate(p.joined_at))}</span>
            </div>
            <div class="em-member-foot">
                <span class="em-member-stat">${notes} یادداشت</span>
                ${canEditFull ? `<button type="button" class="em-link-btn" data-rm-part="${p.id}">حذف</button>` : ''}
            </div>
        </div>
    </article>`;
}

function renderActivityItem(item, esc) {
    if (item.kind === 'joined') {
        const login = item.user_login ? ` <span class="em-activity-login">@${esc(item.user_login)}</span>` : '';
        return `<div class="em-activity-item em-activity-item--join">
            <div class="em-activity-icon">👤</div>
            <div class="em-activity-body">
                <div class="em-activity-head">
                    <strong>${esc(item.user_name)}</strong>${login}
                    <span class="em-activity-role">${esc(item.role_label || MELK_ROLE_LABELS[item.role_type] || '')}</span>
                </div>
                <p class="em-activity-text">به پرونده پیوست — ${esc(item.join_label || '')}</p>
                <time class="em-activity-time">${esc(melkFmtDate(item.at))}</time>
            </div>
        </div>`;
    }
    const login = item.user_login ? ` <span class="em-activity-login">@${esc(item.user_login)}</span>` : '';
    return `<div class="em-activity-item em-activity-item--${esc(item.note_type || 'note')}">
        <div class="em-activity-icon">${item.note_type === 'action' ? '⚡' : '💬'}</div>
        <div class="em-activity-body">
            <div class="em-activity-head">
                <strong>${esc(item.user_name)}</strong>${login}
                <span class="em-activity-badge">${esc(item.note_type_label || MELK_NOTE_TYPES[item.note_type] || 'یادداشت')}</span>
            </div>
            <p class="em-activity-text">${esc(item.body)}</p>
            <time class="em-activity-time">${esc(melkFmtDate(item.at))}</time>
        </div>
    </div>`;
}

function renderNoteCard(n, esc) {
    const login = n.user_login ? `<span class="em-note-login">@${esc(n.user_login)}</span>` : '';
    return `<div class="em-note em-note--${esc(n.note_type || 'note')}" data-note-uid="${n.user_id}">
        <div class="em-note-head">
            <span class="em-note-author">${esc(n.display_name || n.user_name)}</span>
            ${login}
            <span class="em-note-type">${esc(n.note_type_label || MELK_NOTE_TYPES[n.note_type] || n.note_type || '')}</span>
            <time class="em-note-time">${esc(melkFmtDate(n.created_at))}</time>
        </div>
        <p>${esc(n.body)}</p>
    </div>`;
}

/**
 * @param {object} c — پرونده از API
 * @param {object} opts
 */
export function renderMelkCaseCollaboration(c, opts = {}) {
    const esc = opts.esc || melkEsc;
    const canEditFull = !!opts.canEditFull;
    const roleOpts = opts.roleOpts || '';
    const participants = c.participants || [];
    const notes = c.notes || [];
    const timeline = c.activity_timeline || [];
    const pCount = c.participant_count ?? participants.length;
    const nCount = c.note_count ?? notes.length;

    const creatorLine = c.created_by_name
        ? `<div class="em-case-creator">ایجاد پرونده: <strong>${esc(c.created_by_name)}</strong>${c.created_by_login ? ` <span class="em-case-creator-login">@${esc(c.created_by_login)}</span>` : ''} — ${esc(melkFmtDate(c.created_at))}</div>`
        : '';

    return `
    <div class="em-case-collab">
        ${creatorLine}
        <div class="em-case-tabs" role="tablist">
            <button type="button" class="em-case-tab em-case-tab--active" data-case-tab="members" role="tab">👥 اعضا (${pCount})</button>
            <button type="button" class="em-case-tab" data-case-tab="activity" role="tab">📜 فعالیت (${timeline.length})</button>
            <button type="button" class="em-case-tab" data-case-tab="notes" role="tab">📝 نظرات (${nCount})</button>
        </div>
        <div class="em-case-tab-panel em-case-tab-panel--active" data-case-panel="members">
            <div class="em-member-grid">
                ${participants.map(p => renderMemberCard(p, esc, canEditFull)).join('') || '<div class="em-empty-inline">عضوی ثبت نشده</div>'}
            </div>
            ${canEditFull ? `<div class="em-add-part">
                <label class="em-add-part-label">افزودن عضو جدید</label>
                <input data-ref="partUserQ" class="red-inp" placeholder="جستجوی نام یا نام کاربری...">
                <div data-ref="partUserResults" class="em-user-results"></div>
                <select data-ref="partRoleSel">${roleOpts}</select>
            </div>` : ''}
        </div>
        <div class="em-case-tab-panel" data-case-panel="activity" hidden>
            <div class="em-activity-timeline">
                ${timeline.map(item => renderActivityItem(item, esc)).join('') || '<div class="em-empty-inline">فعالیتی ثبت نشده</div>'}
            </div>
        </div>
        <div class="em-case-tab-panel" data-case-panel="notes" hidden>
            <div class="em-notes em-notes--full">
                ${notes.map(n => renderNoteCard(n, esc)).join('') || '<div class="em-empty-inline">یادداشتی ثبت نشده</div>'}
            </div>
            <div class="em-note-form">
                <select data-ref="noteTypeSel">
                    <option value="note">یادداشت</option>
                    <option value="action">اقدام</option>
                    <option value="legal">حقوقی</option>
                    <option value="municipality">شهرداری</option>
                    <option value="registry">ثبت</option>
                </select>
                <textarea data-ref="noteInput" rows="3" placeholder="یادداشت یا اقدام جدید..."></textarea>
                <button type="button" class="red-btn red-btn--primary" data-ref="noteSubmit">ثبت یادداشت</button>
            </div>
        </div>
    </div>`;
}

export function bindMelkCaseTabs(root) {
    if (!root) return;
    const tabs = root.querySelectorAll('[data-case-tab]');
    const panels = root.querySelectorAll('[data-case-panel]');
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const name = tab.dataset.caseTab;
            tabs.forEach(t => t.classList.toggle('em-case-tab--active', t.dataset.caseTab === name));
            panels.forEach(p => {
                const on = p.dataset.casePanel === name;
                p.classList.toggle('em-case-tab-panel--active', on);
                p.hidden = !on;
            });
            if (name === 'notes') {
                root.querySelectorAll('.em-note[data-note-uid]').forEach(el => { el.style.display = ''; });
            }
        });
    });
}

export function filterMelkNotesByMember(root, userId) {
    if (!root || !userId) return;
    const notesTab = root.querySelector('[data-case-tab="notes"]');
    notesTab?.click();
    root.querySelectorAll('.em-note[data-note-uid]').forEach(el => {
        el.style.display = +el.dataset.noteUid === +userId ? '' : 'none';
    });
}
