/**
 * portal-chat-panel.js — پنل چت مشترک برای همه پورتال‌ها
 * قابل استفاده در ملک، فروشگاه، خدمات — بدون وابستگی به SectionBase
 *
 * استفاده:
 *   import { PortalChatPanel } from '/acc-engine/assets/js/shared/portal-chat-panel.js';
 *   const panel = new PortalChatPanel({ container, source:'melk', token, apiBase });
 *   panel.mount();
 */

const PORTAL_LABELS = {
    melk:    { title: 'چت اقتصاد ملک',   icon: '🏠', color: '#0ea5e9', bg: '#f0f9ff' },
    shop:    { title: 'چت فروشگاه',       icon: '🛒', color: '#8b5cf6', bg: '#f5f3ff' },
    service: { title: 'چت خدمات',        icon: '🔧', color: '#10b981', bg: '#f0fdf4' },
    erp:     { title: 'چت پشتیبانی ERP', icon: '💼', color: '#3b82f6', bg: '#eff6ff' },
};

const CSS_ID = 'pcp-styles';
const CSS = `
.pcp-wrap { display:flex;height:100%;min-height:420px;direction:rtl;font-family:inherit;overflow:hidden; }

/* ── لیست گفتگوها ── */
.pcp-sidebar {
    width:280px;flex-shrink:0;display:flex;flex-direction:column;
    border-left:1px solid #e2e8f0;background:#fafafa;
}
.pcp-sidebar-head {
    padding:12px 14px;border-bottom:1px solid #e2e8f0;background:#fff;
    display:flex;flex-direction:column;gap:8px;
}
.pcp-sidebar-title { font-size:.9rem;font-weight:800;color:#1e293b;display:flex;align-items:center;gap:8px; }
.pcp-sidebar-title-icon { width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:1rem;flex-shrink:0; }
.pcp-filter-row { display:flex;gap:6px; }
.pcp-sel { flex:1;padding:6px 8px;border:1.5px solid #e2e8f0;border-radius:8px;font-size:.76rem;font-family:inherit;background:#fff; }
.pcp-refresh { padding:6px 10px;border:1.5px solid #e2e8f0;border-radius:8px;background:#fff;cursor:pointer;font-size:.85rem; }
.pcp-refresh:hover { background:#f8fafc; }

/* آمار */
.pcp-stats { display:flex;gap:0;border-bottom:1px solid #e2e8f0; }
.pcp-stat { flex:1;padding:8px 6px;text-align:center;border-left:1px solid #f1f5f9; }
.pcp-stat:last-child { border-left:none; }
.pcp-stat-n { font-size:1.1rem;font-weight:800; }
.pcp-stat-l { font-size:.65rem;color:#94a3b8; }

/* لیست */
.pcp-list { flex:1;overflow-y:auto; }
.pcp-list::-webkit-scrollbar { width:3px; }
.pcp-list::-webkit-scrollbar-thumb { background:#e2e8f0;border-radius:99px; }

.pcp-room {
    display:flex;align-items:center;gap:10px;padding:11px 14px;
    border-bottom:1px solid #f8fafc;cursor:pointer;transition:background .15s;
    position:relative;
}
.pcp-room:hover { background:#f8fafc; }
.pcp-room--active { background:#eff6ff;border-right:3px solid var(--pc,#3b82f6); }
.pcp-room-av {
    width:38px;height:38px;border-radius:10px;background:#dbeafe;
    display:flex;align-items:center;justify-content:center;
    font-size:1rem;font-weight:800;color:#1d4ed8;flex-shrink:0;
}
.pcp-room-info { flex:1;min-width:0; }
.pcp-room-name { font-size:.82rem;font-weight:700;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; }
.pcp-room-last { font-size:.72rem;color:#94a3b8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px; }
.pcp-room-meta { display:flex;flex-direction:column;align-items:flex-end;gap:4px;flex-shrink:0; }
.pcp-unread { min-width:18px;height:18px;background:#ef4444;color:#fff;border-radius:9px;font-size:.65rem;font-weight:800;display:flex;align-items:center;justify-content:center;padding:0 4px; }
.pcp-status-dot { width:8px;height:8px;border-radius:50%; }
.pcp-time { font-size:.65rem;color:#cbd5e1; }

/* ── پانل گفتگو ── */
.pcp-conv { flex:1;display:flex;flex-direction:column;background:#fff;min-width:0; }
.pcp-empty {
    flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;
    color:#cbd5e1;gap:10px;
}
.pcp-empty-icon { font-size:3.5rem;opacity:.4; }

/* هدر گفتگو */
.pcp-conv-head {
    padding:12px 18px;border-bottom:1px solid #f1f5f9;
    display:flex;align-items:center;gap:12px;
    background:#fff;flex-shrink:0;
}
.pcp-conv-av { width:40px;height:40px;border-radius:10px;background:#dbeafe;display:flex;align-items:center;justify-content:center;font-size:1.1rem;font-weight:800;color:#1d4ed8;flex-shrink:0; }
.pcp-conv-name { font-size:.88rem;font-weight:800;color:#1e293b; }
.pcp-conv-meta { display:flex;gap:6px;margin-top:3px;flex-wrap:wrap; }
.pcp-meta-chip { font-size:.68rem;padding:2px 8px;border-radius:20px;font-weight:600; }
.pcp-conv-actions { display:flex;gap:6px;margin-right:auto; }
.pcp-action-btn { padding:5px 12px;border:1.5px solid #e2e8f0;border-radius:8px;background:#fff;font-size:.74rem;font-weight:600;cursor:pointer;font-family:inherit;transition:all .15s; }
.pcp-action-btn:hover { border-color:#cbd5e1;background:#f8fafc; }
.pcp-action-btn--danger { color:#ef4444;border-color:#fecaca; }
.pcp-action-btn--danger:hover { background:#fef2f2; }

/* پیام‌ها */
.pcp-messages { flex:1;overflow-y:auto;padding:14px 18px;display:flex;flex-direction:column;gap:8px;background:#f8fafc; }
.pcp-messages::-webkit-scrollbar { width:3px; }
.pcp-messages::-webkit-scrollbar-thumb { background:#e2e8f0;border-radius:99px; }

.pcp-msg { display:flex; }
.pcp-msg--out { justify-content:flex-start; }
.pcp-msg--in  { justify-content:flex-end; }
.pcp-msg--sys { justify-content:center; }

.pcp-bubble {
    max-width:72%;padding:9px 13px;border-radius:14px;
    font-size:.82rem;line-height:1.6;word-break:break-word;position:relative;
}
.pcp-msg--out .pcp-bubble { background:#fff;color:#1e293b;border:1.5px solid #e2e8f0;border-bottom-right-radius:4px; }
.pcp-msg--in  .pcp-bubble { background:var(--pc,#3b82f6);color:#fff;border-bottom-left-radius:4px; }
.pcp-msg--sys .pcp-bubble { background:#f1f5f9;color:#94a3b8;font-size:.72rem;padding:4px 12px;border-radius:20px; }
.pcp-msg-time { font-size:.62rem;opacity:.6;margin-top:3px;display:block; }

/* ورودی */
.pcp-input-bar {
    padding:12px 18px;border-top:1px solid #f1f5f9;display:flex;gap:10px;
    background:#fff;align-items:flex-end;flex-shrink:0;
}
.pcp-textarea {
    flex:1;padding:9px 12px;border:1.5px solid #e2e8f0;border-radius:12px;
    font-size:.83rem;font-family:inherit;resize:none;line-height:1.5;
    transition:border-color .2s;max-height:120px;overflow-y:auto;
}
.pcp-textarea:focus { outline:none;border-color:var(--pc,#3b82f6); }
.pcp-send-btn {
    padding:9px 20px;border:none;border-radius:12px;
    background:var(--pc,#3b82f6);color:#fff;
    font-size:.82rem;font-weight:700;cursor:pointer;font-family:inherit;
    transition:opacity .15s;white-space:nowrap;flex-shrink:0;
}
.pcp-send-btn:hover { opacity:.88; }
.pcp-send-btn:disabled { opacity:.5;cursor:default; }

/* بسته‌شده */
.pcp-closed-bar { padding:10px 18px;text-align:center;background:#fef2f2;color:#991b1b;font-size:.78rem;font-weight:600; }

.pcp-spinner { width:28px;height:28px;border:3px solid #f1f5f9;border-top-color:var(--pc,#3b82f6);border-radius:50%;animation:pcp-spin .7s linear infinite;margin:40px auto; }
@keyframes pcp-spin { to{ transform:rotate(360deg) } }
`;

