/**
 * ServiceTalentAdmin — پنل بررسی درخواست‌های جذب (مدیریت / ارشد)
 */
export default class ServiceTalentAdmin {
    constructor({ root, request }) {
        this.root = root;
        this.request = request;
        this.list = [];
        this.stats = null;
        this.filter = 'pending_review';
    }

    async init() {
        await this._load();
        this._paint();
    }

    destroy() {}

    async _load() {
        try {
            const q = this.filter ? `?status=${encodeURIComponent(this.filter)}` : '';
            const res = await this.request('GET', `service/talent/applications${q}`);
            this.list = res?.data ?? [];
            this.stats = res?.stats ?? null;
        } catch {
            this.list = [];
        }
    }

    _paint() {
        const pending = this.stats?.pending ?? 0;
        this.root.innerHTML = `
        <div class="svc-talent-admin" dir="rtl">
            <div class="svc-ws-hero">
                <div class="svc-ws-hero__main">
                    <span class="svc-ws-hero__icon">🌐</span>
                    <div>
                        <div class="svc-ws-hero__name">جذب کارشناس از فضای مجازی</div>
                        <div class="svc-ws-hero__sub">بررسی پروفایل · هویت دیجیتال · نتیجه ارزیابی</div>
                    </div>
                </div>
                <div class="svc-ws-kpis">
                    <div class="svc-ws-kpi"><div class="svc-ws-kpi__val">${pending}</div><div class="svc-ws-kpi__lbl">در انتظار بررسی</div></div>
                    <div class="svc-ws-kpi"><div class="svc-ws-kpi__val">${this.stats?.approved ?? 0}</div><div class="svc-ws-kpi__lbl">تأیید شده</div></div>
                    <div class="svc-ws-kpi"><div class="svc-ws-kpi__val">${this.stats?.pass_rate ?? 0}%</div><div class="svc-ws-kpi__lbl">نرخ قبولی تست</div></div>
                </div>
            </div>
            <div class="svc-ws-tabs">
                ${['pending_review', 'assessed', 'approved', 'rejected', ''].map(s => {
                    const labels = { pending_review: 'در انتظار', assessed: 'ارزیابی‌شده', approved: 'تأیید', rejected: 'رد', '': 'همه' };
                    return `<button class="svc-ws-tab ${this.filter === s ? 'svc-ws-tab--active' : ''}" data-filter="${s}">${labels[s] || s}</button>`;
                }).join('')}
            </div>
            <div class="svc-table-wrap">
                <table class="svc-table">
                    <thead><tr>
                        <th>کد</th><th>نام</th><th>تخصص</th><th>دیجیتال</th><th>ارزیابی</th><th>وضعیت</th><th></th>
                    </tr></thead>
                    <tbody>
                        ${this.list.length ? this.list.map(a => `
                            <tr>
                                <td><code>${this._esc(a.applicant_no)}</code></td>
                                <td>${this._esc(a.full_name)}<br><small>${this._esc(a.phone)}</small></td>
                                <td>${this._esc(a.primary_specialty_label || '—')}</td>
                                <td>${a.digital_presence_score}</td>
                                <td>${a.assessment_score != null ? a.assessment_score + '%' : '—'}</td>
                                <td>${this._esc(a.status_label)}</td>
                                <td><button class="svc-ws-tab" data-review="${a.id}">بررسی</button></td>
                            </tr>
                        `).join('') : '<tr><td colspan="7" class="svc-muted">درخواستی یافت نشد</td></tr>'}
                    </tbody>
                </table>
            </div>
            <div id="talent-review-modal"></div>
        </div>`;

        this.root.querySelectorAll('[data-filter]').forEach(btn => {
            btn.addEventListener('click', async () => {
                this.filter = btn.dataset.filter;
                await this._load();
                this._paint();
            });
        });

        this.root.querySelectorAll('[data-review]').forEach(btn => {
            btn.addEventListener('click', () => this._openReview(parseInt(btn.dataset.review, 10)));
        });
    }

    async _openReview(id) {
        const modal = this.root.querySelector('#talent-review-modal');
        if (!modal) return;
        let app;
        try {
            const res = await this.request('GET', `service/talent/applications/${id}`);
            app = res?.data ?? res;
        } catch (e) {
            modal.innerHTML = `<div class="svc-msg svc-msg--err">${e.message}</div>`;
            return;
        }

        modal.innerHTML = `
        <div class="svc-talent-modal">
            <div class="svc-talent-modal__card">
                <button class="svc-talent-modal__close" id="talent-modal-x">×</button>
                <h3>${this._esc(app.full_name)} — ${this._esc(app.applicant_no)}</h3>
                <div class="svc-talent-modal__grid">
                    <div><strong>ایمیل:</strong> ${this._esc(app.email)}</div>
                    <div><strong>موبایل:</strong> ${this._esc(app.phone)}</div>
                    <div><strong>شهر:</strong> ${this._esc(app.city)}</div>
                    <div><strong>تجربه:</strong> ${app.years_experience} سال</div>
                    <div><strong>امتیاز دیجیتال:</strong> ${app.digital_presence_score}</div>
                    <div><strong>ارزیابی:</strong> ${app.assessment_score ?? '—'}%</div>
                </div>
                ${app.bio ? `<p><strong>بیو:</strong> ${this._esc(app.bio)}</p>` : ''}
                ${(app.identities || []).length ? `<p><strong>پروفایل‌ها:</strong> ${app.identities.map(i => i.platform_label).join('، ')}</p>` : ''}
                <label>یادداشت بررسی<textarea id="talent-review-notes" class="svc-inp svc-talent-ta" rows="2">${this._esc(app.review_notes || '')}</textarea></label>
                <div class="svc-talent-actions">
                    <button class="svc-btn svc-btn--primary" id="talent-approve">✅ تأیید و ایجاد حساب</button>
                    <button class="svc-btn svc-btn--ghost" id="talent-reject" style="color:#f87171">رد درخواست</button>
                </div>
                <div class="svc-msg" id="talent-review-msg"></div>
            </div>
        </div>`;

        modal.querySelector('#talent-modal-x')?.addEventListener('click', () => { modal.innerHTML = ''; });
        modal.querySelector('#talent-approve')?.addEventListener('click', () => this._doReview(id, 'approve', modal));
        modal.querySelector('#talent-reject')?.addEventListener('click', () => this._doReview(id, 'reject', modal));
    }

    async _doReview(id, action, modal) {
        const msg = modal.querySelector('#talent-review-msg');
        const notes = modal.querySelector('#talent-review-notes')?.value || '';
        try {
            await this.request('POST', `service/talent/applications/${id}/review`, { action, notes });
            modal.innerHTML = '';
            await this._load();
            this._paint();
        } catch (e) {
            msg.textContent = e.message;
            msg.className = 'svc-msg svc-msg--err';
        }
    }

    _esc(t) {
        return String(t ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;');
    }
}
