/* /assets/js/firefly-fonts-customizer.js */
(function($){
  'use strict';

  // fireflyFontsData.fontWeights is localized by PHP
  var fontWeightsData = (window.fireflyFontsData && window.fireflyFontsData.fontWeights) || {};
  var targets = (window.fireflyFontsData && window.fireflyFontsData.targets) || [];

  function getAvailableWeights(fontFamily) {
    if (!fontFamily) return ['400','700'];

    // exact key
    if (fontWeightsData[fontFamily]) return fontWeightsData[fontFamily];

    // strip fallback stack
    var base = fontFamily.split(',')[0].trim();
    if (fontWeightsData[base]) return fontWeightsData[base];

    // case-insensitive attempt
    var lower = fontFamily.toLowerCase();
    for (var k in fontWeightsData) if (k.toLowerCase() === lower) return fontWeightsData[k];

    var lowerBase = base.toLowerCase();
    for (var kk in fontWeightsData) {
      if (kk.split(',')[0].trim().toLowerCase() === lowerBase) return fontWeightsData[kk];
    }
    return ['400','700'];
  }

  function updateWeightControl(target, fontFamily) {
    var controlId = 'customize-control-my_plugin_' + target + '_weight_control';
    var $wrap = $('#' + controlId);
    if (!$wrap.length) return;

    var avail = getAvailableWeights(fontFamily);

    // Toggle each radio (show all; disable unavailable)
    $wrap.find('input[type="radio"]').each(function(){
      var $r = $(this);
      var val = $r.val();
      var $label = $r.closest('label');
      var supported = avail.indexOf(val) !== -1;

      $r.prop('disabled', !supported);
      $label.toggleClass('disabled-font-weight', !supported);
    });

    // If current selection is now invalid, switch to the first available
    var $checked = $wrap.find('input[type="radio"]:checked');
    if (!$checked.length || $checked.prop('disabled')) {
      var $first = $wrap.find('input[type="radio"]:not(:disabled)').first();
      if ($first.length) {
        $first.prop('checked', true).trigger('change');
        // sync the Customizer setting
        var settingId = 'my_plugin_' + target + '_weight';
        if (wp && wp.customize && wp.customize(settingId)) {
          wp.customize(settingId).set($first.val());
        }
      }
    }
  }

  function bindFontChange(target) {
    var settingId = 'my_plugin_' + target + '_font';
    var controlSel = '#customize-control-' + settingId + '_control select';

    // 1) React to UI select change
    $(document).on('change', controlSel, function(){
      updateWeightControl(target, $(this).val());
    });

    // 2) React to underlying setting (postMessage updates etc.)
    if (wp && wp.customize && wp.customize(settingId)) {
      wp.customize(settingId, function(setting){
        setting.bind(function(newVal){
          updateWeightControl(target, newVal);
        });
      });
    }

    // 3) Initialize once on ready
    var initialVal = $(controlSel).val();
    if (initialVal) updateWeightControl(target, initialVal);
  }

  wp.customize.bind('ready', function(){
    targets.forEach(bindFontChange);
  });

})(jQuery);
