/**
 * ChatInternalSection.js — چت داخلی ERP (کارمند ↔ کارمند)
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class ChatInternalSection extends SectionBase {

    _rooms      = [];
    _activeRoom = null;
    _lastMsgId  = 0;
    _globalLast = 0;
    _pollTimer  = null;

    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>💼 چت داخلی</h3>
                        <button class="acc-btn acc-btn--xs acc-btn--primary" data-ref="newChatBtn">➕ جدید</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;">💼</div>
                        <div style="color:#94a3b8;font-size:14px;">یک گفتگو را انتخاب کنید</div>
                    </div>
                </main>
            </div>

            <!-- Modal: گفتگوی جدید -->
            <div class="acc-modal-overlay" data-ref="newChatModal" style="display:none;">
                <div class="acc-modal" style="max-width:400px;">
                    <h3 style="margin:0 0 16px;font-size:15px;">💬 گفتگوی جدید</h3>
                    <label style="display:flex;flex-direction:column;gap:4px;font-size:13px;margin-bottom:10px;">نوع
                        <select class="acc-select" data-ref="roomType">
                            <option value="direct">مستقیم (یک نفر)</option>
                            <option value="group">گروهی</option>
                        </select>
                    </label>
                    <label style="display:flex;flex-direction:column;gap:4px;font-size:13px;margin-bottom:10px;">نام گروه (اختیاری)
                        <input class="acc-input" data-ref="roomName" placeholder="مثلاً: تیم فروش">
                    </label>
                    <label style="display:flex;flex-direction:column;gap:4px;font-size:13px;margin-bottom:14px;">کاربران (ID با کاما)
                        <input class="acc-input" data-ref="roomMembers" placeholder="2,5,8">
                    </label>
                    <div style="display:flex;gap:8px;">
                        <button class="acc-btn acc-btn--primary" data-ref="createRoomBtn">ساخت</button>
                        <button class="acc-btn acc-btn--secondary" data-ref="cancelNewChat">لغو</button>
                    </div>
                </div>
            </div>
        </div>`;
    }

    async afterRender() {
        this.on(this.ref("newChatBtn"),    "click", () => { this.ref("newChatModal").style.display = "flex"; });
        this.on(this.ref("cancelNewChat"), "click", () => { this.ref("newChatModal").style.display = "none"; });
        this.on(this.ref("createRoomBtn"), "click", () => this._createRoom());
        await this._loadRooms();
        this._startPoll();
    }

    /* ── Rooms ──────────────────────────────────────── */
    async _loadRooms() {
        try {
            const res = await this.api.get("chat/rooms");
            this._rooms = res?.data ?? [];
            this._renderRooms();
        } catch {}
    }

    _renderRooms() {
        const list = this.ref("roomsList");
        if (!this._rooms.length) {
            list.innerHTML = `<div class="acc-empty" style="padding:16px;text-align:center;color:#94a3b8;font-size:13px;">گفتگویی ندارید<br><small>با دکمه ➕ شروع کنید</small></div>`;
            return;
        }
        list.innerHTML = this._rooms.map(r => {
            const active   = this._activeRoom?.id == r.id;
            const unread   = +r.unread_count || 0;
            const typeIcon = r.type === 'group' ? '👥' : '💬';
            const time     = r.last_msg_at ? this._relTime(r.last_msg_at) : '';
            return `
            <div class="chat-room-item ${active ? 'active' : ''}" data-id="${r.id}">
                <div class="chat-room-avatar">${typeIcon}</div>
                <div class="chat-room-info">
                    <div class="chat-room-name">${this.escape(r.name || `اتاق #${r.id}`)}</div>
                    <div class="chat-room-last">${this.escape((r.last_body || '').slice(0,40))}</div>
                </div>
                <div class="chat-room-meta">
                    ${unread ? `<span class="chat-unread-badge">${unread}</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);
            });
        });
    }

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

        const panel = this.ref("convPanel");
        const icon  = room.type === 'group' ? '👥' : '💬';
        panel.innerHTML = `
        <div class="chat-conv-header">
            <div class="chat-conv-avatar">${icon}</div>
            <div class="chat-conv-info">
                <strong>${this.escape(room.name || `اتاق #${room.id}`)}</strong>
                <small style="color:#94a3b8;">${room.type === 'group' ? 'گروهی' : 'مستقیم'}</small>
            </div>
        </div>
        <div class="chat-messages" data-ref="messages"></div>
        <div class="chat-input-area">
            <textarea class="chat-textarea" data-ref="msgInput" placeholder="پیام..." rows="2"></textarea>
            <button class="chat-send-btn" data-ref="sendBtn">ارسال ➤</button>
        </div>`;

        this._bindRefs();
        this.on(this.ref("sendBtn"), "click", () => this._sendMsg());
        this.on(this.ref("msgInput"), "keydown", e => {
            if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); this._sendMsg(); }
        });

        await this._loadMessages();
        // علامت خوانده
        this.api.post(`chat/rooms/${room.id}/read`, {}).catch(() => {});
    }

    async _loadMessages() {
        if (!this._activeRoom) return;
        try {
            const res = await this.api.get(`chat/rooms/${this._activeRoom.id}/messages`);
            const msgs = res?.data ?? [];
            const container = this.ref("messages");
            if (!container) return;
            container.innerHTML = "";
            msgs.forEach(m => { this._appendMsg(container, m); this._lastMsgId = Math.max(this._lastMsgId, +m.id); });
            container.scrollTop = container.scrollHeight;
        } catch {}
    }

    _appendMsg(container, m) {
        const isMine = m.sender_type === 'user' && +m.sender_id === (window.accCurrentUserId || 0);
        const isSystem = 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 ${isMine ? 'chat-msg--out' : 'chat-msg--in'}`;
            div.innerHTML = `
            ${!isMine ? `<div class="chat-sender-name">${this.escape(m.sender_name || m.user_display_name || '')}</div>` : ''}
            <div class="chat-bubble">${this.escape(m.body)}<span class="chat-time">${time}</span></div>`;
        }
        container.appendChild(div);
    }

    async _sendMsg() {
        if (!this._activeRoom) return;
        const inp  = this.ref("msgInput");
        const body = inp?.value.trim();
        if (!body) return;
        inp.value = "";
        try {
            await this.api.post(`chat/rooms/${this._activeRoom.id}/messages`, { body });
            await this._loadMessages();
        } catch (e) { alert(e.message); }
    }

    async _createRoom() {
        const type    = this.ref("roomType").value;
        const name    = this.ref("roomName").value.trim();
        const members = this.ref("roomMembers").value.split(",").map(s => +s.trim()).filter(Boolean);
        if (!members.length) { alert("حداقل یک کاربر وارد کنید"); return; }
        try {
            const res = await this.api.post("chat/rooms", { type, name, members });
            this.ref("newChatModal").style.display = "none";
            await this._loadRooms();
            const room = this._rooms.find(r => r.id == res.data?.room_id);
            if (room) this._openRoom(room);
        } catch (e) { alert(e.message); }
    }

    /* ── Polling ────────────────────────────────────── */
    _startPoll() {
        this._pollTimer = setInterval(async () => {
            // بررسی پیام جدید از همه اتاق‌ها
            try {
                const res = await this.api.get("chat/poll", { last_id: this._globalLast });
                const msgs = res?.data?.messages ?? [];
                if (msgs.length) {
                    this._globalLast = Math.max(...msgs.map(m => +m.id));
                    // پیام جدید در اتاق فعال
                    if (this._activeRoom) {
                        const newInActive = msgs.filter(m => m.room_id == this._activeRoom.id);
                        if (newInActive.length) {
                            const container = this.ref("messages");
                            if (container) {
                                newInActive.forEach(m => { if (+m.id > this._lastMsgId) { this._appendMsg(container, m); this._lastMsgId = +m.id; }});
                                container.scrollTop = container.scrollHeight;
                            }
                        }
                    }
                    await this._loadRooms();
                }
            } catch {}
        }, 4000);
    }

    /* ── Helpers ────────────────────────────────────── */
    _relTime(dt) {
        const diff = Math.floor((Date.now() - new Date(dt)) / 1000);
        if (diff < 60) return 'الان';
        if (diff < 3600) return `${Math.floor(diff/60)}د`;
        return `${Math.floor(diff/3600)}س`;
    }
    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
    destroy()  { clearInterval(this._pollTimer); super.destroy?.(); }
}
