(function () {
  var presetSelect = document.getElementById('pdt-design-preset');
  var applyPresetButton = document.getElementById('pdt-design-apply-preset');
  var playground = document.getElementById('pdt-design-playground');
  var scopeSelect = document.getElementById('pdt-design-scope');
  var selectedScreensWrap = document.getElementById('pdt-design-selected-screens');
  var presetMap = typeof pdtDesignPresets !== 'undefined' && pdtDesignPresets.presets ? pdtDesignPresets.presets : {};

  var presetKeys = [
    'color_primary',
    'color_bg',
    'color_surface',
    'color_text',
    'color_muted',
    'sidebar_bg',
    'sidebar_text',
    'adminbar_bg',
    'adminbar_text',
    'adminbar_submenu_bg',
    'adminbar_submenu_text',
    'color_border',
    'color_hover',
    'color_focus',
    'color_success',
    'color_warning',
    'color_error',
    'color_table_head',
    'color_input_bg',
    'font_family',
    'type_scale',
    'density',
    'spacing_scale',
    'border_radius',
    'button_radius_preset',
    'link_color',
    'link_hover',
    'link_visited',
    'link_active',
    'link_decoration',
    'link_weight',
    'link_scope'
  ];

  function getByName(name) {
    return document.querySelector('[name="' + name + '"]');
  }

  function getControl(key) {
    return document.getElementById('pdt-design-' + key) || getByName('pdt_design[' + key + ']');
  }

  function getCheckboxControls(key) {
    return document.querySelectorAll('input[name="pdt_design[' + key + '][]"]');
  }

  function getValue(key) {
    var control = getControl(key);
    if (!control) {
      return '';
    }
    if (control.type === 'checkbox') {
      return control.checked ? '1' : '';
    }
    return control.value;
  }

  function setFieldValue(key, value) {
    var controls;
    var i;

    if (key === 'selected_screens' && Array.isArray(value)) {
      controls = getCheckboxControls(key);
      for (i = 0; i < controls.length; i++) {
        controls[i].checked = value.indexOf(controls[i].value) !== -1;
      }
      return;
    }

    var control = getControl(key);
    if (!control) {
      return;
    }

    if (control.type === 'checkbox') {
      control.checked = !!value;
      return;
    }

    control.value = value;
  }

  function sanitizeHex(hex, fallback) {
    if (typeof hex === 'string' && /^#[0-9a-fA-F]{6}$/.test(hex)) {
      return hex;
    }
    return fallback;
  }

  function hexToRgb(hex) {
    hex = sanitizeHex(hex, '#0f172a').slice(1);
    return {
      r: parseInt(hex.slice(0, 2), 16),
      g: parseInt(hex.slice(2, 4), 16),
      b: parseInt(hex.slice(4, 6), 16)
    };
  }

  function channelLuminance(value) {
    value = value / 255;
    return value <= 0.03928 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4);
  }

  function relativeLuminance(hex) {
    var rgb = hexToRgb(hex);
    return (0.2126 * channelLuminance(rgb.r)) +
      (0.7152 * channelLuminance(rgb.g)) +
      (0.0722 * channelLuminance(rgb.b));
  }

  function contrastRatio(left, right) {
    var leftLum = relativeLuminance(left);
    var rightLum = relativeLuminance(right);
    var lighter = Math.max(leftLum, rightLum);
    var darker = Math.min(leftLum, rightLum);
    return (lighter + 0.05) / (darker + 0.05);
  }

  function chooseContrast(background, candidates) {
    var choices = Array.isArray(candidates) ? candidates.slice() : [];
    choices.push('#0f172a', '#f8fafc');

    var best = '#0f172a';
    var bestRatio = 0;
    var i;

    background = sanitizeHex(background, '#ffffff');

    for (i = 0; i < choices.length; i++) {
      var candidate = sanitizeHex(choices[i], '');
      var ratio;

      if (!candidate) {
        continue;
      }

      ratio = contrastRatio(background, candidate);
      if (ratio > bestRatio) {
        bestRatio = ratio;
        best = candidate;
      }
    }

    return best;
  }

  function resolveAccessibleForeground(background, preferred, candidates, minimumRatio) {
    minimumRatio = typeof minimumRatio === 'number' ? minimumRatio : 4.5;
    preferred = sanitizeHex(preferred, '');

    if (preferred && contrastRatio(background, preferred) >= minimumRatio) {
      return preferred;
    }

    return chooseContrast(background, candidates);
  }

  function mixHex(base, mix, percent) {
    var baseRgb = hexToRgb(base);
    var mixRgb = hexToRgb(mix);
    var ratio = Math.max(0, Math.min(100, percent)) / 100;

    function blend(channel) {
      return Math.round(baseRgb[channel] + ((mixRgb[channel] - baseRgb[channel]) * ratio));
    }

    function component(value) {
      return value.toString(16).padStart(2, '0');
    }

    return '#' + component(blend('r')) + component(blend('g')) + component(blend('b'));
  }

  function deriveHover(base, percent) {
    var target = relativeLuminance(base) > 0.55 ? '#0f172a' : '#ffffff';
    return mixHex(base, target, percent);
  }

  function rgba(hex, alpha) {
    var rgb = hexToRgb(hex);
    return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + alpha + ')';
  }

  function resolveScale(value, fallback) {
    var parsed = parseInt(value, 10);
    return isNaN(parsed) ? fallback : parsed;
  }

  function resolveButtonRadius(radius, preset) {
    radius = Math.max(0, Math.min(24, parseInt(radius, 10) || 0));

    switch (preset) {
      case 'soft':
        return Math.max(4, radius) + 'px';
      case 'rounded':
        return Math.min(20, Math.max(8, radius + 6)) + 'px';
      case 'pill':
        return '999px';
      case 'inherit':
      default:
        return radius + 'px';
    }
  }

  function setVar(name, value) {
    if (!playground) {
      return;
    }
    playground.style.setProperty(name, value);
  }

  function updateScopeUI() {
    if (!scopeSelect || !selectedScreensWrap) {
      return;
    }

    selectedScreensWrap.classList.toggle('is-visible', scopeSelect.value === 'selected_screens');
  }

  function updateScreenChipStates() {
    Array.prototype.forEach.call(
      document.querySelectorAll('.pdt-design-screen-chip'),
      function (chip) {
        var input = chip.querySelector('input[type="checkbox"]');
        chip.classList.toggle('is-checked', !!(input && input.checked));
      }
    );
  }

  function updatePlayground() {
    if (!playground) {
      return;
    }

    playground.setAttribute('data-pdt-design-preset', getValue('preset') || 'default');

    var radius = Math.max(0, Math.min(24, parseInt(getValue('border_radius'), 10) || 8));
    var typeScale = resolveScale(getValue('type_scale'), 100);
    var spacingScale = resolveScale(getValue('spacing_scale'), 100);
    var density = getValue('density') || 'cozy';
    var densityMap = {
      compact: 0.9,
      cozy: 1,
      comfortable: 1.12
    };
    var densityScale = densityMap[density] || 1;
    var spaceScale = (spacingScale / 100) * densityScale;

    var primary = sanitizeHex(getValue('color_primary'), '#4f46e5');
    var bg = sanitizeHex(getValue('color_bg'), '#f8fafc');
    var surface = sanitizeHex(getValue('color_surface'), '#ffffff');
    var text = sanitizeHex(getValue('color_text'), '#0f172a');
    var muted = sanitizeHex(getValue('color_muted'), '#64748b');
    var sidebarBg = sanitizeHex(getValue('sidebar_bg'), '#0f172a');
    var sidebarText = sanitizeHex(getValue('sidebar_text'), '#f8fafc');
    var adminbarBg = sanitizeHex(getValue('adminbar_bg'), '#0f172a');
    var adminbarText = sanitizeHex(getValue('adminbar_text'), '#f8fafc');
    var adminbarSubmenuBg = sanitizeHex(getValue('adminbar_submenu_bg'), '#1f2937');
    var adminbarSubmenuText = sanitizeHex(getValue('adminbar_submenu_text'), '#f8fafc');
    var border = sanitizeHex(getValue('color_border'), '#d9e2ef');
    var hover = sanitizeHex(getValue('color_hover'), mixHex(surface, primary, 10));
    var focus = sanitizeHex(getValue('color_focus'), primary);
    var success = sanitizeHex(getValue('color_success'), '#16a34a');
    var warning = sanitizeHex(getValue('color_warning'), '#d97706');
    var error = sanitizeHex(getValue('color_error'), '#dc2626');
    var tableHead = sanitizeHex(getValue('color_table_head'), mixHex(surface, primary, 8));
    var inputBg = sanitizeHex(getValue('color_input_bg'), surface);
    var linkColor = sanitizeHex(getValue('link_color'), primary);
    var linkHover = sanitizeHex(getValue('link_hover'), linkColor);
    var linkActive = sanitizeHex(getValue('link_active'), linkHover);
    var linkVisited = sanitizeHex(getValue('link_visited'), linkColor);
    var linkDecoration = getValue('link_decoration') || 'hover';
    var linkWeight = getValue('link_weight') || 'inherit';
    var buttonRadiusPreset = getValue('button_radius_preset') || 'inherit';
    var surfaceHover = deriveHover(surface, 6);
    var sidebarHover = deriveHover(sidebarBg, 12);
    var noticeSuccessBg = mixHex(surface, success, 14);
    var noticeWarningBg = mixHex(surface, warning, 16);
    var noticeErrorBg = mixHex(surface, error, 14);

    setVar('--pg-primary', primary);
    setVar('--pg-bg', bg);
    setVar('--pg-surface', surface);
    setVar('--pg-text', text);
    setVar('--pg-muted', muted);
    setVar('--pg-sidebar', sidebarBg);
    setVar('--pg-adminbar', adminbarBg);
    setVar('--pg-adminbar-submenu', adminbarSubmenuBg);
    setVar('--pg-border', border);
    setVar('--pg-hover', hover);
    setVar('--pg-focus', focus);
    setVar('--pg-success', success);
    setVar('--pg-warning', warning);
    setVar('--pg-error', error);
    setVar('--pg-table-head', tableHead);
    setVar('--pg-input-bg', inputBg);
    setVar('--pg-radius', radius + 'px');
    setVar('--pg-button-radius', resolveButtonRadius(radius, buttonRadiusPreset));
    setVar('--pg-font', getValue('font_family') || 'Inter, sans-serif');
    setVar('--pg-font-scale', typeScale / 100);
    setVar('--pg-space-scale', spaceScale);
    setVar('--pg-density-scale', densityScale);
    setVar('--pg-on-primary', chooseContrast(primary));
    setVar('--pg-on-surface', resolveAccessibleForeground(surface, text, ['#0f172a', '#f8fafc']));
    setVar('--pg-on-sidebar', resolveAccessibleForeground(sidebarBg, sidebarText, ['#f8fafc', '#0f172a']));
    setVar('--pg-on-adminbar', resolveAccessibleForeground(adminbarBg, adminbarText, ['#f8fafc', '#0f172a']));
    setVar('--pg-on-adminbar-submenu', resolveAccessibleForeground(adminbarSubmenuBg, adminbarSubmenuText, ['#f8fafc', '#0f172a']));
    setVar('--pg-focus-shadow', rgba(focus, 0.18));
    setVar('--pg-surface-hover', surfaceHover);
    setVar('--pg-sidebar-hover', sidebarHover);
    setVar('--pg-notice-success-bg', noticeSuccessBg);
    setVar('--pg-notice-warning-bg', noticeWarningBg);
    setVar('--pg-notice-error-bg', noticeErrorBg);
    setVar('--pg-notice-success-text', resolveAccessibleForeground(noticeSuccessBg, text, ['#0f172a', '#f8fafc']));
    setVar('--pg-notice-warning-text', resolveAccessibleForeground(noticeWarningBg, text, ['#0f172a', '#f8fafc']));
    setVar('--pg-notice-error-text', resolveAccessibleForeground(noticeErrorBg, text, ['#0f172a', '#f8fafc']));
    setVar('--pg-link', linkColor);
    setVar('--pg-link-hover', linkHover);
    setVar('--pg-link-active', linkActive);
    setVar('--pg-link-visited', linkVisited);
    setVar('--pg-link-decoration', linkDecoration === 'underline' ? 'underline' : 'none');
    setVar('--pg-link-decoration-hover', linkDecoration === 'none' ? 'none' : 'underline');
    setVar('--pg-link-weight', linkWeight === 'inherit' ? '600' : linkWeight);
    setVar('--pg-table-head-text', resolveAccessibleForeground(tableHead, text, ['#0f172a', '#f8fafc']));
  }

  function applyPreset() {
    var preset;
    var i;

    if (!presetSelect || !presetMap[presetSelect.value]) {
      return;
    }

    preset = presetMap[presetSelect.value];

    setFieldValue('enabled', true);

    for (i = 0; i < presetKeys.length; i++) {
      if (typeof preset[presetKeys[i]] !== 'undefined') {
        setFieldValue(presetKeys[i], preset[presetKeys[i]]);
      }
    }

    updateScreenChipStates();
    updateScopeUI();
    updatePlayground();
  }

  if (applyPresetButton) {
    applyPresetButton.addEventListener('click', applyPreset);
  }

  if (presetSelect) {
    presetSelect.addEventListener('change', applyPreset);
  }

  if (scopeSelect) {
    scopeSelect.addEventListener('change', updateScopeUI);
  }

  Array.prototype.forEach.call(
    document.querySelectorAll('[name^="pdt_design["]'),
    function (element) {
      element.addEventListener('input', updatePlayground);
      element.addEventListener('change', function () {
        updateScreenChipStates();
        updateScopeUI();
        updatePlayground();
      });
    }
  );

  Array.prototype.forEach.call(
    document.querySelectorAll('[data-pdt-link-preview="1"]'),
    function (link) {
      link.addEventListener('click', function (event) {
        event.preventDefault();
      });
    }
  );

  updateScreenChipStates();
  updateScopeUI();
  updatePlayground();
})();
