/**
 * WppShopSection.js — نمایش محصولات با طرح WooCommerce
 */
import SectionBase from "../../accounting/SectionBase.js";
import { cart }   from "../CartService.js";
import CartModal  from "../CartModal.js";

export default class WppShopSection extends SectionBase {

    _products   = [];
    _categories = [];
    _total      = 0;
    _totalPages = 1;
    _page       = 1;
    _perPage    = 24;
    _search     = "";
    _category   = "";
    _orderby    = "date";
    _order      = "DESC";
    _viewMode   = "grid";
    _cartModal  = null;
    _unsubCart  = null;

    async template() {
        return `
        <div class="wpp-wrap" dir="rtl">
            <!-- نوار ابزار -->
            <div class="wpp-topbar">
                <div class="wpp-search-box">
                    <span class="wpp-search-icon">🔍</span>
                    <input class="wpp-search-input" data-ref="searchInput" placeholder="جستجوی محصول..." autocomplete="off">
                </div>
                <select class="wpp-select" data-ref="catSel">
                    <option value="">همه دسته‌ها</option>
                </select>
                <select class="wpp-select" data-ref="sortSel">
                    <option value="date|DESC">جدیدترین</option>
                    <option value="date|ASC">قدیمی‌ترین</option>
                    <option value="title|ASC">نام (الف-ی)</option>
                    <option value="title|DESC">نام (ی-الف)</option>
                    <option value="price|ASC">ارزان‌ترین</option>
                    <option value="price|DESC">گران‌ترین</option>
                </select>
                <div class="wpp-view-toggle">
                    <button class="wpp-view-btn active" data-ref="gridBtn" title="شبکه‌ای">⊞</button>
                    <button class="wpp-view-btn" data-ref="listBtn" title="لیستی">☰</button>
                </div>
                <button class="wpp-cart-icon-btn" data-ref="cartIconBtn" title="سبد خرید">
                    🛒 <span class="wpp-cart-count" data-ref="cartCountBadge">0</span>
                </button>
                <span class="wpp-result-count" data-ref="countLbl"></span>
            </div>

            <!-- محتوا -->
            <div class="wpp-layout">
                <aside class="wpp-sidebar">
                    <div class="wpp-sidebar-title">📂 دسته‌بندی‌ها</div>
                    <ul class="wpp-cat-list" data-ref="catList">
                        <li class="wpp-cat-item active" data-slug="">همه محصولات</li>
                    </ul>
                </aside>
                <main class="wpp-main">
                    <div class="wpp-grid" data-ref="grid"></div>
                    <div class="wpp-pagination" data-ref="pagination"></div>
                </main>
            </div>

            <!-- Modal -->
            <div class="wpp-modal-overlay" data-ref="modal" style="display:none;">
                <div class="wpp-modal" data-ref="modalBody"></div>
            </div>
        </div>`;
    }

    async afterRender() {
        this._cartModal = new CartModal(this.api);
        this._unsubCart = cart.onChange(() => this._updateCartBadge());
        this._updateCartBadge();

        /* بررسی بازگشت از درگاه پرداخت */
        this._checkPaymentReturn();

        await this._loadCategories();
        await this._loadProducts();
        this._bindTopbar();
    }

    _updateCartBadge() {
        const badge = this.ref("cartCountBadge");
        if (!badge) return;
        const count = cart.count;
        badge.textContent = count;
        badge.style.display = count > 0 ? "inline-flex" : "none";
        const btn = this.ref("cartIconBtn");
        if (btn) btn.classList.toggle("has-items", count > 0);
    }

    _checkPaymentReturn() {
        const params = new URLSearchParams(window.location.search);
        const payment = params.get("payment");
        if (!payment) return;

        /* پاک کردن URL */
        const cleanUrl = window.location.pathname;
        window.history.replaceState({}, "", cleanUrl);

        if (payment === "success") {
            this._cartModal.showResult(true, params.get("ref") || "");
        } else if (payment === "cancelled") {
            this._cartModal.showResult(false, null, "پرداخت توسط شما لغو شد");
        } else if (payment === "failed") {
            this._cartModal.showResult(false, null, "پرداخت ناموفق بود (کد: " + (params.get("code") || "-") + ")");
        }
    }

    /* ── داده ─────────────────────────────────────────── */
    async _loadCategories() {
        try {
            const res = await this.api.get("wp/categories");
            this._categories = res?.data ?? [];
            this._renderCatList();
            this._fillCatSelect();
        } catch {}
    }

