/**
 * melk-construction-panel.js — ساخت‌وساز، مشارکت پیمانکاران و قرارداد مشارکت
 */

const TYPE_META = {
    construction: { label: 'ساخت‌وساز',        icon: '🏗️', color: '#f97316', bg: '#fff7ed' },
    partnership:  { label: 'مشارکت در ساخت',   icon: '🤝', color: '#8b5cf6', bg: '#f5f3ff' },
    renovation:   { label: 'نوسازی',            icon: '🔧', color: '#0ea5e9', bg: '#f0f9ff' },
};
const STATUS_META = {
    draft:     { label: 'پیش‌نویس', color: '#94a3b8', dot: '#94a3b8' },
    active:    { label: 'فعال',     color: '#10b981', dot: '#10b981' },
    completed: { label: 'تکمیل',    color: '#3b82f6', dot: '#3b82f6' },
    cancelled: { label: 'لغو',      color: '#ef4444', dot: '#ef4444' },
};

export function renderConstructionPanel(esc) {
    return `
<style>
.con-panel { padding: 0; font-family: inherit; direction: rtl; }

/* ── نوار بالا ── */
.con-topbar {
    display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
    padding: 18px 20px 14px;
    border-bottom: 1px solid #f1f5f9;
    background: linear-gradient(135deg,#fff7ed 0%,#fff 60%);
}
.con-title { font-size: 1.15rem; font-weight: 800; color: #1e293b; flex: 1; }
.con-title span { color: #f97316; }
.con-actions { display: flex; gap: 8px; }

/* ── آمار سریع ── */
.con-stats {
    display: grid; grid-template-columns: repeat(4,1fr); gap: 10px;
    padding: 14px 20px; background: #fafafa; border-bottom: 1px solid #f1f5f9;
}
.con-stat-card {
    background: #fff; border: 1px solid #e2e8f0; border-radius: 10px;
    padding: 10px 12px; text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,.04);
}
.con-stat-num { font-size: 1.5rem; font-weight: 800; line-height: 1; }
.con-stat-lbl { font-size: .72rem; color: #64748b; margin-top: 3px; }

/* ── فرم ثبت ── */
.con-new-form {
    background: linear-gradient(135deg,#fff7ed,#fff);
    border: 1.5px solid #fed7aa; border-radius: 14px;
    margin: 16px 20px; padding: 18px; display: none;
    box-shadow: 0 4px 20px rgba(249,115,22,.08);
    animation: slideDown .25s ease;
}
@keyframes slideDown { from { opacity:0;transform:translateY(-12px) } to { opacity:1;transform:none } }
.con-new-form h3 { margin: 0 0 14px; font-size: .95rem; color: #c2410c; display:flex;align-items:center;gap:6px; }
.con-form-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }
.con-field label { font-size: .75rem; color: #475569; font-weight: 600; display: block; margin-bottom: 4px; }
.con-inp {
    width: 100%; box-sizing: border-box;
    padding: 8px 10px; border: 1.5px solid #e2e8f0;
    border-radius: 8px; font-size: .85rem; font-family: inherit;
    transition: border-color .2s;
    background: #fff;
}
.con-inp:focus { outline: none; border-color: #f97316; box-shadow: 0 0 0 3px rgba(249,115,22,.1); }
.con-sel { width: 100%; box-sizing: border-box; padding: 8px 10px; border: 1.5px solid #e2e8f0; border-radius: 8px; font-size: .85rem; font-family: inherit; background:#fff; }
.con-form-actions { display: flex; gap: 8px; margin-top: 14px; justify-content: flex-end; }

/* ── لیست ── */
.con-list { padding: 16px 20px; display: grid; gap: 14px; }

/* ── کارت پروژه ── */
.con-card {
    background: #fff; border-radius: 16px;
    border: 1.5px solid #e2e8f0;
    box-shadow: 0 2px 12px rgba(0,0,0,.04);
    overflow: hidden; cursor: pointer;
    transition: transform .18s, box-shadow .18s, border-color .18s;
    animation: cardIn .3s ease both;
}
.con-card:hover { transform: translateY(-2px); box-shadow: 0 8px 28px rgba(0,0,0,.09); border-color: #cbd5e1; }
@keyframes cardIn { from { opacity:0;transform:translateY(16px) } to { opacity:1;transform:none } }

.con-card-top {
    padding: 14px 16px 12px;
    display: flex; align-items: flex-start; gap: 12px;
}
.con-card-icon {
    width: 46px; height: 46px; border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.4rem; flex-shrink: 0;
}
.con-card-info { flex: 1; min-width: 0; }
.con-card-title {
    font-size: .95rem; font-weight: 700; color: #1e293b;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.con-card-meta { font-size: .78rem; color: #64748b; margin-top: 4px; display: flex; gap: 10px; flex-wrap: wrap; }
.con-card-badges { display: flex; gap: 6px; margin-top: 6px; flex-wrap: wrap; }
.con-badge {
    font-size: .7rem; font-weight: 700; padding: 2px 8px;
    border-radius: 20px; border: 1.5px solid;
}
.con-status-dot {
    width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; margin-top: 7px;
}

/* بودجه progress */
.con-card-budget { padding: 0 16px 14px; }
.con-budget-row { display:flex; justify-content:space-between; font-size:.74rem; color:#64748b; margin-bottom:4px; }
.con-budget-bar { height: 5px; background: #f1f5f9; border-radius: 99px; overflow: hidden; }
.con-budget-fill { height: 100%; border-radius: 99px; transition: width .6s ease; }

/* footer کارت */
.con-card-foot {
    padding: 10px 16px;
    border-top: 1px solid #f1f5f9;
    display: flex; align-items: center; gap: 8px;
    background: #fafafa;
}
.con-btn {
    padding: 6px 14px; border-radius: 8px; border: 1.5px solid #e2e8f0;
    background: #fff; font-size: .78rem; font-weight: 600; cursor: pointer;
    font-family: inherit; color: #374151;
    transition: all .15s;
}
.con-btn:hover { border-color: #cbd5e1; background: #f8fafc; }
.con-btn--primary { background: #f97316; color: #fff; border-color: #ea580c; }
.con-btn--primary:hover { background: #ea580c; }
.con-btn--purple { background: #8b5cf6; color: #fff; border-color: #7c3aed; }
.con-btn--purple:hover { background: #7c3aed; }
.con-btn--sm { padding: 4px 10px; font-size: .72rem; }

/* ── پانل جزئیات ── */
.con-detail-overlay {
    position: fixed; inset: 0; background: rgba(0,0,0,.4);
    display: none; align-items: center; justify-content: center;
    z-index: 2000; padding: 20px;
}
.con-detail-modal {
    background: #fff; border-radius: 20px; width: 100%; max-width: 600px;
    max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0,0,0,.2);
    animation: modalIn .25s ease;
}
@keyframes modalIn { from{opacity:0;transform:scale(.95)} to{opacity:1;transform:none} }
.con-detail-head {
    padding: 20px 24px 16px;
    display: flex; align-items: center; gap: 14px;
    border-bottom: 1px solid #f1f5f9;
    position: sticky; top: 0; background: #fff; z-index: 1;
}
.con-detail-icon { width: 52px; height: 52px; border-radius: 14px; display:flex;align-items:center;justify-content:center;font-size:1.6rem;flex-shrink:0; }
.con-detail-ttl { font-size: 1rem; font-weight: 800; color: #1e293b; }
.con-detail-key { font-size: .76rem; color: #94a3b8; font-family: monospace; margin-top: 2px; }
.con-detail-body { padding: 20px 24px; }
.con-sect { margin-bottom: 20px; }
.con-sect-title { font-size: .8rem; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 10px; }
.con-info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.con-info-row { background: #f8fafc; border-radius: 8px; padding: 8px 10px; }
.con-info-lbl { font-size: .72rem; color: #94a3b8; margin-bottom: 2px; }
.con-info-val { font-size: .88rem; color: #1e293b; font-weight: 600; }

/* اعضا */
.con-members-wrap { display: flex; flex-wrap: wrap; gap: 8px; }
.con-member-chip {
    background: #f8fafc; border: 1.5px solid #e2e8f0; border-radius: 10px;
    padding: 6px 10px; display: flex; align-items: center; gap: 6px; font-size: .8rem;
}
.con-member-chip strong { color: #1e293b; }
.con-member-chip span { color: #64748b; font-size: .72rem; }
.con-chip-rm { background: none; border: none; cursor: pointer; color: #ef4444; font-size: .9rem; padding: 0; line-height: 1; }

/* جستجو کاربر */
.con-search-bar { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 10px; }
.con-user-results { margin-top: 6px; display: flex; flex-wrap: wrap; gap: 4px; }
.con-user-pick { padding: 4px 10px; border: 1.5px solid #e2e8f0; border-radius: 8px; background:#fff; font-size:.78rem; cursor:pointer; font-family:inherit; }
.con-user-pick:hover { background: #f0f9ff; border-color: #0ea5e9; }

/* ── اورلی قرارداد ── */
.em-contract-overlay {
    position: fixed; inset: 0; background: rgba(0,0,0,.5);
    display: none; align-items: center; justify-content: center;
    z-index: 3000; padding: 16px;
}
.em-contract-modal {
    background: #fff; border-radius: 20px;
    width: 100%; max-width: 780px; max-height: 94vh;
    display: flex; flex-direction: column;
    box-shadow: 0 24px 80px rgba(0,0,0,.25);
    animation: modalIn .25s ease;
}
.em-contract-modal-head {
    padding: 16px 20px; background: linear-gradient(135deg,#8b5cf6,#6d28d9);
    border-radius: 20px 20px 0 0; color: #fff;
    display: flex; align-items: center; gap: 12px;
}
.em-contract-modal-head h3 { margin: 0; font-size: .95rem; flex: 1; }
.em-contract-form-bar { padding: 16px 20px; border-bottom: 1px solid #f1f5f9; overflow-y: auto; max-height: 320px; }
.em-contract-body { flex: 1; overflow-y: auto; padding: 16px 20px; min-height: 200px; }

/* ── wizard فرم ── */
.cw-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.cw-field label { font-size: .74rem; color: #475569; font-weight: 600; display: block; margin-bottom: 3px; }
.cw-inp { width: 100%; box-sizing: border-box; padding: 7px 9px; border: 1.5px solid #e2e8f0; border-radius: 8px; font-size: .83rem; font-family: inherit; }
.cw-inp:focus { outline: none; border-color: #8b5cf6; box-shadow: 0 0 0 3px rgba(139,92,246,.1); }
.cw-divider { grid-column: 1/-1; font-size: .72rem; font-weight: 700; color: #8b5cf6; text-transform: uppercase; letter-spacing: .06em; padding: 4px 0 2px; border-bottom: 1px solid #ede9fe; }

/* empty / loading */
.con-empty { text-align: center; padding: 48px 20px; color: #94a3b8; font-size: .9rem; }
.con-empty-icon { font-size: 3rem; display: block; margin-bottom: 12px; opacity: .5; }
.con-spinner { width: 36px; height: 36px; border: 3px solid #f1f5f9; border-top-color: #f97316; border-radius: 50%; animation: spin .7s linear infinite; margin: 40px auto; }
@keyframes spin { to { transform: rotate(360deg) } }
</style>

<div class="con-panel" data-ref="constructionPanel">
    <!-- نوار بالایی -->
    <div class="con-topbar">
        <div class="con-title">🔨 ساخت‌وساز و <span>مشارکت پیمانکاران</span></div>
        <div class="con-actions">
            <button type="button" class="con-btn" data-ref="reloadProjectsBtn" title="بارگذاری مجدد">↻</button>
            <button type="button" class="con-btn con-btn--primary" data-ref="newProjectBtn">➕ پروژه جدید</button>
        </div>
    </div>

    <!-- آمار سریع -->
    <div class="con-stats" data-ref="statsBar">
        <div class="con-stat-card"><div class="con-stat-num" style="color:#f97316">—</div><div class="con-stat-lbl">کل پروژه‌ها</div></div>
        <div class="con-stat-card"><div class="con-stat-num" style="color:#10b981">—</div><div class="con-stat-lbl">فعال</div></div>
        <div class="con-stat-card"><div class="con-stat-num" style="color:#94a3b8">—</div><div class="con-stat-lbl">پیش‌نویس</div></div>
        <div class="con-stat-card"><div class="con-stat-num" style="color:#3b82f6">—</div><div class="con-stat-lbl">تکمیل‌شده</div></div>
    </div>

    <!-- فرم پروژه جدید -->
    <div class="con-new-form" data-ref="projectForm">
        <h3>🏗️ ثبت پروژه ساخت جدید</h3>
        <div class="con-form-grid">
            <div class="con-field" style="grid-column:1/3"><label>عنوان پروژه *</label>
                <input class="con-inp" data-ref="projTitle" placeholder="مثلاً: برج مسکونی سعدی">
            </div>
            <div class="con-field"><label>نوع</label>
                <select class="con-sel" data-ref="projType">
                    <option value="construction">🏗️ ساخت‌وساز</option>
                    <option value="partnership">🤝 مشارکت در ساخت</option>
                    <option value="renovation">🔧 نوسازی</option>
                </select>
            </div>
            <div class="con-field"><label>کد نوسازی</label>
                <input class="con-inp" data-ref="projReno" dir="ltr" placeholder="۱۲-۳۴-۵۶۷۸">
            </div>
            <div class="con-field"><label>متراژ (م²)</label>
                <input class="con-inp" data-ref="projArea" type="number" min="0" placeholder="۲۵۰">
            </div>
            <div class="con-field"><label>تعداد طبقات</label>
                <input class="con-inp" data-ref="projFloors" type="number" min="1" placeholder="۴">
            </div>
            <div class="con-field"><label>بودجه تخمینی (تومان)</label>
                <input class="con-inp" data-ref="projBudget" type="number" placeholder="۵۰۰۰۰۰۰۰۰۰">
            </div>
        </div>
        <div class="con-field" style="margin-top:10px"><label>توضیحات</label>
            <textarea class="con-inp" data-ref="projDesc" rows="2" placeholder="خلاصه‌ای از پروژه..."></textarea>
        </div>
        <div class="con-form-actions">
            <button type="button" class="con-btn" data-ref="cancelProjectBtn">انصراف</button>
            <button type="button" class="con-btn con-btn--primary" data-ref="saveProjectBtn">💾 ذخیره پروژه</button>
        </div>
    </div>

    <!-- لیست پروژه‌ها -->
    <div class="con-list" data-ref="projectList"></div>

    <!-- پانل جزئیات (اورلی) -->
    <div class="con-detail-overlay" data-ref="detailOverlay">
        <div class="con-detail-modal" data-ref="detailModal">
            <div class="con-detail-head" data-ref="detailHead"></div>
            <div class="con-detail-body" data-ref="detailBody"></div>
        </div>
    </div>

    <!-- اورلی قرارداد -->
    <div class="em-contract-overlay" data-ref="contractOverlay">
        <div class="em-contract-modal">
            <div class="em-contract-modal-head">
                <h3>📄 قرارداد مشارکت در ساخت — ۱۱ ماده حقوقی</h3>
                <div style="display:flex;gap:6px">
                    <button type="button" class="con-btn con-btn--sm" data-ref="contractPrintBtn" style="background:rgba(255,255,255,.2);color:#fff;border-color:rgba(255,255,255,.3)">🖨️ چاپ</button>
                    <button type="button" class="con-btn con-btn--sm" data-ref="contractSaveBtn" style="background:#10b981;color:#fff;border-color:#059669">💾 ثبت در سیستم</button>
                    <button type="button" class="con-btn con-btn--sm" data-ref="contractCloseBtn" style="background:rgba(255,255,255,.15);color:#fff;border-color:transparent">✕</button>
                </div>
            </div>
            <div class="em-contract-form-bar" data-ref="contractFormBar"></div>
            <div class="em-contract-body" data-ref="contractBody">
                <div class="con-empty"><span class="con-empty-icon">📋</span>پس از پر کردن فرم، قرارداد اینجا نمایش می‌یابد.</div>
            </div>
        </div>
    </div>
</div>`;
}

