/**
 * DocumentIssuanceSection.js
 * صدور سند — ثبت رویداد مالی، پیش‌نمایش جریان‌ها، تأیید / لغو
 */

import SectionBase from "../SectionBase.js";
const BaseView = SectionBase;

export default class DocumentIssuanceSection extends BaseView {

    static title = "";

    constructor(props = {}) {
        super(props);
        this.api        = props.api;
        this._events    = [];
        this._accounts  = [];
        this._dimensions = [];
        this._page      = 1;
        this._pageSize  = 20;
        this._stateFilter = "";
        this._suggest     = null;   // آخرین پیشنهادِ دریافت‌شده
        this._suggestTimer = null;
    }

    async template() {
        return `
            <div class="doc-layout">

                <!-- فرم ثبت رویداد جدید -->
                <div class="doc-form" data-ref="createForm">
                    <div class="doc-form__title">➕ ثبت رویداد مالی جدید</div>

                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نوع رویداد</label>
                            <input data-ref="fEventType" type="text" list="evtTypesList"
                                   placeholder="مثال: SALES_INVOICE" required autocomplete="off">
                            <datalist id="evtTypesList" data-ref="evtTypesList"></datalist>
                        </div>
                        <div class="acc-form-group">
                            <label>مبلغ پایه</label>
                            <input data-ref="fAmount" type="number" min="0" step="any"
                                   placeholder="0" required>
                        </div>
                    </div>

                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>حساب مرجع (اختیاری)</label>
                            <select data-ref="fAccount">
                                <option value="">— انتخاب کنید —</option>
                            </select>
                        </div>
                        <div class="acc-form-group">
                            <label>بُعد (Dimension)</label>
                            <select data-ref="fDimension">
                                <option value="">— انتخاب کنید —</option>
                            </select>
                        </div>
                    </div>

                    <!-- پنلِ پیشنهاد + پیش‌نمایشِ بدهکار/بستانکار -->
                    <div class="doc-suggest" data-ref="suggestPanel" style="display:none;"></div>

                    <div class="doc-metadata">
                        <div class="doc-metadata__title">متادیتا (مقادیر اضافه)</div>
                        <div data-ref="metaRows"></div>
                        <button type="button" class="acc-btn acc-btn--secondary acc-btn--sm"
                                data-ref="addMetaBtn" style="margin-top:8px;">+ افزودن فیلد</button>
                    </div>

                    <div style="margin-top:16px;display:flex;gap:10px;align-items:center;">
                        <button class="acc-btn acc-btn--primary" data-ref="submitEventBtn">
                            ثبت و صدور جریان‌ها
                        </button>
                        <span class="acc-loading" data-ref="createSpinner" style="display:none;padding:0;gap:6px;">
                            <span class="acc-spinner"></span> در حال ثبت...
                        </span>
                    </div>
                </div>

                <!-- لیست رویدادها -->
                <div>
                    <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap;">
                        <strong style="font-size:14px;">📋 رویدادهای ثبت‌شده</strong>
                        <select class="event-type-filter" data-ref="stateFilter">
                            <option value="">همه وضعیت‌ها</option>
                            <option value="pending">در انتظار</option>
                            <option value="posted">ثبت‌شده</option>
                            <option value="confirmed">تأییدشده</option>
                            <option value="cancelled">لغوشده</option>
                            <option value="failed">خطا</option>
                        </select>
                        <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="refreshBtn">🔄 بارگذاری مجدد</button>
                    </div>
                    <div data-ref="eventsList"></div>
                    <div data-ref="pagination" style="display:flex;gap:8px;margin-top:14px;justify-content:center;"></div>
                </div>

            </div>
        `;
    }

    async afterRender() {
        await this._loadLookups();
        await this._loadEventTypes();

        this.on(this.ref("addMetaBtn"),   "click",  () => this._addMetaRow());
        this.on(this.ref("submitEventBtn"), "click", () => this._submitEvent());
        this.on(this.ref("refreshBtn"),   "click",  () => this._loadEvents());
        this.on(this.ref("stateFilter"),  "change", e => {
            this._stateFilter = e.target.value;
            this._page = 1;
            this._loadEvents();
        });

        // نوع‌رویداد تغییر کرد → پیشنهاد بگیر (debounce)
        this.on(this.ref("fEventType"), "input", e => {
            const et = e.target.value.trim();
            clearTimeout(this._suggestTimer);
            this._suggestTimer = setTimeout(() => this._loadSuggestion(et), 350);
        });
        // مبلغِ پایه تغییر کرد → پیش‌نمایش را تازه کن
        this.on(this.ref("fAmount"), "input", () => this._recalcPreview());

        await this._loadEvents();
    }