    async _loadProducts() {
        const grid = this.ref("grid");
        grid.innerHTML = this._skeletons();
        try {
            const res = await this.api.get("wp/products", {
                page: this._page, per_page: this._perPage,
                search: this._search, category: this._category,
                orderby: this._orderby, order: this._order,
            });
            this._products   = res?.data ?? [];
            this._total      = res?.total ?? 0;
            this._totalPages = res?.total_pages ?? 1;
            this._renderGrid();
            this._renderPagination();
            this._updateCount();
        } catch (e) {
            grid.innerHTML = `<div class="acc-error" style="grid-column:1/-1;">⚠️ ${this.escape(e.message)}</div>`;
        }
    }

    /* ── رندر ─────────────────────────────────────────── */
    _renderCatList() {
        const list = this.ref("catList");
        const allItem = `<li class="wpp-cat-item ${!this._category ? 'active' : ''}" data-slug="">همه محصولات <span class="wpp-cat-count">${this._total}</span></li>`;
        const items = this._categories.map(c => `
        <li class="wpp-cat-item ${this._category === c.slug ? 'active' : ''}" data-slug="${c.slug}">
            ${this.escape(c.name)} <span class="wpp-cat-count">${c.count}</span>
        </li>`).join("");
        list.innerHTML = allItem + items;
        list.querySelectorAll(".wpp-cat-item").forEach(li => {
            li.addEventListener("click", () => {
                this._category = li.dataset.slug;
                this._page = 1;
                list.querySelectorAll(".wpp-cat-item").forEach(i => i.classList.remove("active"));
                li.classList.add("active");
                this.ref("catSel").value = this._category;
                this._loadProducts();
            });
        });
    }

    _fillCatSelect() {
        const sel = this.ref("catSel");
        sel.innerHTML = `<option value="">همه دسته‌ها</option>` +
            this._categories.map(c => `<option value="${c.slug}">${this.escape(c.name)}</option>`).join("");
        sel.value = this._category;
    }

    _renderGrid() {
        const grid = this.ref("grid");
        grid.className = this._viewMode === "list" ? "wpp-list" : "wpp-grid";
        if (!this._products.length) {
            grid.innerHTML = `<div class="wpp-empty" style="grid-column:1/-1;"><div class="wpp-empty-icon">🛒</div><div>محصولی یافت نشد</div></div>`;
            return;
        }
        grid.innerHTML = this._products.map(p => this._card(p)).join("");
        grid.querySelectorAll(".wpp-card").forEach(card => {
            card.addEventListener("click", e => {
                const cartBtn = e.target.closest(".wpp-cart-btn");
                if (cartBtn) {
                    const p = this._products.find(x => x.id == cartBtn.dataset.id);
                    if (p) this._addToCart(p, cartBtn);
                    return;
                }
                const p = this._products.find(x => x.id == card.dataset.id);
                if (p) this._openModal(p);
            });
        });
    }

    _card(p) {
        const img = p.image
            ? `<img src="${this.escape(p.image)}" alt="${this.escape(p.name)}" loading="lazy" class="wpp-card-img">`
            : `<div class="wpp-card-img wpp-no-img">📦</div>`;
        const badge = p.on_sale ? `<span class="wpp-badge wpp-badge--sale">تخفیف</span>`
                    : !p.in_stock ? `<span class="wpp-badge wpp-badge--outstock">ناموجود</span>` : '';
        const stars = this._stars(parseFloat(p.average_rating ?? 0));
        const price = this._priceHtml(p);
        const cats  = (p.categories ?? []).map(c => `<span class="wpp-card-cat">${this.escape(c.name)}</span>`).join("");

        if (this._viewMode === "list") return `
        <div class="wpp-card wpp-card--list" data-id="${p.id}">
            <div class="wpp-card-img-wrap">${img}${badge}</div>
            <div class="wpp-card-body">
                <div class="wpp-card-cats">${cats}</div>
                <h3 class="wpp-card-title">${this.escape(p.name)}</h3>
                ${p.short_desc ? `<p class="wpp-card-desc">${this.escape(p.short_desc.slice(0,120))}${p.short_desc.length>120?'…':''}</p>` : ''}
                ${p.sku ? `<div class="wpp-card-sku">SKU: ${this.escape(p.sku)}</div>` : ''}
                <div class="wpp-card-footer">
                    <div class="wpp-card-price">${price}</div>
                    ${p.in_stock ? `<button class="wpp-cart-btn" data-id="${p.id}">🛒 افزودن به سبد</button>` : `<span class="wpp-out-label">ناموجود</span>`}
                </div>
            </div>
        </div>`;

        return `
        <div class="wpp-card" data-id="${p.id}">
            <div class="wpp-card-img-wrap">
                ${img}${badge}
                <div class="wpp-card-overlay"><button class="wpp-quick-view">👁 مشاهده سریع</button></div>
            </div>
            <div class="wpp-card-body">
                <div class="wpp-card-cats">${cats}</div>
                <h3 class="wpp-card-title">${this.escape(p.name)}</h3>
                ${stars ? `<div class="wpp-stars">${stars} <small>(${p.rating_count})</small></div>` : ''}
                <div class="wpp-card-footer">
                    <div class="wpp-card-price">${price}</div>
                    ${p.in_stock ? `<button class="wpp-cart-btn" data-id="${p.id}">🛒</button>` : `<span class="wpp-out-label">ناموجود</span>`}
                </div>
            </div>
        </div>`;
    }

