// assets/js/views/ShopView.js — LEGACY (استفاده نمی‌شود؛ فروشگاه اصلی: AragShopView.js + shop.php)
// فروشگاه عمومی — شبیه WooCommerce

export default class ShopView {

    constructor() {
        this.root     = null;
        this._page    = 1;
        this._catId   = '';
        this._search  = '';
        this._sort    = 'date';
        this._total   = 0;
        this._perPage = 12;
        this._searchTimer = null;
        this._cart    = this._loadCart();
        this._categories = [];
    }

    render(root) {
        this.root = root;
        root.innerHTML = this._skeleton();
        this._bindToolbar();
        this._loadCategories();
        this._loadProducts();
        this._bindCart();
        this._checkProductParam();
    }

    _siteUrl() {
        const base = window.ACC_SHOP_CFG?.baseUrl || '/acc-engine/';
        return base.endsWith('/') ? base : base + '/';
    }

    _skeleton() {
        const siteUrl = this._siteUrl();
        const cartCount = this._cart.reduce((s, i) => s + i.qty, 0);

        return `
        <div class="lp-wrap lp-wrap--shop">

            <header class="lp-header">
                <div class="lp-header__brand">
                    <a href="${siteUrl}" class="lp-header__brand-link">
                        <span class="lp-header__logo">🛒</span>
                        <span class="lp-header__name">فروشگاه ACC</span>
                    </a>
                </div>
                <nav class="lp-header__nav">
                    <a href="${siteUrl}" class="lp-header__link">خانه</a>
                    <a href="${siteUrl}shop.php" class="lp-header__link lp-header__link--active">فروشگاه</a>
                </nav>
                <div class="lp-header__actions">
                    <button class="lp-cart-btn" id="shop-cart-btn" type="button">
                        🛒 سبد خرید
                        <span class="lp-cart-badge" id="shop-cart-badge">${cartCount || ''}</span>
                    </button>
                    <a href="${siteUrl}" class="lp-portal-btn lp-portal-btn--outline">🔐 پورتال</a>
                </div>
            </header>

            <div class="shop-breadcrumb">
                <a href="${siteUrl}">خانه</a>
                <span>›</span>
                <span>فروشگاه</span>
            </div>

            <div class="shop-layout">

                <aside class="shop-sidebar" id="shop-sidebar">
                    <div class="shop-sidebar__title">دسته‌بندی‌ها</div>
                    <ul class="shop-cat-list" id="shop-cat-list">
                        <li><button class="shop-cat-item active" data-cat="">همه محصولات</button></li>
                    </ul>
                </aside>

                <main class="shop-main">

                    <div class="lp-shop-toolbar">
                        <div class="lp-shop-search">
                            <span class="lp-shop-search__icon">🔍</span>
                            <input id="shop-search" placeholder="جستجوی محصول..." class="lp-shop-search__input">
                        </div>
                        <select id="shop-sort" class="lp-shop-select">
                            <option value="date">جدیدترین</option>
                            <option value="price">ارزان‌ترین</option>
                            <option value="price-desc">گران‌ترین</option>
                            <option value="title">نام (الفبا)</option>
                        </select>
                        <span class="lp-shop-count" id="shop-count"></span>
                    </div>

                    <div class="lp-products" id="shop-products">
                        ${this._skeletonCards()}
                    </div>

                    <div class="lp-pagination" id="shop-pagination"></div>
                </main>
            </div>

            <!-- مودال جزئیات محصول -->
            <div class="shop-modal" id="shop-modal" hidden>
                <div class="shop-modal__backdrop" id="shop-modal-backdrop"></div>
                <div class="shop-modal__box" id="shop-modal-box"></div>
            </div>

            <!-- پنل سبد خرید -->
            <div class="shop-cart-panel" id="shop-cart-panel" hidden>
                <div class="shop-cart-panel__head">
                    <span>سبد خرید</span>
                    <button type="button" id="shop-cart-close">✕</button>
                </div>
                <div class="shop-cart-panel__body" id="shop-cart-body"></div>
                <div class="shop-cart-panel__foot" id="shop-cart-foot"></div>
            </div>

            <footer class="lp-footer">
                <div class="lp-footer__inner">
                    <span>© ۱۴۰۴ — فروشگاه ACC Engine</span>
                    <a href="${siteUrl}" class="lp-footer__portal">🏠 صفحه اصلی</a>
                </div>
            </footer>
        </div>`;
    }

