class GravityFormsCssEditor {
  constructor(options = {}) {
    this.options = {
      theme: 'light',
      excludeSelectors: ['#cex-select-btn', '#cex-panel', '.cex-ui', '#gform_wrapper'],
      formId: null,
      ...options,
    };

    this.rootThemeTarget = document.documentElement;
    this.state = {
      selecting: false,
      hoverTarget: null,
      selectedEl: null,
      selectedFormId: null,
      currentSelector: '',
      selectorType: 'current-form',
      liveStyles: new Map(),
      savedStyles: new Map(),
      activeTab: 'regular',
      activeGroup: 'container',
    };

    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

    this._initUI();
    this._initEvents();
    this._applyTheme(isDarkMode ? 'dark' : this.options.theme || 'light');
  }

  /* -------------------- UI -------------------- */

  _initUI() {
    // Selector button with Gravity Forms icon
    const btn = document.createElement('button');
    btn.id = 'cex-select-btn';
    btn.className = 'cex-ui';
    btn.type = 'button';
    btn.title = 'Select a Gravity Forms container to customize';
    btn.innerHTML = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 500" style="enable-background:new 0 0 500 500;" xml:space="preserve"><path fill="currentColor" d="M250,0C111.9,0,0,111.9,0,250s111.9,250,250,250s250-111.9,250-250S388.1,0,250,0z M250,450c-110.5,0-200-89.5-200-200S139.5,50,250,50s200,89.5,200,200S360.5,450,250,450z M250,100c-82.7,0-150,67.3-150,150s67.3,150,150,150s150-67.3,150-150S332.7,100,250,100z M250,350c-55.2,0-100-44.8-100-100s44.8-100,100-100s100,44.8,100,100S305.2,350,250,350z M250,200c-27.6,0-50,22.4-50,50s22.4,50,50,50s50-22.4,50-50S277.6,200,250,200z"/></svg>';
    document.body.appendChild(btn);
    this.selectBtn = btn;

    // Floating Save/Clear buttons
    const floatWrap = document.createElement('div');
    floatWrap.id = 'cex-float-controls';
    floatWrap.className = 'cex-ui';
    floatWrap.style.position = 'fixed';
    floatWrap.style.left = '12px';
    floatWrap.style.bottom = '20px';
    floatWrap.style.display = 'none';
    floatWrap.style.flexDirection = 'column';
    floatWrap.style.gap = '8px';
    floatWrap.style.zIndex = '2147483647';

    const saveBtn = document.createElement('button');
    saveBtn.className = 'cex-btn primary';
    saveBtn.id = 'cex-save';
    saveBtn.innerHTML = '<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 6C4 4.89543 4.89543 4 6 4H12H14.1716C14.702 4 15.2107 4.21071 15.5858 4.58579L19.4142 8.41421C19.7893 8.78929 20 9.29799 20 9.82843V12V18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6Z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M8 4H13V7C13 7.55228 12.5523 8 12 8H9C8.44772 8 8 7.55228 8 7V4Z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M7 15C7 13.8954 7.89543 13 9 13H15C16.1046 13 17 13.8954 17 15V20H7V15Z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg><label>Save CSS</label>';

    const clearBtn = document.createElement('button');
    clearBtn.className = 'cex-btn danger';
    clearBtn.id = 'cex-clear';
    clearBtn.innerHTML = '<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 9L15 15" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M15 9L9 15" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="12" cy="12" r="9" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg><label>Clear CSS</label>';

    floatWrap.append(saveBtn, clearBtn);
    document.body.appendChild(floatWrap);

    this.saveBtn = saveBtn;
    this.clearBtn = clearBtn;
    this.floatControls = floatWrap;

    // Panel
    const panel = document.createElement('aside');
    panel.id = 'cex-panel';
    panel.className = 'cex-ui';
    panel.innerHTML = `
      <div class="cex-shell">
        <div class="cex-header">
          <div class="cex-headline" style="display:flex;align-items:center;justify-content:space-between;padding:12px 14px;border-bottom:1px solid var(--border);background:var(--surface);">
            <div class="cex-title" style="font-weight:700;letter-spacing:.2px; font-size: 13px;">Gravity Forms Customizer</div>
            <div class="cex-actions" style="display:flex;gap:8px;align-items:center;">
              <select id="cex-form-select" style="font-size:12px;padding:4px;border-radius:4px;background:var(--input-bg);color:var(--input-fg);border:1px solid var(--border);">
                <option value="">Select a form...</option>
              </select>
              <button class="cex-icon-btn" id="cex-theme-toggle" title="Toggle theme" aria-label="Toggle theme">
                <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                  <path fill="currentColor" d="M12 4a1 1 0 0 1 1 1v1a1 1 0 1 1-2 0V5a1 1 0 0 1 1-1zm0 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM4 12a1 1 0 0 1 1-1h1a1 1 0 1 1 0 2H5a1 1 0 0 1-1-1zm13 0a1 1 0 0 1 1-1h1a1 1 0 1 1 0 2h-1a1 1 0 0 1-1-1zM6.22 6.22a1 1 0 0 1 1.42 0l.7.7a1 1 0 0 1-1.42 1.42l-.7-.7a1 1 0 0 1 0-1.42zm9.44 9.44a1 1 0 0 1 1.42 0l.7.7a1 1 0 0 1-1.42 1.42l-.7-.7a1 1 0 0 1 0-1.42zM6.22 17.78a1 1 0 0 1 0-1.42l.7-.7a1 1 0 1 1 1.42 1.42l-.7.7a1 1 0 0 1-1.42 0zm9.44-9.44a1 1 0 0 1 0-1.42l.7-.7a1 1 0 1 1 1.42 1.42l-.7.7a1 1 0 0 1-1.42 0z"/>
                </svg>
              </button>
              <button class="cex-icon-btn" id="cex-close" title="Close editor" aria-label="Close">
                <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                  <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M6 6l12 12M6 18L18 6"/>
                </svg>
              </button>
            </div>
          </div>

          <div class="cex-group-selector" style="display:flex;grid-template-columns:repeat(2,1fr) 120px;gap:8px;padding:10px 14px;border-bottom:1px solid var(--border);">
            <select id="cex-group-select" style="font-size:12px;padding:4px;border-radius:4px;flex: 1;">
              <option value="container">Form Container</option>
              <option value="labels">Labels</option>
              <option value="fields">Fields</option>
              <option value="buttons">Buttons</option>
            </select>
            
            <select id="cex-path-type" style="font-size:12px;padding:4px;border-radius:4px; width: 120px;">
              <option value="current-form">Current Form</option>
              <option value="all-forms">All Forms</option>
            </select>
          </div>

          <div class="cex-path" style="display:grid;grid-template-columns:1fr;gap:8px;padding:10px 14px;border-bottom:1px solid var(--border);">
            <input id="cex-path-input" type="text" placeholder="CSS selector path" readonly />
          </div>
        </div>

        <div class="cex-content"></div>

        <div class="cex-footer">
          <label class="cex-label" for="cex-css-output">Generated CSS</label>
          <textarea id="cex-css-output" spellcheck="false" placeholder="/* Live preview updates immediately; Confirm to save */"></textarea>
          <div class="cex-footer-actions" style="display:flex;gap:8px;">
            <button class="cex-btn primary" id="cex-confirm" style="flex:1;display:flex;align-items:center;gap:6px;justify-content:center;">
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M5 13l4 4L19 7"/>
              </svg>
              Apply
            </button>
            <button class="cex-btn" id="cex-reset" style="flex:1;">Reset</button>
          </div>
        </div>
      </div>
    `;
    document.body.appendChild(panel);
    this.panel = panel;

    // Cache controls
    this.pathInput = panel.querySelector('#cex-path-input');
    this.pathType = panel.querySelector('#cex-path-type');
    this.cssOutput = panel.querySelector('#cex-css-output');
    this.closeBtn = panel.querySelector('#cex-close');
    this.themeToggle = panel.querySelector('#cex-theme-toggle');
    this.confirmBtn = panel.querySelector('#cex-confirm');
    this.resetBtn = panel.querySelector('#cex-reset');
    this.formSelect = panel.querySelector('#cex-form-select');
    this.groupSelect = panel.querySelector('#cex-group-select');

    const labelRow = this.panel.querySelector('.cex-footer .cex-label');
    const importantWrap = document.createElement('label');
    importantWrap.style.float = 'right';
    importantWrap.style.fontSize = '12px';
    importantWrap.style.display = 'flex';
    importantWrap.style.alignItems = 'center';
    importantWrap.style.gap = '4px';

    const importantCheckbox = document.createElement('input');
    importantCheckbox.type = 'checkbox';
    importantCheckbox.id = 'cex-important-toggle';

    const importantText = document.createElement('span');
    importantText.textContent = 'Apply !important';

    importantWrap.append(importantCheckbox, importantText);
    labelRow.appendChild(importantWrap);

    this.importantToggle = importantCheckbox;

    // Detect and populate Gravity Forms
    this._detectAndPopulateForms();

    // Build content panels
    this._buildContainerPanel();
    this._buildLabelsPanel();
    this._buildFieldsPanel();
    this._buildButtonsPanel();
    this._buildTransitionPanel();

    // Initial panel visibility
    this._switchGroupPanel('container');
  }

  _detectAndPopulateForms() {
    const forms = document.querySelectorAll('form[id^="gform_"]');
    const formSelect = this.formSelect;
    
    while (formSelect.options.length > 1) {
      formSelect.remove(1);
    }
    
    let firstFormId = null;
    
    forms.forEach((form, index) => {
      const formId = form.id.replace('gform_', '');
      const wrapper = document.getElementById(`gform_wrapper_${formId}`);
      
      let formTitle = `Form ${formId}`;
      if (wrapper && wrapper.getAttribute('data-form-title')) {
        formTitle = wrapper.getAttribute('data-form-title');
      }
      
      const option = document.createElement('option');
      option.value = formId;
      option.textContent = `${formTitle} (ID: ${formId})`;
      formSelect.appendChild(option);
      
      if (index === 0) {
        firstFormId = formId;
      }
    });

    if (firstFormId && forms.length > 0) {
      formSelect.value = firstFormId;
      this.options.formId = firstFormId;
      this.state.selectedFormId = firstFormId;
      this._updateSelector();
    }

    formSelect.addEventListener('change', () => {
      this.options.formId = formSelect.value || null;
      this.state.selectedFormId = formSelect.value || null;
      this._updateSelector();
    });
  }

