/**
 * CartService.js — سرویس مشترک سبد خرید (localStorage)
 * Singleton — import { cart } from "./CartService.js"
 */

const STORAGE_KEY = "acc_cart_v1";

class CartService {
    _items    = [];   // [{id, name, price, image, qty}]
    _listeners = [];

    constructor() {
        this._load();
    }

    /* ── Public API ─────────────────────────────── */
    add(product, qty = 1) {
        const existing = this._items.find(i => i.id === product.id);
        if (existing) {
            existing.qty += qty;
        } else {
            this._items.push({
                id:    product.id,
                name:  product.name,
                price: parseFloat(product.price) || 0,
                image: product.image || null,
                qty,
            });
        }
        this._save();
        this._notify();
    }

    remove(productId) {
        this._items = this._items.filter(i => i.id !== productId);
        this._save();
        this._notify();
    }

    setQty(productId, qty) {
        const item = this._items.find(i => i.id === productId);
        if (!item) return;
        if (qty <= 0) { this.remove(productId); return; }
        item.qty = qty;
        this._save();
        this._notify();
    }

    clear() {
        this._items = [];
        this._save();
        this._notify();
    }

    get items() { return [...this._items]; }
    get count() { return this._items.reduce((s, i) => s + i.qty, 0); }
    get total() { return this._items.reduce((s, i) => s + i.price * i.qty, 0); }

    onChange(fn) {
        this._listeners.push(fn);
        return () => { this._listeners = this._listeners.filter(l => l !== fn); };
    }

    /* ── Internals ──────────────────────────────── */
    _load() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            this._items = raw ? JSON.parse(raw) : [];
        } catch { this._items = []; }
    }

    _save() {
        try { localStorage.setItem(STORAGE_KEY, JSON.stringify(this._items)); } catch {}
    }

    _notify() {
        this._listeners.forEach(fn => fn(this._items));
    }
}

export const cart = new CartService();