    _renderPagination() {
        const el = this.ref("pagination");
        if (this._totalPages <= 1) { el.innerHTML = ""; return; }
        const pages = [];
        for (let i = 1; i <= this._totalPages; i++) {
            if (i === 1 || i === this._totalPages || (i >= this._page - 2 && i <= this._page + 2))
                pages.push(i);
            else if (pages[pages.length - 1] !== '…') pages.push('…');
        }
        el.innerHTML =
            `<button class="wpp-page-btn" data-p="${this._page-1}" ${this._page<=1?'disabled':''}>‹</button>` +
            pages.map(p => p === '…' ? `<span class="wpp-page-dots">…</span>`
                : `<button class="wpp-page-btn ${p===this._page?'active':''}" data-p="${p}">${p}</button>`).join("") +
            `<button class="wpp-page-btn" data-p="${this._page+1}" ${this._page>=this._totalPages?'disabled':''}>›</button>`;
        el.querySelectorAll(".wpp-page-btn:not([disabled])").forEach(btn => {
            btn.addEventListener("click", () => { this._page = +btn.dataset.p; this._loadProducts(); });
        });
    }

    _updateCount() {
        const lbl = this.ref("countLbl");
        if (!lbl) return;
        const from = (this._page - 1) * this._perPage + 1;
        const to   = Math.min(this._page * this._perPage, this._total);
        lbl.textContent = this._total ? `نمایش ${from}–${to} از ${this._total} محصول` : "محصولی یافت نشد";
    }

    /* ── Modal ────────────────────────────────────────── */
    _openModal(p) {
        const modal = this.ref("modal");
        const body  = this.ref("modalBody");
        const price = this._priceHtml(p);
        const stars = this._stars(parseFloat(p.average_rating ?? 0));
        const gallery = [p.image, ...(p.gallery ?? [])].filter(Boolean);

        body.innerHTML = `
        <button class="wpp-modal-close" data-ref="closeBtn">✕</button>
        <div class="wpp-modal-inner">
            <div class="wpp-modal-images">
                ${p.image ? `<img id="wpp-main-img" src="${this.escape(p.image)}" class="wpp-modal-main-img">` : `<div class="wpp-modal-main-img wpp-no-img-lg">📦</div>`}
                ${gallery.length > 1 ? `<div class="wpp-gallery">${gallery.map((img, i) =>
                    `<img src="${this.escape(img)}" class="wpp-gallery-thumb ${i===0?'active':''}"
                         onclick="document.getElementById('wpp-main-img').src='${this.escape(img)}';
                         this.closest('.wpp-gallery').querySelectorAll('.wpp-gallery-thumb').forEach(t=>t.classList.remove('active'));this.classList.add('active');">`
                ).join("")}</div>` : ''}
            </div>
            <div class="wpp-modal-info">
                <div class="wpp-card-cats">${(p.categories??[]).map(c=>`<span class="wpp-card-cat">${this.escape(c.name)}</span>`).join("")}</div>
                <h2 class="wpp-modal-title">${this.escape(p.name)}</h2>
                ${stars ? `<div class="wpp-stars wpp-stars--lg">${stars} <small>${p.rating_count} نظر</small></div>` : ''}
                ${p.sku ? `<div class="wpp-modal-sku">کد محصول: <strong>${this.escape(p.sku)}</strong></div>` : ''}
                <div class="wpp-modal-price">${price}</div>
                <div class="wpp-stock-status ${p.in_stock ? 'wpp-instock' : 'wpp-outstock'}">
                    ${p.in_stock ? `✅ موجود در انبار${p.stock_qty!=null?` (${p.stock_qty} عدد)`:''}` : '❌ ناموجود'}
                </div>
                ${p.short_desc ? `<div class="wpp-modal-short-desc">${this.escape(p.short_desc)}</div>` : ''}
                ${p.in_stock ? `
                <div class="wpp-modal-actions">
                    <div class="wpp-qty-wrap">
                        <button class="wpp-qty-btn" data-ref="qtyMinus">−</button>
                        <input type="number" class="wpp-qty-input" data-ref="qtyInp" value="1" min="1">
                        <button class="wpp-qty-btn" data-ref="qtyPlus">+</button>
                    </div>
                    <button class="wpp-add-cart-btn">🛒 افزودن به سبد خرید</button>
                </div>` : ''}
                ${(p.tags??[]).length ? `<div class="wpp-modal-tags">${p.tags.map(t=>`<span class="wpp-tag">${this.escape(t)}</span>`).join("")}</div>` : ''}
                ${p.permalink ? `<a class="wpp-view-link" href="${this.escape(p.permalink)}" target="_blank">مشاهده در فروشگاه ↗</a>` : ''}
            </div>
        </div>
        ${p.description ? `<div class="wpp-modal-desc"><h4>توضیحات محصول</h4><div class="wpp-desc-text">${this.escape(p.description)}</div></div>` : ''}`;

        this._bindRefs();
        modal.style.display = "flex";
        document.body.style.overflow = "hidden";

        this.ref("closeBtn").addEventListener("click", () => this._closeModal());
        modal.addEventListener("click", e => { if (e.target === modal) this._closeModal(); });
        this.ref("qtyMinus")?.addEventListener("click", () => { const i = this.ref("qtyInp"); if (+i.value > 1) i.value = +i.value - 1; });
        this.ref("qtyPlus")?.addEventListener("click",  () => { const i = this.ref("qtyInp"); i.value = +i.value + 1; });

        body.querySelector(".wpp-add-cart-btn")?.addEventListener("click", () => {
            const qty = parseInt(this.ref("qtyInp")?.value ?? "1", 10) || 1;
            this._addToCart(p, null, qty);
            this._closeModal();
        });
    }