  _updateSelector() {
    const type = this.pathType.value;
    const formId = this.options.formId;
    
    if (type === 'current-form' && formId) {
      this.pathInput.value = `#gform_wrapper_${formId}`;
      this.state.currentSelector = `#gform_wrapper_${formId}`;
    } else {
      this.pathInput.value = '.gform_wrapper';
      this.state.currentSelector = '.gform_wrapper';
    }
    
    this._syncCssFromControls();
  }

  _initEvents() {
    this.selectBtn.addEventListener('click', () => this.toggleSelection());

    this.groupSelect.addEventListener('change', () => {
      const group = this.groupSelect.value;
      this.state.activeGroup = group;
      this._switchGroupPanel(group);
    });

    this.pathType.addEventListener('change', () => {
      this._updateSelector();
    });

    this.saveBtn.addEventListener('click', () => {
      const css = this._getSavedCss();
      saveGravityFormsCSSData(css, this.options.formId);
      this._updateSaveClearVisibility();
    });

    this.clearBtn.addEventListener('click', () => {
      this.state.savedStyles.clear();
      const styleEl = this._getOrCreateStyleTag('saved');
      styleEl.textContent = '';
      this._updateSaveClearVisibility();
    });

    this.importantToggle.addEventListener('change', () => {
      this._syncCssFromControls();
    });

    document.addEventListener('mousemove', (e) => {
      if (!this.state.selecting) return;
      const target = e.target;
      if (this._isExcluded(target)) return this._clearHoverOutline();
      
      const container = this._getGravityFormsContainer(target);
      if (!container) return this._clearHoverOutline();
      
      if (this.state.hoverTarget !== container) {
        this._clearHoverOutline();
        this.state.hoverTarget = container;
        container.classList.add('cex-outline');
      }
    });

    document.addEventListener('click', (e) => {
      if (!this.state.selecting) return;
      const target = e.target;
      if (this._isExcluded(target)) return;
      
      const container = this._getGravityFormsContainer(target);
      if (!container) {
        alert('Please click on a Gravity Forms form container to customize.');
        return;
      }
      
      e.preventDefault();
      e.stopPropagation();
      this._selectContainer(container);
    }, true);

    this.closeBtn.addEventListener('click', () => this.closePanelWithoutSaving());

    this.cssOutput.addEventListener('input', () => {
      this._applyLiveCssFromTextarea();
    });

    this.confirmBtn.addEventListener('click', () => {
      const formatted = this._formatAllCssBlocks();
      if (!formatted.trim()) return;
      const blocks = this._splitBlocks(formatted);
      blocks.forEach(({ selector, cssText }) => {
        this.state.savedStyles.set(selector, cssText);
      });
      this._applySavedCss();
      this.closePanel();
      this._updateSaveClearVisibility();
    });

    this.resetBtn.addEventListener('click', () => this._resetControls());

    this.themeToggle.addEventListener('click', () => {
      const next = this.rootThemeTarget.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
      this._applyTheme(next);
    });
  }

  _getGravityFormsContainer(element) {
    const wrapper = element.closest('.gform_wrapper');
    if (wrapper) return wrapper;
    return null;
  }

  _switchGroupPanel(group) {
    const panels = this.panel.querySelectorAll('.cex-group-panel');
    panels.forEach(p => p.style.display = 'none');
    
    let targetPanel = this.panel.querySelector(`.cex-group-panel[data-group="${group}"]`);
    if (targetPanel) {
      targetPanel.style.display = 'block';
    }
  }

  _updateSaveClearVisibility() {
    const hasSaved = this._hasSavedCss();
    this.floatControls.style.display = hasSaved ? 'flex' : 'none';
  }

  toggleSelection() {
    this.state.selecting = !this.state.selecting;
    if (this.state.selecting) {
      this.selectBtn.classList.add('cex-active-btn');
      this.selectBtn.title = 'Click on a Gravity Forms container to select it';
    } else {
      this.selectBtn.classList.remove('cex-active-btn');
      this.selectBtn.title = 'Select a Gravity Forms container to customize';
    }
    if (!this.state.selecting) this._clearHoverOutline();
  }

  _clearHoverOutline() {
    if (this.state.hoverTarget) {
      this.state.hoverTarget.classList.remove('cex-outline');
      this.state.hoverTarget = null;
    }
  }

  _isExcluded(el) {
    if (!el) return true;
    if (el.closest('#cex-panel')) return true;
    if (el.closest('#cex-select-btn')) return true;
    if (el.closest('#cex-float-controls')) return true;
    if (el.classList && el.classList.contains('cex-ui')) return true;
    return false;
  }

  _selectContainer(container) {
    this.state.selectedEl = container;
    this.state.selecting = false;
    this._clearHoverOutline();
    this.selectBtn.classList.remove('cex-active-btn');
    
    if (container.id && container.id.startsWith('gform_wrapper_')) {
      const formId = container.id.replace('gform_wrapper_', '');
      this.options.formId = formId;
      this.state.selectedFormId = formId;
      if (this.formSelect) {
        this.formSelect.value = formId;
      }
    }
    
    this._updateSelector();
    this._openPanel();
    this._resetControls();
    this._switchGroupPanel('container');
    this.groupSelect.value = 'container';
    this._loadSavedCssIntoOutput();
    this._syncCssFromControls();
  }

  _openPanel() {
    this.panel.classList.add('active');
    this.selectBtn.style.display = 'none';
  }

  closePanel() {
    this.panel.classList.remove('active');
    this.state.selectedEl = null;
    this.cssOutput.value = '';
    this.selectBtn.style.display = 'flex';
    this._clearLiveStyles();
  }

  closePanelWithoutSaving() {
    this._clearLiveStyles();
    this.closePanel();
  }

  _applyTheme(theme) {
    this.rootThemeTarget.setAttribute('data-theme', theme);
  }

  /* -------------------- Build Container Panel -------------------- */

  _buildContainerPanel() {
    const content = this.panel.querySelector('.cex-content');

    const wrap = document.createElement('section');
    wrap.className = 'cex-group-panel';
    wrap.dataset.group = 'container';
    wrap.innerHTML = `
      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Border</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="border"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Border Radius</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="border-radius"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Background</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="background"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Margin</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="margin"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Padding</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="padding"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Grid Gap</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="grid-gap"></div>
      </div>
    `;
    content.appendChild(wrap);

    // Initialize all panels with toggle functionality (closed by default)
    wrap.querySelectorAll('.cex-panel').forEach(panel => {
      this._initPanelToggle(panel, false);
    });

    // Build sections
    this._buildContainerBorderSection(wrap);
    this._buildContainerBorderRadiusSection(wrap);
    this._buildContainerBackgroundSection(wrap);
    this._buildContainerMarginSection(wrap);
    this._buildContainerPaddingSection(wrap);
    this._buildContainerGridGapSection(wrap);
  }

  _buildContainerBorderSection(container) {
    const body = container.querySelector('[data-section="border"]');
    
    this._addSectionHeader(body, 'Border Width, Color & Style');
    this._buildBorderSectionWithLink(body, 'container', 'regular', true);
  }

  _buildContainerBorderRadiusSection(container) {
    const body = container.querySelector('[data-section="border-radius"]');
    
    this._addSectionHeader(body, 'Corner Radius');
    this._buildBorderRadiusSectionWithLink(body, 'container', 'regular');
  }

  _buildContainerBackgroundSection(container) {
    const body = container.querySelector('[data-section="background"]');
    
    this._addSectionHeader(body, 'Background Color & Gradient');
    this._buildField(body, 'container', { key: 'background-color', label: 'Background color', type: 'color' }, 'regular');
    this._buildField(body, 'container', { key: 'background', label: 'Background gradient', type: 'text', placeholder: 'linear-gradient(...)' }, 'regular');
  }

  _buildContainerMarginSection(container) {
    const body = container.querySelector('[data-section="margin"]');
    
    this._addSectionHeader(body, 'Outside Spacing');
    this._buildSpacingSectionWithLink(body, 'container', 'margin', 'Margin', 'regular');
  }

  _buildContainerPaddingSection(container) {
    const body = container.querySelector('[data-section="padding"]');
    
    this._addSectionHeader(body, 'Inside Spacing');
    this._buildSpacingSectionWithLink(body, 'container', 'padding', 'Padding', 'regular');
  }

  _buildContainerGridGapSection(container) {
    const body = container.querySelector('[data-section="grid-gap"]');
    
    this._addSectionHeader(body, 'Gap Between Fields');
    // These are special fields that need to target .gform_fields
    this._buildField(body, 'grid-gap', { key: 'row-gap', label: 'Row gap', type: 'unit' }, 'regular');
    this._buildField(body, 'grid-gap', { key: 'column-gap', label: 'Column gap', type: 'unit' }, 'regular');
  }

  /* -------------------- Build Labels Panel -------------------- */

  _buildLabelsPanel() {
    const content = this.panel.querySelector('.cex-content');

    const wrap = document.createElement('section');
    wrap.className = 'cex-group-panel';
    wrap.dataset.group = 'labels';
    wrap.style.display = 'none';
    wrap.innerHTML = `
      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Main Labels</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="main-labels"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Sub Labels</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="sub-labels"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Descriptions</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="descriptions"></div>
      </div>
    `;
    content.appendChild(wrap);

    wrap.querySelectorAll('.cex-panel').forEach(panel => {
      this._initPanelToggle(panel, false);
    });

    this._buildMainLabelsSection(wrap);
    this._buildSubLabelsSection(wrap);
    this._buildDescriptionsSection(wrap);
  }