export class PortalChatPanel {
    /**
     * @param {Object} opts
     * @param {HTMLElement} opts.container
     * @param {string}      opts.source    — 'melk' | 'shop' | 'service' | ''
     * @param {string}      opts.token     — JWT توکن
     * @param {string}      [opts.apiBase] — پیش‌فرض: /acc-engine/api.php/acc/v1
     */
    constructor({ container, source = '', token = '', apiBase = '/acc-engine/api.php/acc/v1' }) {
        this.container  = container;
        this.source     = source;
        this.token      = token;
        this.apiBase    = apiBase;
        this.meta       = PORTAL_LABELS[source] || PORTAL_LABELS.erp;
        this._rooms     = [];
        this._activeRoom = null;
        this._lastMsgId  = 0;
        this._pollTimer  = null;
        this._filter     = 'open';
        this._destroyed  = false;
    }

    /* ── mount ── */
    mount() {
        this._injectCSS();
        this.container.innerHTML = this._html();
        this.container.style.setProperty('--pc', this.meta.color);
        this._bindRefs();
        this._bindEvents();
        this._loadRooms();
        this._startPoll();
    }

    destroy() {
        clearInterval(this._pollTimer);
        this._destroyed = true;
    }

    /* ── ساختار HTML ── */
    _html() {
        return `
        <div class="pcp-wrap">
            <div class="pcp-sidebar">
                <div class="pcp-sidebar-head">
                    <div class="pcp-sidebar-title">
                        <div class="pcp-sidebar-title-icon" style="background:${this.meta.bg};">${this.meta.icon}</div>
                        <span>${this.meta.title}</span>
                    </div>
                    <div class="pcp-filter-row">
                        <select class="pcp-sel" data-ref="filterSel">
                            <option value="open">باز</option>
                            <option value="pending">در انتظار</option>
                            <option value="closed">بسته</option>
                            <option value="all">همه</option>
                        </select>
                        <button class="pcp-refresh" data-ref="refreshBtn" title="بارگذاری مجدد">↻</button>
                    </div>
                </div>
                <div class="pcp-stats" data-ref="statsBar">
                    <div class="pcp-stat"><div class="pcp-stat-n" style="color:${this.meta.color}">—</div><div class="pcp-stat-l">کل</div></div>
                    <div class="pcp-stat"><div class="pcp-stat-n" style="color:#10b981">—</div><div class="pcp-stat-l">باز</div></div>
                    <div class="pcp-stat"><div class="pcp-stat-n" style="color:#ef4444">—</div><div class="pcp-stat-l">منتظر</div></div>
                </div>
                <div class="pcp-list" data-ref="listEl"></div>
            </div>
            <div class="pcp-conv" data-ref="convEl">
                <div class="pcp-empty" data-ref="emptyEl">
                    <div class="pcp-empty-icon">${this.meta.icon}</div>
                    <b style="font-size:.88rem;font-weight:700;color:#64748b">${this.meta.title}</b>
                    <span style="font-size:.76rem">یک گفتگو را از لیست انتخاب کنید</span>
                </div>
            </div>
        </div>`;
    }

