(function(){
  'use strict';

  function setSelectedPreview(details, input){
    if(!details || !input) return;

    var labelText = input.getAttribute('data-matewa-language-label') || input.value || '';
    var summaryLabel = details.querySelector('[data-matewa-language-summary]');
    if(summaryLabel) summaryLabel.textContent = labelText;

    var row = input.closest ? input.closest('.matewa-language-admin-row') : null;
    var rowFlagImg = row ? row.querySelector('.matewa-language-admin-flag img') : null;
    var summaryFlag = details.querySelector('.matewa-language-harmonica-summary > .matewa-language-admin-flag');
    var src = input.getAttribute('data-matewa-language-flag-src') || (rowFlagImg ? rowFlagImg.getAttribute('src') : '');

    if(summaryFlag){
      summaryFlag.innerHTML = '';
      if(src){
        var img = document.createElement('img');
        img.src = src;
        img.alt = '';
        img.decoding = 'async';
        summaryFlag.appendChild(img);
      }
    }
  }

  function init(){
    document.querySelectorAll('[data-matewa-language-harmonica]').forEach(function(details){
      var checked = details.querySelector('input[type="radio"]:checked');
      if(checked) setSelectedPreview(details, checked);

      details.addEventListener('change', function(e){
        var input = e.target;
        if(!input || input.type !== 'radio') return;
        setSelectedPreview(details, input);
        details.open = false;
      });
    });
  }

  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
})();