  _buildMainLabelsSection(container) {
    const body = container.querySelector('[data-section="main-labels"]');
    
    this._addSectionHeader(body, 'Font Settings');
    const fontFields = [
      { key: 'font-family', label: 'Font family', type: 'text' },
      { key: 'font-size', label: 'Font size', type: 'unit' },
      { key: 'line-height', label: 'Line height', type: 'unit' },
      { key: 'letter-spacing', label: 'Letter spacing', type: 'unit' },
      { key: 'font-weight', label: 'Font weight', type: 'select', options: ['', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'bold'] },
      { key: 'font-style', label: 'Font style', type: 'select', options: ['', 'normal', 'italic'] },
      { key: 'text-transform', label: 'Text transform', type: 'select', options: ['', 'none', 'uppercase', 'lowercase', 'capitalize'] },
      { key: 'color', label: 'Text color', type: 'color' },
    ];
    fontFields.forEach(f => this._buildField(body, 'labels-main', f, 'regular'));

    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'labels-main', { key: 'background-color', label: 'Background color', type: 'color' }, 'regular');

    this._addSectionHeader(body, 'Margin');
    this._buildSpacingSectionWithLink(body, 'labels-main', 'margin', 'Margin', 'regular');

    this._addSectionHeader(body, 'Padding');
    this._buildSpacingSectionWithLink(body, 'labels-main', 'padding', 'Padding', 'regular');
  }

  _buildSubLabelsSection(container) {
    const body = container.querySelector('[data-section="sub-labels"]');
    
    this._addSectionHeader(body, 'Font Settings');
    const fontFields = [
      { key: 'font-family', label: 'Font family', type: 'text' },
      { key: 'font-size', label: 'Font size', type: 'unit' },
      { key: 'line-height', label: 'Line height', type: 'unit' },
      { key: 'font-weight', label: 'Font weight', type: 'select', options: ['', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'bold'] },
      { key: 'color', label: 'Text color', type: 'color' },
    ];
    fontFields.forEach(f => this._buildField(body, 'labels-sub', f, 'regular'));
  }

  _buildDescriptionsSection(container) {
    const body = container.querySelector('[data-section="descriptions"]');
    
    this._addSectionHeader(body, 'Font Settings');
    const fontFields = [
      { key: 'font-family', label: 'Font family', type: 'text' },
      { key: 'font-size', label: 'Font size', type: 'unit' },
      { key: 'line-height', label: 'Line height', type: 'unit' },
      { key: 'font-weight', label: 'Font weight', type: 'select', options: ['', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'bold'] },
      { key: 'color', label: 'Text color', type: 'color' },
    ];
    fontFields.forEach(f => this._buildField(body, 'labels-desc', f, 'regular'));
  }

  /* -------------------- Build Fields Panel -------------------- */

  _buildFieldsPanel() {
    const content = this.panel.querySelector('.cex-content');

    const wrap = document.createElement('section');
    wrap.className = 'cex-group-panel';
    wrap.dataset.group = 'fields';
    wrap.style.display = 'none';
    wrap.innerHTML = `
      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Regular State</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="regular"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Hover State</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="hover"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Focus State</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="focus"></div>
      </div>
    `;
    content.appendChild(wrap);

    wrap.querySelectorAll('.cex-panel').forEach(panel => {
      this._initPanelToggle(panel, false);
    });

    this._buildFieldsRegularSection(wrap);
    this._buildFieldsHoverSection(wrap);
    this._buildFieldsFocusSection(wrap);
  }

  _buildFieldsRegularSection(container) {
    const body = container.querySelector('[data-section="regular"]');
    
    this._addSectionHeader(body, 'Font Settings');
    const fontFields = [
      { key: 'font-family', label: 'Font family', type: 'text' },
      { key: 'font-size', label: 'Font size', type: 'unit' },
      { key: 'line-height', label: 'Line height', type: 'unit' },
      { key: 'letter-spacing', label: 'Letter spacing', type: 'unit' },
      { key: 'font-weight', label: 'Font weight', type: 'select', options: ['', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'bold'] },
      { key: 'color', label: 'Text color', type: 'color' },
    ];
    fontFields.forEach(f => this._buildField(body, 'fields', f, 'regular'));

    this._addSectionHeader(body, 'Border');
    this._buildBorderSectionWithLink(body, 'fields', 'regular', true);
    
    this._addSectionHeader(body, 'Border Radius');
    this._buildBorderRadiusSectionWithLink(body, 'fields', 'regular');

    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'fields', { key: 'background-color', label: 'Background color', type: 'color' }, 'regular');
    this._buildField(body, 'fields', { key: 'background', label: 'Background gradient', type: 'text', placeholder: 'linear-gradient(...)' }, 'regular');

    this._addSectionHeader(body, 'Box Shadow');
    this._buildBoxShadowSection(body, 'fields', 'regular');

    this._addSectionHeader(body, 'Outline');
    this._buildOutlineSection(body, 'fields', 'regular');

    this._addSectionHeader(body, 'Margin');
    this._buildSpacingSectionWithLink(body, 'fields', 'margin', 'Margin', 'regular');

    this._addSectionHeader(body, 'Padding');
    this._buildSpacingSectionWithLink(body, 'fields', 'padding', 'Padding', 'regular');
  }

  _buildFieldsHoverSection(container) {
    const body = container.querySelector('[data-section="hover"]');
    
    this._addSectionHeader(body, 'Text Color');
    this._buildField(body, 'fields', { key: 'color', label: 'Text color', type: 'color' }, 'hover');
    
    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'fields', { key: 'background-color', label: 'Background color', type: 'color' }, 'hover');
    
    this._addSectionHeader(body, 'Border');
    this._buildBorderSectionWithLink(body, 'fields', 'hover', true);
    
    this._addSectionHeader(body, 'Border Radius');
    this._buildBorderRadiusSectionWithLink(body, 'fields', 'hover');
    
    this._addSectionHeader(body, 'Box Shadow');
    this._buildBoxShadowSection(body, 'fields', 'hover');
    
    this._addSectionHeader(body, 'Outline');
    this._buildOutlineSection(body, 'fields', 'hover');
  }

  _buildFieldsFocusSection(container) {
    const body = container.querySelector('[data-section="focus"]');
    
    this._addSectionHeader(body, 'Text Color');
    this._buildField(body, 'fields', { key: 'color', label: 'Text color', type: 'color' }, 'focus');
    
    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'fields', { key: 'background-color', label: 'Background color', type: 'color' }, 'focus');
    
    this._addSectionHeader(body, 'Border');
    this._buildBorderSectionWithLink(body, 'fields', 'focus', true);
    
    this._addSectionHeader(body, 'Border Radius');
    this._buildBorderRadiusSectionWithLink(body, 'fields', 'focus');
    
    this._addSectionHeader(body, 'Box Shadow');
    this._buildBoxShadowSection(body, 'fields', 'focus');
    
    this._addSectionHeader(body, 'Outline');
    this._buildOutlineSection(body, 'fields', 'focus');
  }

  /* -------------------- Build Buttons Panel -------------------- */

  _buildButtonsPanel() {
    const content = this.panel.querySelector('.cex-content');

    const wrap = document.createElement('section');
    wrap.className = 'cex-group-panel';
    wrap.dataset.group = 'buttons';
    wrap.style.display = 'none';
    wrap.innerHTML = `
      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Regular State</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="regular"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Hover State</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="hover"></div>
      </div>

      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Focus State</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="focus"></div>
      </div>
    `;
    content.appendChild(wrap);

    wrap.querySelectorAll('.cex-panel').forEach(panel => {
      this._initPanelToggle(panel, false);
    });

    this._buildButtonsRegularSection(wrap);
    this._buildButtonsHoverSection(wrap);
    this._buildButtonsFocusSection(wrap);
  }

  _buildButtonsRegularSection(container) {
    const body = container.querySelector('[data-section="regular"]');
    
    this._addSectionHeader(body, 'Font Settings');
    const fontFields = [
      { key: 'font-family', label: 'Font family', type: 'text' },
      { key: 'font-size', label: 'Font size', type: 'unit' },
      { key: 'line-height', label: 'Line height', type: 'unit' },
      { key: 'letter-spacing', label: 'Letter spacing', type: 'unit' },
      { key: 'font-weight', label: 'Font weight', type: 'select', options: ['', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'bold'] },
      { key: 'color', label: 'Text color', type: 'color' },
    ];
    fontFields.forEach(f => this._buildField(body, 'buttons', f, 'regular'));

    this._addSectionHeader(body, 'Border');
    this._buildBorderSectionWithLink(body, 'buttons', 'regular', true);
    
    this._addSectionHeader(body, 'Border Radius');
    this._buildBorderRadiusSectionWithLink(body, 'buttons', 'regular');

    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'buttons', { key: 'background-color', label: 'Background color', type: 'color' }, 'regular');
    this._buildField(body, 'buttons', { key: 'background', label: 'Background gradient', type: 'text', placeholder: 'linear-gradient(...)' }, 'regular');

    this._addSectionHeader(body, 'Box Shadow');
    this._buildBoxShadowSection(body, 'buttons', 'regular');

    this._addSectionHeader(body, 'Outline');
    this._buildOutlineSection(body, 'buttons', 'regular');

    this._addSectionHeader(body, 'Margin');
    this._buildSpacingSectionWithLink(body, 'buttons', 'margin', 'Margin', 'regular');

    this._addSectionHeader(body, 'Padding');
    this._buildSpacingSectionWithLink(body, 'buttons', 'padding', 'Padding', 'regular');
  }

  _buildButtonsHoverSection(container) {
    const body = container.querySelector('[data-section="hover"]');
    
    this._addSectionHeader(body, 'Text Color');
    this._buildField(body, 'buttons', { key: 'color', label: 'Text color', type: 'color' }, 'hover');
    
    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'buttons', { key: 'background-color', label: 'Background color', type: 'color' }, 'hover');
    
    this._addSectionHeader(body, 'Border');
    this._buildBorderSectionWithLink(body, 'buttons', 'hover', true);
    
    this._addSectionHeader(body, 'Border Radius');
    this._buildBorderRadiusSectionWithLink(body, 'buttons', 'hover');
    
    this._addSectionHeader(body, 'Box Shadow');
    this._buildBoxShadowSection(body, 'buttons', 'hover');
    
    this._addSectionHeader(body, 'Outline');
    this._buildOutlineSection(body, 'buttons', 'hover');
  }

  _buildButtonsFocusSection(container) {
    const body = container.querySelector('[data-section="focus"]');
    
    this._addSectionHeader(body, 'Text Color');
    this._buildField(body, 'buttons', { key: 'color', label: 'Text color', type: 'color' }, 'focus');
    
    this._addSectionHeader(body, 'Background');
    this._buildField(body, 'buttons', { key: 'background-color', label: 'Background color', type: 'color' }, 'focus');
    
    this._addSectionHeader(body, 'Border');
    this._buildBorderSectionWithLink(body, 'buttons', 'focus', true);
    
    this._addSectionHeader(body, 'Border Radius');
    this._buildBorderRadiusSectionWithLink(body, 'buttons', 'focus');
    
    this._addSectionHeader(body, 'Box Shadow');
    this._buildBoxShadowSection(body, 'buttons', 'focus');
    
    this._addSectionHeader(body, 'Outline');
    this._buildOutlineSection(body, 'buttons', 'focus');
  }

  /* -------------------- Build Transition Panel -------------------- */

  _buildTransitionPanel() {
    const content = this.panel.querySelector('.cex-content');

    const wrap = document.createElement('section');
    wrap.className = 'cex-group-panel';
    wrap.dataset.group = 'transition';
    wrap.style.display = 'none';
    wrap.innerHTML = `
      <div class="cex-panel">
        <div class="cex-panel-header">
          <div class="cex-panel-title">Transition Settings</div>
          <button class="cex-panel-toggle" type="button" aria-expanded="false">▸</button>
        </div>
        <div class="cex-panel-body" data-section="transition"></div>
      </div>
    `;
    content.appendChild(wrap);

    wrap.querySelectorAll('.cex-panel').forEach(panel => {
      this._initPanelToggle(panel, false);
    });

    const body = wrap.querySelector('[data-section="transition"]');
    
    this._addSectionHeader(body, 'Transition Timing');
    this._buildField(body, 'transition', { key: 'transition-property', label: 'Property', type: 'select', options: ['', 'all', 'opacity', 'color', 'background-color', 'transform', 'border', 'box-shadow'] }, 'transition');
    this._buildField(body, 'transition', { key: 'transition-duration', label: 'Duration', type: 'unit' }, 'transition');
    this._buildField(body, 'transition', { key: 'transition-delay', label: 'Delay', type: 'unit' }, 'transition');
    this._buildField(body, 'transition', { key: 'transition-timing-function', label: 'Timing function', type: 'select', options: ['', 'ease', 'linear', 'ease-in', 'ease-out', 'ease-in-out'] }, 'transition');
  }

  /* -------------------- Helper Methods -------------------- */

  _addSectionHeader(panel, title) {
    const header = document.createElement('div');
    header.className = 'cex-section-header';
    header.textContent = title;
    header.style.fontSize = '11px';
    header.style.fontWeight = '600';
    header.style.textTransform = 'uppercase';
    header.style.letterSpacing = '0.5px';
    header.style.color = 'var(--text-secondary)';
    header.style.paddingBottom = '4px';
    header.style.borderBottom = '1px solid currentColor';
    header.style.marginBottom = '0.5em';
    
    // Check if this is not the first child
    if (panel.children.length > 0) {
      header.style.marginTop = '2em';
    }
    
    panel.appendChild(header);
  }

  _initPanelToggle(panel, defaultOpen = false) {
    const header = panel.querySelector('.cex-panel-header');
    const toggle = panel.querySelector('.cex-panel-toggle');
    
    if (defaultOpen) {
      panel.classList.add('open');
      toggle.textContent = '▾';
      toggle.setAttribute('aria-expanded', 'true');
    } else {
      panel.classList.remove('open');
      toggle.textContent = '▸';
      toggle.setAttribute('aria-expanded', 'false');
    }
    
    header.addEventListener('click', (e) => {
      e.stopPropagation();
      panel.classList.toggle('open');
      const open = panel.classList.contains('open');
      toggle.textContent = open ? '▾' : '▸';
      toggle.setAttribute('aria-expanded', String(open));
    });
  }

  _buildField(host, group, f, scope) {
    const row = document.createElement('div');
    row.className = 'cex-field-row';
    row.dataset.group = group;
    row.dataset.scope = scope;
    row.dataset.prop = f.key;

    const label = document.createElement('div');
    label.className = 'cex-label';
    label.textContent = f.label;
    label.style.fontSize = '12px';

    let control;
    switch (f.type) {
      case 'unit': {
        control = document.createElement('div');
        control.className = 'cex-unit';
        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = f.placeholder || 'Value';
        input.dataset.role = 'value';
        input.style.fontSize = '12px';

        const select = document.createElement('select');
        select.dataset.role = 'unit';
        ['px', '%', 'em', 'rem'].forEach(u => {
          const opt = document.createElement('option');
          opt.value = u;
          opt.textContent = u;
          select.appendChild(opt);
        });
        select.style.fontSize = '12px';

        control.appendChild(input);
        control.appendChild(select);

        input.addEventListener('input', () => this._onFieldChange(row));
        select.addEventListener('change', () => this._onFieldChange(row));
        break;
      }
      case 'select': {
        control = document.createElement('select');
        f.options.forEach(val => {
          const opt = document.createElement('option');
          opt.value = val;
          opt.textContent = val || '—';
          control.appendChild(opt);
        });
        control.style.fontSize = '12px';
        control.addEventListener('change', () => this._onFieldChange(row));
        break;
      }
      case 'color': {
        control = this._buildPopupColorField(row);
        break;
      }
      case 'checkbox': {
        control = document.createElement('input');
        control.type = 'checkbox';
        control.addEventListener('change', () => this._onFieldChange(row));
        break;
      }
      default: {
        control = document.createElement('input');
        control.type = 'text';
        control.placeholder = f.placeholder || 'Value';
        control.style.fontSize = '12px';
        control.addEventListener('input', () => this._onFieldChange(row));
      }
    }

    row.appendChild(label);
    row.appendChild(control);
    host.appendChild(row);
  }

  _buildBorderSectionWithLink(host, group, scope, includeColor = true) {
    const container = document.createElement('div');
    container.className = 'cex-linked-section';
    
    const linkBtn = document.createElement('button');
    linkBtn.type = 'button';
    linkBtn.classList.add('cex-link-button', 'cex-active');
    linkBtn.innerHTML = `<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2C16.714 2 19.0711 2 20.5355 3.46447C22 4.92893 22 7.28595 22 12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22ZM9.198 7.25H9.30203C10.2005 7.24997 10.9497 7.24995 11.5445 7.32991C12.1723 7.41432 12.7391 7.59999 13.1945 8.05546C13.65 8.51093 13.8357 9.07773 13.9201 9.70552C14.0001 10.3003 14 11.0495 14 11.948L14 12C14 12.4142 13.6642 12.75 13.25 12.75C12.8358 12.75 12.5 12.4142 12.5 12C12.5 11.036 12.4984 10.3884 12.4335 9.9054C12.3714 9.44393 12.2642 9.24644 12.1339 9.11612C12.0036 8.9858 11.8061 8.87858 11.3446 8.81654C10.8616 8.7516 10.214 8.75 9.25 8.75C8.28599 8.75 7.63843 8.7516 7.15539 8.81654C6.69393 8.87858 6.49644 8.9858 6.36612 9.11612C6.2358 9.24644 6.12858 9.44393 6.06654 9.9054C6.0016 10.3884 6 11.036 6 12C6 12.964 6.0016 13.6116 6.06654 14.0946C6.12858 14.5561 6.2358 14.7536 6.36612 14.8839C6.49644 15.0142 6.69393 15.1214 7.15539 15.1835C7.63843 15.2484 8.28599 15.25 9.25 15.25C9.66422 15.25 10 15.5858 10 16C10 16.4142 9.66422 16.75 9.25 16.75L9.19798 16.75C8.29951 16.75 7.5503 16.7501 6.95552 16.6701C6.32773 16.5857 5.76093 16.4 5.30546 15.9445C4.84999 15.4891 4.66432 14.9223 4.57991 14.2945C4.49995 13.6997 4.49997 12.9505 4.5 12.052V11.948C4.49997 11.0495 4.49995 10.3003 4.57991 9.70552C4.66432 9.07773 4.84999 8.51093 5.30546 8.05546C5.76093 7.59999 6.32773 7.41432 6.95552 7.32991C7.55029 7.24995 8.29954 7.24997 9.198 7.25ZM16.8446 8.81654C16.3616 8.7516 15.714 8.75 14.75 8.75C14.3358 8.75 14 8.41422 14 8C14 7.58579 14.3358 7.25 14.75 7.25L14.802 7.25C15.7005 7.24997 16.4497 7.24995 17.0445 7.32991C17.6723 7.41432 18.2391 7.59999 18.6945 8.05546C19.15 8.51093 19.3357 9.07773 19.4201 9.70552C19.5001 10.3003 19.5 11.0495 19.5 11.9479V12.052C19.5 12.9505 19.5001 13.6997 19.4201 14.2945C19.3357 14.9223 19.15 15.4891 18.6945 15.9445C18.2391 16.4 17.6723 16.5857 17.0445 16.6701C16.4497 16.7501 15.7005 16.75 14.802 16.75H14.698C13.7995 16.75 13.0503 16.7501 12.4555 16.6701C11.8277 16.5857 11.2609 16.4 10.8055 15.9445C10.35 15.4891 10.1643 14.9223 10.0799 14.2945C9.99995 13.6997 9.99997 12.9505 10 12.052L10 12C10 11.5858 10.3358 11.25 10.75 11.25C11.1642 11.25 11.5 11.5858 11.5 12C11.5 12.964 11.5016 13.6116 11.5665 14.0946C11.6286 14.5561 11.7358 14.7536 11.8661 14.8839C11.9964 15.0142 12.1939 15.1214 12.6554 15.1835C13.1384 15.2484 13.786 15.25 14.75 15.25C15.714 15.25 16.3616 15.2484 16.8446 15.1835C17.3061 15.1214 17.5036 15.0142 17.6339 14.8839C17.7642 14.7536 17.8714 14.5561 17.9335 14.0946C17.9984 13.6116 18 12.964 18 12C18 11.036 17.9984 10.3884 17.9335 9.9054C17.8714 9.44393 17.7642 9.24644 17.6339 9.11612C17.5036 8.9858 17.3061 8.87858 16.8446 8.81654Z"/></svg>`;
    linkBtn.style.fontSize = '11px';
    linkBtn.style.marginBottom = '4px';
    container.appendChild(linkBtn);

    const fields = {
      top: this._createUnitField(container, group, 'border-top-width', 'Top', scope),
      right: this._createUnitField(container, group, 'border-right-width', 'Right', scope),
      bottom: this._createUnitField(container, group, 'border-bottom-width', 'Bottom', scope),
      left: this._createUnitField(container, group, 'border-left-width', 'Left', scope),
    };

    let linked = true;
    const sync = (srcRow, srcPos) => {
      if (!linked) return;
      const srcInput = srcRow.querySelector('input[data-role="value"]');
      const srcSelect = srcRow.querySelector('select[data-role="unit"]');
      if (!srcInput || !srcSelect) return;
      
      const val = srcInput.value;
      const unit = srcSelect.value;
      
      Object.keys(fields).forEach(pos => {
        if (pos === srcPos) return;
        const row = fields[pos];
        const input = row.querySelector('input[data-role="value"]');
        const select = row.querySelector('select[data-role="unit"]');
        if (input && select) {
          input.value = val;
          select.value = unit;
        }
      });
      this._syncCssFromControls();
    };

    Object.keys(fields).forEach(pos => {
      const row = fields[pos];
      const input = row.querySelector('input[data-role="value"]');
      const select = row.querySelector('select[data-role="unit"]');
      if (input && select) {
        input.addEventListener('input', () => {
          sync(row, pos);
          this._syncCssFromControls(); // Ensure sync after individual change
        });
        select.addEventListener('change', () => {
          sync(row, pos);
          this._syncCssFromControls(); // Ensure sync after individual change
        });
      }
    });

    linkBtn.addEventListener('click', () => {
      linked = !linked;
      if (linked) linkBtn.classList.add('cex-active');
      else linkBtn.classList.remove('cex-active');
      this._syncCssFromControls(); // Sync after toggling link state
    });

    host.appendChild(container);

    if (includeColor) {
      this._buildField(host, group, { key: 'border-color', label: 'Border color', type: 'color' }, scope);
      this._buildField(host, group, {
        key: 'border-style', label: 'Border style', type: 'select',
        options: ['', 'none', 'solid', 'dashed', 'dotted', 'double', 'groove', 'ridge']
      }, scope);
    }
  }

  _buildBorderRadiusSectionWithLink(host, group, scope) {
    const container = document.createElement('div');
    container.className = 'cex-linked-section';
    
    const linkBtn = document.createElement('button');
    linkBtn.type = 'button';
    linkBtn.classList.add('cex-link-button', 'cex-active');
    linkBtn.innerHTML = `<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2C16.714 2 19.0711 2 20.5355 3.46447C22 4.92893 22 7.28595 22 12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22ZM9.198 7.25H9.30203C10.2005 7.24997 10.9497 7.24995 11.5445 7.32991C12.1723 7.41432 12.7391 7.59999 13.1945 8.05546C13.65 8.51093 13.8357 9.07773 13.9201 9.70552C14.0001 10.3003 14 11.0495 14 11.948L14 12C14 12.4142 13.6642 12.75 13.25 12.75C12.8358 12.75 12.5 12.4142 12.5 12C12.5 11.036 12.4984 10.3884 12.4335 9.9054C12.3714 9.44393 12.2642 9.24644 12.1339 9.11612C12.0036 8.9858 11.8061 8.87858 11.3446 8.81654C10.8616 8.7516 10.214 8.75 9.25 8.75C8.28599 8.75 7.63843 8.7516 7.15539 8.81654C6.69393 8.87858 6.49644 8.9858 6.36612 9.11612C6.2358 9.24644 6.12858 9.44393 6.06654 9.9054C6.0016 10.3884 6 11.036 6 12C6 12.964 6.0016 13.6116 6.06654 14.0946C6.12858 14.5561 6.2358 14.7536 6.36612 14.8839C6.49644 15.0142 6.69393 15.1214 7.15539 15.1835C7.63843 15.2484 8.28599 15.25 9.25 15.25C9.66422 15.25 10 15.5858 10 16C10 16.4142 9.66422 16.75 9.25 16.75L9.19798 16.75C8.29951 16.75 7.5503 16.7501 6.95552 16.6701C6.32773 16.5857 5.76093 16.4 5.30546 15.9445C4.84999 15.4891 4.66432 14.9223 4.57991 14.2945C4.49995 13.6997 4.49997 12.9505 4.5 12.052V11.948C4.49997 11.0495 4.49995 10.3003 4.57991 9.70552C4.66432 9.07773 4.84999 8.51093 5.30546 8.05546C5.76093 7.59999 6.32773 7.41432 6.95552 7.32991C7.55029 7.24995 8.29954 7.24997 9.198 7.25ZM16.8446 8.81654C16.3616 8.7516 15.714 8.75 14.75 8.75C14.3358 8.75 14 8.41422 14 8C14 7.58579 14.3358 7.25 14.75 7.25L14.802 7.25C15.7005 7.24997 16.4497 7.24995 17.0445 7.32991C17.6723 7.41432 18.2391 7.59999 18.6945 8.05546C19.15 8.51093 19.3357 9.07773 19.4201 9.70552C19.5001 10.3003 19.5 11.0495 19.5 11.9479V12.052C19.5 12.9505 19.5001 13.6997 19.4201 14.2945C19.3357 14.9223 19.15 15.4891 18.6945 15.9445C18.2391 16.4 17.6723 16.5857 17.0445 16.6701C16.4497 16.7501 15.7005 16.75 14.802 16.75H14.698C13.7995 16.75 13.0503 16.7501 12.4555 16.6701C11.8277 16.5857 11.2609 16.4 10.8055 15.9445C10.35 15.4891 10.1643 14.9223 10.0799 14.2945C9.99995 13.6997 9.99997 12.9505 10 12.052L10 12C10 11.5858 10.3358 11.25 10.75 11.25C11.1642 11.25 11.5 11.5858 11.5 12C11.5 12.964 11.5016 13.6116 11.5665 14.0946C11.6286 14.5561 11.7358 14.7536 11.8661 14.8839C11.9964 15.0142 12.1939 15.1214 12.6554 15.1835C13.1384 15.2484 13.786 15.25 14.75 15.25C15.714 15.25 16.3616 15.2484 16.8446 15.1835C17.3061 15.1214 17.5036 15.0142 17.6339 14.8839C17.7642 14.7536 17.8714 14.5561 17.9335 14.0946C17.9984 13.6116 18 12.964 18 12C18 11.036 17.9984 10.3884 17.9335 9.9054C17.8714 9.44393 17.7642 9.24644 17.6339 9.11612C17.5036 8.9858 17.3061 8.87858 16.8446 8.81654Z"/></svg>`;
    linkBtn.style.fontSize = '11px';
    linkBtn.style.marginBottom = '4px';
    container.appendChild(linkBtn);

    const fields = {
      tl: this._createUnitField(container, group, 'border-top-left-radius', 'Top left', scope),
      tr: this._createUnitField(container, group, 'border-top-right-radius', 'Top right', scope),
      br: this._createUnitField(container, group, 'border-bottom-right-radius', 'Bottom right', scope),
      bl: this._createUnitField(container, group, 'border-bottom-left-radius', 'Bottom left', scope),
    };

    let linked = true;
    const sync = (srcRow, srcPos) => {
      if (!linked) return;
      const srcInput = srcRow.querySelector('input[data-role="value"]');
      const srcSelect = srcRow.querySelector('select[data-role="unit"]');
      if (!srcInput || !srcSelect) return;
      
      const val = srcInput.value;
      const unit = srcSelect.value;
      
      Object.keys(fields).forEach(pos => {
        if (pos === srcPos) return;
        const row = fields[pos];
        const input = row.querySelector('input[data-role="value"]');
        const select = row.querySelector('select[data-role="unit"]');
        if (input && select) {
          input.value = val;
          select.value = unit;
        }
      });
      this._syncCssFromControls();
    };

    Object.keys(fields).forEach(pos => {
      const row = fields[pos];
      const input = row.querySelector('input[data-role="value"]');
      const select = row.querySelector('select[data-role="unit"]');
      if (input && select) {
        input.addEventListener('input', () => {
          sync(row, pos);
          this._syncCssFromControls();
        });
        select.addEventListener('change', () => {
          sync(row, pos);
          this._syncCssFromControls();
        });
      }
    });

    linkBtn.addEventListener('click', () => {
      linked = !linked;
      if (linked) linkBtn.classList.add('cex-active');
      else linkBtn.classList.remove('cex-active');
      this._syncCssFromControls();
    });

    host.appendChild(container);
  }

  _buildSpacingSectionWithLink(host, group, base, title, scope) {
    const container = document.createElement('div');
    container.className = 'cex-linked-section';
    
    const linkBtn = document.createElement('button');
    linkBtn.type = 'button';
    linkBtn.classList.add('cex-link-button', 'cex-active');
    linkBtn.innerHTML = `<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2C16.714 2 19.0711 2 20.5355 3.46447C22 4.92893 22 7.28595 22 12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22ZM9.198 7.25H9.30203C10.2005 7.24997 10.9497 7.24995 11.5445 7.32991C12.1723 7.41432 12.7391 7.59999 13.1945 8.05546C13.65 8.51093 13.8357 9.07773 13.9201 9.70552C14.0001 10.3003 14 11.0495 14 11.948L14 12C14 12.4142 13.6642 12.75 13.25 12.75C12.8358 12.75 12.5 12.4142 12.5 12C12.5 11.036 12.4984 10.3884 12.4335 9.9054C12.3714 9.44393 12.2642 9.24644 12.1339 9.11612C12.0036 8.9858 11.8061 8.87858 11.3446 8.81654C10.8616 8.7516 10.214 8.75 9.25 8.75C8.28599 8.75 7.63843 8.7516 7.15539 8.81654C6.69393 8.87858 6.49644 8.9858 6.36612 9.11612C6.2358 9.24644 6.12858 9.44393 6.06654 9.9054C6.0016 10.3884 6 11.036 6 12C6 12.964 6.0016 13.6116 6.06654 14.0946C6.12858 14.5561 6.2358 14.7536 6.36612 14.8839C6.49644 15.0142 6.69393 15.1214 7.15539 15.1835C7.63843 15.2484 8.28599 15.25 9.25 15.25C9.66422 15.25 10 15.5858 10 16C10 16.4142 9.66422 16.75 9.25 16.75L9.19798 16.75C8.29951 16.75 7.5503 16.7501 6.95552 16.6701C6.32773 16.5857 5.76093 16.4 5.30546 15.9445C4.84999 15.4891 4.66432 14.9223 4.57991 14.2945C4.49995 13.6997 4.49997 12.9505 4.5 12.052V11.948C4.49997 11.0495 4.49995 10.3003 4.57991 9.70552C4.66432 9.07773 4.84999 8.51093 5.30546 8.05546C5.76093 7.59999 6.32773 7.41432 6.95552 7.32991C7.55029 7.24995 8.29954 7.24997 9.198 7.25ZM16.8446 8.81654C16.3616 8.7516 15.714 8.75 14.75 8.75C14.3358 8.75 14 8.41422 14 8C14 7.58579 14.3358 7.25 14.75 7.25L14.802 7.25C15.7005 7.24997 16.4497 7.24995 17.0445 7.32991C17.6723 7.41432 18.2391 7.59999 18.6945 8.05546C19.15 8.51093 19.3357 9.07773 19.4201 9.70552C19.5001 10.3003 19.5 11.0495 19.5 11.9479V12.052C19.5 12.9505 19.5001 13.6997 19.4201 14.2945C19.3357 14.9223 19.15 15.4891 18.6945 15.9445C18.2391 16.4 17.6723 16.5857 17.0445 16.6701C16.4497 16.7501 15.7005 16.75 14.802 16.75H14.698C13.7995 16.75 13.0503 16.7501 12.4555 16.6701C11.8277 16.5857 11.2609 16.4 10.8055 15.9445C10.35 15.4891 10.1643 14.9223 10.0799 14.2945C9.99995 13.6997 9.99997 12.9505 10 12.052L10 12C10 11.5858 10.3358 11.25 10.75 11.25C11.1642 11.25 11.5 11.5858 11.5 12C11.5 12.964 11.5016 13.6116 11.5665 14.0946C11.6286 14.5561 11.7358 14.7536 11.8661 14.8839C11.9964 15.0142 12.1939 15.1214 12.6554 15.1835C13.1384 15.2484 13.786 15.25 14.75 15.25C15.714 15.25 16.3616 15.2484 16.8446 15.1835C17.3061 15.1214 17.5036 15.0142 17.6339 14.8839C17.7642 14.7536 17.8714 14.5561 17.9335 14.0946C17.9984 13.6116 18 12.964 18 12C18 11.036 17.9984 10.3884 17.9335 9.9054C17.8714 9.44393 17.7642 9.24644 17.6339 9.11612C17.5036 8.9858 17.3061 8.87858 16.8446 8.81654Z"/></svg>`;
    linkBtn.style.fontSize = '11px';
    linkBtn.style.marginBottom = '4px';
    container.appendChild(linkBtn);

    const fields = {
      top: this._createUnitField(container, group, `${base}-top`, `${title} top`, scope),
      right: this._createUnitField(container, group, `${base}-right`, `${title} right`, scope),
      bottom: this._createUnitField(container, group, `${base}-bottom`, `${title} bottom`, scope),
      left: this._createUnitField(container, group, `${base}-left`, `${title} left`, scope),
    };

    let linked = true;
    const sync = (srcRow, srcPos) => {
      if (!linked) return;
      const srcInput = srcRow.querySelector('input[data-role="value"]');
      const srcSelect = srcRow.querySelector('select[data-role="unit"]');
      if (!srcInput || !srcSelect) return;
      
      const val = srcInput.value;
      const unit = srcSelect.value;
      
      Object.keys(fields).forEach(pos => {
        if (pos === srcPos) return;
        const row = fields[pos];
        const input = row.querySelector('input[data-role="value"]');
        const select = row.querySelector('select[data-role="unit"]');
        if (input && select) {
          input.value = val;
          select.value = unit;
        }
      });
      this._syncCssFromControls();
    };

    Object.keys(fields).forEach(pos => {
      const row = fields[pos];
      const input = row.querySelector('input[data-role="value"]');
      const select = row.querySelector('select[data-role="unit"]');
      if (input && select) {
        input.addEventListener('input', () => {
          sync(row, pos);
          this._syncCssFromControls();
        });
        select.addEventListener('change', () => {
          sync(row, pos);
          this._syncCssFromControls();
        });
      }
    });

    linkBtn.addEventListener('click', () => {
      linked = !linked;
      if (linked) linkBtn.classList.add('cex-active');
      else linkBtn.classList.remove('cex-active');
      this._syncCssFromControls();
    });

    host.appendChild(container);
  }

  _buildBoxShadowSection(host, group, scope) {
    this._buildField(host, group, { key: 'box-shadow-color', label: 'Color', type: 'color' }, scope);
    this._buildField(host, group, { key: 'box-shadow-x', label: 'Position X', type: 'unit' }, scope);
    this._buildField(host, group, { key: 'box-shadow-y', label: 'Position Y', type: 'unit' }, scope);
    this._buildField(host, group, { key: 'box-shadow-blur', label: 'Blur', type: 'unit' }, scope);
    this._buildField(host, group, { key: 'box-shadow-spread', label: 'Spread', type: 'unit' }, scope);
    this._buildField(host, group, { key: 'box-shadow-inset', label: 'Inset', type: 'checkbox' }, scope);
  }

  _buildOutlineSection(host, group, scope) {
    this._buildField(host, group, { key: 'outline-width', label: 'Outline width', type: 'unit' }, scope);
    this._buildField(host, group, { key: 'outline-color', label: 'Outline color', type: 'color' }, scope);
    this._buildField(host, group, {
      key: 'outline-style', label: 'Outline style', type: 'select',
      options: ['', 'none', 'solid', 'dashed', 'dotted', 'double']
    }, scope);
  }

  _createUnitField(container, group, key, label, scope) {
    const row = document.createElement('div');
    row.className = 'cex-field-row';
    row.dataset.group = group;
    row.dataset.scope = scope;
    row.dataset.prop = key;

    const lbl = document.createElement('div');
    lbl.className = 'cex-label';
    lbl.textContent = label;
    lbl.style.fontSize = '12px';

    const control = document.createElement('div');
    control.className = 'cex-unit';
    const input = document.createElement('input');
    input.type = 'text';
    input.placeholder = 'Value';
    input.dataset.role = 'value';
    input.style.fontSize = '12px';
    
    const select = document.createElement('select');
    select.dataset.role = 'unit';
    ['px', '%', 'em', 'rem'].forEach(u => {
      const opt = document.createElement('option');
      opt.value = u;
      opt.textContent = u;
      select.appendChild(opt);
    });
    select.style.fontSize = '12px';
    
    control.append(input, select);
    row.append(lbl, control);
    container.appendChild(row);
    
    return row;
  }

  _buildPopupColorField(row) {
    const wrapper = document.createElement('div');
    wrapper.style.display = 'flex';
    wrapper.style.gap = '6px';
    wrapper.style.alignItems = 'center';
    wrapper.style.flexWrap = 'wrap';

    const text = document.createElement('input');
    text.type = 'text';
    text.placeholder = 'rgba(...) or hex';
    text.dataset.role = 'value';
    text.style.fontSize = '12px';
    text.style.flex = '1';

    const icon = document.createElement('button');
    icon.type = 'button';
    icon.className = 'cex-icon-btn';
    icon.title = 'Pick color';
    icon.innerHTML = `
    <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
      <path fill="currentColor" d="M12 3a9 9 0 1 1-6.364 15.364A9 9 0 0 1 12 3zm0 4a5 5 0 1 0 0 10 5 5 0 0 0 0-10z"/>
    </svg>`;

    const inlinePanel = document.createElement('div');
    inlinePanel.style.display = 'none';
    inlinePanel.style.width = '100%';
    inlinePanel.style.marginTop = '6px';
    inlinePanel.style.padding = '6px';
    inlinePanel.style.border = '1px solid var(--border)';
    inlinePanel.style.borderRadius = '6px';
    inlinePanel.style.background = 'var(--panel-bg)';

    const picker = document.createElement('input');
    picker.type = 'color';
    picker.value = '#000000';
    picker.style.width = '60px';

    const alphaLabel = document.createElement('div');
    alphaLabel.textContent = 'Alpha';
    alphaLabel.style.fontSize = '11px';

    const alpha = document.createElement('input');
    alpha.type = 'range';
    alpha.min = '0';
    alpha.max = '1';
    alpha.step = '0.01';
    alpha.value = '1';
    alpha.style.width = '100%';

    inlinePanel.append(picker, alphaLabel, alpha);

    const updateFromPicker = () => {
      const hex = picker.value;
      const r = parseInt(hex.substring(1, 3), 16);
      const g = parseInt(hex.substring(3, 5), 16);
      const b = parseInt(hex.substring(5, 7), 16);
      const a = parseFloat(alpha.value || '1');
      if (a >= 1) {
        text.value = hex;
      } else {
        text.value = `rgba(${r}, ${g}, ${b}, ${a})`;
      }
      this._onFieldChange(row);
    };

    picker.addEventListener('input', updateFromPicker);
    alpha.addEventListener('input', updateFromPicker);
    text.addEventListener('input', () => this._onFieldChange(row));

    icon.addEventListener('click', (e) => {
      e.preventDefault();
      inlinePanel.style.display = inlinePanel.style.display === 'none' ? 'block' : 'none';
    });

    wrapper.append(text, icon, inlinePanel);
    return wrapper;
  }

  _onFieldChange(row) {
    this._syncCssFromControls();
  }

  /* -------------------- CSS application -------------------- */

  _styleTagId(kind = 'live') {
    return kind === 'saved' ? 'cex-gf-saved-styles' : 'cex-gf-live-styles';
  }

  _getOrCreateStyleTag(kind = 'live') {
    const id = this._styleTagId(kind);
    let style = document.getElementById(id);
    if (!style) {
      style = document.createElement('style');
      style.id = id;
      style.type = 'text/css';
      document.head.appendChild(style);
    }
    return style;
  }

  _composeCss(map) {
    let out = '';
    for (const [selector, cssText] of map.entries()) {
      const blockText = (cssText || '').trim();
      if (!selector || !blockText) continue;
      out += `${selector} {\n${this._indentLines(blockText, 2)}\n}\n\n`;
    }
    return out;
  }

  _indentLines(text, spaces = 2) {
    const pad = ' '.repeat(spaces);
    return text.split('\n').map(l => (l.trim() ? pad + l : l)).join('\n');
  }

  _applyLiveCssFromTextarea() {
    const raw = this.cssOutput.value || '';
    const blocks = this._splitBlocks(raw);
    this.state.liveStyles.clear();
    blocks.forEach(({ selector, cssText }) => {
      if (selector && cssText.trim()) this.state.liveStyles.set(selector, cssText.trim());
    });
    const styleEl = this._getOrCreateStyleTag('live');
    styleEl.textContent = this._composeCss(this.state.liveStyles);
  }

  _applySavedCss() {
    const styleEl = this._getOrCreateStyleTag('saved');
    styleEl.textContent = this._composeCss(this.state.savedStyles);
  }

  _hasSavedCss() {
    const styleEl = this._getOrCreateStyleTag('saved');
    return styleEl.textContent != '';
  }

  _getSavedCss() {
    const styleEl = this._getOrCreateStyleTag('saved');
    return styleEl.textContent;
  }

  _clearLiveStyles() {
    this.state.liveStyles.clear();
    const styleEl = this._getOrCreateStyleTag('live');
    styleEl.textContent = '';
  }

  _splitBlocks(text) {
    const out = [];
    const regex = /([^{]+)\{([^}]*)\}/gms;
    let m;
    while ((m = regex.exec(text)) !== null) {
      const selector = m[1].trim();
      const cssText = (m[2] || '').trim();
      if (selector) out.push({ selector, cssText });
    }
    return out;
  }

  _getSelectorsByGroup() {
    const baseSelector = this.state.currentSelector;
    
    return {
      container: baseSelector,
      'grid-gap': `${baseSelector} .gform_fields`,
      'labels-main': `${baseSelector} .gfield_label, ${baseSelector} .gform-field-label`,
      'labels-sub': `${baseSelector} .gform-field-label--type-sub`,
      'labels-desc': `${baseSelector} .gfield_description`,
      'fields': `${baseSelector} input:not([type="radio"]):not([type="checkbox"]):not([type="submit"]), ${baseSelector} select, ${baseSelector} textarea`,
      'buttons': `${baseSelector} .gform_button, ${baseSelector} input[type="submit"]`,
      'transition': baseSelector
    };
  }

  _applyStateToSelector(selector, state) {
    if (state === 'regular') return selector;
    
    // Split multiple selectors and apply state to each
    const parts = selector.split(',').map(s => s.trim());
    const withState = parts.map(part => {
      // Add state to the end of each selector
      return `${part}:${state}`;
    }).join(', ');
    
    return withState;
  }

  _collectValuesByGroup() {
    const values = {
      container: { regular: {}, hover: {}, focus: {}, transition: {} },
      'grid-gap': { regular: {}, hover: {}, focus: {}, transition: {} },
      'labels-main': { regular: {}, hover: {}, focus: {}, transition: {} },
      'labels-sub': { regular: {}, hover: {}, focus: {}, transition: {} },
      'labels-desc': { regular: {}, hover: {}, focus: {}, transition: {} },
      'fields': { regular: {}, hover: {}, focus: {}, transition: {} },
      'buttons': { regular: {}, hover: {}, focus: {}, transition: {} },
      'transition': { regular: {}, hover: {}, focus: {}, transition: {} }
    };

    this.panel.querySelectorAll('.cex-field-row').forEach(row => {
      const group = row.dataset.group;
      const scope = row.dataset.scope;
      if (!values[group] || !values[group][scope]) return;
      
      const prop = row.dataset.prop;
      let val = '';

      const unitWrap = row.querySelector('.cex-unit');
      if (unitWrap) {
        const v = unitWrap.querySelector('[data-role="value"]').value.trim();
        const u = unitWrap.querySelector('[data-role="unit"]').value.trim();
        val = v ? (u ? `${v}${u}` : v) : '';
      } else {
        const textInput = row.querySelector('input[type="text"]');
        const select = row.querySelector('select');
        const checkbox = row.querySelector('input[type="checkbox"]');
        if (checkbox) {
          val = checkbox.checked ? 'inset' : '';
        } else if (select && !select.dataset.role) {
          val = select.value.trim();
        } else if (textInput) {
          val = textInput.value.trim();
        }
      }

      if (val) values[group][scope][prop] = val;
    });

    return values;
  }

  _formatAllCssBlocks() {
    const values = this._collectValuesByGroup();
    const selectors = this._getSelectorsByGroup();
    let output = '';

    // Helper to add CSS block
    const addBlock = (selector, css) => {
      if (css.trim()) {
        output += `${selector} {\n${this._indentLines(css.trim(), 2)}\n}\n\n`;
      }
    };

    // Container (no states)
    const containerRegular = this._cssFromValues(values.container.regular);
    const containerTransition = this._cssFromValues(values.container.transition);
    if (containerRegular || containerTransition) {
      addBlock(selectors.container, containerRegular + '\n' + containerTransition);
    }

    // Grid Gap (special - targets .gform_fields)
    const gridGapRegular = this._cssFromValues(values['grid-gap'].regular);
    if (gridGapRegular) {
      addBlock(selectors['grid-gap'], gridGapRegular);
    }

    // Main Labels
    const mainRegular = this._cssFromValues(values['labels-main'].regular);
    const mainTransition = this._cssFromValues(values['labels-main'].transition);
    if (mainRegular || mainTransition) {
      addBlock(selectors['labels-main'], mainRegular + '\n' + mainTransition);
    }

    // Sub Labels
    const subRegular = this._cssFromValues(values['labels-sub'].regular);
    if (subRegular) {
      addBlock(selectors['labels-sub'], subRegular);
    }

    // Descriptions
    const descRegular = this._cssFromValues(values['labels-desc'].regular);
    if (descRegular) {
      addBlock(selectors['labels-desc'], descRegular);
    }

    // Fields with proper state handling
    const fieldsRegular = this._cssFromValues(values.fields.regular);
    const fieldsHover = this._cssFromValues(values.fields.hover);
    const fieldsFocus = this._cssFromValues(values.fields.focus);
    const fieldsTransition = this._cssFromValues(values.fields.transition);
    
    if (fieldsRegular || fieldsTransition) {
      addBlock(selectors.fields, fieldsRegular + '\n' + fieldsTransition);
    }
    if (fieldsHover) {
      addBlock(this._applyStateToSelector(selectors.fields, 'hover'), fieldsHover);
    }
    if (fieldsFocus) {
      addBlock(this._applyStateToSelector(selectors.fields, 'focus'), fieldsFocus);
    }

    // Buttons with proper state handling
    const buttonsRegular = this._cssFromValues(values.buttons.regular);
    const buttonsHover = this._cssFromValues(values.buttons.hover);
    const buttonsFocus = this._cssFromValues(values.buttons.focus);
    const buttonsTransition = this._cssFromValues(values.buttons.transition);
    
    if (buttonsRegular || buttonsTransition) {
      addBlock(selectors.buttons, buttonsRegular + '\n' + buttonsTransition);
    }
    if (buttonsHover) {
      addBlock(this._applyStateToSelector(selectors.buttons, 'hover'), buttonsHover);
    }
    if (buttonsFocus) {
      addBlock(this._applyStateToSelector(selectors.buttons, 'focus'), buttonsFocus);
    }

    // Global Transition (applies to all elements that have transitions)
    const globalTransition = this._cssFromValues(values.transition.transition);
    if (globalTransition) {
      if (containerRegular || containerTransition) addBlock(selectors.container, globalTransition);
      if (mainRegular || mainTransition) addBlock(selectors['labels-main'], globalTransition);
      if (subRegular) addBlock(selectors['labels-sub'], globalTransition);
      if (descRegular) addBlock(selectors['labels-desc'], globalTransition);
      if (fieldsRegular || fieldsTransition) addBlock(selectors.fields, globalTransition);
      if (buttonsRegular || buttonsTransition) addBlock(selectors.buttons, globalTransition);
    }

    return output.trim();
  }

  _loadSavedCssIntoOutput() {
    const selectors = this._getSelectorsByGroup();
    let combined = '';

    // Load all saved styles
    const addSavedBlock = (selector) => {
      const css = this.state.savedStyles.get(selector) || '';
      if (css.trim()) {
        combined += `${selector} {\n${this._indentLines(css.trim(), 2)}\n}\n\n`;
      }
    };

    addSavedBlock(selectors.container);
    addSavedBlock(selectors['grid-gap']);
    addSavedBlock(selectors['labels-main']);
    addSavedBlock(selectors['labels-sub']);
    addSavedBlock(selectors['labels-desc']);
    addSavedBlock(selectors.fields);
    addSavedBlock(this._applyStateToSelector(selectors.fields, 'hover'));
    addSavedBlock(this._applyStateToSelector(selectors.fields, 'focus'));
    addSavedBlock(selectors.buttons);
    addSavedBlock(this._applyStateToSelector(selectors.buttons, 'hover'));
    addSavedBlock(this._applyStateToSelector(selectors.buttons, 'focus'));

    this.cssOutput.value = combined.trim();
  }

  _cssFromValues(values) {
    const lines = [];
    const useImportant = this.importantToggle?.checked;
    const suffix = useImportant ? ' !important' : '';

    // Box Shadow
    if (values['box-shadow-x'] || values['box-shadow-y'] || values['box-shadow-blur'] || 
        values['box-shadow-spread'] || values['box-shadow-color']) {
      const inset = values['box-shadow-inset'] ? 'inset ' : '';
      const x = values['box-shadow-x'] || '0px';
      const y = values['box-shadow-y'] || '0px';
      const blur = values['box-shadow-blur'] || '0px';
      const spread = values['box-shadow-spread'] || '0px';
      const color = values['box-shadow-color'] || 'rgba(0,0,0,0.5)';
      lines.push(`box-shadow: ${inset}${x} ${y} ${blur} ${spread} ${color}${suffix};`);
    }

    // Outline
    if (values['outline-width'] || values['outline-color'] || values['outline-style']) {
      const width = values['outline-width'] || '0px';
      const style = values['outline-style'] || 'solid';
      const color = values['outline-color'] || 'transparent';
      lines.push(`outline: ${width} ${style} ${color}${suffix};`);
    }

    // Transition
    if (values['transition-property'] && values['transition-duration']) {
      const prop = values['transition-property'];
      const dur = values['transition-duration'];
      const timing = values['transition-timing-function'] || 'ease';
      const delay = values['transition-delay'] || '0s';
      lines.push(`transition: ${prop} ${dur} ${timing} ${delay}${suffix};`);
    }

    // Border properties
    if (values['border-top-width'] || values['border-right-width'] || 
        values['border-bottom-width'] || values['border-left-width']) {
      
      if (values['border-top-width'] === values['border-right-width'] &&
          values['border-right-width'] === values['border-bottom-width'] &&
          values['border-bottom-width'] === values['border-left-width'] &&
          values['border-top-width'] !== undefined) {
        lines.push(`border-width: ${values['border-top-width']}${suffix};`);
      } else {
        if (values['border-top-width']) lines.push(`border-top-width: ${values['border-top-width']}${suffix};`);
        if (values['border-right-width']) lines.push(`border-right-width: ${values['border-right-width']}${suffix};`);
        if (values['border-bottom-width']) lines.push(`border-bottom-width: ${values['border-bottom-width']}${suffix};`);
        if (values['border-left-width']) lines.push(`border-left-width: ${values['border-left-width']}${suffix};`);
      }
    }

    if (values['border-color']) lines.push(`border-color: ${values['border-color']}${suffix};`);
    if (values['border-style']) lines.push(`border-style: ${values['border-style']}${suffix};`);

    // Border radius
    if (values['border-top-left-radius'] || values['border-top-right-radius'] ||
        values['border-bottom-right-radius'] || values['border-bottom-left-radius']) {
      
      if (values['border-top-left-radius'] === values['border-top-right-radius'] &&
          values['border-top-right-radius'] === values['border-bottom-right-radius'] &&
          values['border-bottom-right-radius'] === values['border-bottom-left-radius'] &&
          values['border-top-left-radius'] !== undefined) {
        lines.push(`border-radius: ${values['border-top-left-radius']}${suffix};`);
      } else {
        if (values['border-top-left-radius']) lines.push(`border-top-left-radius: ${values['border-top-left-radius']}${suffix};`);
        if (values['border-top-right-radius']) lines.push(`border-top-right-radius: ${values['border-top-right-radius']}${suffix};`);
        if (values['border-bottom-right-radius']) lines.push(`border-bottom-right-radius: ${values['border-bottom-right-radius']}${suffix};`);
        if (values['border-bottom-left-radius']) lines.push(`border-bottom-left-radius: ${values['border-bottom-left-radius']}${suffix};`);
      }
    }

    // Margin
    if (values['margin-top'] || values['margin-right'] || values['margin-bottom'] || values['margin-left']) {
      if (values['margin-top'] === values['margin-right'] &&
          values['margin-right'] === values['margin-bottom'] &&
          values['margin-bottom'] === values['margin-left'] &&
          values['margin-top'] !== undefined) {
        lines.push(`margin: ${values['margin-top']}${suffix};`);
      } else {
        if (values['margin-top']) lines.push(`margin-top: ${values['margin-top']}${suffix};`);
        if (values['margin-right']) lines.push(`margin-right: ${values['margin-right']}${suffix};`);
        if (values['margin-bottom']) lines.push(`margin-bottom: ${values['margin-bottom']}${suffix};`);
        if (values['margin-left']) lines.push(`margin-left: ${values['margin-left']}${suffix};`);
      }
    }

    // Padding
    if (values['padding-top'] || values['padding-right'] || values['padding-bottom'] || values['padding-left']) {
      if (values['padding-top'] === values['padding-right'] &&
          values['padding-right'] === values['padding-bottom'] &&
          values['padding-bottom'] === values['padding-left'] &&
          values['padding-top'] !== undefined) {
        lines.push(`padding: ${values['padding-top']}${suffix};`);
      } else {
        if (values['padding-top']) lines.push(`padding-top: ${values['padding-top']}${suffix};`);
        if (values['padding-right']) lines.push(`padding-right: ${values['padding-right']}${suffix};`);
        if (values['padding-bottom']) lines.push(`padding-bottom: ${values['padding-bottom']}${suffix};`);
        if (values['padding-left']) lines.push(`padding-left: ${values['padding-left']}${suffix};`);
      }
    }

    // All other properties
    for (const [prop, val] of Object.entries(values)) {
      if (!val) continue;
      if (prop.startsWith('box-shadow-')) continue;
      if (prop.startsWith('transition-')) continue;
      if (prop === 'outline-width' || prop === 'outline-color' || prop === 'outline-style') continue;
      if (prop === 'border-color' || prop === 'border-style') continue;
      if (prop.startsWith('border-') && (prop.includes('width') || prop.includes('radius'))) continue;
      if (prop.startsWith('margin-')) continue;
      if (prop.startsWith('padding-')) continue;
      
      lines.push(`${prop}: ${val}${suffix};`);
    }

    return lines.join('\n');
  }

  _syncCssFromControls() {
    if (!this.state.currentSelector) {
      this.cssOutput.value = '';
      this._clearLiveStyles();
      return;
    }

    const formatted = this._formatAllCssBlocks();
    this.cssOutput.value = formatted;
    const blocks = this._splitBlocks(formatted);
    this.state.liveStyles.clear();
    blocks.forEach(({ selector, cssText }) => {
      if (selector && cssText.trim()) this.state.liveStyles.set(selector, cssText.trim());
    });
    const styleEl = this._getOrCreateStyleTag('live');
    styleEl.textContent = this._composeCss(this.state.liveStyles);
  }

  _resetControls() {
    this.panel.querySelectorAll('.cex-field-row').forEach(row => {
      const inputs = row.querySelectorAll('input, select');
      inputs.forEach(inp => {
        if (inp.tagName === 'SELECT') {
          inp.selectedIndex = 0;
        } else if (inp.type === 'range') {
          inp.value = '1';
        } else if (inp.type === 'color') {
          inp.value = '#000000';
        } else if (inp.type === 'checkbox') {
          inp.checked = false;
        } else {
          inp.value = '';
        }
      });
    });

    this.cssOutput.value = '';
    this._clearLiveStyles();
  }

  getGeneratedCss() {
    return this._composeCss(this.state.savedStyles).trim();
  }

  setFormId(formId) {
    this.options.formId = formId;
    if (this.formSelect) {
      this.formSelect.value = formId || '';
    }
    this._updateSelector();
  }
}

