Zum Inhalt springen

MediaWiki:Common.js: Unterschied zwischen den Versionen

Aus ADOS Wiki
Keine Bearbeitungszusammenfassung
Markierung: Manuelle Zurücksetzung
Keine Bearbeitungszusammenfassung
Markierung: Zurückgesetzt
Zeile 219: Zeile 219:




/* ADOS Whisky-Ratings – RatePage Frontend (robust + Stats + Summary) */
mw.loader.using(['mediawiki.api', 'mediawiki.user']).then(function () {


/* Whisky-Ratings – eigenes Frontend für RatePage (Variante B, robust + Stats) */
  // ---------- Initialisierung ----------
mw.loader.using(['mediawiki.api', 'mediawiki.user']).then(function () {
  function boot($root) {
    // Interaktive Widgets in diesem Root initialisieren
    ($root || document).querySelectorAll('.whisky-rating__item').forEach(setupWidget);
    // Ø-Übersichten in diesem Root initialisieren
    ($root || document).querySelectorAll('[data-ratepage-summary="true"]').forEach(renderSummary);
    // Meta-only Durchschnittsausgaben (falls benutzt)
    ($root || document).querySelectorAll('.whisky-rating__meta-only').forEach(renderMetaOnly);
  }


   function init() {
   // Erstes Laden
     document.querySelectorAll('.whisky-rating__item').forEach(setupWidget);
  if (document.readyState === 'loading') {
     initMetaOnly(); // unsere extra Anzeige nur mit Ø/Stimmen
     document.addEventListener('DOMContentLoaded', function(){ boot(document); });
  } else {
     boot(document);
   }
   }
  // Bei nachträglich eingeblendeten Inhalten (z. B. VisualEditor)
  mw.hook('wikipage.content').add(function($content) {
    // $content ist ein jQuery-Objekt; wir wollen das DOM-Element
    if ($content && $content[0]) boot($content[0]);
  });


  // ---------- Widget (Gläser) ----------
   function setupWidget(box) {
   function setupWidget(box) {
     const pageId  = mw.config.get('wgArticleId');
     const pageId  = mw.config.get('wgArticleId');
     const contest = box.dataset.ratepageContest || undefined;
     const contest = box.dataset.ratepageContest || undefined;   // "NASE" | "GESCHMACK" | "ABGANG"
     const scale  = parseInt(box.dataset.ratepageScale || '10', 10);
     const scale  = parseInt(box.dataset.ratepageScale || '10', 10);


Zeile 239: Zeile 256:
     if (isAnon) {
     if (isAnon) {
       box.classList.add('whisky-rating--disabled');
       box.classList.add('whisky-rating--disabled');
       meta.textContent = 'Bitte einloggen, um zu bewerten.';
       if (meta) meta.textContent = 'Bitte einloggen, um zu bewerten.';
     }
     }


     // --- Buttons bauen ---
     // Buttons bauen
     const buttons = [];
     const buttons = [];
     for (let i = 1; i <= scale; i++) {
     for (let i = 1; i <= scale; i++) {
Zeile 280: Zeile 297:
     }
     }


    // Stats laden (Ø & Stimmen, eigene Stimme, canVote/see)
    function updateStats() {
      const api = new mw.Api();
      api.get({
        action: 'query',
        prop: 'pagerating',
        pageids: pageId,
        prcontest: contest || undefined,
        format: 'json'
      }).done(function (data) {
        try {
          const pages = (data && data.query && data.query.pages) || {};
          const pid = Object.keys(pages)[0];
          const page = pages[pid] || {};
          const pr = page.pagerating;


// --- Stats laden (Ø & Stimmen, eigene Stimme, canVote/see) ---
          if (!meta) return;
function updateStats() {
  const api = new mw.Api();
  api.get({
    action: 'query',
    prop: 'pagerating',
    pageids: pageId,
    prcontest: contest || undefined,
    format: 'json'
  }).done(function (data) {
    try {
      // Robuster Zugriff: Page-ID-String aus dem Response nehmen
      const pages = (data && data.query && data.query.pages) || {};
      const pid = Object.keys(pages)[0];
      const page = pages[pid] || {};
      const pr = page.pagerating;


      if (!pr) {
          if (!pr) {
        // Keine Daten – lieber neutralen Text setzen
            if (!meta.textContent) meta.textContent = 'Noch keine Bewertungen';
        meta.textContent = meta.textContent || 'Noch keine Bewertungen';
            return;
        return;
          }
      }


      // Ergebnisse sichtbar?
          if (typeof pr.canSee !== 'undefined' && pr.canSee === 0) {
      if (typeof pr.canSee !== 'undefined' && pr.canSee === 0) {
            meta.textContent = 'Bewertungen sind verborgen.';
        meta.textContent = 'Bewertungen sind verborgen.';
          } else {
      } else {
            const hist = pr.pageRating || {};
        const hist = pr.pageRating || {};
            let total = 0, sum = 0;
        let total = 0, sum = 0;
            Object.keys(hist).forEach(k => {
        Object.keys(hist).forEach(k => {
              const s = parseInt(k, 10), c = parseInt(hist[k], 10);
          const s = parseInt(k, 10), c = parseInt(hist[k], 10);
              if (!isNaN(s) && !isNaN(c)) { total += c; sum += s * c; }
          if (!isNaN(s) && !isNaN(c)) { total += c; sum += s * c; }
            });
        });
            meta.textContent = total
        meta.textContent = total
              ? ('Ø ' + (Math.round((sum/total)*10)/10) + ' (' + total + ' Stimmen)')
          ? ('Ø ' + (Math.round((sum/total)*10)/10) + ' (' + total + ' Stimmen)')
              : 'Noch keine Bewertungen';
          : 'Noch keine Bewertungen';
          }
      }


      // eigene Stimme hervorheben
          if (pr.userVote) {
      if (pr.userVote) {
            current = pr.userVote;
        current = pr.userVote;
            highlight(current);
        highlight(current);
          }
      }


      // Voting ggf. deaktivieren
          if (typeof pr.canVote !== 'undefined' && pr.canVote === 0) {
      if (typeof pr.canVote !== 'undefined' && pr.canVote === 0) {
            box.classList.add('whisky-rating--disabled');
        box.classList.add('whisky-rating--disabled');
            widget.querySelectorAll('.whisky-glass').forEach(b => b.disabled = true);
        widget.querySelectorAll('.whisky-glass').forEach(b => b.disabled = true);
            if (!/nicht abstimmen/.test(meta.textContent)) {
        if (!/nicht abstimmen/.test(meta.textContent)) {
              meta.textContent += (meta.textContent ? ' • ' : '') + 'Du darfst hier nicht abstimmen.';
          meta.textContent += (meta.textContent ? ' • ' : '') + 'Du darfst hier nicht abstimmen.';
            }
          }
        } catch (e) {
          console.error(e);
          if (meta && !meta.textContent) meta.textContent = 'Bewertungen konnten nicht geladen werden.';
         }
         }
       }
       }).fail(function (xhr) {
    } catch (e) {
        console.error('Pagerating-Load-Error', xhr);
      console.error(e);
        if (meta && !meta.textContent) meta.textContent = 'Bewertungen konnten nicht geladen werden.';
      if (!meta.textContent) meta.textContent = 'Bewertungen konnten nicht geladen werden.';
      });
     }
     }
  }).fail(function (xhr) {
    console.error('Pagerating-Load-Error', xhr);
    if (!meta.textContent) meta.textContent = 'Bewertungen konnten nicht geladen werden.';
  });
}


// --- Vote senden (per pageid) ---
    // Vote senden
function vote(value) {
    function vote(value) {
  const api = new mw.Api();
      const api = new mw.Api();
  meta.textContent = 'Wird gespeichert …';
      if (meta) meta.textContent = 'Wird gespeichert …';


  // Sicherheitsnetz: nach 8s nicht hängen bleiben
      let saved = false;
  let saved = false;
      const failTimer = setTimeout(function () {
  const failTimer = setTimeout(function () {
        if (!saved && meta) meta.textContent = 'Speichern dauert ungewöhnlich lange … bitte Seite neu laden.';
    if (!saved) meta.textContent = 'Speichern dauert ungewöhnlich lange … bitte Seite neu laden.';
      }, 8000);
  }, 8000);


  api.postWithToken('csrf', {
      api.postWithToken('csrf', {
    action: 'ratepage',
        action: 'ratepage',
    pageid: pageId,                 // ROBUST
        pageid: pageId,
    answer: value,                 // 1..10
        answer: value,
    contest: contest || undefined, // Kategorie
        contest: contest || undefined,
    format: 'json'
        format: 'json'
  }).done(function () {
      }).done(function () {
    saved = true;
        saved = true;
    clearTimeout(failTimer);
        clearTimeout(failTimer);
    current = value;
        current = value;
    highlight(current);
        highlight(current);
        if (meta) meta.textContent = 'Danke! Deine Bewertung: ' + value + ' / ' + scale;
        updateStats();
      }).fail(function (xhr) {
        clearTimeout(failTimer);
        let msg = 'Unbekannter Fehler';
        try {
          const j = xhr && xhr.responseJSON ? xhr.responseJSON : xhr;
          if (j && j.error) {
            msg = (j.error.code ? j.error.code + ': ' : '') + (j.error.info || '');
          }
        } catch(e){}
        console.error('RatePage-API-Fehler:', xhr);
        if (meta) meta.textContent = 'Speichern fehlgeschlagen: ' + msg;
      });
    }


     // Sofort eine Bestätigung anzeigen …
     updateStats();
    meta.textContent = 'Danke! Deine Bewertung: ' + value + ' / ' + scale;
  }


    // … und dann die echten Ø/Count nachladen
  // ---------- Meta-only Ø für einzelne Kategorien ----------
    updateStats();
   function renderMetaOnly(box) {
   }).fail(function (xhr) {
     const pageId = parseInt(box.dataset.ratepagePageid || mw.config.get('wgArticleId'), 10);
     clearTimeout(failTimer);
     const contest = box.dataset.ratepageContest || undefined;
     let msg = 'Unbekannter Fehler';
    new mw.Api().get({
     try {
      action: 'query',
       const j = xhr && xhr.responseJSON ? xhr.responseJSON : xhr;
      prop: 'pagerating',
       if (j && j.error) {
      pageids: pageId,
        msg = (j.error.code ? j.error.code + ': ' : '') + (j.error.info || '');
      prcontest: contest || undefined,
       }
      format: 'json'
    } catch(e){}
     }).done(function (data) {
    console.error('RatePage-API-Fehler:', xhr);
       const pages = data?.query?.pages || {};
    meta.textContent = 'Speichern fehlgeschlagen: ' + msg;
       const pid = Object.keys(pages)[0];
  });
      const pr = pages[pid]?.pagerating;
}
      if (!pr) { box.textContent = ''; return; }
    updateStats();
      if (typeof pr.canSee !== 'undefined' && pr.canSee === 0) { box.textContent = 'Bewertung verborgen'; return; }
      const hist = pr.pageRating || {};
       let total = 0, sum = 0;
      Object.keys(hist).forEach(k => { const s = +k, c = +hist[k]; if (s && c) { total += c; sum += s * c; } });
      box.textContent = total ? ('Ø ' + (Math.round((sum/total)*10)/10) + ' (' + total + ' Stimmen)') : 'Noch keine Bewertungen';
    });
   }
   }


   /* --- Extra-Funktion für meta-only-Anzeigen --- */
   // ---------- Kompakte Ø-Tabelle oben ----------
   function initMetaOnly() {
   function renderSummary(container) {
     document.querySelectorAll('.whisky-rating__meta-only').forEach(function (box) {
     const pageId  = mw.config.get('wgArticleId');
      const pageId = parseInt(box.dataset.ratepagePageid || mw.config.get('wgArticleId'), 10);
    const contests = (container.dataset.ratepageContests || 'NASE,GESCHMACK,ABGANG')
      const contest = box.dataset.ratepageContest || undefined;
                      .split(',').map(s => s.trim()).filter(Boolean);
       const api = new mw.Api();
 
      api.get({
    const labels = { NASE: 'Nase', GESCHMACK: 'Geschmack', ABGANG: 'Abgang' };
    container.textContent = 'Lade Bewertungen …';
 
    function fetchContest(contest) {
       return new mw.Api().get({
         action: 'query',
         action: 'query',
         prop: 'pagerating',
         prop: 'pagerating',
         pageids: pageId,
         pageids: pageId,
         prcontest: contest || undefined,
         prcontest: contest,
         format: 'json'
         format: 'json'
       }).done(function (data) {
       }).then(function (data) {
         const pr = data.query.pages[pageId].pagerating;
         const pages = data?.query?.pages || {};
         if (!pr) { box.textContent = ''; return; }
        const pid = Object.keys(pages)[0];
        if (typeof pr.canSee !== 'undefined' && pr.canSee === 0) {
        const pr = pages[pid]?.pagerating;
          box.textContent = 'Bewertung verborgen';
         if (!pr || (typeof pr.canSee !== 'undefined' && pr.canSee === 0)) {
           return;
           return { contest, total: 0, avg: null, label: labels[contest] || contest };
         }
         }
         const hist = pr.pageRating || {};
         const hist = pr.pageRating || {};
         let total = 0, sum = 0;
         let total = 0, sum = 0;
         Object.keys(hist).forEach(k => {
         Object.keys(hist).forEach(k => { const s = +k, c = +hist[k]; if (s && c) { total += c; sum += s * c; } });
          const s = parseInt(k, 10), c = parseInt(hist[k], 10);
         const avg = total ? Math.round((sum / total) * 10) / 10 : null;
          if (!isNaN(s) && !isNaN(c)) { total += c; sum += s * c; }
        return { contest, total, avg, label: labels[contest] || contest };
        });
      });
         box.textContent = total
    }
          ? ('Ø ' + (Math.round((sum/total)*10)/10) + ' (' + total + ' Stimmen)')
 
          : 'Noch keine Bewertungen';
    Promise.all(contests.map(fetchContest)).then(function (rows) {
      const table = document.createElement('table');
      table.className = 'whisky-summary__table';
 
      const thead = document.createElement('thead');
      thead.innerHTML = '<tr><th>Kategorie</th><th>Ø</th><th>Stimmen</th></tr>';
      table.appendChild(thead);
 
      const tbody = document.createElement('tbody');
      rows.forEach(r => {
        const avgText = (r.avg !== null) ? r.avg.toFixed(1) : '';
        const totalText = r.total ? String(r.total) : '0';
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${r.label}</td><td>${avgText}</td><td>${totalText}</td>`;
        tbody.appendChild(tr);
       });
       });
      table.appendChild(tbody);
      container.replaceChildren(table);
     });
     });
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
   }
   }


});
});

Version vom 5. September 2025, 21:30 Uhr

/* Das folgende JavaScript wird für alle Benutzer geladen. */

// === Skript 1 ===
/* Charity-Popup (v9) – mit zwei Buttons nebeneinander/untereinander je nach Platz */
mw.loader.using(['mediawiki.util', 'jquery']).then(function () {
  (function ($, mw) {
    'use strict';

    var CONFIG = {
      enabled: true,
      id: 'charity_notice_v9', // Version hochsetzen, damit alle es sehen
      title: 'Charity für kinderherzen e.V',
      logoUrl: 'https://www.kinderherzen.de/wp-content/uploads/2019/03/kinderherzen.de_orange_RGB.jpg',
      html:
        '<p>Liebe Whisky, ADoS Heads,</p>' +
        '<p>wir wurden jetzt schon gefragt, ob ihr dieses Wiki-Projekt unterstützen könnt.</p>' +
        '<p>Wir freuen uns sehr, dass dieses Projekt so gut angenommen wurde.</p>' +
        '<p>Wir würden uns daher sehr freuen, wenn ihr anstatt uns, lieber das Projekt vom Whiskywaiter unterstützen würdet.</p>' +
        '<p><strong>Jede Spende zählt!</strong></p>' +
        '<p><a href="https://www.kinderherzen.de/whisky-fuer-den-guten-zweck/" target="_blank" rel="noopener" class="mw-ui-button">Mehr erfahren</a></p>',
      wikiButton: {
        text: 'Mehr auf dem Wiki',
        url: 'https://ados-wiki.de/index.php?title=Charity-Event_%E2%80%9EWhisky_f%C3%BCr_den_guten_Zweck%E2%80%9C_%E2%80%93_The_Whisky_Waiter'
      },
      showOnNamespaces: 'all',
      dailyLimit: 1,
      escToClose: true,
      clickBackdropToClose: true
    };

    if (!CONFIG.enabled) return;

    var ns = mw.config.get('wgNamespaceNumber');
    if (CONFIG.showOnNamespaces !== 'all' &&
        $.isArray(CONFIG.showOnNamespaces) &&
        $.inArray(ns, CONFIG.showOnNamespaces) === -1) {
      return;
    }

    var isAnon = mw.config.get('wgUserName') === null;
    function storageGet(k){ try { return window.localStorage.getItem(k); } catch (e) { return null; } }
    function storageSet(k,v){ try { window.localStorage.setItem(k, v); } catch (e) {} }
    var key = 'popup_' + CONFIG.id + (isAnon ? ':anon' : ':user');
    var today = (function(d){ return d.getFullYear() + '-' + ('0'+(d.getMonth()+1)).slice(-2) + '-' + ('0'+d.getDate()).slice(-2); })(new Date());
    if (storageGet(key) === today) return;
    function markSeen(){ storageSet(key, today); }

    $(function () {
      var $overlay = $('<div>', { 'class': 'mw-popup-overlay' });
      var $modal = $('<div>', {
        'class': 'mw-popup-modal',
        'role': 'dialog',
        'aria-modal': 'true',
        'aria-labelledby': 'mw-popup-title'
      });

      var $logoWrap = $('<div>', { 'class': 'mw-popup-logo' })
        .append($('<div>', { 'class': 'mw-popup-heart' }))
        .append($('<img>', { src: CONFIG.logoUrl, alt: 'Kinderherzen Logo' }));

      var $title = $('<h2>', { id: 'mw-popup-title' }).text(CONFIG.title);
      var $content = $('<div>', { 'class': 'mw-popup-content' }).html(CONFIG.html);

      var $btnOk = $('<button>', { 'class': 'mw-popup-close', type: 'button' }).text('OK');
      var $btnWiki = $('<a>', {
        'class': 'mw-popup-wiki-button',
        'href': CONFIG.wikiButton.url,
        'target': '_blank',
        'rel': 'noopener'
      }).text(CONFIG.wikiButton.text);

      var $btnWrapper = $('<div>', { 'class': 'mw-popup-button-row' }).append($btnOk, $btnWiki);

      $modal.append($logoWrap, $title, $content, $btnWrapper);
      $('body').append($overlay, $modal);

      // Fokus setzen
      setTimeout(function(){ try { $modal.attr('tabindex','-1').focus(); } catch(e) {} }, 0);

      function close() {
        markSeen();
        $overlay.remove();
        $modal.remove();
        $(document).off('keydown.mwpopup');
      }

      $btnOk.on('click', close);
      if (CONFIG.clickBackdropToClose) $overlay.on('click', close);
      if (CONFIG.escToClose) {
        $(document).on('keydown.mwpopup', function (e) {
          var key = e.key || e.keyCode;
          if (key === 'Escape' || key === 'Esc' || key === 27) {
            e.preventDefault();
            close();
          }
        });
      }

      markSeen();
    });
  })(jQuery, mw);
});



// === Skript 2 ===
/* Sticky Charity Banner (v1) – MediaWiki
   - Fix am oberen Rand
   - Schließen mit Erinnerung (session/day/forever)
   - Automatisches Ende via endISO
   - Links: Extern + interne Wiki-Seite
*/
mw.loader.using(['mediawiki.util', 'jquery']).then(function () {
  (function ($, mw) {
    'use strict';

    var CONFIG = {
      enabled: true,
      id: 'charity_banner_v1',              // Bei inhaltlichen Änderungen erhöhen
      text: '❤️ Unterstütze die Kinderherzen-Charity – Jede Spende zählt!',
      primary: {                            // Externer Link
        label: 'Mehr erfahren',
        href: 'https://www.kinderherzen.de/whisky-fuer-den-guten-zweck/'
      },
      secondary: {                          // Interner Wiki-Link
        label: 'Mehr auf dem Wiki',
        href: 'https://ados-wiki.de/index.php?title=Charity-Event_%E2%80%9EWhisky_f%C3%BCr_den_guten_Zweck%E2%80%9C_%E2%80%93_The_Whisky_Waiter'
      },
      showOnNamespaces: 'all',              // 'all' oder Array z. B. [0,4]
      endISO: null,                         // z. B. '2025-10-06T23:59:59Z' (danach ausgeblendet)
      dismiss: { mode: 'day' },             // 'session' | 'day' | 'forever'
      zIndex: 10050                         // über normalen Headern
    };

    if (!CONFIG.enabled) return;

    // Zeitfenster prüfen
    if (CONFIG.endISO && new Date() > new Date(CONFIG.endISO)) return;

    // Namespace-Filter
    var ns = mw.config.get('wgNamespaceNumber');
    if (CONFIG.showOnNamespaces !== 'all' &&
        $.isArray(CONFIG.showOnNamespaces) &&
        $.inArray(ns, CONFIG.showOnNamespaces) === -1) {
      return;
    }

    // Dismiss-Speicher
    function getLS(k){ try { return localStorage.getItem(k); } catch(e){ return null; } }
    function setLS(k,v){ try { localStorage.setItem(k,v); } catch(e){} }
    var key = 'sticky_banner:' + CONFIG.id;
    var today = (function(d){ return d.getFullYear()+'-'+('0'+(d.getMonth()+1)).slice(-2)+'-'+('0'+d.getDate()).slice(-2); })(new Date());
    var dismissed = getLS(key);

    if (CONFIG.dismiss.mode === 'forever' && dismissed) return;
    if (CONFIG.dismiss.mode === 'day' && dismissed === today) return;
    // session: nicht in localStorage speichern → immer wieder pro Session möglich

    $(function () {
      // Banner HTML
      var $bar = $('<div>', {
        'class': 'mw-sticky-banner',
        'role': 'region',
        'aria-label': 'Charity-Hinweis',
        'style': 'z-index:' + CONFIG.zIndex + ';'
      });

      var $inner = $('<div>', { 'class': 'mw-sticky-banner__inner' });

      var $text = $('<div>', { 'class': 'mw-sticky-banner__text', 'html': mw.html.escape(CONFIG.text) });

      // Buttons
      var $btns = $('<div>', { 'class': 'mw-sticky-banner__btns' });
      if (CONFIG.primary && CONFIG.primary.href) {
        $btns.append($('<a>', {
          'class': 'mw-sticky-banner__btn mw-sticky-banner__btn--primary',
          'href': CONFIG.primary.href,
          'target': '_blank',
          'rel': 'noopener'
        }).text(CONFIG.primary.label || 'Mehr erfahren'));
      }
      if (CONFIG.secondary && CONFIG.secondary.href) {
        $btns.append($('<a>', {
          'class': 'mw-sticky-banner__btn mw-sticky-banner__btn--secondary',
          'href': CONFIG.secondary.href
        }).text(CONFIG.secondary.label || 'Mehr auf dem Wiki'));
      }

      var $close = $('<button>', {
        'class': 'mw-sticky-banner__close',
        'type': 'button',
        'aria-label': 'Banner schließen'
      }).text('×');

      $inner.append($text, $btns, $close);
      $bar.append($inner);
      $('body').prepend($bar);
      $('body').addClass('mw-sticky-banner-active');

      function rememberDismiss() {
        if (CONFIG.dismiss.mode === 'forever') { setLS(key, '1'); }
        else if (CONFIG.dismiss.mode === 'day') { setLS(key, today); }
        // session → nichts speichern
      }

      function close() {
        rememberDismiss();
        $bar.remove();
        $('body').removeClass('mw-sticky-banner-active');
      }

      $close.on('click', close);
    });
  })(jQuery, mw);
});





/* ADOS Whisky-Ratings – RatePage Frontend (robust + Stats + Summary) */
mw.loader.using(['mediawiki.api', 'mediawiki.user']).then(function () {

  // ---------- Initialisierung ----------
  function boot($root) {
    // Interaktive Widgets in diesem Root initialisieren
    ($root || document).querySelectorAll('.whisky-rating__item').forEach(setupWidget);
    // Ø-Übersichten in diesem Root initialisieren
    ($root || document).querySelectorAll('[data-ratepage-summary="true"]').forEach(renderSummary);
    // Meta-only Durchschnittsausgaben (falls benutzt)
    ($root || document).querySelectorAll('.whisky-rating__meta-only').forEach(renderMetaOnly);
  }

  // Erstes Laden
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function(){ boot(document); });
  } else {
    boot(document);
  }
  // Bei nachträglich eingeblendeten Inhalten (z. B. VisualEditor)
  mw.hook('wikipage.content').add(function($content) {
    // $content ist ein jQuery-Objekt; wir wollen das DOM-Element
    if ($content && $content[0]) boot($content[0]);
  });

  // ---------- Widget (Gläser) ----------
  function setupWidget(box) {
    const pageId  = mw.config.get('wgArticleId');
    const contest = box.dataset.ratepageContest || undefined;   // "NASE" | "GESCHMACK" | "ABGANG"
    const scale   = parseInt(box.dataset.ratepageScale || '10', 10);

    const widget  = box.querySelector('.whisky-rating__widget');
    const meta    = box.querySelector('.whisky-rating__meta');

    const isAnon  = mw.user.isAnon();
    if (isAnon) {
      box.classList.add('whisky-rating--disabled');
      if (meta) meta.textContent = 'Bitte einloggen, um zu bewerten.';
    }

    // Buttons bauen
    const buttons = [];
    for (let i = 1; i <= scale; i++) {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'whisky-glass';
      btn.setAttribute('aria-label', i + ' von ' + scale);
      btn.setAttribute('aria-pressed', 'false');

      if (isAnon) {
        btn.disabled = true;
        btn.title = 'Nur für registrierte Benutzer';
      } else {
        btn.title = i + ' / ' + scale;
        btn.addEventListener('mouseenter', () => highlight(i));
        btn.addEventListener('mouseleave', () => highlight(current));
        btn.addEventListener('click', () => vote(i));
        btn.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); vote(i); }
          if (e.key === 'ArrowRight' && i < scale) buttons[i].focus();
          if (e.key === 'ArrowLeft'  && i > 1)     buttons[i-2].focus();
        });
      }
      widget.appendChild(btn);
      buttons.push(btn);
    }

    let current = 0;
    highlight(current);

    function highlight(n) {
      buttons.forEach((b, idx) => {
        const active = (idx < n);
        b.classList.toggle('is-active', active);
        b.setAttribute('aria-pressed', active ? 'true' : 'false');
      });
    }

    // Stats laden (Ø & Stimmen, eigene Stimme, canVote/see)
    function updateStats() {
      const api = new mw.Api();
      api.get({
        action: 'query',
        prop: 'pagerating',
        pageids: pageId,
        prcontest: contest || undefined,
        format: 'json'
      }).done(function (data) {
        try {
          const pages = (data && data.query && data.query.pages) || {};
          const pid = Object.keys(pages)[0];
          const page = pages[pid] || {};
          const pr = page.pagerating;

          if (!meta) return;

          if (!pr) {
            if (!meta.textContent) meta.textContent = 'Noch keine Bewertungen';
            return;
          }

          if (typeof pr.canSee !== 'undefined' && pr.canSee === 0) {
            meta.textContent = 'Bewertungen sind verborgen.';
          } else {
            const hist = pr.pageRating || {};
            let total = 0, sum = 0;
            Object.keys(hist).forEach(k => {
              const s = parseInt(k, 10), c = parseInt(hist[k], 10);
              if (!isNaN(s) && !isNaN(c)) { total += c; sum += s * c; }
            });
            meta.textContent = total
              ? ('Ø ' + (Math.round((sum/total)*10)/10) + ' (' + total + ' Stimmen)')
              : 'Noch keine Bewertungen';
          }

          if (pr.userVote) {
            current = pr.userVote;
            highlight(current);
          }

          if (typeof pr.canVote !== 'undefined' && pr.canVote === 0) {
            box.classList.add('whisky-rating--disabled');
            widget.querySelectorAll('.whisky-glass').forEach(b => b.disabled = true);
            if (!/nicht abstimmen/.test(meta.textContent)) {
              meta.textContent += (meta.textContent ? ' • ' : '') + 'Du darfst hier nicht abstimmen.';
            }
          }
        } catch (e) {
          console.error(e);
          if (meta && !meta.textContent) meta.textContent = 'Bewertungen konnten nicht geladen werden.';
        }
      }).fail(function (xhr) {
        console.error('Pagerating-Load-Error', xhr);
        if (meta && !meta.textContent) meta.textContent = 'Bewertungen konnten nicht geladen werden.';
      });
    }

    // Vote senden
    function vote(value) {
      const api = new mw.Api();
      if (meta) meta.textContent = 'Wird gespeichert …';

      let saved = false;
      const failTimer = setTimeout(function () {
        if (!saved && meta) meta.textContent = 'Speichern dauert ungewöhnlich lange … bitte Seite neu laden.';
      }, 8000);

      api.postWithToken('csrf', {
        action: 'ratepage',
        pageid: pageId,
        answer: value,
        contest: contest || undefined,
        format: 'json'
      }).done(function () {
        saved = true;
        clearTimeout(failTimer);
        current = value;
        highlight(current);
        if (meta) meta.textContent = 'Danke! Deine Bewertung: ' + value + ' / ' + scale;
        updateStats();
      }).fail(function (xhr) {
        clearTimeout(failTimer);
        let msg = 'Unbekannter Fehler';
        try {
          const j = xhr && xhr.responseJSON ? xhr.responseJSON : xhr;
          if (j && j.error) {
            msg = (j.error.code ? j.error.code + ': ' : '') + (j.error.info || '');
          }
        } catch(e){}
        console.error('RatePage-API-Fehler:', xhr);
        if (meta) meta.textContent = 'Speichern fehlgeschlagen: ' + msg;
      });
    }

    updateStats();
  }

  // ---------- Meta-only Ø für einzelne Kategorien ----------
  function renderMetaOnly(box) {
    const pageId = parseInt(box.dataset.ratepagePageid || mw.config.get('wgArticleId'), 10);
    const contest = box.dataset.ratepageContest || undefined;
    new mw.Api().get({
      action: 'query',
      prop: 'pagerating',
      pageids: pageId,
      prcontest: contest || undefined,
      format: 'json'
    }).done(function (data) {
      const pages = data?.query?.pages || {};
      const pid = Object.keys(pages)[0];
      const pr = pages[pid]?.pagerating;
      if (!pr) { box.textContent = ''; return; }
      if (typeof pr.canSee !== 'undefined' && pr.canSee === 0) { box.textContent = 'Bewertung verborgen'; return; }
      const hist = pr.pageRating || {};
      let total = 0, sum = 0;
      Object.keys(hist).forEach(k => { const s = +k, c = +hist[k]; if (s && c) { total += c; sum += s * c; } });
      box.textContent = total ? ('Ø ' + (Math.round((sum/total)*10)/10) + ' (' + total + ' Stimmen)') : 'Noch keine Bewertungen';
    });
  }

  // ---------- Kompakte Ø-Tabelle oben ----------
  function renderSummary(container) {
    const pageId   = mw.config.get('wgArticleId');
    const contests = (container.dataset.ratepageContests || 'NASE,GESCHMACK,ABGANG')
                      .split(',').map(s => s.trim()).filter(Boolean);

    const labels = { NASE: 'Nase', GESCHMACK: 'Geschmack', ABGANG: 'Abgang' };
    container.textContent = 'Lade Bewertungen …';

    function fetchContest(contest) {
      return new mw.Api().get({
        action: 'query',
        prop: 'pagerating',
        pageids: pageId,
        prcontest: contest,
        format: 'json'
      }).then(function (data) {
        const pages = data?.query?.pages || {};
        const pid = Object.keys(pages)[0];
        const pr = pages[pid]?.pagerating;
        if (!pr || (typeof pr.canSee !== 'undefined' && pr.canSee === 0)) {
          return { contest, total: 0, avg: null, label: labels[contest] || contest };
        }
        const hist = pr.pageRating || {};
        let total = 0, sum = 0;
        Object.keys(hist).forEach(k => { const s = +k, c = +hist[k]; if (s && c) { total += c; sum += s * c; } });
        const avg = total ? Math.round((sum / total) * 10) / 10 : null;
        return { contest, total, avg, label: labels[contest] || contest };
      });
    }

    Promise.all(contests.map(fetchContest)).then(function (rows) {
      const table = document.createElement('table');
      table.className = 'whisky-summary__table';

      const thead = document.createElement('thead');
      thead.innerHTML = '<tr><th>Kategorie</th><th>Ø</th><th>Stimmen</th></tr>';
      table.appendChild(thead);

      const tbody = document.createElement('tbody');
      rows.forEach(r => {
        const avgText = (r.avg !== null) ? r.avg.toFixed(1) : '–';
        const totalText = r.total ? String(r.total) : '0';
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${r.label}</td><td>${avgText}</td><td>${totalText}</td>`;
        tbody.appendChild(tr);
      });
      table.appendChild(tbody);

      container.replaceChildren(table);
    });
  }

});