// source --> https://leohaz.com/wordpress/wp-content/themes/sydney-child/leohaz-favorites.js 
(function () {
  'use strict';

  var AJAX_URL = '/wordpress/wp-admin/admin-ajax.php';
  var STORE_KEY = 'lhz_favs';

  var _favs = [];

  // Speicher: versuche sessionStorage, dann localStorage, dann Cookie
  function saveToStorage(data) {
    var str = JSON.stringify(data);
    try { sessionStorage.setItem(STORE_KEY, str); return; } catch(e) {}
    try { localStorage.setItem(STORE_KEY, str); return; } catch(e) {}
    try {
      var d = new Date();
      d.setTime(d.getTime() + 24*60*60*1000);
      document.cookie = STORE_KEY + '=' + encodeURIComponent(str) + ';expires=' + d.toUTCString() + ';path=/';
    } catch(e) {}
  }

  function loadFromStorage() {
    // sessionStorage
    try {
      var s = sessionStorage.getItem(STORE_KEY);
      if (s) return JSON.parse(s);
    } catch(e) {}
    // localStorage
    try {
      var l = localStorage.getItem(STORE_KEY);
      if (l) return JSON.parse(l);
    } catch(e) {}
    // Cookie
    try {
      var name = STORE_KEY + '=';
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) === 0) {
          return JSON.parse(decodeURIComponent(c.substring(name.length)));
        }
      }
    } catch(e) {}
    return [];
  }

  function getFavs() { return _favs; }

  function isFav(id) {
    return _favs.some(function (f) { return f.id === id; });
  }

  function toggleFav(item) {
    var idx = _favs.findIndex(function (f) { return f.id === item.id; });
    if (idx > -1) {
      _favs.splice(idx, 1);
    } else {
      _favs.push(item);
    }
    saveToStorage(_favs);
    refreshBadges();
    return idx === -1;
  }

  function getContact() {
    try { return JSON.parse(sessionStorage.getItem('lhz_contact')) || {}; }
    catch (e) { return {}; }
  }
  function setContact(name, email) {
    try { sessionStorage.setItem('lhz_contact', JSON.stringify({name: name, email: email})); }
    catch (e) {}
  }

  function esc(s) {
    return (s || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;')
                    .replace(/'/g,'&#39;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  }

  function makeId(src) {
    var h = 0, s = src || '';
    for (var i = 0; i < s.length; i++) { h = ((h << 5) - h) + s.charCodeAt(i); h |= 0; }
    return 'lh' + Math.abs(h).toString(36);
  }

  function parseAlt(alt) {
    var raw = alt.slice('artwork:'.length).trim();
    var parts = raw.split('|');
    return {
      title: parts[0].trim(),
      desc:  parts[1] ? parts[1].trim() : ''
    };
  }

  function showError(msg) {
    var st = document.getElementById('lhz-status');
    if (!st) return;
    st.style.cssText = 'display:block;color:#ff6060;font-size:13px;padding:4px 0;';
    st.textContent = msg;
    setTimeout(function () {
      st.style.display = 'none';
      st.textContent = '';
    }, 4000);
  }

  function subscribeMailchimp(email) {
    var fd = new FormData();
    fd.append('action', 'leohaz_mailchimp');
    fd.append('email',  email);
    fetch(AJAX_URL, {method: 'POST', body: fd}).catch(function () {});
  }

  var toastTimer = null;

  function showToast(title, added) {
    var toast = document.getElementById('lhz-toast');
    if (!toast) {
      toast = document.createElement('div');
      toast.id = 'lhz-toast';
      document.body.appendChild(toast);
    }

    if (added) {
      toast.innerHTML =
        '<div class="lhz-toast-row">' +
          '<span class="lhz-toast-heart">&#9829;</span>' +
          '<span class="lhz-toast-msg">&ldquo;' + esc(title) + '&rdquo; added to your Favorites</span>' +
        '</div>' +
        '<button type="button" class="lhz-toast-btn" id="lhz-toast-view">View Favorites</button>';
    } else {
      toast.innerHTML =
        '<div class="lhz-toast-row">' +
          '<span class="lhz-toast-heart lhz-toast-heart-off">&#9825;</span>' +
          '<span class="lhz-toast-msg">&ldquo;' + esc(title) + '&rdquo; removed from Favorites</span>' +
        '</div>';
    }

    toast.classList.remove('lhz-toast-hide');
    toast.classList.add('lhz-toast-show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(function () {
      toast.classList.remove('lhz-toast-show');
      toast.classList.add('lhz-toast-hide');
    }, 4000);

    var viewBtn = document.getElementById('lhz-toast-view');
    if (viewBtn) {
      viewBtn.addEventListener('click', function () {
        toast.classList.remove('lhz-toast-show');
        toast.classList.add('lhz-toast-hide');
        openPopup();
      });
    }
  }

  function refreshBadges() {
    var n = getFavs().length;

    var hBtn = document.querySelector('.leohaz-heart-btn');
    if (hBtn) {
      var b = hBtn.querySelector('.leohaz-fav-count');
      if (!b) {
        b = document.createElement('span');
        b.className = 'leohaz-fav-count';
        hBtn.appendChild(b);
      }
      b.textContent = n > 0 ? String(n) : '';
      b.style.display = n > 0 ? 'flex' : 'none';
    }

    document.querySelectorAll(
      'li#menu-item-8899 a.sydney-dropdown-link,' +
      'a.sydney-dropdown-link[href*="/favorites"],' +
      'a.sydney-dropdown-link[href*="/Favorites"]'
    ).forEach(function (a) {
      a.style.position = 'relative';
      var b = a.querySelector('.leohaz-menu-count');
      if (!b) {
        b = document.createElement('span');
        b.className = 'leohaz-menu-count';
        a.appendChild(b);
      }
      b.textContent          = n > 0 ? String(n) : '';
      b.style.display        = n > 0 ? 'flex' : 'none';
      b.style.position       = 'absolute';
      b.style.top            = '50%';
      b.style.left           = '50%';
      b.style.transform      = 'translate(-50%, -50%)';
      b.style.zIndex         = '20';
      b.style.color          = '#7f7f7f';
      b.style.fontWeight     = '900';
      b.style.fontFamily     = 'sans-serif';
      b.style.lineHeight     = '1';
      b.style.pointerEvents  = 'none';
      b.style.background     = 'transparent';
      b.style.fontSize       = '9.5px';
      b.style.alignItems     = 'center';
      b.style.justifyContent = 'center';
    });

    document.querySelectorAll('img[src*="heart-green"]').forEach(function (img) {
      var wrap = img.closest('.lhz-hw');
      if (!wrap) {
        wrap = document.createElement('span');
        wrap.className = 'lhz-hw';
        wrap.style.cssText = 'position:relative;display:inline-flex;align-items:center;justify-content:center;';
        img.parentNode.insertBefore(wrap, img);
        wrap.appendChild(img);
      }
      var b = wrap.querySelector('.leohaz-menu-count');
      if (!b) {
        b = document.createElement('span');
        b.className = 'leohaz-menu-count';
        wrap.appendChild(b);
      }
      b.textContent          = n > 0 ? String(n) : '';
      b.style.display        = n > 0 ? 'flex' : 'none';
      b.style.position       = 'absolute';
      b.style.top            = '50%';
      b.style.left           = '50%';
      b.style.transform      = 'translate(-50%, -50%)';
      b.style.zIndex         = '10';
      b.style.color          = '#7f7f7f';
      b.style.fontWeight     = '900';
      b.style.fontFamily     = 'sans-serif';
      b.style.fontSize       = '12px';
      b.style.lineHeight     = '1';
      b.style.pointerEvents  = 'none';
      b.style.background     = 'transparent';
      b.style.alignItems     = 'center';
      b.style.justifyContent = 'center';
    });

    var pop = document.getElementById('lhz-popup');
    if (pop && pop.classList.contains('lhz-open')) renderList();
  }

  function injectHearts() {
    document.querySelectorAll(
      '.elementor-widget-image img,' +
      '.elementor-widget-image a img,' +
      '.elementor-image img,' +
      '.swiper-slide img,' +
      'figure img,' +
      '.wp-block-image img'
    ).forEach(function (img) {
      if (img.closest('.lhz-wrap')) return;
      if (img.closest('.lhz-thumb')) return;
      if (!img.src || /heart-green|heart-gray|hamburger/i.test(img.src)) return;

      var w = img.getBoundingClientRect().width || img.offsetWidth || 0;
      if (w && w < 80) return;

      var alt = (img.getAttribute('alt') || '').trim();
      if (!alt.toLowerCase().startsWith('artwork:')) return;
      var parsed = parseAlt(alt);
      if (parsed.title.length < 2) return;

      var src  = img.currentSrc || img.src;
      var id   = makeId(src);
      var item = {id: id, title: parsed.title, desc: parsed.desc, src: src};

      var wrap = document.createElement('div');
      wrap.className = 'lhz-wrap';
      img.parentNode.insertBefore(wrap, img);
      wrap.appendChild(img);

      var btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'lhz-heart' + (isFav(id) ? ' lhz-on' : '');
      btn.setAttribute('aria-label', 'Add to Favorites');
      btn.innerHTML =
        '<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">' +
        '<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 ' +
        '2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09 ' +
        'C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5 ' +
        'c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" fill="currentColor"/></svg>';

      btn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var added = toggleFav(item);
        btn.classList.toggle('lhz-on', added);
        document.querySelectorAll('.lhz-heart').forEach(function (b) {
          var w2 = b.closest('.lhz-wrap');
          if (w2 && w2.querySelector('img') && makeId(w2.querySelector('img').src) === id) {
            b.classList.toggle('lhz-on', added);
          }
        });
        showToast(parsed.title, added);
      });

      wrap.appendChild(btn);
    });
  }

  function buildPopup() {
    if (document.getElementById('lhz-popup')) return;
    var pop = document.createElement('div');
    pop.id = 'lhz-popup';
    pop.setAttribute('role', 'dialog');
    pop.setAttribute('aria-modal', 'true');
    pop.innerHTML =
      '<div class="lhz-inner">' +
        '<div class="lhz-head">' +
          '<span>My Favorites</span>' +
          '<button type="button" class="lhz-close" aria-label="Close">&#x2715;</button>' +
        '</div>' +
        '<div class="lhz-body">' +
          '<div class="lhz-list"></div>' +
          '<div class="lhz-form" style="display:none">' +
            '<input id="lhz-name" type="text" placeholder="Your Name" autocomplete="name" autocorrect="off" autocapitalize="words"/>' +
            '<input id="lhz-email" type="email" placeholder="Your Email" autocomplete="email" autocorrect="off" autocapitalize="off" inputmode="email"/>' +
            '<div id="lhz-status" style="display:none;"></div>' +
            '<button type="button" id="lhz-send">Send Inquiry</button>' +
          '</div>' +
          '<p class="lhz-empty">No favorites yet.<br>Tap &#9825; on any artwork.</p>' +
        '</div>' +
      '</div>' +
      '<div class="lhz-overlay"></div>';
    document.body.appendChild(pop);

    pop.querySelector('.lhz-close').addEventListener('click', closePopup);
    pop.querySelector('.lhz-overlay').addEventListener('click', closePopup);
    document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closePopup(); });
    pop.querySelector('#lhz-send').addEventListener('click', sendInquiry);
  }

  function renderList() {
    var favs  = getFavs();
    var list  = document.querySelector('.lhz-list');
    var form  = document.querySelector('.lhz-form');
    var empty = document.querySelector('.lhz-empty');
    if (!list) return;

    list.innerHTML = '';
    var show = favs.length > 0;
    if (empty) empty.style.display = show ? 'none' : 'block';
    if (form)  form.style.display  = show ? 'flex'  : 'none';
    if (!show) return;

    favs.forEach(function (f) {
      var d = document.createElement('div');
      d.className = 'lhz-item';
      d.innerHTML =
        '<img src="' + esc(f.src) + '" alt="' + esc(f.title) + '" class="lhz-thumb" loading="lazy"/>' +
        '<span class="lhz-name">' + esc(f.title) + '</span>' +
        '<button type="button" class="lhz-rm" data-id="' + esc(f.id) + '" aria-label="Remove">&#x2715;</button>';
      list.appendChild(d);
    });

    list.querySelectorAll('.lhz-rm').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var id = this.dataset.id;
        _favs = _favs.filter(function (f) { return f.id !== id; });
        saveToStorage(_favs);
        document.querySelectorAll('.lhz-heart').forEach(function (b) {
          var w = b.closest('.lhz-wrap');
          if (w && w.querySelector('img') && makeId(w.querySelector('img').src) === id) {
            b.classList.remove('lhz-on');
          }
        });
        refreshBadges();
        renderList();
      });
    });

    var c = getContact();
    var ne = document.getElementById('lhz-name');
    var ee = document.getElementById('lhz-email');
    if (ne && !ne.value) ne.value = c.name  || '';
    if (ee && !ee.value) ee.value = c.email || '';
  }

  function openPopup() {
    buildPopup();
    renderList();
    document.getElementById('lhz-popup').classList.add('lhz-open');
    document.body.style.overflow = 'hidden';
  }

  function closePopup() {
    var p = document.getElementById('lhz-popup');
    if (p) p.classList.remove('lhz-open');
    document.body.style.overflow = '';
  }

  function sendInquiry() {
    var name  = ((document.getElementById('lhz-name')  || {}).value || '').trim();
    var email = ((document.getElementById('lhz-email') || {}).value || '').trim();
    var st    = document.getElementById('lhz-status');
    var btn   = document.getElementById('lhz-send');

    if (!name) { showError('Please enter your name.'); return; }
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
    if (!emailRegex.test(email)) {
      showError('Please enter a valid email address (e.g. name@domain.com).');
      return;
    }
    var favs = getFavs();
    if (!favs.length) { showError('No favorites selected.'); return; }

    setContact(name, email);
    var msg = favs.map(function (f) { return '\u2022 ' + f.title; }).join('\n');

    btn.disabled = true;
    st.style.cssText = 'display:block;color:#aaa;font-size:13px;padding:4px 0;';
    st.textContent = 'Sending\u2026';

    var fd = new FormData();
    fd.append('action',  'leohaz_send');
    fd.append('name',    name);
    fd.append('email',   email);
    fd.append('message', 'Artwork Inquiry:\n\n' + msg);

    fetch(AJAX_URL, {method: 'POST', body: fd})
      .then(function (r) { return r.json(); })
      .then(function (d) {
        if (d && d.success) {
          st.style.color = '#00ff00';
          st.textContent = 'Sent! We will be in touch.';
          subscribeMailchimp(email);
        } else { throw new Error('fail'); }
      })
      .catch(function () {
        st.style.color = '#ff6060';
        st.textContent = 'Could not send. Please try again or email office@leohaz.com';
      })
      .finally(function () { btn.disabled = false; });
  }

  function bindTriggers() {
    var hBtn = document.querySelector('.leohaz-heart-btn');
    if (hBtn && !hBtn._lhzBound) {
      hBtn._lhzBound = true;
      hBtn.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); openPopup(); });
    }

    document.querySelectorAll('img[src*="heart-green"]').forEach(function (img) {
      var p = img.closest('a,button') || img.parentElement;
      if (p && !p._lhzBound) {
        p._lhzBound = true;
        p.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); openPopup(); });
      }
    });

    document.querySelectorAll(
      'li#menu-item-8899 a.sydney-dropdown-link,' +
      'a.sydney-dropdown-link[href*="/favorites"],' +
      'a.sydney-dropdown-link[href*="/Favorites"]'
    ).forEach(function (a) {
      if (!a._lhzBound) {
        a._lhzBound = true;
        a.style.pointerEvents = 'auto';
        a.style.cursor = 'pointer';
        a.addEventListener('click', function (e) {
          e.preventDefault();
          e.stopPropagation();
          openPopup();
        });
      }
      var li = a.closest('li#menu-item-8899');
      if (li && !li._lhzBound) {
        li._lhzBound = true;
        li.addEventListener('click', function (e) {
          e.preventDefault();
          e.stopPropagation();
          openPopup();
        });
      }
    });
  }

  function init() {
    // Favoriten beim Start laden
    _favs = loadFromStorage();

    bindTriggers();
    refreshBadges();

    var run = function () {
      setTimeout(function () {
        injectHearts();
        bindTriggers();
        refreshBadges();
      }, 500);
    };

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', run);
    } else {
      run();
    }
    window.addEventListener('load', function () {
      setTimeout(function () {
        injectHearts();
        bindTriggers();
        refreshBadges();
      }, 300);
    });
  }

  init();
}());