    _closeModal() {
        this.ref("modal").style.display = "none";
        document.body.style.overflow = "";
    }

    /* ── افزودن به سبد ──────────────────────────────── */
    _addToCart(product, btnEl, qty = 1) {
        cart.add(product, qty);
        if (btnEl) {
            const orig = btnEl.innerHTML;
            btnEl.innerHTML = "✓ اضافه شد";
            btnEl.disabled = true;
            setTimeout(() => { if (btnEl) { btnEl.innerHTML = orig; btnEl.disabled = false; } }, 1200);
        }
    }

    /* ── Events ───────────────────────────────────────── */
    _bindTopbar() {
        let timer;
        this.ref("searchInput").addEventListener("input", e => {
            clearTimeout(timer);
            timer = setTimeout(() => { this._search = e.target.value.trim(); this._page = 1; this._loadProducts(); }, 400);
        });
        this.ref("catSel").addEventListener("change", e => {
            this._category = e.target.value; this._page = 1;
            this._renderCatList(); this._loadProducts();
        });
        this.ref("sortSel").addEventListener("change", e => {
            [this._orderby, this._order] = e.target.value.split("|"); this._page = 1; this._loadProducts();
        });
        this.ref("gridBtn").addEventListener("click", () => {
            this._viewMode = "grid";
            this.ref("gridBtn").classList.add("active"); this.ref("listBtn").classList.remove("active");
            this._renderGrid();
        });
        this.ref("listBtn").addEventListener("click", () => {
            this._viewMode = "list";
            this.ref("listBtn").classList.add("active"); this.ref("gridBtn").classList.remove("active");
            this._renderGrid();
        });
        document.addEventListener("keydown", e => { if (e.key === "Escape") this._closeModal(); });
        this.ref("cartIconBtn").addEventListener("click", () => this._cartModal.open());
    }

    /* ── Helpers ──────────────────────────────────────── */
    _priceHtml(p) {
        const fmt = v => v ? new Intl.NumberFormat("fa-IR").format(Math.round(+v)) + " تومان" : "";
        if (p.on_sale && p.sale_price && p.regular_price) {
            const pct = Math.round((1 - p.sale_price / p.regular_price) * 100);
            return `<span class="wpp-price-sale">${fmt(p.sale_price)}</span>
                    <span class="wpp-price-old">${fmt(p.regular_price)}</span>
                    <span class="wpp-price-pct">−${pct}%</span>`;
        }
        if (p.price) return `<span class="wpp-price-normal">${fmt(p.price)}</span>`;
        return `<span class="wpp-price-contact">تماس بگیرید</span>`;
    }

    _stars(avg) {
        if (!avg) return "";
        return "★".repeat(Math.floor(avg)) + (avg - Math.floor(avg) >= 0.5 ? "½" : "") + "☆".repeat(5 - Math.floor(avg) - (avg - Math.floor(avg) >= 0.5 ? 1 : 0));
    }

    _skeletons(n = 8) {
        return Array.from({ length: n }, () => `
        <div class="wpp-skeleton">
            <div class="wpp-sk-img sk-anim"></div>
            <div class="wpp-sk-line sk-anim" style="width:80%"></div>
            <div class="wpp-sk-line sk-anim" style="width:50%"></div>
        </div>`).join("");
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }

    destroy() {
        this._unsubCart?.();
        this._cartModal?.close();
        super.destroy?.();
    }
}