    _skeletonCards() {
        return Array(8).fill(0).map(() => `
            <div class="lp-card lp-card--skeleton">
                <div class="lp-card__img sk-anim"></div>
                <div class="lp-card__body">
                    <div class="lp-sk-line sk-anim" style="width:70%"></div>
                    <div class="lp-sk-line sk-anim" style="width:40%;margin-top:6px"></div>
                </div>
            </div>`).join('');
    }

    _bindToolbar() {
        const searchInp = this.root.querySelector('#shop-search');
        searchInp?.addEventListener('input', () => {
            clearTimeout(this._searchTimer);
            this._searchTimer = setTimeout(() => {
                this._search = searchInp.value.trim();
                this._page   = 1;
                this._loadProducts();
            }, 400);
        });

        this.root.querySelector('#shop-sort')?.addEventListener('change', e => {
            this._sort = e.target.value;
            this._page = 1;
            this._loadProducts();
        });
    }

    async _loadCategories() {
        try {
            const res  = await this._get('/public/categories');
            const cats = res.data || [];
            this._categories = cats;
            const list = this.root.querySelector('#shop-cat-list');

            cats.forEach(c => {
                const li = document.createElement('li');
                li.innerHTML = `<button class="shop-cat-item" data-cat="${c.id}">${this._esc(c.name)} <small>(${c.count})</small></button>`;
                list.appendChild(li);
            });

            list.querySelectorAll('.shop-cat-item').forEach(btn => {
                btn.addEventListener('click', () => {
                    list.querySelectorAll('.shop-cat-item').forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    this._catId = btn.dataset.cat;
                    this._page  = 1;
                    this._loadProducts();
                });
            });
        } catch {}
    }

    async _loadProducts() {
        const grid    = this.root.querySelector('#shop-products');
        const countEl = this.root.querySelector('#shop-count');
        grid.innerHTML = this._skeletonCards();

        const [orderby, order] = this._sortParams();

        try {
            const res = await this._get(
                `/public/products?page=${this._page}&per_page=${this._perPage}` +
                `&search=${encodeURIComponent(this._search)}` +
                `&category=${this._catId}` +
                `&orderby=${orderby}&order=${order}`
            );
            const products = res.data || [];
            this._total = res.total || products.length;

            countEl.textContent = `${this._total.toLocaleString('fa-IR')} محصول`;

            if (!products.length) {
                grid.innerHTML = `<div class="lp-empty">😕 محصولی یافت نشد</div>`;
                this.root.querySelector('#shop-pagination').innerHTML = '';
                return;
            }

            grid.innerHTML = products.map(p => this._cardHtml(p)).join('');
            this._renderPagination(res.total_pages || 1);

            grid.querySelectorAll('.lp-card[data-id]').forEach(card => {
                card.addEventListener('click', e => {
                    if (e.target.closest('.lp-card__btn-cart')) return;
                    this._openProduct(+card.dataset.id);
                });
            });

            grid.querySelectorAll('.lp-card__btn-cart').forEach(btn => {
                btn.addEventListener('click', e => {
                    e.stopPropagation();
                    const id = +btn.closest('.lp-card').dataset.id;
                    const name = btn.dataset.name;
                    const price = parseFloat(btn.dataset.price) || 0;
                    this._addToCart(id, name, price);
                });
            });
        } catch (e) {
            grid.innerHTML = `<div class="lp-empty">❌ خطا در بارگذاری محصولات</div>`;
        }
    }