    /* ---------- Event types (datalist) ---------- */

    async _loadEventTypes() {
        try {
            const res = await this.api.get("/accounting/event-types");
            const list = this.ref("evtTypesList");
            if (!list) return;
            list.innerHTML = (res?.data ?? []).map(t => `<option value="${this.escape(t)}">`).join("");
        } catch { /* non-fatal */ }
    }

    /* ---------- Lookups ---------- */

    async _loadLookups() {
        try {
            const [accRes, dimRes] = await Promise.all([
                this.api.get("/accounting/accounts"),
                this.api.get("/accounting/dimensions"),
            ]);

            const accounts   = accRes?.data  ?? [];
            const dimensions = dimRes?.data  ?? [];

            const accSel = this.ref("fAccount");
            accounts.forEach(a => {
                const opt = document.createElement("option");
                opt.value = a.id;
                opt.textContent = `${a.code} — ${a.name}`;
                accSel.appendChild(opt);
            });

            const dimSel = this.ref("fDimension");
            dimensions.forEach(d => {
                const opt = document.createElement("option");
                opt.value = d.id;
                const grp = d.group_name || d.dim_type || "بُعد";
                opt.textContent = `${grp}: ${d.name ?? ("#" + (d.entity_id ?? ""))}`;
                dimSel.appendChild(opt);
            });

            this._accounts   = accounts;
            this._dimensions = dimensions;
        } catch { /* non-fatal */ }
    }

    /* ---------- Meta rows ---------- */

    _addMetaRow(key = "", value = "", locked = false) {
        const rows = this.ref("metaRows");
        const row  = document.createElement("div");
        row.className = "doc-metadata-row";
        row.innerHTML = `
            <input type="text"  placeholder="کلید (مثال: vat_amount)" value="${this.escape(key)}"
                   class="meta-key" ${locked ? "readonly style='background:#f1f5f9'" : ""}>
            <input type="number" placeholder="مقدار" value="${this.escape(value)}"
                   class="meta-val" step="any">
        `;
        // تغییرِ مقدار → پیش‌نمایش را تازه کن
        row.querySelector(".meta-val").addEventListener("input", () => this._recalcPreview());
        rows.appendChild(row);
    }

    _collectMeta() {
        const result = {};
        this.ref("metaRows").querySelectorAll(".doc-metadata-row").forEach(row => {
            const key = row.querySelector(".meta-key").value.trim();
            const val = row.querySelector(".meta-val").value.trim();
            if (key) result[key] = Number(val) || val;
        });
        return Object.keys(result).length ? result : null;
    }

    /* ---------- Suggestion engine (پیشنهاد + پیش‌نمایش) ---------- */

    _currentPayload() {
        const p = {};
        const amt = parseFloat(this.ref("fAmount")?.value);
        if (!isNaN(amt)) p.amount = amt;
        this.ref("metaRows")?.querySelectorAll(".doc-metadata-row").forEach(row => {
            const k = row.querySelector(".meta-key").value.trim();
            const v = row.querySelector(".meta-val").value.trim();
            if (k && v !== "") p[k] = Number(v) || 0;
        });
        return p;
    }

    async _loadSuggestion(et) {
        const panel = this.ref("suggestPanel");
        if (!et) { this._suggest = null; this._lastTplKey = null; if (panel) panel.style.display = "none"; return; }
        try {
            const res = await this.api.get("/accounting/suggest", { event_type: et });
            this._suggest = res?.data ?? null;
        } catch { this._suggest = null; }
        if (!this._suggest) { if (panel) panel.style.display = "none"; return; }

        const tpl = this._suggest.template;
        const key = tpl ? `tpl:${tpl.id}` : `none:${et}`;
        // فقط وقتی template عوض شد، فیلدهای source_field را بساز (تا مقادیر پاک نشوند)
        if (key !== this._lastTplKey) {
            this._lastTplKey = key;
            if (tpl) {
                this.ref("metaRows").innerHTML = "";
                (this._suggest.source_fields || []).forEach(f => {
                    if (f !== "amount") this._addMetaRow(f, "", true);
                });
            }
        }
        this._renderSuggest();
        this._recalcPreview();
    }