    _bindRefs() {
        const $ = (n) => this.container.querySelector(`[data-ref="${n}"]`);
        this._refs = {
            filterSel: $('filterSel'),
            refreshBtn: $('refreshBtn'),
            statsBar:   $('statsBar'),
            listEl:     $('listEl'),
            convEl:     $('convEl'),
            emptyEl:    $('emptyEl'),
        };
    }

    _bindEvents() {
        this._refs.refreshBtn.addEventListener('click', () => this._loadRooms());
        this._refs.filterSel.addEventListener('change', (e) => {
            this._filter = e.target.value;
            this._loadRooms();
        });
    }

    /* ── API ── */
    async _api(method, path, body = null) {
        const url = `${this.apiBase}/${path}`;
        const opts = {
            method,
            headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.token}` },
        };
        if (body) opts.body = JSON.stringify(body);
        const res = await fetch(url, opts);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
    }

    /* ── بارگذاری لیست ── */
    async _loadRooms() {
        const listEl = this._refs.listEl;
        listEl.innerHTML = `<div class="pcp-spinner"></div>`;
        try {
            const params = new URLSearchParams({ status: this._filter });
            if (this.source) params.append('source', this.source);
            const res = await this._api('GET', `chat/support/rooms?${params}`);
            this._rooms = res?.data ?? [];
            this._updateStats();
            this._renderList();
        } catch (e) {
            listEl.innerHTML = `<div style="padding:20px;text-align:center;color:#ef4444;font-size:.78rem;">خطا: ${this._esc(e.message)}</div>`;
        }
    }

    _updateStats() {
        const nums = this._refs.statsBar.querySelectorAll('.pcp-stat-n');
        nums[0].textContent = this._rooms.length;
        nums[1].textContent = this._rooms.filter(r => r.status === 'open').length;
        nums[2].textContent = this._rooms.filter(r => r.status === 'pending').length;
    }

    _renderList() {
        const listEl = this._refs.listEl;
        if (!this._rooms.length) {
            listEl.innerHTML = `<div style="padding:32px 16px;text-align:center;color:#94a3b8;font-size:.8rem;">گفتگویی یافت نشد</div>`;
            return;
        }
        listEl.innerHTML = '';
        this._rooms.forEach(r => {
            const isActive = this._activeRoom?.id == r.id;
            const name     = r.visitor_name || 'بازدیدکننده';
            const statusDot = { open:'#10b981', pending:'#f59e0b', closed:'#94a3b8' }[r.status] || '#94a3b8';
            const unread   = +r.unread_count || +r.visitor_msg_count || 0;
            const div = document.createElement('div');
            div.className = `pcp-room${isActive ? ' pcp-room--active' : ''}`;
            div.innerHTML = `
                <div class="pcp-room-av" style="background:${isActive ? this.meta.bg : '#f0f9ff'};color:${this.meta.color}">
                    ${name.charAt(0).toUpperCase()}
                </div>
                <div class="pcp-room-info">
                    <div class="pcp-room-name">${this._esc(name)}</div>
                    <div class="pcp-room-last">${this._esc((r.last_body || '—').slice(0, 40))}</div>
                </div>
                <div class="pcp-room-meta">
                    ${unread ? `<span class="pcp-unread">${unread}</span>` : `<span class="pcp-status-dot" style="background:${statusDot}"></span>`}
                    <span class="pcp-time">${this._relTime(r.updated_at || r.created_at)}</span>
                </div>`;
            div.addEventListener('click', () => this._openRoom(r));
            listEl.appendChild(div);
        });
    }

    /* ── باز کردن گفتگو ── */
    async _openRoom(room) {
        this._activeRoom = room;
        this._lastMsgId  = 0;
        this._renderList();
        this._refs.emptyEl.style.display = 'none';

        const conv = this._refs.convEl;
        const name = room.visitor_name || 'بازدیدکننده';

        conv.innerHTML = `
        <div class="pcp-conv-head">
            <div class="pcp-conv-av" style="background:${this.meta.bg};color:${this.meta.color}">${name.charAt(0).toUpperCase()}</div>
            <div style="flex:1;min-width:0;">
                <div class="pcp-conv-name">${this._esc(name)}</div>
                <div class="pcp-conv-meta">
                    ${room.visitor_phone ? `<span class="pcp-meta-chip" style="background:#dcfce7;color:#166534;">📱 ${this._esc(room.visitor_phone)}</span>` : ''}
                    ${room.tracking_code ? `<span class="pcp-meta-chip" style="background:${this.meta.bg};color:${this.meta.color};font-family:monospace;">🎫 ${this._esc(room.tracking_code)}</span>` : ''}
                    <span class="pcp-meta-chip" style="background:${{ open:'#dcfce7', pending:'#fef3c7', closed:'#f1f5f9' }[room.status]||'#f1f5f9'};color:${{ open:'#166534', pending:'#92400e', closed:'#64748b' }[room.status]||'#64748b'}">
                        ${{ open:'باز', pending:'در انتظار', closed:'بسته' }[room.status]||room.status}
                    </span>
                </div>
            </div>
            <div class="pcp-conv-actions">
                ${room.status !== 'closed' ? `<button class="pcp-action-btn pcp-action-btn--danger" data-ref="closeBtn">🔒 بستن گفتگو</button>` : ''}
            </div>
        </div>
        <div class="pcp-messages" data-ref="msgsEl"></div>
        ${room.status !== 'closed' ? `
        <div class="pcp-input-bar">
            <textarea class="pcp-textarea" data-ref="replyTa" rows="2" placeholder="پیام خود را بنویسید…"></textarea>
            <button class="pcp-send-btn" data-ref="sendBtn">ارسال ➤</button>
        </div>` : `<div class="pcp-closed-bar">🔒 این گفتگو بسته شده است</div>`}`;

        // bind
        const q = (n) => conv.querySelector(`[data-ref="${n}"]`);
        q('sendBtn')?.addEventListener('click', () => this._sendReply());
        q('replyTa')?.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this._sendReply(); }
        });
        q('closeBtn')?.addEventListener('click', () => this._closeRoom(room.id));

        await this._loadMessages();
    }

    async _loadMessages() {
        if (!this._activeRoom) return;
        try {
            const res = await this._api('GET', `chat/support/rooms/${this._activeRoom.id}?last_id=${this._lastMsgId}`);
            const msgs = res?.data?.messages ?? [];
            const container = this._refs.convEl.querySelector('[data-ref="msgsEl"]');
            if (!container) return;
            msgs.forEach(m => {
                if (m.id > this._lastMsgId) {
                    this._lastMsgId = +m.id;
                    this._appendMsg(container, m);
                }
            });
            container.scrollTop = container.scrollHeight;
        } catch {}
    }

    _appendMsg(container, m) {
        const isOperator = m.sender_type === 'agent' || (m.sender_type === 'user' && m.msg_type !== 'system');
        const isSystem   = m.sender_type === 'system' || m.msg_type === 'system';
        const time = new Date(m.created_at).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' });
        const div = document.createElement('div');
        if (isSystem) {
            div.className = 'pcp-msg pcp-msg--sys';
            div.innerHTML = `<div class="pcp-bubble">${this._esc(m.body || m.message)}</div>`;
        } else {
            div.className = `pcp-msg ${isOperator ? 'pcp-msg--out' : 'pcp-msg--in'}`;
            div.innerHTML = `<div class="pcp-bubble">${this._esc(m.body || m.message)}<span class="pcp-msg-time">${time}</span></div>`;
        }
        container.appendChild(div);
    }

    async _sendReply() {
        if (!this._activeRoom) return;
        const ta = this._refs.convEl.querySelector('[data-ref="replyTa"]');
        const body = ta?.value.trim();
        if (!body) return;
        ta.value = '';
        try {
            await this._api('POST', `chat/support/rooms/${this._activeRoom.id}/reply`, { body });
            await this._loadMessages();
        } catch (e) { alert(e.message); }
    }

    async _closeRoom(id) {
        if (!confirm('این گفتگو بسته شود؟')) return;
        await this._api('POST', `chat/support/rooms/${id}/close`, {});
        await this._loadRooms();
        this._activeRoom = null;
        this._refs.convEl.innerHTML = `<div class="pcp-empty"><div class="pcp-empty-icon">✅</div><span style="font-size:.8rem;color:#64748b">گفتگو بسته شد</span></div>`;
    }

    /* ── Polling ── */
    _startPoll() {
        this._pollTimer = setInterval(async () => {
            if (this._destroyed) return;
            await this._loadRooms();
            if (this._activeRoom) await this._loadMessages();
        }, 6000);
    }

    /* ── helpers ── */
    _relTime(dt) {
        if (!dt) return '—';
        const diff = Math.floor((Date.now() - new Date(dt)) / 1000);
        if (diff < 60)    return 'همین الان';
        if (diff < 3600)  return `${Math.floor(diff / 60)} دق`;
        if (diff < 86400) return `${Math.floor(diff / 3600)} ساعت`;
        return `${Math.floor(diff / 86400)} روز`;
    }
    _esc(s) { return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }

    _injectCSS() {
        if (document.getElementById(CSS_ID)) return;
        const s = document.createElement('style');
        s.id = CSS_ID; s.textContent = CSS;
        document.head.appendChild(s);
    }
}