window.addEventListener('DOMContentLoaded', () => {
  if (!window.__gravityFormsCssEditorInstance) {
    window.__gravityFormsCssEditorInstance = new GravityFormsCssEditor();
  }
});

function saveGravityFormsCSSData(content, formId = null) {
  if (typeof sccCustomizerData === 'undefined') {
    console.error('Customizer data not found.');
    return;
  }

  function reloadWithoutParams(paramsToRemove = []) {
    const url = new URL(window.location.href);
    paramsToRemove.forEach(param => url.searchParams.delete(param));
    window.location.href = url.pathname + url.search;
  }

  if (SCCCustomizer && SCCCustomizer.preloader) {
    SCCCustomizer.preloader.show('Saving Gravity Forms CSS ...');
  }

  const { nonce, post_id, rest_url } = sccCustomizerData;

  fetch(rest_url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
      'X-WP-Nonce': nonce,
    },
    body: JSON.stringify({
      post_id: post_id,
      content: content,
      form_id: formId,
      type: 'gravityforms',
    }),
  })
    .then(response => {
      if (!response.ok) {
        if (SCCCustomizer && SCCCustomizer.preloader) SCCCustomizer.preloader.hide();
        throw new Error(`Server responded with status ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      if (data.success) {
        console.log('✅ Gravity Forms CSS saved successfully:', data.message);
        if (SCCCustomizer && SCCCustomizer.preloader) SCCCustomizer.preloader.hide();
        alert('Gravity Forms CSS Saved. Reloading...');
        reloadWithoutParams(['scc_customizer', 'scc']);
      } else {
        console.warn('⚠️ Save failed:', data);
        if (SCCCustomizer && SCCCustomizer.preloader) SCCCustomizer.preloader.hide();
        alert('Gravity Forms CSS save failed. Reloading...');
        reloadWithoutParams(['scc_customizer', 'scc']);
      }
    })
    .catch(error => {
      console.error('❌ Error saving CSS:', error);
      if (SCCCustomizer && SCCCustomizer.preloader) SCCCustomizer.preloader.hide();
      alert('Gravity Forms CSS save error. Reloading...');
      reloadWithoutParams(['scc_customizer', 'scc']);
    });
}