    _renderSuggest() {
        const panel = this.ref("suggestPanel");
        if (!panel || !this._suggest) return;
        const s = this._suggest;
        panel.style.display = "block";

        if (s.template) {
            const t = s.template;
            const arts = t.pairs.map(p => `
                <div class="doc-sg-art">
                    <span class="flow-direction__from">${this.escape(p.dr_code)} ${this.escape(p.dr_name)}</span>
                    <span style="color:#94a3b8">→</span>
                    <span class="flow-direction__to">${this.escape(p.cr_code)} ${this.escape(p.cr_name)}</span>
                    <span class="doc-sg-src">[${this.escape(p.source_field || "amount")}]</span>
                    ${p.article_code ? `<span class="doc-sg-link" title="${this.escape(p.article_label || "")}">🔗 ${this.escape(p.article_code)}</span>` : ""}
                </div>`).join("");
            const hist = s.history.posted_count
                ? `${new Intl.NumberFormat("fa-IR").format(s.history.posted_count)} بار قبلاً ثبت شده`
                : "تا حالا ثبت نشده";
            panel.innerHTML = `
                <div class="doc-sg-head">🔮 ${this.escape(t.template_name || s.event_type || "")} <small>v${t.version} · ${hist}</small></div>
                <div class="doc-sg-arts">${arts}</div>
                <div data-ref="docPreview"></div>`;
        } else {
            const sugg = s.suggested_articles || [];
            const hint = sugg.length
                ? `<div class="doc-sg-arts">${sugg.map(a => `<div class="doc-sg-art"><b>${this.escape(a.code)}</b> ${this.escape(a.label)} <span class="doc-sg-src">[${this.escape(a.amount_source)}]</span></div>`).join("")}</div>`
                : "";
            panel.innerHTML = `
                <div class="doc-sg-head" style="color:#b45309">⚠️ برای «${this.escape(s.event_type)}» template فعالی نیست.</div>
                <div style="font-size:12px;color:#64748b;margin:4px 0 8px;">مقادیر را با «متادیتا» دستی وارد کنید، یا یک template بسازید.${sugg.length ? " آرتیکل‌های پیشنهادیِ هم‌دسته:" : ""}</div>
                ${hint}`;
        }
    }

    _recalcPreview() {
        const panel = this.ref("suggestPanel");
        if (!panel) return;
        const box = panel.querySelector("[data-ref='docPreview']");
        if (!box || !this._suggest?.template) return;

        const payload = this._currentPayload();
        const n = v => new Intl.NumberFormat("fa-IR").format(Number(v || 0));
        let total = 0; const rows = [];
        this._suggest.template.pairs.forEach(p => {
            const amt = (p.source_field && p.source_field !== "")
                ? Number(payload[p.source_field] || 0)
                : Number(payload.amount || 0);
            if (!amt) return;
            total += amt;
            rows.push(`<tr>
                <td><span class="flow-direction__from">${this.escape(p.dr_code)}</span> ${this.escape(p.dr_name)}</td>
                <td><span class="flow-direction__to">${this.escape(p.cr_code)}</span> ${this.escape(p.cr_name)}</td>
                <td class="num">${n(amt)}</td>
            </tr>`);
        });

        if (!rows.length) {
            box.innerHTML = `<div style="font-size:12px;color:#94a3b8;padding:8px 0;">مبالغ را وارد کنید تا پیش‌نمایشِ آرتیکل‌ها بیاید.</div>`;
            return;
        }
        box.innerHTML = `
            <table class="flows-table" style="margin-top:8px;">
                <thead><tr><th>حساب بدهکار</th><th>حساب بستانکار</th><th>مبلغ</th></tr></thead>
                <tbody>${rows.join("")}</tbody>
                <tfoot><tr style="font-weight:700;background:#f8fafc;"><td colspan="2">جمع</td><td class="num">${n(total)}</td></tr></tfoot>
            </table>
            <div style="font-size:11px;color:#059669;margin-top:4px;">✓ هر آرتیکل در یک ردیف، ذاتاً تراز (بدهکار = بستانکار).</div>`;
    }

