/**
 * TitanCart — Product Compare.
 *
 * Manages a compare list in localStorage, shows floating compare bar,
 * and opens a side-by-side comparison modal.
 *
 * Reads titancartConfig.apiUrl, titancartConfig.symbol, titancartConfig.allowCompare.
 *
 * @package TitanCart
 */
(function () {
    'use strict';

    var cfg = window.titancartConfig || {};
    if (!cfg.allowCompare) return;

    var API     = (cfg.apiUrl || '/wp-json/titancart/v1') + '/store/products/by-ids';
    var SYMBOL  = cfg.symbol || '$';
    var MAX     = 4; // Max products to compare
    var STORE_KEY = 'tc_compare_list';

    // ── State ───────────────────────────────────────────────────────────────
    function getList() {
        try { return JSON.parse(localStorage.getItem(STORE_KEY)) || []; }
        catch (e) { return []; }
    }
    function saveList(ids) {
        localStorage.setItem(STORE_KEY, JSON.stringify(ids.slice(0, MAX)));
        syncUI();
    }
    function toggle(id) {
        id = Number(id);
        var list = getList();
        var idx  = list.indexOf(id);
        if (idx > -1) {
            list.splice(idx, 1);
        } else {
            if (list.length >= MAX) {
                showToast('Compare list is full (max ' + MAX + ' products)');
                return;
            }
            list.push(id);
        }
        saveList(list);
    }
    function remove(id) {
        var list = getList().filter(function (x) { return x !== Number(id); });
        saveList(list);
    }
    function clearAll() {
        saveList([]);
    }

    // ── Toast ───────────────────────────────────────────────────────────────
    function showToast(msg) {
        var el = document.createElement('div');
        el.className = 'tc-compare-toast';
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function () { el.classList.add('tc-compare-toast--show'); }, 10);
        setTimeout(function () {
            el.classList.remove('tc-compare-toast--show');
            setTimeout(function () { el.remove(); }, 300);
        }, 2500);
    }

    // ── Floating Compare Bar ────────────────────────────────────────────────
    var bar = null;
    function ensureBar() {
        if (bar) return;
        bar = document.createElement('div');
        bar.className = 'tc-compare-bar';
        bar.innerHTML =
            '<div class="tc-compare-bar__inner">' +
                '<div class="tc-compare-bar__items" id="tc-compare-bar-items"></div>' +
                '<div class="tc-compare-bar__actions">' +
                    '<span class="tc-compare-bar__count" id="tc-compare-bar-count"></span>' +
                    '<button class="tc-compare-bar__btn tc-compare-bar__btn--compare" id="tc-compare-bar-open">Compare</button>' +
                    '<button class="tc-compare-bar__btn tc-compare-bar__btn--clear" id="tc-compare-bar-clear">Clear</button>' +
                '</div>' +
            '</div>';
        document.body.appendChild(bar);

        document.getElementById('tc-compare-bar-open').addEventListener('click', openModal);
        document.getElementById('tc-compare-bar-clear').addEventListener('click', function () {
            clearAll();
        });
    }

    // ── Sync all UI: buttons, bar ───────────────────────────────────────────
    function syncUI() {
        var list = getList();

        // Toggle active class on all compare buttons.
        document.querySelectorAll('.tc-compare-toggle').forEach(function (btn) {
            var pid = Number(btn.dataset.productId);
            var isIn = list.indexOf(pid) > -1;
            btn.classList.toggle('tc-compare-toggle--active', isIn);
            // Update icon.
            var icon = btn.querySelector('i.bi');
            if (icon) {
                icon.className = isIn ? 'bi bi-check-lg' : 'bi bi-arrow-left-right';
            }
        });

        // Show/hide bar.
        if (list.length > 0) {
            ensureBar();
            bar.classList.add('tc-compare-bar--visible');
            document.getElementById('tc-compare-bar-count').textContent = list.length + ' of ' + MAX;
        } else if (bar) {
            bar.classList.remove('tc-compare-bar--visible');
        }
    }

    // ── Event delegation for toggle buttons ─────────────────────────────────
    document.addEventListener('click', function (e) {
        var btn = e.target.closest('.tc-compare-toggle');
        if (!btn) return;
        e.preventDefault();
        e.stopPropagation();
        toggle(btn.dataset.productId);
    });

    // ── Compare Modal ───────────────────────────────────────────────────────
    var modal = null;
    function createModal() {
        if (modal) return;
        modal = document.createElement('div');
        modal.className = 'tc-compare-modal-overlay';
        modal.innerHTML =
            '<div class="tc-compare-modal">' +
                '<div class="tc-compare-modal__header">' +
                    '<h3>Compare Products</h3>' +
                    '<button class="tc-compare-modal__close" id="tc-compare-close">&times;</button>' +
                '</div>' +
                '<div class="tc-compare-modal__body" id="tc-compare-body">' +
                    '<div class="tc-compare-modal__loading"><div class="tc-spinner"></div> Loading products…</div>' +
                '</div>' +
            '</div>';
        document.body.appendChild(modal);

        modal.addEventListener('click', function (e) {
            if (e.target === modal) closeModal();
        });
        document.getElementById('tc-compare-close').addEventListener('click', closeModal);
    }

    function openModal() {
        var list = getList();
        if (list.length < 2) {
            showToast('Add at least 2 products to compare');
            return;
        }
        createModal();
        modal.classList.add('tc-compare-modal-overlay--open');
        document.body.style.overflow = 'hidden';

        // Fetch product data.
        var body = document.getElementById('tc-compare-body');
        body.innerHTML = '<div class="tc-compare-modal__loading"><div class="tc-spinner"></div> Loading products…</div>';

        fetch(API + '?ids=' + list.join(','))
            .then(function (r) { return r.json(); })
            .then(function (data) {
                var products = data.data || data.products || data || [];
                if (!products.length) {
                    body.innerHTML = '<p style="padding:24px;color:#999">Could not load product data.</p>';
                    return;
                }
                renderComparison(products, body);
            })
            .catch(function () {
                body.innerHTML = '<p style="padding:24px;color:#c84646">Error loading products. Please try again.</p>';
            });
    }

    function closeModal() {
        if (modal) {
            modal.classList.remove('tc-compare-modal-overlay--open');
            document.body.style.overflow = '';
        }
    }

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal && modal.classList.contains('tc-compare-modal-overlay--open')) {
            closeModal();
        }
    });

    function esc(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
    function fmtPrice(n) { return Number(n).toFixed(2); }

    function renderComparison(products, container) {
        // Build attribute rows. Collect all unique attribute names across products.
        var attrMap = {};  // { 'Color': [ 'Black', 'Red', null, 'Blue' ] }
        products.forEach(function (p, i) {
            var feats = p.features || p.attributes || [];
            feats.forEach(function (f) {
                var name = f.name || f.feature_name || '';
                if (!name) return;
                if (!attrMap[name]) attrMap[name] = new Array(products.length).fill('—');
                var val = f.variant_name || f.value_str || f.value_text || '';
                if (f.value_int !== undefined && f.value_int !== null && f.value_int !== '') val = String(f.value_int);
                if (f.value_float !== undefined && f.value_float !== null && f.value_float !== '') val = String(f.value_float);
                if (val) attrMap[name][i] = val;
            });
        });

        var colW = Math.max(180, Math.floor(100 / products.length));
        var html = '<div class="tc-compare-table-wrap"><table class="tc-compare-table">';

        // Header: product images + names.
        html += '<thead><tr><th class="tc-compare-table__label"></th>';
        products.forEach(function (p) {
            var imgUrl = '';
            if (p.image_url) imgUrl = p.image_url;
            else if (p.image && p.image.url) imgUrl = p.image.url;
            html += '<th class="tc-compare-table__product">' +
                (imgUrl ? '<img src="' + esc(imgUrl) + '" alt="' + esc(p.name) + '" class="tc-compare-table__img">' : '') +
                '<a href="' + esc(p.url || '#') + '" class="tc-compare-table__name">' + esc(p.name) + '</a>' +
                '<button class="tc-compare-table__remove" data-remove-id="' + p.id + '" title="Remove">&times;</button>' +
            '</th>';
        });
        html += '</tr></thead><tbody>';

        // Price row.
        html += '<tr><td class="tc-compare-table__label">Price</td>';
        products.forEach(function (p) {
            var price = Number(p.price || 0);
            var listP = Number(p.list_price || 0);
            var cell = '<strong>' + SYMBOL + fmtPrice(price) + '</strong>';
            if (listP > price && listP > 0) {
                cell += ' <s style="color:#999;font-size:13px">' + SYMBOL + fmtPrice(listP) + '</s>';
            }
            html += '<td>' + cell + '</td>';
        });
        html += '</tr>';

        // Availability row.
        html += '<tr><td class="tc-compare-table__label">Availability</td>';
        products.forEach(function (p) {
            var inStock = (p.stock_status || p.in_stock) === 'in_stock' || p.in_stock === true;
            html += '<td>' + (inStock
                ? '<span style="color:#16a34a;font-weight:500">In Stock</span>'
                : '<span style="color:#dc2626;font-weight:500">Out of Stock</span>') + '</td>';
        });
        html += '</tr>';

        // Product Code row.
        html += '<tr><td class="tc-compare-table__label">Product Code</td>';
        products.forEach(function (p) {
            html += '<td>' + esc(p.sku || p.product_code || '—') + '</td>';
        });
        html += '</tr>';

        // Attribute rows.
        Object.keys(attrMap).forEach(function (name) {
            html += '<tr><td class="tc-compare-table__label">' + esc(name) + '</td>';
            attrMap[name].forEach(function (val) {
                html += '<td>' + esc(val) + '</td>';
            });
            html += '</tr>';
        });

        html += '</tbody></table></div>';
        container.innerHTML = html;

        // Remove buttons.
        container.querySelectorAll('.tc-compare-table__remove').forEach(function (btn) {
            btn.addEventListener('click', function () {
                remove(btn.dataset.removeId);
                var list = getList();
                if (list.length < 2) {
                    closeModal();
                } else {
                    openModal(); // Re-fetch and re-render.
                }
            });
        });
    }

    // ── Init ────────────────────────────────────────────────────────────────
    syncUI();
})();
