/**
 * MessagesSection.js — پیام‌رسانی بین اعضای پروژه
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class MessagesSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this.cpmView    = props.cpmView ?? null;
        this._projectId = null;
        this._members   = [];
        this._messages  = [];
        this._senderId  = null; // عضو فرستنده (انتخاب‌شده توسط کاربر)
        this._pollTimer = null;
    }

    async template() {
        return `
            <div class="cpm-section-wrap">
                <div class="cpm-section-notice" data-ref="notice">
                    <span>⚠️ لطفاً ابتدا یک پروژه از تب «پروژه‌ها» انتخاب کنید.</span>
                </div>
                <div class="cpm-chat-wrap" data-ref="chatWrap" style="display:none">
                    <div class="cpm-chat-sidebar" data-ref="sidebar">
                        <div class="cpm-chat-sidebar__title">اعضای تیم</div>
                        <div class="cpm-chat-member-list" data-ref="memberList"></div>
                        <div class="cpm-chat-identity">
                            <label style="font-size:11px;color:#94a3b8;margin-bottom:4px;display:block">ارسال به‌عنوان:</label>
                            <select data-ref="senderSel" style="width:100%;padding:6px 10px;border:1.5px solid #d1d5db;border-radius:8px;font-size:12px;">
                                <option value="">— انتخاب هویت —</option>
                            </select>
                        </div>
                    </div>
                    <div class="cpm-chat-main">
                        <div class="cpm-chat-header" data-ref="chatHeader">
                            <span>💬 گفتگوی عمومی پروژه</span>
                            <button class="acc-btn acc-btn--secondary acc-btn--xs" data-ref="refreshBtn" title="بارگذاری مجدد">🔄</button>
                        </div>
                        <div class="cpm-chat-messages" data-ref="msgList"></div>
                        <form class="cpm-chat-form" data-ref="msgForm">
                            <select data-ref="receiverSel" style="min-width:130px;padding:8px 10px;border:1.5px solid #d1d5db;border-radius:8px;font-size:12px;">
                                <option value="">📢 همه اعضا</option>
                            </select>
                            <input type="text" data-ref="msgInput" placeholder="پیام خود را بنویسید..." autocomplete="off" required>
                            <button type="submit" class="acc-btn acc-btn--primary">ارسال ↑</button>
                        </form>
                    </div>
                </div>
            </div>
        `;
    }

    async afterRender() {
        // notice shown by default
    }

    async onProjectChange(project) {
        this._stopPoll();
        this._projectId = project?.id ?? null;
        if (!this._projectId) {
            this.ref("notice").style.display = "flex";
            this.ref("chatWrap").style.display = "none";
            return;
        }
        this.ref("notice").style.display = "none";
        this.ref("chatWrap").style.display = "flex";

        await this._loadMembers();
        await this._loadMessages();
        this._bindEvents();
        this._startPoll();
    }

    async _loadMembers() {
        try {
            const r = await this.api.get(`/pc/projects/${this._projectId}/members`);
            this._members = (r?.data ?? []).filter(m => m.is_active);
        } catch { this._members = []; }

        // Member list (sidebar)
        const list = this.ref("memberList");
        if (list) {
            list.innerHTML = this._members.map(m => `
                <div class="cpm-chat-member" data-mid="${m.id}">
                    <span class="cpm-chat-member__avatar">${(m.name || "?")[0]}</span>
                    <span class="cpm-chat-member__name">${this.escape(m.name)}</span>
                </div>
            `).join("") || `<div style="padding:12px;font-size:12px;color:#94a3b8">عضوی یافت نشد</div>`;
        }

        // Sender selector
        const senderSel   = this.ref("senderSel");
        const receiverSel = this.ref("receiverSel");
        if (senderSel) {
            senderSel.innerHTML = `<option value="">— انتخاب هویت —</option>` +
                this._members.map(m => `<option value="${m.id}">${this.escape(m.name)}</option>`).join("");
            // Restore previous sender
            if (this._senderId) senderSel.value = this._senderId;
        }
        if (receiverSel) {
            receiverSel.innerHTML = `<option value="">📢 همه اعضا</option>` +
                this._members.map(m => `<option value="${m.id}">🔒 ${this.escape(m.name)}</option>`).join("");
        }
    }

    async _loadMessages(silent = false) {
        if (!silent) {
            const msgList = this.ref("msgList");
            if (msgList) msgList.innerHTML = `<div class="cpm-loading" style="justify-content:center;padding:24px"><div class="acc-spinner"></div></div>`;
        }
        try {
            const r = await this.api.get(`/pc/projects/${this._projectId}/messages`);
            this._messages = r?.data ?? [];
            this._renderMessages();
        } catch {
            const msgList = this.ref("msgList");
            if (msgList && !silent) msgList.innerHTML = `<div class="acc-empty">خطا در بارگذاری پیام‌ها</div>`;
        }
    }

    _renderMessages() {
        const msgList = this.ref("msgList");
        if (!msgList) return;

        const senderId = parseInt(this.ref("senderSel")?.value || "0");
        const wasAtBottom = msgList.scrollHeight - msgList.scrollTop - msgList.clientHeight < 60;

        if (!this._messages.length) {
            msgList.innerHTML = `<div class="cpm-chat-empty">هنوز پیامی ارسال نشده. اولین نفر باشید! 💬</div>`;
            return;
        }

        msgList.innerHTML = "";
        let lastDate = "";
        this._messages.forEach(msg => {
            const dateStr = msg.created_at?.slice(0, 10) ?? "";
            if (dateStr && dateStr !== lastDate) {
                lastDate = dateStr;
                const sep = document.createElement("div");
                sep.className = "cpm-chat-date-sep";
                sep.textContent = dateStr;
                msgList.appendChild(sep);
            }

            const isMine = senderId && msg.sender_member_id == senderId;
            const isPrivate = msg.receiver_member_id != null;
            const bubble = document.createElement("div");
            bubble.className = "cpm-chat-bubble" + (isMine ? " cpm-chat-bubble--mine" : " cpm-chat-bubble--other");

            const receiverName = isPrivate
                ? (this._members.find(m => m.id == msg.receiver_member_id)?.name ?? "")
                : "";

            bubble.innerHTML = `
                <div class="cpm-chat-bubble__meta">
                    <span class="cpm-chat-bubble__sender">${this.escape(msg.sender_name || "ناشناس")}</span>
                    ${isPrivate ? `<span class="cpm-chat-bubble__private" title="پیام خصوصی">🔒 → ${this.escape(receiverName)}</span>` : ""}
                    <span class="cpm-chat-bubble__time">${msg.created_at?.slice(11, 16) ?? ""}</span>
                </div>
                <div class="cpm-chat-bubble__text">${this.escape(msg.message)}</div>
                ${isMine ? `<button class="cpm-chat-del" data-mid="${msg.id}" title="حذف">✕</button>` : ""}
            `;
            bubble.querySelector(".cpm-chat-del")?.addEventListener("click", () => this._deleteMsg(msg.id));
            msgList.appendChild(bubble);
        });

        if (wasAtBottom) msgList.scrollTop = msgList.scrollHeight;
    }

    _bindEvents() {
        const form = this.ref("msgForm");
        if (form && !form._bound) {
            form._bound = true;
            form.addEventListener("submit", async ev => {
                ev.preventDefault();
                const senderId = parseInt(this.ref("senderSel")?.value || "0");
                if (!senderId) { alert("لطفاً هویت فرستنده را انتخاب کنید."); return; }
                const text       = this.ref("msgInput")?.value?.trim();
                const receiverId = this.ref("receiverSel")?.value || null;
                if (!text) return;
                const btn = form.querySelector("[type='submit']");
                btn.disabled = true;
                try {
                    await this.api.post(`/pc/projects/${this._projectId}/messages`, {
                        sender_member_id:   senderId,
                        receiver_member_id: receiverId || null,
                        message:            text,
                    });
                    if (this.ref("msgInput")) this.ref("msgInput").value = "";
                    await this._loadMessages(true);
                    const msgList = this.ref("msgList");
                    if (msgList) msgList.scrollTop = msgList.scrollHeight;
                } catch (err) {
                    alert("خطا در ارسال: " + (err?.message ?? ""));
                } finally {
                    btn.disabled = false;
                }
            });
        }

        const senderSel = this.ref("senderSel");
        if (senderSel && !senderSel._bound) {
            senderSel._bound = true;
            senderSel.addEventListener("change", () => {
                this._senderId = parseInt(senderSel.value || "0");
                this._renderMessages();
            });
        }

        const refreshBtn = this.ref("refreshBtn");
        if (refreshBtn && !refreshBtn._bound) {
            refreshBtn._bound = true;
            refreshBtn.addEventListener("click", () => this._loadMessages());
        }
    }

    async _deleteMsg(id) {
        if (!confirm("حذف این پیام؟")) return;
        try {
            await this.api.delete(`/pc/messages/${id}`);
            await this._loadMessages(true);
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    _startPoll() {
        this._pollTimer = setInterval(() => {
            if (this._projectId) this._loadMessages(true);
        }, 30000); // هر ۳۰ ثانیه
    }

    _stopPoll() {
        if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
    }

    destroy() {
        this._stopPoll();
        super.destroy();
    }
}