    /* ---------- Submit event ---------- */

    async _submitEvent() {
        const eventType  = this.ref("fEventType").value.trim();
        const amount     = parseFloat(this.ref("fAmount").value);
        const accountId  = this.ref("fAccount").value   || null;
        const dimId      = this.ref("fDimension").value || null;
        const metadata   = this._collectMeta();

        if (!eventType) { alert("نوع رویداد الزامی است."); return; }
        if (isNaN(amount) || amount <= 0) { alert("مبلغ معتبر وارد کنید."); return; }

        const btn = this.ref("submitEventBtn");
        const spn = this.ref("createSpinner");
        btn.disabled = true;
        spn.style.display = "flex";

        try {
            const body = {
                event_type:   eventType,
                amount:       amount,
                account_id:   accountId ? Number(accountId) : null,
                dimension_id: dimId     ? Number(dimId)     : null,
                metadata:     metadata,
            };
            const res = await this.api.post("/accounting/events", body);
            const newEventId = res?.data?.id;

            // reset form
            this.ref("fEventType").value = "";
            this.ref("fAmount").value    = "";
            this.ref("fAccount").value   = "";
            this.ref("fDimension").value = "";
            this.ref("metaRows").innerHTML = "";
            this._suggest = null;
            this._lastTplKey = null;
            const sp = this.ref("suggestPanel");
            if (sp) { sp.style.display = "none"; sp.innerHTML = ""; }
            this._loadEventTypes();

            await this._loadEvents();

            if (newEventId) {
                this._highlightEvent(newEventId);
            }

        } catch (err) {
            alert("خطا: " + (err?.message ?? "لطفاً دوباره تلاش کنید"));
        } finally {
            btn.disabled = false;
            spn.style.display = "none";
        }
    }

    /* ---------- Events list ---------- */

    async _loadEvents() {
        const list = this.ref("eventsList");
        list.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;

        try {
            const params = { page: this._page, per_page: this._pageSize };
            if (this._stateFilter) params.state = this._stateFilter;

            const res    = this._stateFilter
                ? await this.api.get("/accounting/events", params)
                : await this.api.get("/accounting/events", params);

            this._events = res?.data ?? [];
            const total  = res?.total ?? this._events.length;

            this._renderEvents(list);
            this._renderPagination(total);
        } catch {
            list.innerHTML = `<div class="acc-error">خطا در دریافت رویدادها</div>`;
        }
    }

    _renderEvents(list) {
        if (!this._events.length) {
            list.innerHTML = `<div class="acc-empty">رویدادی یافت نشد.</div>`;
            return;
        }

        list.innerHTML = "";
        this._events.forEach(ev => {
            const card = this._buildEventCard(ev);
            list.appendChild(card);
        });
    }

