/**
 * ChatSupportSection.js — پنل پشتیبانی Live Chat
 * مدیریت گفتگوهای بازدیدکنندگان سایت
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class ChatSupportSection extends SectionBase {

    _rooms       = [];
    _activeRoom  = null;
    _lastMsgId   = 0;
    _pollTimer   = null;
    _filter      = "open";
    _source      = "";

    async template() {
        return `
        <div class="chat-support-wrap" dir="rtl">
            <div class="chat-support-layout">
                <!-- ستون چپ: لیست گفتگوها -->
                <aside class="chat-rooms-panel">
                    <div class="chat-rooms-header">
                        <h3>💬 Live Chat</h3>
                        <select class="acc-select acc-select--sm" data-ref="sourceSel" title="فیلتر پورتال" style="max-width:110px;">
                            <option value="">همه پورتال‌ها</option>
                            <option value="melk">🏠 اقتصاد ملک</option>
                            <option value="shop">🛒 فروشگاه</option>
                            <option value="service">🔧 خدمات</option>
                            <option value="erp">💼 ERP</option>
                            <option value="website">🌐 سایت</option>
                        </select>
                        <select class="acc-select acc-select--sm" data-ref="filterSel">
                            <option value="open">باز</option>
                            <option value="pending">در انتظار</option>
                            <option value="closed">بسته</option>
                            <option value="all">همه</option>
                        </select>
                        <button class="acc-btn acc-btn--xs acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                    </div>
                    <div class="chat-rooms-list" data-ref="roomsList">
                        <div class="acc-loading">⏳ بارگذاری...</div>
                    </div>
                </aside>

                <!-- ستون راست: پنجره گفتگو -->
                <main class="chat-conversation-panel" data-ref="convPanel">
                    <div class="chat-empty-state">
                        <div style="font-size:48px;margin-bottom:12px;">💬</div>
                        <div style="color:#94a3b8;font-size:14px;">یک گفتگو را از لیست انتخاب کنید</div>
                    </div>
                </main>
            </div>
        </div>`;
    }

    async afterRender() {
        this.on(this.ref("refreshBtn"), "click", () => this._loadRooms());
        this.on(this.ref("filterSel"),  "change", e => { this._filter = e.target.value; this._loadRooms(); });
        this.on(this.ref("sourceSel"),  "change", e => { this._source = e.target.value; this._loadRooms(); });
        this.listen("chat:support:openRoom", async ({ conversationId }) => {
            if (!conversationId) return;
            await this._loadRooms();
            let room = this._rooms.find(r => +r.id === +conversationId);
            if (!room) {
                try {
                    const res = await this.api.get(`chat/support/rooms/${conversationId}`);
                    room = res?.data;
                } catch {}
            }
            if (room) await this._openRoom(room);
        });
        await this._loadRooms();
        this._startPoll();
    }

    /* ── Rooms ────────────────────────────────────── */
    async _loadRooms() {
        try {
            const params = { status: this._filter };
            if (this._source) params.source = this._source;
            const res = await this.api.get("chat/support/rooms", params);
            this._rooms = res?.data ?? [];
            this._renderRooms();
        } catch (e) {
            this.ref("roomsList").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _renderRooms() {
        const list = this.ref("roomsList");
        if (!this._rooms.length) {
            list.innerHTML = `<div class="acc-empty" style="padding:20px;text-align:center;color:#94a3b8;">گفتگویی وجود ندارد</div>`;
            return;
        }
        list.innerHTML = this._rooms.map(r => {
            const isActive  = this._activeRoom?.id == r.id;
            const statusCls = { open:'chat-status--open', closed:'chat-status--closed' }[r.status] ?? '';
            const time      = this._relTime(r.updated_at || r.created_at);
            const name      = r.visitor_name || 'بازدیدکننده';
            const code      = r.tracking_code ? `<span style="font-size:9px;background:#dbeafe;color:#1d4ed8;border-radius:3px;padding:1px 4px;margin-right:4px;font-family:monospace;font-weight:bold;">${this.escape(r.tracking_code)}</span>` : '';
            const unread    = +r.visitor_msg_count || 0;
            const srcMap    = { melk: ['🏠','#0ea5e9','#f0f9ff'], shop: ['🛒','#8b5cf6','#f5f3ff'], service: ['🔧','#10b981','#f0fdf4'], erp: ['💼','#3b82f6','#eff6ff'], website: ['🌐','#6366f1','#eef2ff'] };
            const [srcIcon, srcColor, srcBg] = srcMap[r.source] || ['💬','#64748b','#f1f5f9'];
            const srcBadge  = r.source ? `<span style="font-size:9px;background:${srcBg};color:${srcColor};border-radius:10px;padding:1px 6px;font-weight:700;">${srcIcon} ${r.source}</span>` : '';
            return `
            <div class="chat-room-item ${isActive ? 'active' : ''}" data-id="${r.id}">
                <div class="chat-room-avatar" style="background:${r.status==='closed'?'#f1f5f9':'#dbeafe'};">
                    ${name.charAt(0).toUpperCase()}
                </div>
                <div class="chat-room-info">
                    <div class="chat-room-name">${code}${this.escape(name)}</div>
                    <div class="chat-room-last" style="display:flex;align-items:center;gap:4px;">${srcBadge}<span>${this.escape((r.last_body || '').slice(0, 32))}</span></div>
                </div>
                <div class="chat-room-meta">
                    ${unread ? `<span class="chat-unread-badge">${unread}</span>` : `<span class="chat-status-badge ${statusCls}">${this._statusLabel(r.status)}</span>`}
                    <small style="color:#94a3b8;font-size:10px;">${time}</small>
                </div>
            </div>`;
        }).join("");

        list.querySelectorAll(".chat-room-item").forEach(el => {
            el.addEventListener("click", () => {
                const room = this._rooms.find(r => r.id == el.dataset.id);
                if (room) this._openRoom(room);
            });
        });
    }

    /* ── Open Room ────────────────────────────────── */
    async _openRoom(room) {
        this._activeRoom = room;
        this._lastMsgId  = 0;
        this._renderRooms(); // highlight

        const panel = this.ref("convPanel");
        const name  = room.visitor_name || 'بازدیدکننده';
        const portalLabels = { melk:'🏠 اقتصاد ملک', shop:'🛒 فروشگاه', service:'🔧 خدمات', erp:'💼 ERP', website:'🌐 سایت' };
        const portalColors = { melk:'#0ea5e9', shop:'#8b5cf6', service:'#10b981', erp:'#3b82f6', website:'#6366f1' };
        const portalBgs    = { melk:'#f0f9ff', shop:'#f5f3ff', service:'#f0fdf4', erp:'#eff6ff', website:'#eef2ff' };
        const portalLbl    = room.source ? (portalLabels[room.source] || room.source) : null;
        const portalColor  = portalColors[room.source] || '#64748b';
        const portalBg     = portalBgs[room.source]    || '#f8fafc';
        panel.innerHTML = `
        <div class="chat-conv-header">
            <div class="chat-conv-avatar" style="background:${portalBg};color:${portalColor};font-weight:700;">
                ${name.charAt(0).toUpperCase()}
            </div>
            <div class="chat-conv-info">
                <strong>${this.escape(name)}</strong>
                <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:2px;">
                    ${portalLbl ? `<small style="color:${portalColor};background:${portalBg};padding:2px 8px;border-radius:12px;font-weight:700;">${portalLbl}</small>` : ''}
                    ${room.visitor_phone ? `<small style="color:#166534;background:#dcfce7;padding:1px 6px;border-radius:4px;">📱 ${this.escape(room.visitor_phone)}</small>` : ''}
                    ${room.visitor_email ? `<small style="color:#64748b;">📧 ${this.escape(room.visitor_email)}</small>` : ''}
                    ${room.tracking_code ? `<small style="color:#1d4ed8;font-family:monospace;font-weight:bold;background:#dbeafe;padding:1px 6px;border-radius:4px;">🎫 ${this.escape(room.tracking_code)}</small>` : ''}
                    <small style="color:#94a3b8;">🌐 ${this.escape(room.visitor_ip || '-')}</small>
                </div>
            </div>
            <div style="display:flex;gap:6px;">
                <span class="chat-status-badge ${this._statusCls(room.status)}">${this._statusLabel(room.status)}</span>
                ${room.status !== 'closed' ? `<button class="acc-btn acc-btn--xs acc-btn--danger" data-ref="closeRoomBtn">🔒 بستن</button>` : ''}
            </div>
        </div>
        <div class="chat-messages" data-ref="messages"></div>
        <div class="chat-input-area" ${room.status === 'closed' ? 'style="display:none;"' : ''}>
            <textarea class="chat-textarea" data-ref="replyInput" placeholder="پیام خود را بنویسید..." rows="2"></textarea>
            <button class="chat-send-btn" data-ref="sendBtn">ارسال ➤</button>
        </div>`;

        this._bindRefs();
        this.ref("sendBtn")?.addEventListener("click", () => this._sendReply());
        this.ref("replyInput")?.addEventListener("keydown", e => {
            if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); this._sendReply(); }
        });
        this.ref("closeRoomBtn")?.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.ref("messages");
            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 = "chat-msg chat-msg--system";
            div.innerHTML = `<span>${this.escape(m.body)}</span>`;
        } else {
            div.className = `chat-msg ${isOperator ? 'chat-msg--out' : 'chat-msg--in'}`;
            div.innerHTML = `
            <div class="chat-bubble">
                ${this.escape(m.body || m.message)}
                <span class="chat-time">${time}</span>
            </div>`;
        }
        container.appendChild(div);
    }

    async _sendReply() {
        if (!this._activeRoom) return;
        const inp  = this.ref("replyInput");
        const body = inp?.value.trim();
        if (!body) return;
        inp.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.ref("convPanel").innerHTML = `<div class="chat-empty-state"><div style="font-size:48px;">✅</div><div style="color:#94a3b8;">گفتگو بسته شد</div></div>`;
    }

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

    /* ── Helpers ──────────────────────────────────── */
    _statusLabel(s) { return { open:'باز', pending:'در انتظار', closed:'بسته' }[s] ?? s; }
    _statusCls(s)   { return { open:'chat-status--open', pending:'chat-status--pending', closed:'chat-status--closed' }[s] ?? ''; }
    _relTime(dt) {
        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)} روز پیش`;
    }
    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }

    destroy() { clearInterval(this._pollTimer); super.destroy?.(); }
}
