/**
 * CrmPipelineSection.js — پایپ‌لاین Kanban + پانل جزئیات لید (با LocationPicker)
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

const STAGES = [
    { key:'new_lead',    label:'سرنخ جدید',  icon:'🌱', color:'#94a3b8' },
    { key:'interested',  label:'علاقه‌مند',  icon:'💡', color:'#3b82f6' },
    { key:'visited',     label:'بازدید کرده',icon:'👀', color:'#8b5cf6' },
    { key:'negotiating', label:'مذاکره',     icon:'🤝', color:'#f59e0b' },
    { key:'proposed',    label:'پیشنهاد',    icon:'📄', color:'#f97316' },
    { key:'reserved',    label:'رزرو',       icon:'⭐', color:'#10b981' },
];
const LOST_CONVERTED = [
    { key:'converted', label:'تبدیل شد', icon:'✅', color:'#059669' },
    { key:'lost',      label:'از دست رفت',icon:'❌', color:'#ef4444' },
];

const SOURCE_LABEL = { referral:'معرفی', website:'سایت', social:'شبکه اجتماعی', advertisement:'تبلیغات', exhibition:'نمایشگاه', cold_call:'تماس سرد', other:'سایر' };
const ACT_ICON     = { call:'📞', meeting:'👥', visit:'🏠', message:'💬', email:'📧', note:'📝' };
const ACT_LABEL    = { call:'تماس', meeting:'جلسه', visit:'بازدید', message:'پیام', email:'ایمیل', note:'یادداشت' };
const RES_COLOR    = { positive:'#10b981', neutral:'#64748b', negative:'#ef4444', no_answer:'#f59e0b' };
const RES_LABEL    = { positive:'مثبت', neutral:'خنثی', negative:'منفی', no_answer:'پاسخ ندادند' };

export default class CrmPipelineSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._leads    = [];
        this._selected = null;
        this._panelOpen= false;
        this._activeTab= 'activity';
        this._projects = [];
        this._filter   = { search:'', project_id:'' };
    }

    async template() { return `<div data-ref="root" style="direction:rtl;"></div>`; }

    async afterRender() {
        try {
            const r = await this.api.get('/pc/projects',{per_page:200});
            this._projects = r?.data??[];
        } catch {}
        await this._render();
    }

    async _render() {
        const root = this.ref('root');
        const projOpts = `<option value="">همه پروژه‌ها</option>` +
            this._projects.map(p=>`<option value="${p.id}">${this.escape(p.name)}</option>`).join('');

        root.innerHTML = `
        <div class="crm-wrap" data-ref="wrap">
            <!-- تولبار -->
            <div class="crm-toolbar">
                <input type="text" class="acc-input" data-ref="searchInp" placeholder="🔍 نام یا تلفن..." style="flex:1;max-width:220px;">
                <select class="event-type-filter" data-ref="projSel">${projOpts}</select>
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">➕ لید جدید</button>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="refreshBtn">🔄</button>
            </div>
            <!-- Kanban -->
            <div class="crm-board-wrap">
                <div class="crm-board" data-ref="board"></div>
                <!-- پانل راست -->
                <div class="crm-detail-pane" data-ref="detailPane">
                    <div class="crm-detail-inner" data-ref="detailInner"></div>
                </div>
            </div>
        </div>`;

        root.querySelectorAll('[data-ref]').forEach(el=>{ this.refs[el.dataset.ref]=el; });
        this.on(this.ref('searchInp'),'input',()=>{ this._filter.search=this.ref('searchInp').value; this._load(); });
        this.on(this.ref('projSel'),  'change',()=>{ this._filter.project_id=this.ref('projSel').value; this._load(); });
        this.on(this.ref('addBtn'),   'click', ()=>this._openLeadModal());
        this.on(this.ref('refreshBtn'),'click',()=>this._load());
        await this._load();
    }

    async _load() {
        const board = this.ref('board');
        board.innerHTML = `<div class="acc-loading" style="padding:40px;"><div class="acc-spinner"></div></div>`;
        const params = { include_all:1 };
        if (this._filter.project_id) params.project_id = this._filter.project_id;
        if (this._filter.search)     params.search      = this._filter.search;
        try {
            const res = await this.api.get('/crm/leads', params);
            this._leads = res?.data??[];
            this._renderBoard();
        } catch {
            board.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _renderBoard() {
        const board = this.ref('board');
        board.innerHTML = '';

        [...STAGES, ...LOST_CONVERTED].forEach(stage => {
            const items = this._leads.filter(l=>l.status===stage.key);
            const col   = document.createElement('div');
            col.className = 'crm-col';
            col.innerHTML = `
            <div class="crm-col-header" style="border-top:3px solid ${stage.color};">
                <span>${stage.icon} ${stage.label}</span>
                <span class="crm-col-count" style="background:${stage.color};">${items.length}</span>
            </div>
            <div class="crm-col-body" data-stage="${stage.key}">
                ${items.map(l=>this._leadCard(l,stage)).join('')}
            </div>`;

            // کلیک روی کارت
            col.querySelectorAll('[data-lead-id]').forEach(card=>{
                const lead = this._leads.find(l=>String(l.id)===card.dataset.leadId);
                if (lead) card.addEventListener('click',()=>this._openDetail(lead));
            });
            board.appendChild(col);
        });
    }

    _leadCard(l, stage) {
        const fmt   = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const days  = parseInt(l.days_since_contact)||0;
        const cold  = l.last_contact_date && days > 7;
        const isActive = this._selected?.id==l.id;

        return `
        <div class="crm-lead-card ${isActive?'crm-lead-card--active':''} ${cold?'crm-lead-card--cold':''}"
             data-lead-id="${l.id}">
            <div class="crm-lead-name">${this.escape(l.name)}</div>
            ${l.phone?`<div class="crm-lead-phone">📞 ${l.phone}</div>`:''}
            ${l.budget_max?`<div class="crm-lead-budget">💰 تا ${fmt(l.budget_max)} ریال</div>`:''}
            ${l.project_name?`<div class="crm-lead-project">🏗️ ${this.escape(l.project_name)}</div>`:''}
            <div class="crm-lead-meta">
                <span title="${SOURCE_LABEL[l.source]||l.source}" style="color:#94a3b8;font-size:10px;">📌 ${SOURCE_LABEL[l.source]||l.source}</span>
                ${l.score>0?`<span class="crm-score-badge" style="background:${l.score>=70?'#10b981':l.score>=40?'#f59e0b':'#94a3b8'};">${l.score}</span>`:''}
            </div>
            ${cold?`<div style="font-size:10px;color:#f59e0b;">⚠️ ${days} روز بدون تماس</div>`:''}
            ${l.pending_reminders>0?`<div style="font-size:10px;color:#ef4444;">🔔 ${l.pending_reminders} یادآور</div>`:''}
        </div>`;
    }

    /* ── پانل جزئیات ─────────────────────────────────────────── */
    async _openDetail(leadSummary) {
        this._selected = leadSummary;
        this._renderBoard();
        const pane  = this.ref('detailPane');
        const inner = this.ref('detailInner');
        if (!this._panelOpen) {
            pane.classList.add('crm-detail-pane--open');
            this._panelOpen = true;
        }
        inner.innerHTML = `<div class="acc-loading" style="padding:40px;"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get(`/crm/leads/${leadSummary.id}`);
            const l   = res?.data;
            if (!l) return;
            this._selected = l;
            this._renderDetail(l);
        } catch { inner.innerHTML=`<div class="acc-error">خطا</div>`; }
    }

    _renderDetail(l) {
        const inner   = this.ref('detailInner');
        const fmt     = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const stage   = [...STAGES,...LOST_CONVERTED].find(s=>s.key===l.status)||STAGES[0];

        inner.innerHTML = `
        <!-- هدر -->
        <div class="crm-detail-header">
            <div style="flex:1;">
                <div class="crm-detail-name">${this.escape(l.name)}</div>
                <div style="display:flex;gap:6px;margin-top:4px;flex-wrap:wrap;">
                    <span style="background:${stage.color};color:#fff;padding:2px 8px;border-radius:6px;font-size:11px;">
                        ${stage.icon} ${stage.label}
                    </span>
                    <span style="font-size:11px;color:#64748b;">${SOURCE_LABEL[l.source]||l.source}</span>
                    ${l.score>0?`<span class="crm-score-badge" style="background:${l.score>=70?'#10b981':l.score>=40?'#f59e0b':'#94a3b8'};">${l.score}/۱۰۰</span>`:''}
                </div>
            </div>
            <button class="gis-panel-close" data-ref="closeBtn">✕</button>
        </div>

        <!-- اطلاعات سریع -->
        <div class="crm-quick-info">
            ${l.phone  ?`<div>📞 <a href="tel:${l.phone}">${l.phone}</a></div>`:''}
            ${l.phone2 ?`<div>📞 ${l.phone2}</div>`:''}
            ${l.email  ?`<div>📧 ${l.email}</div>`:''}
            ${l.budget_max?`<div>💰 بودجه: تا ${fmt(l.budget_max)} ریال</div>`:''}
            ${l.preferred_type&&l.preferred_type!=='any'?`<div>🏢 نوع: ${l.preferred_type}</div>`:''}
            ${l.project_name?`<div>🏗️ پروژه: ${this.escape(l.project_name)}</div>`:''}
            ${l.next_followup?`<div>📅 پیگیری: ${l.next_followup}</div>`:''}
        </div>

        <!-- حرکت در پایپ‌لاین -->
        <div class="crm-stage-selector" data-ref="stageSel">
            ${STAGES.map(s=>`
            <button class="crm-stage-btn ${l.status===s.key?'crm-stage-btn--active':''}"
                    style="border-color:${l.status===s.key?s.color:'#e2e8f0'};${l.status===s.key?'background:'+s.color+';color:#fff;':''}"
                    data-move="${s.key}">${s.icon} ${s.label}</button>`).join('')}
            <button class="crm-stage-btn" style="border-color:#ef4444;color:#ef4444;" data-move="lost">❌ از دست رفت</button>
        </div>

        <!-- تب‌ها -->
        <div class="gis-panel-tabs" data-ref="detailTabs">
            <button class="gis-panel-tab ${this._activeTab==='activity'?'gis-panel-tab--active':''}" data-tab="activity">
                📞 فعالیت‌ها (${(l.activities||[]).length})
            </button>
            <button class="gis-panel-tab ${this._activeTab==='reminder'?'gis-panel-tab--active':''}" data-tab="reminder">
                🔔 یادآور (${(l.reminders||[]).filter(r=>r.status==='pending').length})
            </button>
            <button class="gis-panel-tab ${this._activeTab==='units'?'gis-panel-tab--active':''}" data-tab="units">
                🏢 واحدها
            </button>
        </div>
        <div class="crm-tab-body" data-ref="tabBody">
            ${this._renderTabContent(this._activeTab, l)}
        </div>

        <!-- اکشن‌ها -->
        <div class="gis-panel-actions">
            <button class="gis-btn gis-btn--primary" data-ref="editBtn">✏️ ویرایش</button>
            <button class="gis-btn" data-ref="locBtn" style="background:#dbeafe;color:#1e40af;">📍 موقعیت‌ها</button>
            <button class="gis-btn gis-btn--success" data-ref="convertBtn">✅ تبدیل به مشتری</button>
            <button class="gis-btn gis-btn--danger"  data-ref="delBtn">🗑️</button>
        </div>`;

        inner.querySelectorAll('[data-ref]').forEach(el=>{ this.refs[el.dataset.ref]=el; });

        // بستن
        this.on(this.ref('closeBtn'),'click',()=>{
            this.ref('detailPane').classList.remove('crm-detail-pane--open');
            this._panelOpen=false; this._selected=null; this._renderBoard();
        });

        // حرکت مرحله
        inner.querySelectorAll('[data-move]').forEach(btn=>{
            btn.addEventListener('click',async()=>{
                try {
                    await this.api.post(`/crm/leads/${l.id}/move`,{status:btn.dataset.move});
                    this._toast('✅ مرحله تغییر کرد');
                    await this._load();
                    this._openDetail({id:l.id});
                } catch{}
            });
        });

        // تب‌ها
        inner.querySelectorAll('.gis-panel-tab').forEach(btn=>{
            btn.addEventListener('click',()=>{
                inner.querySelectorAll('.gis-panel-tab').forEach(b=>b.classList.remove('gis-panel-tab--active'));
                btn.classList.add('gis-panel-tab--active');
                this._activeTab = btn.dataset.tab;
                this.ref('tabBody').innerHTML = this._renderTabContent(btn.dataset.tab,l);
                this._bindTabActions(btn.dataset.tab,l);
            });
        });

        this.on(this.ref('editBtn'),   'click',()=>this._openLeadModal(l));
        this.on(this.ref('locBtn'),    'click',()=>LocationPicker.openModal({
            api: this.api, entityType: 'lead', entityId: l.id, entityName: l.full_name || l.name || `#${l.id}`,
        }));
        this.on(this.ref('convertBtn'),'click',()=>this._openConvertModal(l));
        this.on(this.ref('delBtn'),    'click',async()=>{
            if (!confirm('حذف این لید؟')) return;
            await this.api.delete(`/crm/leads/${l.id}`);
            this._toast('🗑️ حذف شد');
            this.ref('detailPane').classList.remove('crm-detail-pane--open');
            this._panelOpen=false; this._selected=null;
            this._load();
        });

        this._bindTabActions(this._activeTab,l);
    }

    _renderTabContent(tab,l) {
        switch(tab) {
            case 'activity': return this._renderActivities(l.activities||[]);
            case 'reminder': return this._renderReminders(l.reminders||[]);
            case 'units':    return this._renderUnitsTab(l);
            default:         return '';
        }
    }

    _renderActivities(acts) {
        return `<div class="gis-tab-content">
            <div class="gis-section-title">فعالیت‌ها
                <button class="gis-btn gis-btn--xs" data-action="add-act">+ ثبت فعالیت</button>
            </div>
            ${acts.length ? `<div class="crm-timeline">` +
                acts.map(a=>`
                <div class="crm-tl-item">
                    <div class="crm-tl-icon">${ACT_ICON[a.type]||'📝'}</div>
                    <div class="crm-tl-body">
                        <div style="display:flex;justify-content:space-between;">
                            <b style="font-size:13px;">${this.escape(a.subject)}</b>
                            <span style="font-size:10px;color:${RES_COLOR[a.result]||'#64748b'};">${RES_LABEL[a.result]||''}</span>
                        </div>
                        <div style="font-size:11px;color:#64748b;">
                            ${ACT_LABEL[a.type]||a.type} | ${a.activity_date?.slice(0,16)||''}
                            ${a.duration_min?' | '+a.duration_min+' دقیقه':''}
                        </div>
                        ${a.body?`<div style="font-size:12px;color:#475569;margin-top:3px;">${this.escape(a.body)}</div>`:''}
                        ${a.next_action?`<div style="font-size:11px;color:#8b5cf6;margin-top:2px;">➡️ ${this.escape(a.next_action)}</div>`:''}
                        <button class="gis-btn gis-btn--xs gis-btn--danger" data-del-act="${a.id}" style="margin-top:4px;">🗑️</button>
                    </div>
                </div>`).join('') + '</div>'
            : '<div class="gis-empty-tab">فعالیتی ثبت نشده.</div>'}
        </div>`;
    }

    _renderReminders(reminders) {
        const sColor = { pending:'#f59e0b', done:'#10b981', cancelled:'#94a3b8' };
        const sLabel = { pending:'⏳ در انتظار', done:'✅ انجام شد', cancelled:'❌ لغو' };
        return `<div class="gis-tab-content">
            <div class="gis-section-title">یادآورها
                <button class="gis-btn gis-btn--xs" data-action="add-rem">+ افزودن</button>
            </div>
            ${reminders.length ? reminders.map(r=>`
            <div class="crm-reminder-card" style="border-right:3px solid ${sColor[r.status]||'#94a3b8'};">
                <div style="display:flex;justify-content:space-between;">
                    <b>${this.escape(r.title)}</b>
                    <span style="font-size:10px;color:${sColor[r.status]};">${sLabel[r.status]||r.status}</span>
                </div>
                <div style="font-size:11px;color:#64748b;">📅 ${r.due_date}${r.due_time?' ⏰ '+r.due_time:''}</div>
                <div style="display:flex;gap:4px;margin-top:6px;">
                    ${r.status==='pending'?`<button class="gis-btn gis-btn--xs" style="background:#dcfce7;color:#166534;" data-done-rem="${r.id}">✅ انجام شد</button>`:''}
                    <button class="gis-btn gis-btn--xs gis-btn--danger" data-del-rem="${r.id}">🗑️</button>
                </div>
            </div>`).join('')
            : '<div class="gis-empty-tab">یادآوری ثبت نشده.</div>'}
        </div>`;
    }

    _renderUnitsTab(l) {
        return `<div class="gis-tab-content">
            <div class="gis-section-title">واحدهای پیشنهادی بر اساس بودجه</div>
            <div data-ref="unitsResult">
                <div class="acc-loading"><div class="acc-spinner"></div></div>
            </div>
        </div>`;
    }

    _bindTabActions(tab,l) {
        const body = this.ref('tabBody');
        if (!body) return;

        if (tab==='activity') {
            body.querySelector('[data-action="add-act"]')?.addEventListener('click',()=>this._openActModal(l.id));
            body.querySelectorAll('[data-del-act]').forEach(btn=>{
                btn.addEventListener('click',async()=>{
                    if (!confirm('حذف؟')) return;
                    await this.api.delete(`/crm/activities/${btn.dataset.delAct}`);
                    this._toast('🗑️ حذف شد'); this._openDetail({id:l.id});
                });
            });
        }

        if (tab==='reminder') {
            body.querySelector('[data-action="add-rem"]')?.addEventListener('click',()=>this._openRemModal(l.id));
            body.querySelectorAll('[data-done-rem]').forEach(btn=>{
                btn.addEventListener('click',async()=>{
                    await this.api.put(`/crm/reminders/${btn.dataset.doneRem}`,{status:'done'});
                    this._toast('✅ انجام شد','#10b981'); this._openDetail({id:l.id});
                });
            });
            body.querySelectorAll('[data-del-rem]').forEach(btn=>{
                btn.addEventListener('click',async()=>{
                    await this.api.delete(`/crm/reminders/${btn.dataset.delRem}`);
                    this._toast('🗑️'); this._openDetail({id:l.id});
                });
            });
        }

        if (tab==='units') {
            // بارگذاری واحدهای پیشنهادی
            this.api.get(`/crm/leads/${l.id}/units`).then(res=>{
                const units = res?.data??[];
                const fmt   = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
                const resultEl = body.querySelector('[data-ref="unitsResult"]');
                if (!resultEl) return;
                if (!units.length) {
                    resultEl.innerHTML = '<div class="gis-empty-tab">واحد مطابق بودجه یافت نشد.</div>';
                    return;
                }
                resultEl.innerHTML = units.map(u=>`
                <div class="crm-unit-card">
                    <div style="font-weight:700;">واحد ${this.escape(u.unit_number)} — طبقه ${u.floor}</div>
                    <div style="font-size:11px;color:#64748b;">${this.escape(u.project_name||'—')} | ${u.area_sqm||'—'} م²</div>
                    <div style="font-weight:700;color:#10b981;margin-top:4px;">${fmt(u.base_price)} ریال</div>
                </div>`).join('');
            }).catch(()=>{});
        }
    }

    /* ── مودال لید ─────────────────────────────────────────── */
    _openLeadModal(l=null) {
        const isEdit = !!l;
        const ld = l||{};
        const projOpts = `<option value="">—</option>` +
            this._projects.map(p=>`<option value="${p.id}" ${ld.project_id==p.id?'selected':''}>${this.escape(p.name)}</option>`).join('');
        const selS = k=>ld.source===k?'selected':'';

        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:500px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🎯 ${isEdit?'ویرایش':'لید جدید'}</div>
            <form>
                <div class="acc-form-group"><label>نام *</label>
                    <input name="name" required value="${this.escape(ld.name||'')}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تلفن</label>
                        <input name="phone" type="tel" value="${this.escape(ld.phone||'')}">
                    </div>
                    <div class="acc-form-group"><label>تلفن دوم</label>
                        <input name="phone2" type="tel" value="${this.escape(ld.phone2||'')}">
                    </div>
                </div>
                <div class="acc-form-group"><label>ایمیل</label>
                    <input name="email" type="email" value="${this.escape(ld.email||'')}">
                </div>
                <div class="acc-form-group"><label>منبع آشنایی</label>
                    <select name="source">
                        <option value="referral"    ${selS('referral')}>معرفی</option>
                        <option value="website"     ${selS('website')}>سایت</option>
                        <option value="social"      ${selS('social')}>شبکه اجتماعی</option>
                        <option value="advertisement" ${selS('advertisement')}>تبلیغات</option>
                        <option value="exhibition"  ${selS('exhibition')}>نمایشگاه</option>
                        <option value="cold_call"   ${selS('cold_call')}>تماس سرد</option>
                        <option value="other"       ${selS('other')}>سایر</option>
                    </select>
                </div>
                <div class="acc-form-group"><label>پروژه مورد علاقه</label>
                    <select name="project_id">${projOpts}</select>
                </div>
                <div class="gis-info-divider">بودجه و ترجیحات</div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>حداقل بودجه (ریال)</label>
                        <input name="budget_min" type="number" value="${ld.budget_min||''}">
                    </div>
                    <div class="acc-form-group"><label>حداکثر بودجه (ریال)</label>
                        <input name="budget_max" type="number" value="${ld.budget_max||''}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>نوع واحد</label>
                        <select name="preferred_type">
                            <option value="any" ${ld.preferred_type==='any'||!ld.preferred_type?'selected':''}>هر نوع</option>
                            <option value="residential" ${ld.preferred_type==='residential'?'selected':''}>مسکونی</option>
                            <option value="commercial"  ${ld.preferred_type==='commercial'?'selected':''}>تجاری</option>
                            <option value="office"      ${ld.preferred_type==='office'?'selected':''}>اداری</option>
                        </select>
                    </div>
                    <div class="acc-form-group"><label>متراژ (م²)</label>
                        <input name="preferred_area_sqm" type="number" value="${ld.preferred_area_sqm||''}">
                    </div>
                </div>
                <div class="acc-form-group"><label>تاریخ پیگیری بعدی</label>
                    <input name="next_followup" type="date" value="${ld.next_followup||''}">
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2">${this.escape(ld.notes||'')}</textarea>
                </div>
                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">${isEdit?'ذخیره':'افزودن لید'}</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(ov);
        const close=()=>ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click',close);
        ov.querySelector('[data-action="cancel"]').addEventListener('click',close);
        ov.addEventListener('click',ev=>{if(ev.target===ov)close();});
        ov.querySelector('form').addEventListener('submit',async ev=>{
            ev.preventDefault();
            const body=Object.fromEntries(new FormData(ev.target).entries());
            ['budget_min','budget_max','preferred_area_sqm','project_id','next_followup'].forEach(k=>{if(!body[k])delete body[k];});
            const btn=ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                if (isEdit) await this.api.put(`/crm/leads/${l.id}`,body);
                else        await this.api.post('/crm/leads',body);
                close(); this._toast(isEdit?'✅ ویرایش شد':'✅ لید افزوده شد');
                await this._load();
                if (isEdit) this._openDetail({id:l.id});
            } catch(e){alert('خطا: '+(e?.message||'')); btn.disabled=false;}
        });
    }

    /* ── مودال فعالیت ──────────────────────────────────────── */
    _openActModal(leadId) {
        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:420px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">📞 ثبت فعالیت</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>نوع</label>
                        <select name="type">
                            <option value="call">📞 تماس</option>
                            <option value="meeting">👥 جلسه</option>
                            <option value="visit">🏠 بازدید</option>
                            <option value="message">💬 پیام</option>
                            <option value="email">📧 ایمیل</option>
                            <option value="note">📝 یادداشت</option>
                        </select>
                    </div>
                    <div class="acc-form-group"><label>نتیجه</label>
                        <select name="result">
                            <option value="positive">✅ مثبت</option>
                            <option value="neutral" selected>➡️ خنثی</option>
                            <option value="negative">❌ منفی</option>
                            <option value="no_answer">📵 پاسخ ندادند</option>
                        </select>
                    </div>
                </div>
                <div class="acc-form-group"><label>موضوع *</label>
                    <input name="subject" required placeholder="خلاصه مکالمه/جلسه...">
                </div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <textarea name="body" rows="3" placeholder="جزئیات..."></textarea>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ و ساعت</label>
                        <input name="activity_date" type="datetime-local" value="${new Date().toISOString().slice(0,16)}">
                    </div>
                    <div class="acc-form-group"><label>مدت (دقیقه)</label>
                        <input name="duration_min" type="number" min="0" placeholder="اختیاری">
                    </div>
                </div>
                <div class="acc-form-group"><label>اقدام بعدی</label>
                    <input name="next_action" placeholder="مثلاً: پیگیری در ۳ روز آینده">
                </div>
                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">ثبت</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(ov);
        const close=()=>ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click',close);
        ov.querySelector('[data-action="cancel"]').addEventListener('click',close);
        ov.addEventListener('click',ev=>{if(ev.target===ov)close();});
        ov.querySelector('form').addEventListener('submit',async ev=>{
            ev.preventDefault();
            const body=Object.fromEntries(new FormData(ev.target).entries());
            ['duration_min','next_action'].forEach(k=>{if(!body[k])delete body[k];});
            const btn=ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                await this.api.post(`/crm/leads/${leadId}/activities`,body);
                close(); this._toast('✅ فعالیت ثبت شد');
                this._openDetail({id:leadId});
            } catch(e){alert('خطا'); btn.disabled=false;}
        });
    }

    /* ── مودال یادآور ──────────────────────────────────────── */
    _openRemModal(leadId) {
        const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate()+1);
        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:380px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🔔 یادآور جدید</div>
            <form>
                <div class="acc-form-group"><label>عنوان *</label>
                    <input name="title" required placeholder="مثلاً: پیگیری تلفنی">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ</label>
                        <input name="due_date" type="date" value="${tomorrow.toISOString().split('T')[0]}">
                    </div>
                    <div class="acc-form-group"><label>ساعت</label>
                        <input name="due_time" type="time" value="10:00">
                    </div>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2"></textarea>
                </div>
                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">افزودن</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(ov);
        const close=()=>ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click',close);
        ov.querySelector('[data-action="cancel"]').addEventListener('click',close);
        ov.addEventListener('click',ev=>{if(ev.target===ov)close();});
        ov.querySelector('form').addEventListener('submit',async ev=>{
            ev.preventDefault();
            const body=Object.fromEntries(new FormData(ev.target).entries());
            if (!body.notes) delete body.notes;
            const btn=ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                await this.api.post(`/crm/leads/${leadId}/reminders`,body);
                close(); this._toast('🔔 یادآور ثبت شد','#f59e0b');
                this._openDetail({id:leadId});
            } catch(e){alert('خطا'); btn.disabled=false;}
        });
    }

    /* ── مودال تبدیل به مشتری ───────────────────────────────── */
    _openConvertModal(l) {
        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:360px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">✅ تبدیل به مشتری</div>
            <div style="background:#f0fdf4;border-radius:8px;padding:12px;margin-bottom:14px;font-size:13px;">
                لید «${this.escape(l.name)}» به عنوان مشتری واقعی ثبت خواهد شد.
            </div>
            <div class="acc-form-group"><label>شماره فروش (اختیاری)</label>
                <input id="sale-id-inp" type="number" placeholder="اگر واحدی فروخته شده">
            </div>
            <div class="acc-modal__actions">
                <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                <button class="acc-btn acc-btn--success" id="confirm-convert">✅ تأیید تبدیل</button>
            </div>
        </div>`;
        document.body.appendChild(ov);
        const close=()=>ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click',close);
        ov.querySelector('[data-action="cancel"]').addEventListener('click',close);
        ov.addEventListener('click',ev=>{if(ev.target===ov)close();});
        ov.querySelector('#confirm-convert').addEventListener('click',async()=>{
            const saleId = ov.querySelector('#sale-id-inp').value;
            try {
                await this.api.post(`/crm/leads/${l.id}/convert`,{ sale_id: saleId||undefined });
                close(); this._toast('✅ لید به مشتری تبدیل شد','#10b981');
                await this._load();
                this.ref('detailPane').classList.remove('crm-detail-pane--open');
                this._panelOpen=false; this._selected=null;
            } catch(e){alert('خطا');}
        });
    }

    _toast(msg,bg='#10b981'){
        const t=document.createElement('div');
        t.style.cssText=`position:fixed;bottom:24px;left:24px;background:${bg};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;direction:rtl;`;
        t.textContent=msg; document.body.appendChild(t);
        setTimeout(()=>t.remove(),3000);
    }
}