    _buildEventCard(ev) {
        const stateClass = {
            draft:      "status-badge--draft",
            pending:    "status-badge--draft",
            processing: "status-badge--pending",
            posted:     "status-badge--confirmed",
            confirmed:  "status-badge--confirmed",
            cancelled:  "status-badge--cancelled",
            failed:     "status-badge--cancelled",
        }[ev.workflow_state] ?? "status-badge--pending";

        const stateLabel = {
            draft:      "پیش‌نویس",
            pending:    "در انتظار",
            processing: "در پردازش",
            posted:     "ثبت‌شده",
            confirmed:  "تأییدشده",
            cancelled:  "لغوشده",
            failed:     "خطا",
        }[ev.workflow_state] ?? ev.workflow_state;

        const card = document.createElement("div");
        card.className = "doc-event-card";
        card.dataset.eventId = ev.id;
        card.style.cssText = "background:#fff;border:1.5px solid #e2e8f0;border-radius:12px;padding:16px 18px;margin-bottom:10px;";

        const reversalBadge = ev.reverses_event_id
            ? `<span class="status-badge status-badge--pending" title="برگشت رویداد #${ev.reverses_event_id}">↩ برگشتی</span>`
            : ev.reversed_by_event_id
                ? `<span class="status-badge status-badge--cancelled" title="برگشت خورده — سند #${ev.reversed_by_event_id}">⊘ خنثی‌شده</span>`
                : "";
        const canReverse = ["posted", "confirmed"].includes(ev.workflow_state) && !ev.reversed_by_event_id;

        card.innerHTML = `
            <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;">
                <div>
                    <span style="font-size:12px;color:#94a3b8;font-family:monospace;">#${ev.id}</span>
                    <span style="font-size:14px;font-weight:700;color:#1e293b;margin-right:8px;">${this.escape(ev.event_type)}</span>
                    <span class="status-badge ${stateClass}">${stateLabel}</span>
                    ${reversalBadge}
                </div>
                <div style="font-size:13px;color:#475569;">
                    ${new Intl.NumberFormat("fa-IR").format(ev.amount)} ریال
                </div>
            </div>
            <div style="margin-top:8px;display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-action="flows">
                    🔍 نمایش جریان‌ها
                </button>
                ${["draft","pending","failed"].includes(ev.workflow_state) ? `
                    <button class="acc-btn acc-btn--primary acc-btn--sm" data-action="post"
                            title="پست رویداد با Acc_Event_Engine">🔁 ثبت در دفتر</button>
                ` : ""}
                ${ev.workflow_state === "posted" ? `
                    <button class="acc-btn acc-btn--success acc-btn--sm" data-action="confirm">✅ تأیید نهایی</button>
                    <button class="acc-btn acc-btn--danger  acc-btn--sm" data-action="cancel">❌ لغو</button>
                ` : ""}
                ${canReverse ? `
                    <button class="acc-btn acc-btn--warning acc-btn--sm" data-action="reverse"
                            title="صدور سند برگشتی (storno)">↩ سند برگشتی</button>
                ` : ""}
            </div>
            <div class="flows-panel" data-ref="flows-${ev.id}" style="display:none;margin-top:12px;"></div>
        `;

        card.querySelector("[data-action='flows']")?.addEventListener("click", () =>
            this._toggleFlows(ev.id, card)
        );
        card.querySelector("[data-action='post']")?.addEventListener("click", () =>
            this._postToLedger(ev.id, card)
        );
        card.querySelector("[data-action='confirm']")?.addEventListener("click", () =>
            this._confirmEvent(ev.id)
        );
        card.querySelector("[data-action='reverse']")?.addEventListener("click", () =>
            this._reverseEvent(ev.id)
        );
        card.querySelector("[data-action='cancel']")?.addEventListener("click", () =>
            this._cancelEvent(ev.id)
        );

        return card;
    }

    /* ---------- Flows panel ---------- */

    async _toggleFlows(eventId, card) {
        const panel = card.querySelector(`.flows-panel`);
        if (!panel) return;

        if (panel.style.display !== "none") {
            panel.style.display = "none";
            return;
        }

        panel.style.display = "block";
        panel.innerHTML = `<div class="acc-loading" style="padding:16px 0;"><div class="acc-spinner"></div></div>`;

        try {
            const res   = await this.api.get("/accounting/flows", { event_id: eventId });
            const flows = res?.data ?? [];
            this._renderFlowsPanel(panel, flows);
        } catch {
            panel.innerHTML = `<div class="acc-error">خطا در دریافت جریان‌ها</div>`;
        }
    }

    _renderFlowsPanel(panel, flows) {
        if (!flows.length) {
            panel.innerHTML = `<div class="acc-empty" style="padding:16px 0;">جریانی تولید نشده است.</div>`;
            return;
        }

        panel.innerHTML = `
            <div class="flows-preview">
                <div class="flows-preview__title">
                    جریان‌های مالی
                    <span class="flows-preview__badge">${flows.length} جریان</span>
                </div>
                <table class="flows-table">
                    <thead>
                        <tr>
                            <th>از حساب</th>
                            <th>به حساب</th>
                            <th>مبلغ (ریال)</th>
                            <th>وضعیت</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${flows.map(f => `
                            <tr>
                                <td>
                                    <div class="flow-direction__from">
                                        ${this.escape(f.from_account_name ?? "#" + f.from_account_id)}
                                    </div>
                                </td>
                                <td>
                                    <div class="flow-direction__to">
                                        ${this.escape(f.to_account_name ?? "#" + f.to_account_id)}
                                    </div>
                                </td>
                                <td class="flow-amount num">
                                    ${new Intl.NumberFormat("fa-IR").format(f.amount)}
                                </td>
                                <td>
                                    <span class="status-badge ${f.is_confirmed ? "status-badge--confirmed" : "status-badge--draft"}">
                                        ${f.is_confirmed ? "تأیید" : "پیش‌نویس"}
                                    </span>
                                </td>
                            </tr>
                        `).join("")}
                    </tbody>
                </table>
            </div>
        `;
    }