    async _openProduct(id) {
        const modal = this.root.querySelector('#shop-modal');
        const box   = this.root.querySelector('#shop-modal-box');
        modal.hidden = false;
        box.innerHTML = `<div class="shop-modal__loading">در حال بارگذاری...</div>`;

        try {
            const res = await this._get(`/public/products/${id}`);
            const p   = res.data;
            if (!p) throw new Error('یافت نشد');

            const img = p.image
                ? `<img src="${p.image}" alt="${this._esc(p.name)}" class="shop-modal__img">`
                : `<div class="shop-modal__img shop-modal__img--none">🛍️</div>`;

            const price = p.sale_price
                ? `<span class="lp-price lp-price--sale">${this._fmt(p.sale_price)}</span> <s class="lp-price--old">${this._fmt(p.regular_price)}</s>`
                : (p.price ? `<span class="lp-price">${this._fmt(p.price)}</span>` : '');

            const cats = (p.categories || []).map(c => c.name).join('، ');

            box.innerHTML = `
                <button class="shop-modal__close" id="shop-modal-close" type="button">✕</button>
                <div class="shop-modal__grid">
                    <div class="shop-modal__media">${img}</div>
                    <div class="shop-modal__info">
                        <h2>${this._esc(p.name)}</h2>
                        ${cats ? `<div class="shop-modal__cats">${this._esc(cats)}</div>` : ''}
                        <div class="shop-modal__price">${price}</div>
                        <p class="shop-modal__desc">${this._esc(p.short_desc || p.description || '')}</p>
                        <div class="shop-modal__meta">
                            ${p.sku ? `<span>کد: ${this._esc(p.sku)}</span>` : ''}
                            <span>${p.in_stock ? '✅ موجود' : '❌ ناموجود'}</span>
                        </div>
                        <button class="lp-btn shop-modal__add" type="button" id="shop-modal-add"
                            ${!p.in_stock ? 'disabled' : ''}>
                            افزودن به سبد خرید
                        </button>
                    </div>
                </div>`;

            box.querySelector('#shop-modal-add')?.addEventListener('click', () => {
                const priceVal = parseFloat(p.sale_price || p.price) || 0;
                this._addToCart(p.id, p.name, priceVal);
            });
        } catch {
            box.innerHTML = `<div class="shop-modal__loading">❌ محصول یافت نشد</div>`;
        }

        const close = () => { modal.hidden = true; };
        this.root.querySelector('#shop-modal-close')?.addEventListener('click', close);
        this.root.querySelector('#shop-modal-backdrop')?.addEventListener('click', close);
    }

    _checkProductParam() {
        const params = new URLSearchParams(window.location.search);
        const id = parseInt(params.get('product'), 10);
        if (id > 0) this._openProduct(id);
    }

    _cardHtml(p) {
        const img = p.image
            ? `<img src="${p.image}" alt="${this._esc(p.name)}" loading="lazy" class="lp-card__img">`
            : `<div class="lp-card__img lp-card__img--none">🛍️</div>`;
        const price = p.sale_price
            ? `<span class="lp-price lp-price--sale">${this._fmt(p.sale_price)}</span> <s class="lp-price--old">${this._fmt(p.regular_price)}</s>`
            : (p.price ? `<span class="lp-price">${this._fmt(p.price)}</span>` : `<span class="lp-price lp-price--contact">تماس بگیرید</span>`);
        const badge = p.on_sale ? `<span class="lp-badge">تخفیف</span>` : '';
        const priceVal = p.sale_price || p.price || 0;

        return `
        <div class="lp-card" data-id="${p.id}">
            <div class="lp-card__img-wrap">${img}${badge}</div>
            <div class="lp-card__body">
                <div class="lp-card__name">${this._esc(p.name)}</div>
                <div class="lp-card__price">${price}</div>
                <button class="lp-card__btn lp-card__btn-cart" type="button"
                    data-name="${this._esc(p.name)}" data-price="${priceVal}"
                    ${!p.in_stock ? 'disabled' : ''}>
                    🛒 افزودن
                </button>
            </div>
        </div>`;
    }

