/**
 * TitanCart — My Account JavaScript
 *
 * Handles:
 *  - Login/Register toggle (show/hide cards)
 *  - Password visibility toggle
 *  - Mobile sidebar toggle
 *  - Profile form AJAX save
 *  - Password change AJAX
 *  - Address CRUD (modal, create, edit, delete, set default)
 */
(function () {
    'use strict';

    var API  = (window.TitancartAccount || {}).apiUrl || '/wp-json/titancart/v1';
    var NONCE = (window.TitancartAccount || {}).nonce || '';
    var I18N  = (window.TitancartAccount || {}).i18n || {};

    // ── Helpers ──────────────────────────────────────────────────────────

    function qs(sel, ctx) { return (ctx || document).querySelector(sel); }
    function qsa(sel, ctx) { return Array.from((ctx || document).querySelectorAll(sel)); }

    function apiRequest(endpoint, method, body) {
        var opts = {
            method: method || 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': NONCE,
            },
        };
        if (body) opts.body = JSON.stringify(body);
        return fetch(API + endpoint, opts).then(function (r) {
            return r.json().then(function (data) {
                if (!r.ok) throw data;
                return data;
            });
        });
    }

    function showMsg(container, text, type) {
        var el = typeof container === 'string' ? qs(container) : container;
        if (!el) return;
        el.innerHTML = '<div class="tc-msg--' + (type || 'success') + '">' + escHtml(text) + '</div>';
        el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        if (type !== 'error') {
            setTimeout(function () { el.innerHTML = ''; }, 5000);
        }
    }

    function escHtml(str) {
        var d = document.createElement('div');
        d.textContent = str;
        return d.innerHTML;
    }

    // ── Auth toggle (Login ↔ Register) ──────────────────────────────────

    qsa('.tc-auth-toggle').forEach(function (link) {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            var show = this.getAttribute('data-show');
            var loginCard = qs('#tc-auth-login');
            var regCard   = qs('#tc-auth-register');
            if (!loginCard || !regCard) return;

            if (show === 'register') {
                loginCard.classList.add('tc-auth-card--hidden');
                regCard.classList.remove('tc-auth-card--hidden');
            } else {
                regCard.classList.add('tc-auth-card--hidden');
                loginCard.classList.remove('tc-auth-card--hidden');
            }
        });
    });

    // Show register card if there's a register error present.
    if (qs('#tc-auth-register .tc-auth-msg--error')) {
        var lc = qs('#tc-auth-login');
        var rc = qs('#tc-auth-register');
        if (lc && rc) {
            lc.classList.add('tc-auth-card--hidden');
            rc.classList.remove('tc-auth-card--hidden');
        }
    }

    // ── Password visibility toggle ──────────────────────────────────────

    qsa('.tc-pw-toggle').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var input = this.parentElement.querySelector('input');
            if (!input) return;
            var showing = input.type === 'text';
            input.type = showing ? 'password' : 'text';
            var icon = this.querySelector('i');
            if (icon) {
                icon.className = showing ? 'bi bi-eye-slash' : 'bi bi-eye';
            }
        });
    });

    // ── Mobile sidebar toggle ───────────────────────────────────────────

    var sidebarToggle = qs('#tc-sidebar-toggle');
    var sidebarNav    = qs('#tc-account-nav');
    if (sidebarToggle && sidebarNav) {
        sidebarToggle.addEventListener('click', function () {
            sidebarNav.classList.toggle('tc-open');
        });
    }

    // ── Profile form ────────────────────────────────────────────────────

    var profileForm = qs('#tc-profile-form');
    if (profileForm) {
        profileForm.addEventListener('submit', function (e) {
            e.preventDefault();
            var btn = this.querySelector('button[type="submit"]');
            var origText = btn.textContent;
            btn.textContent = I18N.saving || 'Saving…';
            btn.classList.add('tc-btn--loading');

            var data = {
                first_name: qs('#tc-prof-first').value,
                last_name:  qs('#tc-prof-last').value,
                email:      qs('#tc-prof-email').value,
                phone:      qs('#tc-prof-phone').value,
            };

            // Collect custom (non-system) contact field values (S127.C-1).
            // Inputs follow the tc_cf_<id> convention. For checkboxes, two
            // inputs share the name (hidden=0 then checkbox=1) — iterating
            // in DOM order means the checkbox writes last, naturally
            // overriding the hidden when checked.
            var cfNodes = profileForm.querySelectorAll(
                'input[name^="tc_cf_"], textarea[name^="tc_cf_"], select[name^="tc_cf_"]'
            );
            for (var i = 0; i < cfNodes.length; i++) {
                var el = cfNodes[i];
                if (el.type === 'checkbox') {
                    data[el.name] = el.checked ? '1' : '0';
                } else if (el.type !== 'hidden' || data[el.name] === undefined) {
                    // Hidden companions only seed the value; let the checkbox
                    // overwrite. For non-checkbox hiddens we still take them.
                    data[el.name] = el.value;
                }
            }

            apiRequest('/account/profile', 'PUT', data)
                .then(function () {
                    showMsg('#tc-profile-msg', I18N.saved || 'Changes saved!', 'success');
                })
                .catch(function (err) {
                    var msg = (err && err.message) || I18N.error || 'Something went wrong.';
                    showMsg('#tc-profile-msg', msg, 'error');
                })
                .finally(function () {
                    btn.textContent = origText;
                    btn.classList.remove('tc-btn--loading');
                });
        });
    }

    // ── Password change form ────────────────────────────────────────────

    var pwForm = qs('#tc-password-form');
    if (pwForm) {
        pwForm.addEventListener('submit', function (e) {
            e.preventDefault();
            var newPw  = qs('#tc-pw-new').value;
            var confPw = qs('#tc-pw-confirm').value;

            if (newPw !== confPw) {
                showMsg('#tc-profile-msg', 'Passwords do not match.', 'error');
                return;
            }

            var btn = this.querySelector('button[type="submit"]');
            var origText = btn.textContent;
            btn.textContent = I18N.saving || 'Saving…';
            btn.classList.add('tc-btn--loading');

            apiRequest('/account/profile', 'PUT', {
                current_password: qs('#tc-pw-current').value,
                new_password: newPw,
            })
                .then(function () {
                    showMsg('#tc-profile-msg', 'Password updated successfully!', 'success');
                    qs('#tc-pw-current').value = '';
                    qs('#tc-pw-new').value = '';
                    qs('#tc-pw-confirm').value = '';
                })
                .catch(function (err) {
                    var msg = (err && err.message) || I18N.error || 'Something went wrong.';
                    showMsg('#tc-profile-msg', msg, 'error');
                })
                .finally(function () {
                    btn.textContent = origText;
                    btn.classList.remove('tc-btn--loading');
                });
        });
    }

    // ── Address CRUD ────────────────────────────────────────────────────

    var addrModal     = qs('#tc-address-modal');
    var addrForm      = qs('#tc-address-form');
    var addrAddBtn    = qs('#tc-add-address-btn');
    var addrCloseBtn  = qs('#tc-address-modal-close');
    var addrCancelBtn = qs('#tc-address-modal-cancel');

    function openAddrModal(title, data) {
        if (!addrModal) return;
        qs('#tc-address-modal-title').textContent = title || 'Add New Address';
        qs('#tc-addr-id').value        = (data && data.id) || '';
        qs('#tc-addr-first').value     = (data && data.first_name) || '';
        qs('#tc-addr-last').value      = (data && data.last_name) || '';
        qs('#tc-addr-company').value   = (data && data.company) || '';
        qs('#tc-addr-address1').value  = (data && data.address_1) || '';
        qs('#tc-addr-address2').value  = (data && data.address_2) || '';
        qs('#tc-addr-city').value      = (data && data.city) || '';
        qs('#tc-addr-state').value     = (data && data.state) || '';
        qs('#tc-addr-postcode').value  = (data && data.postcode) || '';
        qs('#tc-addr-country').value   = (data && data.country) || '';
        qs('#tc-addr-phone').value     = (data && data.phone) || '';
        qs('#tc-addr-type').value      = (data && data.type) || 'shipping';
        addrModal.style.display = 'flex';
    }

    function closeAddrModal() {
        if (addrModal) addrModal.style.display = 'none';
    }

    if (addrAddBtn) {
        addrAddBtn.addEventListener('click', function () {
            openAddrModal('Add New Address');
        });
    }
    if (addrCloseBtn) addrCloseBtn.addEventListener('click', closeAddrModal);
    if (addrCancelBtn) addrCancelBtn.addEventListener('click', closeAddrModal);

    // Close modal on overlay click.
    if (addrModal) {
        addrModal.addEventListener('click', function (e) {
            if (e.target === addrModal) closeAddrModal();
        });
    }

    // Save address.
    if (addrForm) {
        addrForm.addEventListener('submit', function (e) {
            e.preventDefault();
            var id = qs('#tc-addr-id').value;
            var body = {
                first_name: qs('#tc-addr-first').value,
                last_name:  qs('#tc-addr-last').value,
                company:    qs('#tc-addr-company').value,
                address_1:  qs('#tc-addr-address1').value,
                address_2:  qs('#tc-addr-address2').value,
                city:       qs('#tc-addr-city').value,
                state:      qs('#tc-addr-state').value,
                postcode:   qs('#tc-addr-postcode').value,
                country:    qs('#tc-addr-country').value,
                phone:      qs('#tc-addr-phone').value,
                type:       qs('#tc-addr-type').value,
            };

            var endpoint = id ? '/account/addresses/' + id : '/account/addresses';
            var method   = id ? 'PUT' : 'POST';

            apiRequest(endpoint, method, body)
                .then(function () {
                    closeAddrModal();
                    window.location.reload();
                })
                .catch(function (err) {
                    var msg = (err && err.message) || I18N.error || 'Something went wrong.';
                    showMsg('#tc-address-msg', msg, 'error');
                });
        });
    }

    // Edit address.
    qsa('.tc-addr-edit').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = this.getAttribute('data-id');
            apiRequest('/account/addresses', 'GET')
                .then(function (addrs) {
                    var addr = (addrs || []).find(function (a) { return String(a.id) === String(id); });
                    if (addr) openAddrModal('Edit Address', addr);
                });
        });
    });

    // Delete address.
    qsa('.tc-addr-delete').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (!confirm(I18N.confirm_delete || 'Are you sure you want to delete this address?')) return;
            var id = this.getAttribute('data-id');
            apiRequest('/account/addresses/' + id, 'DELETE')
                .then(function () { window.location.reload(); })
                .catch(function (err) {
                    var msg = (err && err.message) || I18N.error || 'Something went wrong.';
                    showMsg('#tc-address-msg', msg, 'error');
                });
        });
    });

    // Set default address.
    qsa('.tc-addr-default').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = this.getAttribute('data-id');
            apiRequest('/account/addresses/' + id + '/default', 'POST')
                .then(function () { window.location.reload(); })
                .catch(function (err) {
                    showMsg('#tc-address-msg', (err && err.message) || 'Error', 'error');
                });
        });
    });

    // ── Wishlist: Remove item ──────────────────────────────────────────

    qsa('.tc-wl-card__remove').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var pid  = this.getAttribute('data-product-id');
            var card = this.closest('.tc-wl-card');
            if (!pid) return;

            // Optimistic removal animation.
            if (card) card.style.opacity = '0.4';

            apiRequest('/wishlist/items/' + pid, 'DELETE')
                .then(function () {
                    if (card) {
                        card.style.transition = 'opacity 0.3s, transform 0.3s';
                        card.style.opacity = '0';
                        card.style.transform = 'scale(0.9)';
                        setTimeout(function () {
                            card.remove();
                            // Update count.
                            var grid = qs('.tc-wishlist__grid');
                            var remaining = grid ? grid.querySelectorAll('.tc-wl-card').length : 0;
                            var countEl = qs('.tc-wishlist__count');
                            if (countEl) {
                                countEl.textContent = remaining + (remaining === 1 ? ' item' : ' items');
                            }
                            // Show empty state if nothing left.
                            if (remaining === 0) {
                                window.location.reload();
                            }
                        }, 300);
                    }
                })
                .catch(function () {
                    if (card) card.style.opacity = '1';
                });
        });
    });

    // ── Wishlist: Add to Cart (without removing from wishlist) ─────────

    qsa('.tc-wl-add-cart').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var pid  = this.getAttribute('data-product-id');
            if (!pid) return;

            var origText = this.innerHTML;
            this.innerHTML = '<i class="bi bi-arrow-repeat"></i> Adding…';
            this.disabled = true;
            var self = this;

            // Add to cart only — do NOT remove from wishlist.
            apiRequest('/cart/items', 'POST', { product_id: parseInt(pid, 10), quantity: 1 })
                .then(function (result) {
                    self.innerHTML = '&#10003; Added';
                    setTimeout(function () {
                        self.innerHTML = origText;
                        self.disabled = false;
                    }, 1500);
                    // Update cart badge if it exists.
                    var cart = result.cart || result;
                    var badges = qsa('.tc-cart-count');
                    if (badges.length) {
                        var count = cart.item_count || ((parseInt(badges[0].textContent, 10) || 0) + 1);
                        badges.forEach(function (b) {
                            b.textContent = count;
                        });
                    }
                    // Open the cart drawer (triggers refresh + open via cart.js).
                    var cartTrigger = qs('.tc-cart-trigger');
                    if (cartTrigger) cartTrigger.click();
                })
                .catch(function (err) {
                    self.innerHTML = origText;
                    self.disabled = false;
                    alert((err && err.message) || 'Could not add to cart.');
                });
        });
    });

})();