    /* ---------- Post to Ledger (Acc_Event_Engine) ---------- */

    async _postToLedger(eventId, card) {
        const postBtn = card.querySelector("[data-action='post']");
        if (postBtn) { postBtn.disabled = true; postBtn.textContent = "⏳ در حال ثبت..."; }

        try {
            const res = await this.api.post(`/accounting/events/${eventId}/post`, {});

            if (res?.success) {
                // نمایش موفقیت
                const msg = res.message ?? "ثبت موفق";
                const toast = document.createElement("div");
                toast.style.cssText = "position:fixed;bottom:24px;right:24px;background:#059669;color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;box-shadow:0 4px 20px rgba(0,0,0,.15);";
                toast.textContent = "✅ " + msg;
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 3000);

                await this._loadEvents();
            } else {
                const errMsg = res?.message ?? "خطای نامشخص";
                alert(`خطا در ثبت سند:\n${errMsg}`);
                if (postBtn) { postBtn.disabled = false; postBtn.textContent = "🔁 ثبت در دفتر"; }
            }
        } catch (err) {
            alert("خطا: " + (err?.message ?? ""));
            if (postBtn) { postBtn.disabled = false; postBtn.textContent = "🔁 ثبت در دفتر"; }
        }
    }

    /* ---------- Confirm / Cancel ---------- */

    async _confirmEvent(eventId) {
        if (!confirm("تأیید این رویداد؟ پس از تأیید قابل لغو نیست.")) return;
        try {
            await this.api.post(`/accounting/events/${eventId}/confirm`, {});
            await this._loadEvents();
        } catch (err) {
            alert("خطا: " + (err?.message ?? ""));
        }
    }

    async _reverseEvent(eventId) {
        if (!confirm("صدور سند برگشتی (storno) برای این رویداد؟")) return;
        try {
            const res = await this.api.post(`/accounting/events/${eventId}/reverse`, {});
            alert(res?.message || (res?.success ? "سند برگشتی صادر شد" : "خطا"));
            await this._loadEvents();
        } catch (e) {
            alert("خطا: " + (e?.message ?? ""));
        }
    }

    async _cancelEvent(eventId) {
        if (!confirm("لغو این رویداد؟")) return;
        try {
            await this.api.post(`/accounting/events/${eventId}/cancel`, {});
            await this._loadEvents();
        } catch (err) {
            alert("خطا: " + (err?.message ?? ""));
        }
    }

    /* ---------- Pagination ---------- */

    _renderPagination(total) {
        const pages = Math.ceil(total / this._pageSize);
        const pg    = this.ref("pagination");
        if (!pg || pages <= 1) { if (pg) pg.innerHTML = ""; return; }

        pg.innerHTML = "";

        for (let i = 1; i <= pages; i++) {
            const btn = document.createElement("button");
            btn.className = `acc-btn acc-btn--sm ${i === this._page ? "acc-btn--primary" : "acc-btn--secondary"}`;
            btn.textContent = i;
            btn.addEventListener("click", () => {
                this._page = i;
                this._loadEvents();
            });
            pg.appendChild(btn);
        }
    }

    /* ---------- Highlight new event ---------- */

    _highlightEvent(id) {
        setTimeout(() => {
            const card = this.ref("eventsList")?.querySelector(`[data-event-id="${id}"]`);
            if (card) {
                card.style.borderColor = "#2563eb";
                card.scrollIntoView({ behavior: "smooth", block: "nearest" });
                setTimeout(() => { card.style.borderColor = ""; }, 2000);
            }
        }, 300);
    }
}
