/**
 * Content-Blocker Generator (Borlabs-Parity).
 *
 * Returns a small JS snippet that scans the page for blockable third-party
 * embeds (YouTube, Vimeo, Google Maps, Spotify, Twitter, Facebook) and
 * replaces them with a click-to-consent placeholder until the user agrees
 * to the relevant cookie category.
 *
 * The customer drops a SECOND script tag next to the banner:
 *   <script src="/cookie-banner.js"></script>
 *   <script src="/cookie-content-blocker.js"></script>
 *
 * Author writes content as either:
 *   <bp-consent-block category="EXTERNAL_MEDIA"
 *                     provider="YouTube"
 *                     src="https://www.youtube.com/embed/...">
 *     <!-- the original iframe / embed code -->
 *   </bp-consent-block>
 *
 * OR auto-detect: any <iframe src="https://www.youtube.com/...">
 * gets wrapped on page load.
 */

const KNOWN_EMBEDS: Array<{ host: string; provider: string; category: string }> = [
  { host: 'youtube.com', provider: 'YouTube',     category: 'EXTERNAL_MEDIA' },
  { host: 'youtu.be',    provider: 'YouTube',     category: 'EXTERNAL_MEDIA' },
  { host: 'vimeo.com',   provider: 'Vimeo',       category: 'EXTERNAL_MEDIA' },
  { host: 'google.com/maps',     provider: 'Google Maps', category: 'EXTERNAL_MEDIA' },
  { host: 'maps.googleapis.com', provider: 'Google Maps', category: 'EXTERNAL_MEDIA' },
  { host: 'spotify.com',  provider: 'Spotify',     category: 'EXTERNAL_MEDIA' },
  { host: 'soundcloud.com', provider: 'SoundCloud', category: 'EXTERNAL_MEDIA' },
  { host: 'twitter.com',  provider: 'Twitter / X', category: 'PERSONALIZATION' },
  { host: 'facebook.com', provider: 'Facebook',    category: 'PERSONALIZATION' },
  { host: 'instagram.com', provider: 'Instagram',  category: 'PERSONALIZATION' },
]

export function generateContentBlockerJS(cookieName: string = 'cookie_consent'): string {
  return `(function () {
  'use strict';
  var COOKIE_NAME = ${JSON.stringify(cookieName)};
  var KNOWN_EMBEDS = ${JSON.stringify(KNOWN_EMBEDS)};

  function getConsent() {
    var c = document.cookie.split('; ').find(function (r) {
      return r.indexOf(COOKIE_NAME + '=') === 0;
    });
    if (!c) return null;
    try { return JSON.parse(decodeURIComponent(c.split('=')[1])); } catch (e) { return null; }
  }

  function categoryGranted(cat) {
    var c = getConsent();
    if (!c) return false;
    var k = String(cat).toLowerCase();
    return c[cat] === true || c[k] === true;
  }

  function classifyByHost(src) {
    if (!src) return null;
    for (var i = 0; i < KNOWN_EMBEDS.length; i++) {
      if (src.indexOf(KNOWN_EMBEDS[i].host) > -1) return KNOWN_EMBEDS[i];
    }
    return null;
  }

  function makePlaceholder(provider, category, originalHTML, parent) {
    var ph = document.createElement('div');
    ph.className = 'bp-consent-placeholder';
    ph.style.cssText = 'border:2px dashed #cbd5e1;background:#f8fafc;padding:24px;' +
      'border-radius:8px;text-align:center;font-family:-apple-system,sans-serif;color:#475569';
    ph.innerHTML =
      '<div style="font-size:14px;font-weight:600;color:#1e293b;margin-bottom:8px">' +
      'Inhalt von ' + provider + ' blockiert</div>' +
      '<div style="font-size:12px;margin-bottom:12px">' +
      'Zum Anzeigen dieses Inhalts wird Ihre Einwilligung fuer die Kategorie ' +
      '<strong>' + category + '</strong> benoetigt. ' +
      'Beim Akzeptieren werden Cookies von ' + provider + ' gesetzt.</div>' +
      '<button class="bp-consent-load-btn" ' +
      'style="background:#7c3aed;color:white;border:none;padding:8px 16px;' +
      'border-radius:6px;font-size:13px;cursor:pointer;margin-right:6px">' +
      'Inhalt einmalig laden</button>' +
      '<button class="bp-consent-accept-btn" ' +
      'style="background:#16a34a;color:white;border:none;padding:8px 16px;' +
      'border-radius:6px;font-size:13px;cursor:pointer">' +
      category + ' akzeptieren</button>';
    ph.querySelector('.bp-consent-load-btn').addEventListener('click', function () {
      var div = document.createElement('div');
      div.innerHTML = originalHTML;
      while (div.firstChild) parent.insertBefore(div.firstChild, ph);
      ph.remove();
    });
    ph.querySelector('.bp-consent-accept-btn').addEventListener('click', function () {
      var c = getConsent() || {};
      c[category] = true;
      var date = new Date();
      date.setTime(date.getTime() + 180 * 86400000);
      document.cookie = COOKIE_NAME + '=' + encodeURIComponent(JSON.stringify(c)) +
                        ';expires=' + date.toUTCString() + ';path=/;SameSite=Lax';
      window.dispatchEvent(new CustomEvent('cookieConsentUpdated', { detail: c }));
      // Re-scan: placeholders for THIS category get replaced now
      processAll();
    });
    return ph;
  }

  function processWrapped() {
    var wrapped = document.querySelectorAll('bp-consent-block, [data-bp-consent-block]');
    wrapped.forEach(function (el) {
      var cat = el.getAttribute('category') || el.getAttribute('data-category') || 'EXTERNAL_MEDIA';
      var prov = el.getAttribute('provider') || el.getAttribute('data-provider') || 'Drittanbieter';
      if (categoryGranted(cat)) {
        // Already consented: unwrap the inner content
        var html = el.innerHTML;
        var tmp = document.createElement('div');
        tmp.innerHTML = html;
        var parent = el.parentNode;
        while (tmp.firstChild) parent.insertBefore(tmp.firstChild, el);
        el.remove();
      } else {
        var parent = el.parentNode;
        var inner = el.innerHTML;
        var ph = makePlaceholder(prov, cat, inner, parent);
        parent.insertBefore(ph, el);
        el.remove();
      }
    });
  }

  function processBareIframes() {
    var iframes = document.querySelectorAll('iframe[src]:not([data-bp-processed])');
    iframes.forEach(function (f) {
      var match = classifyByHost(f.getAttribute('src') || '');
      if (!match) return;
      f.setAttribute('data-bp-processed', '1');
      if (categoryGranted(match.category)) return;
      var html = f.outerHTML;
      var parent = f.parentNode;
      var ph = makePlaceholder(match.provider, match.category, html, parent);
      parent.replaceChild(ph, f);
    });
  }

  function processAll() {
    processWrapped();
    processBareIframes();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', processAll);
  } else {
    processAll();
  }
  // Re-process when consent updates
  window.addEventListener('cookieConsentUpdated', processAll);
})();`
}
