(function(){
  function text(v){ return (typeof v === 'string' || typeof v === 'number') ? String(v) : ''; }
  function isUrl(v){ return typeof v === 'string' && /^https?:\/\//i.test(v); }
  function cleanText(v){
    if (v === null || v === undefined) return '';
    if (typeof v === 'string' || typeof v === 'number') return String(v).trim();
    return '';
  }
  function stripHtml(v){
    return cleanText(v).replace(/<[^>]*>/g,' ').replace(/\s+/g,' ').trim();
  }
  function truncate(v, max){
    var t = stripHtml(v);
    if (!t) return '';
    if (t.length <= max) return t;
    var cut = t.slice(0, max).replace(/\s+\S*$/, '');
    return cut + ' …';
  }
  function pickNumber(obj, keys){
    for (var i=0;i<keys.length;i++){
      var k=keys[i];
      if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== '') {
        var n = parseFloat(String(obj[k]).replace(',', '.'));
        if (!isNaN(n)) return n;
      }
    }
    return null;
  }
  function pickNumberDeep(obj, keys, depth){
    if (!obj || depth > 4) return null;
    if (typeof obj === 'object') {
      var direct = pickNumber(obj, keys);
      if (direct !== null) return direct;
      for (var k in obj) {
        if (Object.prototype.hasOwnProperty.call(obj,k)) {
          var n = pickNumberDeep(obj[k], keys, depth+1);
          if (n !== null) return n;
        }
      }
    }
    return null;
  }
  function haversineKm(lat1, lon1, lat2, lon2){
    if ([lat1,lon1,lat2,lon2].some(function(x){ return typeof x !== 'number' || isNaN(x); })) return null;
    var R=6371, toRad=function(d){return d*Math.PI/180;};
    var dLat=toRad(lat2-lat1), dLon=toRad(lon2-lon1);
    var a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.sin(dLon/2)*Math.sin(dLon/2);
    return R*2*Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  }
  function pick(obj, keys){
    for (var i=0;i<keys.length;i++){
      var k=keys[i];
      if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== '') {
        if (typeof obj[k] === 'string' || typeof obj[k] === 'number') return String(obj[k]);
      }
    }
    return '';
  }
  function pickUrlFromObject(obj, depth){
    if (!obj || depth > 5) return '';
    if (isUrl(obj)) return obj;
    if (Array.isArray(obj)) {
      for (var i=0;i<obj.length;i++){ var u=pickUrlFromObject(obj[i], depth+1); if (u) return u; }
      return '';
    }
    if (typeof obj !== 'object') return '';
    var priority=['url','src','source_url','full','medium_large','thumbnail','original','image','image_url','profile_image','profilbild','featured_image','avatar','portrait'];
    for (var p=0;p<priority.length;p++){
      var key=priority[p];
      if (obj[key] !== undefined) { var u=pickUrlFromObject(obj[key], depth+1); if (u) return u; }
    }
    if (obj.sizes) { var su=pickUrlFromObject(obj.sizes, depth+1); if (su) return su; }
    for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj,k)) { var u2=pickUrlFromObject(obj[k], depth+1); if (u2) return u2; } }
    return '';
  }
  function readableList(v){
    if (!v) return '';
    if (typeof v === 'string') return v;
    if (Array.isArray(v)) {
      return v.map(function(x){
        if (typeof x === 'string' || typeof x === 'number') return String(x);
        if (x && typeof x === 'object') return cleanText(x.name || x.label || x.title || x.value || '');
        return '';
      }).filter(Boolean).join(', ');
    }
    if (typeof v === 'object') return cleanText(v.name || v.label || v.title || v.value || '');
    return '';
  }
  function listFromPayload(payload){
    if (Array.isArray(payload)) return payload;
    if (!payload || typeof payload !== 'object') return [];
    var keys=['redner','speakers','items','data','results'];
    for (var i=0;i<keys.length;i++){
      if (Array.isArray(payload[keys[i]])) return payload[keys[i]];
    }
    return [];
  }
  function normalize(s, context){
    var name = pick(s, ['name','display_name','titel','title','redner_name','post_title']) || 'Rednerprofil';
    var city = pick(s, ['city','ort','stadt','homebase_name','homebase_city','region_name','bundesland']) || readableList(s.homebase || s.location || s.region || s.locations || s.regions);
    if ((!city || city.indexOf(',') !== -1) && s.homebase && typeof s.homebase === 'object') { city = pick(s.homebase, ['city','ort','stadt']) || city; }
    var url = pick(s, ['url','profile_url','profil_url','permalink','link','ceremony_profile_url','zeremonieprofil_url']);
    if (!url && s.links) url = pickUrlFromObject(s.links, 0);
    var img = '';
    var imageCandidates=['image','image_url','profile_image','profilbild','portrait','avatar','thumbnail','thumbnail_url','featured_image','featured_image_url','photo','foto','bild'];
    for (var i=0;i<imageCandidates.length && !img;i++) if (s[imageCandidates[i]] !== undefined) img = pickUrlFromObject(s[imageCandidates[i]], 0);
    if (!img && s.images) img = pickUrlFromObject(s.images,0);
    if (!img && s.media) img = pickUrlFromObject(s.media,0);

    var excerpt = pick(s, ['short_description','shortDescription','description','excerpt','bio','teaser','kurzbeschreibung','profiltext','about','intro','summary']);
    if (!excerpt && s.profile) excerpt = pick(s.profile, ['short_description','description','excerpt','bio','teaser','kurzbeschreibung','profiltext']);
    if (!excerpt && s.content) excerpt = pick(s.content, ['rendered','raw']);

    var lat = pickNumberDeep(s, ['lat','latitude','geo_lat','homebase_lat','home_lat'], 0);
    var lng = pickNumberDeep(s, ['lng','lon','longitude','geo_lng','geo_lon','homebase_lng','homebase_lon','home_lng'], 0);
    var distance = null;
    if (context && context.lat !== null && context.lng !== null && lat !== null && lng !== null) {
      distance = haversineKm(context.lat, context.lng, lat, lng);
    }
    var hay = JSON.stringify(s).toLowerCase();
    return {name:cleanText(name), city:cleanText(city), url:cleanText(url), img:cleanText(img), excerpt:truncate(excerpt, 230), distance:distance, hay:hay};
  }
  function filterWasChanged(filters){
    var defaults={saekular:50, christlich:50, humor:50, ritualtiefe:50, individualitaet:50, emotions_balance:55, modern_lifestyle_affinity:70, guest_integration:50, improvisation_flexibility:75, music_relevance_coordination:80};
    if (filters.language) return true;
    for (var k in defaults) {
      if (filters[k] !== undefined && filters[k] !== '' && Math.abs(Number(filters[k])-defaults[k]) > 4) return true;
    }
    return false;
  }
  function matchPercent(item, filters){
    var pct = 54;
    if (item.distance !== null && !isNaN(item.distance)) {
      if (item.distance <= 25) pct += 28;
      else if (item.distance <= 50) pct += 24;
      else if (item.distance <= 80) pct += 18;
      else if (item.distance <= 120) pct += 10;
      else if (item.distance <= 250) pct += 4;
      else pct -= 8;
    } else { pct += 8; }
    if (item.hay.indexOf('trauung') !== -1 || item.hay.indexOf('trauredner') !== -1 || item.hay.indexOf('freie') !== -1) pct += 6;
    if (filters.language && item.hay.indexOf(filters.language.toLowerCase()) !== -1) pct += 5;
    if (Number(filters.humor || 50) > 60 && item.hay.indexOf('humor') !== -1) pct += 3;
    if (Number(filters.christlich || 50) > 60 && (item.hay.indexOf('christ') !== -1 || item.hay.indexOf('theolog') !== -1)) pct += 3;
    if (Number(filters.saekular || 50) > 60 && (item.hay.indexOf('weltlich') !== -1 || item.hay.indexOf('säkular') !== -1 || item.hay.indexOf('saekular') !== -1)) pct += 3;
    if (Number(filters.ritualtiefe || 50) > 60 && (item.hay.indexOf('ritual') !== -1 || item.hay.indexOf('tief') !== -1)) pct += 2;
    if (Number(filters.individualitaet || 50) > 60 && (item.hay.indexOf('persönlich') !== -1 || item.hay.indexOf('individuell') !== -1)) pct += 2;
    return Math.max(35, Math.min(98, Math.round(pct)));
  }
  function formatDistance(km, tone){
    if (km === null || km === undefined || isNaN(km)) return '';
    var rounded = km < 10 ? Math.round(km*10)/10 : Math.round(km);
    var du = tone !== 'sie';
    return du ? 'ca. ' + rounded + ' km von Eurer Eventlocation entfernt' : 'ca. ' + rounded + ' km von Ihrer Eventlocation entfernt';
  }
  function card(item, tone){
    var link = item.url || 'https://rent-a-pastor.com/trauredner/';
    var img = item.img ? '<img src="'+escapeAttr(item.img)+'" alt="'+escapeAttr(item.name)+'" loading="lazy">' : '<div class="wae-result-img-fallback">R</div>';
    var label = 'Trauredner kennenlernen';
    var subtitle = item.city ? 'Trauredner aus ' + item.city : 'Trauredner im Rent-a-Pastor Netzwerk';
    var distance = formatDistance(item.distance, tone);
    var percent = item.match_percent ? item.match_percent : '';
    return '<article class="wae-result-card">'+
      '<div class="wae-result-media">'+img+'</div>'+
      '<div class="wae-result-body"><h4>'+escapeHtml(item.name)+'</h4>'+
      '<div class="wae-result-meta">'+escapeHtml(subtitle)+'</div>'+
      (percent ? '<div class="wae-result-score">'+escapeHtml(percent)+' % Match</div>' : '')+
      (distance ? '<div class="wae-result-distance">📍 '+escapeHtml(distance)+'</div>' : '')+
      '<a class="wae-result-link" href="'+escapeAttr(link)+'" target="_blank" rel="noopener">'+escapeHtml(label)+'</a></div></article>';
  }
  function escapeHtml(str){ return cleanText(str).replace(/[&<>'"]/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[c]; }); }
  function escapeAttr(str){ return escapeHtml(str); }
  function getFilters(box){
    var out={};
    box.querySelectorAll('[data-wae-filter]').forEach(function(el){ out[el.getAttribute('data-wae-filter')]=el.value || ''; });
    return out;
  }
  function renderFallback(results, tone){
    var demo=[
      {name:'Samuel Diekmann', city:'Rhein-Main / Seligenstadt', url:'https://rent-a-pastor.com/zeremonie-freie-trauung/seligenstadt-samuel-diekmann/', excerpt:'Erfahrener Trauredner und Gründer von Rent-a-Pastor für persönliche freie Trauungen mit moderner, auf Wunsch christlich offener Gestaltung.'},
      {name:'Rent-a-Pastor Rednernetzwerk', city:'Deutschland, Österreich und Schweiz', url:'https://rent-a-pastor.com/trauredner/', excerpt:'Weitere passende Traurednerinnen und Trauredner aus dem Netzwerk werden in der fertigen Version dynamisch aus der öffentlichen Rednerdatenbank geladen.'}
    ];
    results.innerHTML = '<div class="wae-results-note">Die öffentliche Rednerdatenbank konnte in dieser Vorschau nicht vollständig geladen werden. Zur Orientierung werden Beispielkarten angezeigt.</div>' + demo.map(function(i){return card(i,tone);}).join('');
  }
  function run(box){
    var results = box.querySelector('[data-wae-results]');
    var api = box.getAttribute('data-api');
    var tone = box.getAttribute('data-tone') || 'du';
    var context = {
      location: box.getAttribute('data-location') || '',
      city: box.getAttribute('data-city') || '',
      zip: box.getAttribute('data-zip') || '',
      lat: pickNumber(box.dataset || {}, ['lat','latitude']),
      lng: pickNumber(box.dataset || {}, ['lng','lon','longitude'])
    };
    results.innerHTML = '<div class="wae-live-loading">Rednerprofile werden geladen ...</div>';
    var sep = api.indexOf('?') === -1 ? '?' : '&';
    var requestUrl = api + sep + 'service=trauung&location=' + encodeURIComponent(context.location || context.city || context.zip) + '&_wae_ts=' + Date.now();
    fetch(requestUrl, {credentials:'omit', cache:'no-store'}).then(function(r){ return r.json(); }).then(function(payload){
      var filters = getFilters(box);
      var list = listFromPayload(payload).map(function(s){ return normalize(s, context); }).filter(function(item){
        return item.name && (item.url || item.hay.indexOf('trau') !== -1 || item.hay.indexOf('redner') !== -1);
      });
      var radius = parseFloat(filters.radius || '120');
      var changed = filterWasChanged(filters);
      list = list.filter(function(item){
        if (item.distance === null || isNaN(item.distance)) return true;
        if (radius >= 500) return true;
        return item.distance <= radius;
      });
      list.forEach(function(item){ item.match_percent = matchPercent(item, filters); });
      list.sort(function(a,b){
        if (changed) {
          if (b.match_percent !== a.match_percent) return b.match_percent - a.match_percent;
          return (a.distance || 99999) - (b.distance || 99999);
        }
        return (a.distance || 99999) - (b.distance || 99999);
      });
      list = list.slice(0, 6);
      if (!list.length) { renderFallback(results, tone); return; }
      results.innerHTML = list.map(function(item){ return card(item, tone); }).join('');
    }).catch(function(){ renderFallback(results, tone); });
  }
  document.addEventListener('click', function(e){
    var btn = e.target.closest('[data-wae-run-matching]');
    if (!btn) return;
    var box = btn.closest('[data-wae-matching]');
    if (box) run(box);
  });
})();