    _renderPagination(totalPages) {
        const pg  = this.root.querySelector('#shop-pagination');
        const cur = this._page;
        if (totalPages <= 1) { pg.innerHTML = ''; return; }
        let html = '';
        if (cur > 1) html += `<button class="lp-pg-btn" data-p="${cur - 1}">‹ قبلی</button>`;
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || Math.abs(i - cur) <= 2) {
                html += `<button class="lp-pg-btn ${i === cur ? 'active' : ''}" data-p="${i}">${i}</button>`;
            } else if (Math.abs(i - cur) === 3) {
                html += `<span class="lp-pg-dots">…</span>`;
            }
        }
        if (cur < totalPages) html += `<button class="lp-pg-btn" data-p="${cur + 1}">بعدی ›</button>`;
        pg.innerHTML = html;
        pg.querySelectorAll('.lp-pg-btn').forEach(b => {
            b.addEventListener('click', () => {
                this._page = +b.dataset.p;
                this._loadProducts();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
        });
    }

    /* ── سبد خرید (localStorage) ── */
    _loadCart() {
        try {
            return JSON.parse(localStorage.getItem('acc_shop_cart') || '[]');
        } catch { return []; }
    }

    _saveCart() {
        localStorage.setItem('acc_shop_cart', JSON.stringify(this._cart));
        this._updateCartBadge();
    }

    _addToCart(id, name, price) {
        const item = this._cart.find(i => i.id === id);
        if (item) item.qty++;
        else this._cart.push({ id, name, price, qty: 1 });
        this._saveCart();
        this._renderCartPanel();
        this.root.querySelector('#shop-cart-panel').hidden = false;
    }

    _updateCartBadge() {
        const n = this._cart.reduce((s, i) => s + i.qty, 0);
        const badge = this.root.querySelector('#shop-cart-badge');
        if (badge) badge.textContent = n > 0 ? n : '';
    }

    _bindCart() {
        this.root.querySelector('#shop-cart-btn')?.addEventListener('click', () => {
            this._renderCartPanel();
            this.root.querySelector('#shop-cart-panel').hidden = false;
        });
        this.root.querySelector('#shop-cart-close')?.addEventListener('click', () => {
            this.root.querySelector('#shop-cart-panel').hidden = true;
        });
        this._renderCartPanel();
    }

    _renderCartPanel() {
        const body = this.root.querySelector('#shop-cart-body');
        const foot = this.root.querySelector('#shop-cart-foot');
        if (!this._cart.length) {
            body.innerHTML = `<div class="shop-cart-empty">سبد خرید خالی است</div>`;
            foot.innerHTML = '';
            return;
        }

        let total = 0;
        body.innerHTML = this._cart.map((item, idx) => {
            const sub = item.price * item.qty;
            total += sub;
            return `
            <div class="shop-cart-item">
                <div class="shop-cart-item__name">${this._esc(item.name)}</div>
                <div class="shop-cart-item__row">
                    <span>${item.qty} × ${this._fmt(item.price)}</span>
                    <button type="button" class="shop-cart-remove" data-idx="${idx}">حذف</button>
                </div>
            </div>`;
        }).join('');

        foot.innerHTML = `
            <div class="shop-cart-total">جمع: <strong>${this._fmt(total)}</strong></div>
            <button class="lp-btn" type="button" id="shop-checkout-btn">تکمیل خرید</button>`;

        body.querySelectorAll('.shop-cart-remove').forEach(btn => {
            btn.addEventListener('click', () => {
                this._cart.splice(+btn.dataset.idx, 1);
                this._saveCart();
                this._renderCartPanel();
            });
        });

        foot.querySelector('#shop-checkout-btn')?.addEventListener('click', () => {
            alert('سفارش شما ثبت شد! (نسخه نمایشی — اتصال به درگاه پرداخت در آینده)');
            this._cart = [];
            this._saveCart();
            this._renderCartPanel();
            this.root.querySelector('#shop-cart-panel').hidden = true;
        });
    }

    _sortParams() {
        switch (this._sort) {
            case 'price':      return ['price', 'ASC'];
            case 'price-desc': return ['price', 'DESC'];
            case 'title':      return ['title', 'ASC'];
            default:           return ['date', 'DESC'];
        }
    }

    _apiBase() {
        const cfg = window.ACC_SHOP_CFG?.api || '/acc-engine/api.php/acc/v1';
        return cfg.replace(/\/$/, '');
    }

    async _get(path) {
        const r = await fetch(this._apiBase() + path);
        if (!r.ok) {
            const err = await r.json().catch(() => ({}));
            throw new Error(err.message || `HTTP ${r.status}`);
        }
        return r.json();
    }

    _fmt(price) {
        const n = parseFloat(price);
        if (isNaN(n)) return price;
        return n.toLocaleString('fa-IR') + ' تومان';
    }

    _esc(str) {
        return String(str || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }
}