export async function bindConstructionPanel(root, { request, esc, toast }) {
    const $ = (n) => root.querySelector(`[data-ref="${n}"]`);
    let currentProjectId = null;
    let currentContractHtml = '';
    let currentContractParams = {};

    /* ── بارگذاری و نمایش لیست ── */
    async function load() {
        const list = $('projectList');
        if (!list) return;
        list.innerHTML = `<div class="con-spinner"></div>`;
        try {
            const res = await request('GET', 'melk/construction');
            const items = res?.data ?? [];
            updateStats(items);
            if (!items.length) {
                list.innerHTML = `<div class="con-empty">
                    <span class="con-empty-icon">🏗️</span>
                    هنوز هیچ پروژه‌ای ثبت نشده.<br>
                    <button class="con-btn con-btn--primary" style="margin-top:14px" onclick="this.closest('[data-ref=constructionPanel]').querySelector('[data-ref=newProjectBtn]').click()">➕ ثبت اولین پروژه</button>
                </div>`;
                return;
            }
            list.innerHTML = '';
            items.forEach((p, idx) => {
                const tm   = TYPE_META[p.project_type] || TYPE_META.construction;
                const sm   = STATUS_META[p.status]     || STATUS_META.draft;
                const card = document.createElement('div');
                card.className = 'con-card';
                card.style.animationDelay = `${idx * 60}ms`;
                card.innerHTML = `
                    <div class="con-card-top">
                        <div class="con-card-icon" style="background:${tm.bg};font-size:1.4rem">${tm.icon}</div>
                        <div class="con-card-info">
                            <div class="con-card-title">${esc(p.title)}</div>
                            <div class="con-card-meta">
                                ${p.renovation_code ? `<span>🔗 ${esc(p.renovation_code)}</span>` : ''}
                                ${p.area_sqm ? `<span>📐 ${p.area_sqm} م²</span>` : ''}
                                ${p.floors ? `<span>🏢 ${p.floors} طبقه</span>` : ''}
                                <span>👥 ${p.participant_count ?? 0} عضو</span>
                            </div>
                            <div class="con-card-badges">
                                <span class="con-badge" style="color:${tm.color};border-color:${tm.color};background:${tm.bg}">${tm.label}</span>
                                <span class="con-badge" style="color:${sm.color};border-color:${sm.color};background:#fff">
                                    <span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:${sm.dot};margin-left:4px;vertical-align:middle"></span>${sm.label}
                                </span>
                                ${p.project_key ? `<span style="font-size:.68rem;color:#94a3b8;font-family:monospace;padding:2px 6px;background:#f8fafc;border-radius:6px">${esc(p.project_key)}</span>` : ''}
                            </div>
                        </div>
                    </div>
                    ${p.budget ? `
                    <div class="con-card-budget">
                        <div class="con-budget-row">
                            <span>بودجه تخمینی</span>
                            <span style="font-weight:700;color:#1e293b">${Number(p.budget).toLocaleString('fa-IR')} تومان</span>
                        </div>
                        <div class="con-budget-bar"><div class="con-budget-fill" style="width:${p.status==='completed'?100:p.status==='active'?45:10}%;background:${tm.color}"></div></div>
                    </div>` : ''}
                    <div class="con-card-foot">
                        <button type="button" class="con-btn con-btn--sm" data-open-proj="${p.id}">📂 مشاهده</button>
                        <button type="button" class="con-btn con-btn--sm con-btn--purple" data-contract-proj="${p.id}">📄 قرارداد</button>
                        <span style="flex:1"></span>
                        <span style="font-size:.7rem;color:#cbd5e1">${p.created_at ? p.created_at.slice(0,10) : ''}</span>
                    </div>`;
                card.querySelector('[data-open-proj]').addEventListener('click', (e) => { e.stopPropagation(); openDetail(+p.id); });
                card.querySelector('[data-contract-proj]').addEventListener('click', (e) => { e.stopPropagation(); openContractWizard(+p.id); });
                card.addEventListener('click', () => openDetail(+p.id));
                list.appendChild(card);
            });
        } catch (e) {
            list.innerHTML = `<div class="con-empty"><span class="con-empty-icon">⚠️</span>${esc(e.message)}</div>`;
        }
    }

    function updateStats(items) {
        const bar = $('statsBar');
        if (!bar) return;
        const nums = bar.querySelectorAll('.con-stat-num');
        nums[0].textContent = items.length;
        nums[1].textContent = items.filter(i => i.status === 'active').length;
        nums[2].textContent = items.filter(i => i.status === 'draft').length;
        nums[3].textContent = items.filter(i => i.status === 'completed').length;
    }

    /* ── جزئیات پروژه ── */
    async function openDetail(id) {
        currentProjectId = id;
        const overlay = $('detailOverlay');
        const head    = $('detailHead');
        const body    = $('detailBody');
        overlay.style.display = 'flex';
        head.innerHTML = '<div class="con-spinner" style="margin:0 auto;width:24px;height:24px;border-width:2px"></div>';
        body.innerHTML = '';

        try {
            const res = await request('GET', `melk/construction/${id}`);
            const p   = res?.data;
            if (!p) return;
            const tm  = TYPE_META[p.project_type] || TYPE_META.construction;
            const sm  = STATUS_META[p.status]     || STATUS_META.draft;
            const parts = p.participants ?? [];

            head.innerHTML = `
                <div class="con-detail-icon" style="background:${tm.bg}">${tm.icon}</div>
                <div style="flex:1;min-width:0">
                    <div class="con-detail-ttl">${esc(p.title)}</div>
                    <div class="con-detail-key">${esc(p.project_key || '')} · <span style="color:${sm.color}">${sm.label}</span></div>
                </div>
                <button type="button" class="con-btn con-btn--sm con-btn--purple" data-detail-contract="${id}">📄 قرارداد</button>
                <button type="button" class="con-btn con-btn--sm" data-close-detail>✕</button>`;

            body.innerHTML = `
                <div class="con-sect">
                    <div class="con-sect-title">اطلاعات پروژه</div>
                    <div class="con-info-grid">
                        ${p.renovation_code ? infoBox('🔗 کد نوسازی', p.renovation_code) : ''}
                        ${p.area_sqm ? infoBox('📐 متراژ', p.area_sqm + ' م²') : ''}
                        ${p.floors ? infoBox('🏢 طبقات', p.floors + ' طبقه') : ''}
                        ${p.budget ? infoBox('💰 بودجه', Number(p.budget).toLocaleString('fa-IR') + ' ت') : ''}
                        ${infoBox('🏗️ نوع', tm.label)}
                        ${infoBox('📅 تاریخ ثبت', (p.created_at||'').slice(0,10))}
                    </div>
                    ${p.description ? `<div style="margin-top:10px;padding:10px 12px;background:#f8fafc;border-radius:10px;font-size:.83rem;color:#475569;border-right:3px solid ${tm.color}">${esc(p.description)}</div>` : ''}
                </div>

                <div class="con-sect">
                    <div class="con-sect-title">👥 اعضا و پیمانکاران (${parts.length})</div>
                    <div class="con-members-wrap" data-ref="membersList">
                        ${parts.length ? parts.map(pt => memberChip(pt, esc)).join('') : '<span style="font-size:.8rem;color:#94a3b8">هنوز عضوی اضافه نشده</span>'}
                    </div>
                    <div class="con-search-bar" style="margin-top:12px">
                        <input class="con-inp" data-ref="partQ" placeholder="🔍 جستجوی کاربر..." style="flex:1">
                        <select class="con-sel" data-ref="partRole" style="width:130px">
                            <option value="contractor">پیمانکار</option>
                            <option value="owner">مالک</option>
                            <option value="supervisor">ناظر</option>
                            <option value="investor">سرمایه‌گذار</option>
                        </select>
                        <input class="con-inp" data-ref="partShare" type="number" placeholder="سهم %" style="width:80px">
                        <button type="button" class="con-btn con-btn--primary con-btn--sm" data-ref="addPartBtn">+ افزودن</button>
                    </div>
                    <div data-ref="partResults" class="con-user-results"></div>
                </div>`;

            // بستن اورلی
            head.querySelector('[data-close-detail]').addEventListener('click', () => {
                overlay.style.display = 'none';
            });
            overlay.addEventListener('click', (e) => { if (e.target === overlay) overlay.style.display = 'none'; });

            // قرارداد از هدر جزئیات
            head.querySelector('[data-detail-contract]').addEventListener('click', () => openContractWizard(id));

            // حذف عضو
            body.querySelectorAll('[data-rm-part]').forEach(btn => {
                btn.addEventListener('click', async (e) => {
                    e.stopPropagation();
                    if (!confirm('این عضو حذف شود؟')) return;
                    await request('DELETE', `melk/construction/${id}/participants/${btn.dataset.rmPart}`);
                    toast('عضو حذف شد'); openDetail(id);
                });
            });

            // جستجو و افزودن عضو
            let selectedUser = null;
            bindUserSearch(body, request, esc, (uid, name) => {
                selectedUser = { uid, name };
                body.querySelector('[data-ref="partQ"]').value = name;
                body.querySelector('[data-ref="partResults"]').innerHTML = '';
            });
            body.querySelector('[data-ref="addPartBtn"]')?.addEventListener('click', async () => {
                if (!selectedUser) { toast('ابتدا کاربری انتخاب کنید', true); return; }
                await request('POST', `melk/construction/${id}/participants`, {
                    user_id: selectedUser.uid,
                    role_type: body.querySelector('[data-ref="partRole"]')?.value || 'contractor',
                    share_percent: body.querySelector('[data-ref="partShare"]')?.value || null,
                });
                selectedUser = null; toast('عضو اضافه شد'); openDetail(id);
            });
        } catch (e) {
            body.innerHTML = `<div class="con-empty"><span class="con-empty-icon">⚠️</span>${esc(e.message)}</div>`;
        }
    }

    function infoBox(lbl, val) {
        return `<div class="con-info-row"><div class="con-info-lbl">${lbl}</div><div class="con-info-val">${val}</div></div>`;
    }
    function memberChip(pt, esc) {
        const roleLabel = {contractor:'پیمانکار',owner:'مالک',supervisor:'ناظر',investor:'سرمایه‌گذار'}[pt.role_type||pt.role_label] || pt.role_label || '';
        return `<div class="con-member-chip">
            <strong>${esc(pt.display_name)}</strong>
            <span>${roleLabel}${pt.share_percent != null ? ` — ${pt.share_percent}%` : ''}</span>
            <button class="con-chip-rm" data-rm-part="${pt.id}" title="حذف">✕</button>
        </div>`;
    }

    /* ── ویزارد قرارداد ── */
    async function openContractWizard(id) {
        let proj = null;
        try {
            const res = await request('GET', `melk/construction/${id}`);
            proj = res?.data;
        } catch (e) { toast(e.message, true); return; }

        const overlay = $('contractOverlay');
        const formBar = $('contractFormBar');
        const body    = $('contractBody');

        formBar.innerHTML = `
        <div class="cw-grid">
            <div class="cw-field cw-divider">طرف اول — مالک</div>
            <div class="cw-field"><label>نام و نام خانوادگی *</label><input class="cw-inp" id="cw-owner-name" placeholder="علی رضایی"></div>
            <div class="cw-field"><label>کد ملی</label><input class="cw-inp" id="cw-owner-nid" dir="ltr" placeholder="0012345678"></div>
            <div class="cw-field"><label>تلفن</label><input class="cw-inp" id="cw-owner-phone" dir="ltr" placeholder="0917…"></div>
            <div class="cw-field"><label>آدرس</label><input class="cw-inp" id="cw-owner-addr" placeholder="شیراز، خ…"></div>
            <div class="cw-field cw-divider">طرف دوم — پیمانکار</div>
            <div class="cw-field"><label>نام و نام خانوادگی *</label><input class="cw-inp" id="cw-cont-name" placeholder="محمد محمدی"></div>
            <div class="cw-field"><label>کد ملی</label><input class="cw-inp" id="cw-cont-nid" dir="ltr"></div>
            <div class="cw-field"><label>تلفن</label><input class="cw-inp" id="cw-cont-phone" dir="ltr"></div>
            <div class="cw-field"><label>آدرس</label><input class="cw-inp" id="cw-cont-addr"></div>
            <div class="cw-field cw-divider">شرایط مشارکت</div>
            <div class="cw-field"><label>سهم مالک (%)</label><input class="cw-inp" id="cw-owner-pct" type="number" value="50" min="0" max="100"></div>
            <div class="cw-field"><label>سهم پیمانکار (%)</label><input class="cw-inp" id="cw-cont-pct" type="number" value="50" min="0" max="100"></div>
            <div class="cw-field"><label>مدت اجرا (ماه)</label><input class="cw-inp" id="cw-dur" type="number" value="${proj?.floors ? proj.floors * 6 : 24}" min="1"></div>
            <div class="cw-field"><label>پیش‌پرداخت اجاره (تومان)</label><input class="cw-inp" id="cw-advance" type="number" placeholder="۵۰۰۰۰۰۰۰۰"></div>
            <div class="cw-field"><label>جریمه روزانه تأخیر (تومان)</label><input class="cw-inp" id="cw-penalty" type="number" placeholder="۱۰۰۰۰۰۰"></div>
            <div class="cw-field"><label>شهر</label><input class="cw-inp" id="cw-city" value="شیراز"></div>
        </div>
        <div style="display:flex;gap:8px;margin-top:12px;justify-content:flex-end">
            <button type="button" class="con-btn" id="cw-cancel-wizard">انصراف</button>
            <button type="button" class="con-btn con-btn--purple" id="cw-gen-btn">📄 تولید و نمایش قرارداد</button>
        </div>`;

        body.innerHTML = `<div class="con-empty"><span class="con-empty-icon">📋</span>اطلاعات را تکمیل کنید و «تولید قرارداد» را بزنید.</div>`;
        overlay.style.display = 'flex';

        document.getElementById('cw-cancel-wizard')?.addEventListener('click', () => { overlay.style.display = 'none'; });

        document.getElementById('cw-gen-btn')?.addEventListener('click', async () => {
            const owner = document.getElementById('cw-owner-name')?.value?.trim();
            const cont  = document.getElementById('cw-cont-name')?.value?.trim();
            if (!owner || !cont) { toast('نام مالک و پیمانکار الزامی است', true); return; }

            const genBtn = document.getElementById('cw-gen-btn');
            genBtn.disabled = true; genBtn.textContent = '⏳ در حال تولید…';

            currentContractParams = {
                melk_project_id:      id,
                owner_name:           owner,
                owner_nid:            document.getElementById('cw-owner-nid')?.value ?? '',
                owner_phone:          document.getElementById('cw-owner-phone')?.value ?? '',
                owner_address:        document.getElementById('cw-owner-addr')?.value ?? '',
                contractor_name:      cont,
                contractor_nid:       document.getElementById('cw-cont-nid')?.value ?? '',
                contractor_phone:     document.getElementById('cw-cont-phone')?.value ?? '',
                contractor_address:   document.getElementById('cw-cont-addr')?.value ?? '',
                parcel_description:   proj?.renovation_code ? 'کد نوسازی ' + proj.renovation_code : (proj?.title ?? ''),
                renovation_code:      proj?.renovation_code ?? '',
                area_sqm:             proj?.area_sqm ?? '',
                floors:               proj?.floors ?? '',
                owner_percent:        document.getElementById('cw-owner-pct')?.value ?? '50',
                contractor_percent:   document.getElementById('cw-cont-pct')?.value ?? '50',
                duration_months:      document.getElementById('cw-dur')?.value ?? '24',
                advance_amount:       document.getElementById('cw-advance')?.value ?? '0',
                penalty_daily:        document.getElementById('cw-penalty')?.value ?? '0',
                city:                 document.getElementById('cw-city')?.value ?? 'شیراز',
            };

            const params = new URLSearchParams(currentContractParams);
            try {
                const res = await request('GET', `contract/template/partnership-construction?${params}`);
                currentContractHtml = res?.data?.html ?? '';
                body.innerHTML = currentContractHtml || '<p style="color:red">خطا در دریافت قالب</p>';
                $('contractSaveBtn').dataset.projId = id;
                $('contractSaveBtn').disabled = false;
                $('contractSaveBtn').textContent = '💾 ثبت در سیستم';
            } catch (e) {
                toast('خطا در تولید قرارداد: ' + e.message, true);
            } finally {
                genBtn.disabled = false; genBtn.textContent = '📄 تولید و نمایش قرارداد';
            }
        });
    }

    /* ── چاپ ── */
    $('contractPrintBtn')?.addEventListener('click', () => {
        if (!currentContractHtml) { toast('ابتدا قرارداد را تولید کنید', true); return; }
        const win = window.open('', '_blank', 'width=900,height=700');
        win.document.write(`<!DOCTYPE html><html lang="fa" dir="rtl"><head>
            <meta charset="utf-8"><title>قرارداد مشارکت در ساخت</title>
            <style>body{font-family:Tahoma,sans-serif;direction:rtl}@media print{button{display:none}}</style>
        </head><body>${currentContractHtml}<script>window.print();<\/script></body></html>`);
        win.document.close();
    });

    /* ── ثبت در ERP ── */
    $('contractSaveBtn')?.addEventListener('click', async () => {
        const btn = $('contractSaveBtn');
        const projId = btn.dataset.projId;
        if (!projId || !currentContractHtml) { toast('ابتدا قرارداد را تولید کنید', true); return; }
        btn.disabled = true; btn.textContent = '⏳ در حال ثبت…';
        try {
            const res = await request('POST', 'contract/from-melk-project', {
                ...currentContractParams,
                total_amount: currentContractParams.advance_amount || 0,
            });
            if (res?.contract_id) {
                toast(`✅ قرارداد #${res.contract_id} در ماژول ERP ثبت شد`);
                btn.textContent = `✅ ثبت شد — #${res.contract_id}`;
            }
        } catch (e) { toast('خطا در ثبت: ' + e.message, true); btn.disabled = false; btn.textContent = '💾 ثبت در سیستم'; }
    });

    $('contractCloseBtn')?.addEventListener('click', () => {
        $('contractOverlay').style.display = 'none';
        currentContractHtml = '';
    });

    /* ── فرم پروژه ── */
    $('newProjectBtn')?.addEventListener('click',    () => { $('projectForm').style.display = ''; $('projTitle')?.focus(); });
    $('cancelProjectBtn')?.addEventListener('click', () => { $('projectForm').style.display = 'none'; });
    $('reloadProjectsBtn')?.addEventListener('click', load);

    $('saveProjectBtn')?.addEventListener('click', async () => {
        const title = $('projTitle')?.value?.trim();
        if (!title) { toast('عنوان الزامی است', true); return; }
        const btn = $('saveProjectBtn');
        btn.disabled = true; btn.textContent = '⏳ ذخیره…';
        try {
            await request('POST', 'melk/construction', {
                title,
                project_type:    $('projType')?.value,
                renovation_code: $('projReno')?.value,
                area_sqm:        $('projArea')?.value  || null,
                floors:          $('projFloors')?.value || null,
                budget:          $('projBudget')?.value || null,
                description:     $('projDesc')?.value,
            });
            $('projTitle').value = ''; $('projDesc').value = '';
            $('projectForm').style.display = 'none';
            toast('✅ پروژه ثبت شد');
            load();
        } catch (e) { toast(e.message, true); }
        finally { btn.disabled = false; btn.textContent = '💾 ذخیره پروژه'; }
    });

    await load();
}

function bindUserSearch(container, request, esc, onPick) {
    const input   = container.querySelector('[data-ref="partQ"]');
    const results = container.querySelector('[data-ref="partResults"]');
    if (!input || !results) return;
    let t;
    input.addEventListener('input', () => {
        clearTimeout(t);
        t = setTimeout(async () => {
            const q = input.value.trim();
            if (q.length < 2) { results.innerHTML = ''; return; }
            try {
                const ur = await request('GET', `melk/users?q=${encodeURIComponent(q)}`);
                results.innerHTML = (ur?.data ?? []).map(u =>
                    `<button type="button" class="con-user-pick" data-uid="${u.id}">${esc(u.display_name)} <span style="color:#94a3b8">@${esc(u.user_login)}</span></button>`).join('');
                results.querySelectorAll('.con-user-pick').forEach(pb =>
                    pb.addEventListener('click', () => onPick(+pb.dataset.uid, pb.firstChild?.textContent?.trim() || pb.textContent)));
            } catch { /* */ }
        }, 300);
    });
}
