/**
 * TitanCart — Wishlist AJAX script.
 *
 * Handles "Add to Wishlist" heart button clicks on product cards
 * and the product single page. Communicates with:
 *
 *   POST   /titancart/v1/wishlist/items              — add item
 *   DELETE /titancart/v1/wishlist/items/{product_id} — remove item
 *
 * Buttons use class `.tc-wishlist-toggle` with `data-product-id`.
 * The `titancartWishlist` object is localised by WishlistModule::enqueue_scripts().
 *
 * @package TitanCart
 */

/* global titancartWishlist, fetch */
( function () {
    'use strict';

    var cfg = window.titancartWishlist || {};

    // ── API helper ─────────────────────────────────────────────────────────

    function apiFetch( url, method, body ) {
        var opts = {
            method: method || 'GET',
            headers: {
                'X-WP-Nonce': cfg.nonce || '',
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
        };
        if ( body ) {
            opts.body = JSON.stringify( body );
        }
        return fetch( url, opts ).then( function ( r ) {
            return r.json().then( function ( d ) {
                return { ok: r.ok, data: d, status: r.status };
            } );
        } );
    }

    // ── Toast notification ─────────────────────────────────────────────────

    function showToast( message ) {
        var el = document.createElement( 'div' );
        el.className = 'tc-toast';
        el.textContent = message;
        document.body.appendChild( el );
        setTimeout( function () { el.classList.add( 'tc-toast--visible' ); }, 10 );
        setTimeout( function () {
            el.classList.remove( 'tc-toast--visible' );
            setTimeout( function () { el.remove(); }, 300 );
        }, 2500 );
    }

    // ── Button state helpers ────────────────────────────────────────────────

    function updateButton( btn, inList ) {
        var i18n = cfg.i18n || {};

        btn.dataset.inList = inList ? 'true' : 'false';
        btn.classList.toggle( 'tc-wishlist-toggle--active', inList );

        var label = inList
            ? ( i18n.removeFromWishlist || 'Remove from Wishlist' )
            : ( i18n.addToWishlist || 'Add to Wishlist' );

        btn.setAttribute( 'aria-label', label );
        btn.title = label;

        // Handle SVG heart (inline SVG with <path> — used on product detail page)
        var heartPath = btn.querySelector( 'svg path' );
        if ( heartPath ) {
            heartPath.setAttribute( 'fill', inList ? 'currentColor' : 'none' );
        }

        // Handle Bootstrap Icon heart (<i class="bi bi-heart"> or <i class="bi bi-heart-fill">)
        var biIcon = btn.querySelector( 'i.bi' );
        if ( biIcon ) {
            biIcon.className = inList ? 'bi bi-heart-fill' : 'bi bi-heart';
        }
    }

    function updateWishlistCount( count ) {
        document.querySelectorAll( '.tc-wishlist-count' ).forEach( function ( el ) {
            el.textContent = count;
        } );
    }

    // ── Initialise button states from server ──────────────────────────────
    // If user is logged in, fetch their wishlist IDs and mark buttons active.
    function initButtonStates() {
        if ( ! cfg.isLoggedIn || ! cfg.restUrl ) return;

        var buttons = document.querySelectorAll( '.tc-wishlist-toggle' );
        if ( ! buttons.length ) return;

        apiFetch( cfg.restUrl, 'GET' ).then( function ( r ) {
            if ( ! r.ok || ! r.data ) return;
            // The REST endpoint returns the items array directly (not wrapped in {items:[…]}).
            var items = Array.isArray( r.data ) ? r.data : ( r.data.items || [] );
            if ( ! items.length ) return;
            var ids = items.map( function ( item ) { return String( item.product_id ); } );

            buttons.forEach( function ( btn ) {
                var pid = btn.dataset.productId;
                if ( pid && ids.indexOf( pid ) !== -1 ) {
                    updateButton( btn, true );
                }
            } );
        } ).catch( function () { /* silent */ } );
    }

    initButtonStates();

    // ── Click handler ──────────────────────────────────────────────────────

    document.addEventListener( 'click', function ( e ) {
        var btn = e.target.closest( '.tc-wishlist-toggle' );
        if ( ! btn ) return;

        e.preventDefault();

        var productId = parseInt( btn.dataset.productId, 10 );
        if ( ! productId ) return;

        // Require login.
        if ( ! cfg.isLoggedIn ) {
            var i18n = cfg.i18n || {};
            showToast( i18n.loginRequired || 'Please log in to save items to your wishlist.' );
            setTimeout( function () {
                window.location.href = cfg.loginUrl || '/my-account/';
            }, 1200 );
            return;
        }

        var inList = btn.dataset.inList === 'true';

        // Optimistically update UI.
        updateButton( btn, ! inList );
        btn.disabled = true;

        if ( inList ) {
            // Remove from wishlist.
            apiFetch( cfg.restUrl + '/items/' + productId, 'DELETE' ).then( function ( r ) {
                btn.disabled = false;
                if ( r.ok ) {
                    if ( r.data && r.data.count !== undefined ) {
                        updateWishlistCount( r.data.count );
                    }
                    showToast( 'Removed from wishlist.' );
                    // Also update all other buttons for same product on page.
                    syncAllButtons( productId, false );
                } else {
                    updateButton( btn, true );
                    showToast( ( r.data && r.data.message ) || 'Error removing item.' );
                }
            } );
        } else {
            // Add to wishlist.
            apiFetch( cfg.restUrl + '/items', 'POST', { product_id: productId } ).then( function ( r ) {
                btn.disabled = false;
                if ( r.ok ) {
                    if ( r.data && r.data.count !== undefined ) {
                        updateWishlistCount( r.data.count );
                    }
                    showToast( 'Saved to wishlist!' );
                    syncAllButtons( productId, true );
                } else {
                    updateButton( btn, false );
                    showToast( ( r.data && r.data.message ) || 'Error adding item.' );
                }
            } );
        }
    } );

    // Update all wishlist toggle buttons for a given product ID.
    function syncAllButtons( productId, inList ) {
        document.querySelectorAll( '.tc-wishlist-toggle[data-product-id="' + productId + '"]' ).forEach( function ( b ) {
            updateButton( b, inList );
        } );
    }

}() );
