const BaseExtractor = require('./base');

class BojokoExtractor extends BaseExtractor {
  constructor() {
    super();
    this.patterns = [
      /bojoko/,
    ];
  }

  getExtractCode() {
    return `
      (function() {
        var HOST = location.hostname.replace('www.', '');
        var results = [];
        var seen = {};

        function clean(name) {
          if (!name || typeof name !== 'string') return '';
          return name
            .replace(/^Casino /gi, '')
            .replace(/ cover\s*$/i, '')
            .replace(/Logo/gi, '')
            .trim();
        }

        function isBrand(n) {
          if (!n || n.length < 2 || !/[a-zA-Z]/.test(n[0])) return false;
          var bad = ['menu', 'nav', 'social', 'icon', 'visa', 'mastercard', 
            'bitcoin', 'ethereum', 'interac', 'jeton', 'mifinity', 
            'litecoin', 'tether', 'neteller', 'skrill', 'paysafecard',
            'muchbetter', 'apple pay', 'google pay'];
          for (var j = 0; j < bad.length; j++) { if (n.toLowerCase().includes(bad[j])) return false; }
          return true;
        }

        function getLink(node) {
          try {
            var anchors = node.querySelectorAll('a[href]');
            for (var i = 0; i < Math.min(anchors.length, 3); i++) {
              var url = new URL(anchors[i].href, document.baseURI);
              if (url.hostname.replace('www.', '') !== HOST) return url.origin;
            }
          } catch(e) {}
          return '';
        }

        // Bojoko uses divs with class "card-toplist-row__header" for casino brand logos
        // Payment method imgs use "card-toplist-row__banking-method" which we skip via isBrand check
        var headerDivs = document.querySelectorAll('[class*="toplist-row__header"]');
        for (var h = 0; h < headerDivs.length; h++) {
          var hdr = headerDivs[h];
          var img = hdr.querySelector('img[alt]');
          if (!img) continue;

          var name = clean(img.alt);
          if (!isBrand(name) || seen[name]) continue;

          // Walk up to find the nearest div containing an off-site affiliate link
          var container = hdr.parentElement;
          var link = '';
          while (container && !link) {
            try {
              for (var a of container.querySelectorAll('a[href]')) {
                var u = new URL(a.href, document.baseURI);
                if (u.hostname.replace('www.', '') !== HOST) { link = u.origin; break; }
              }
            } catch(e) {}
            container = container.parentElement;
          }

          if (!link) continue;

          seen[name] = true;
          results.push({ name: name, link: link, bonus: '' });
        }

        return results.slice(0, 25);
      })();
    `;
  }
}

module.exports = BojokoExtractor;