(function(){
  'use strict';
  const $ = (sel) => document.querySelector(sel);
  const on = (el, ev, cb) => { if(el) el.addEventListener(ev, cb); };

  const HEX_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

  function syncPair(colorSel, textSel){
    const colorEl = $(colorSel);
    const textEl = $(textSel);
    if(!colorEl || !textEl) return;
    // color -> text
    on(colorEl, 'input', () => { textEl.value = colorEl.value || ''; updatePreview(); validate(textEl); });
    // text -> color (on input validate but do not force)
    on(textEl, 'input', () => { validate(textEl); if(HEX_RE.test(textEl.value)){ colorEl.value = textEl.value; updatePreview(); }});
    on(textEl, 'change', () => { if(!HEX_RE.test(textEl.value)) textEl.value=''; colorEl.value = textEl.value; updatePreview(); validate(textEl); });
  }

  function validate(input){
    if(!input) return;
    if(!input.value){ input.classList.remove('foodord-invalid'); return; }
    if(HEX_RE.test(input.value)) input.classList.remove('foodord-invalid');
    else input.classList.add('foodord-invalid');
  }

  function luminance(hex){
    if(!HEX_RE.test(hex)) return 0;
    const h = hex.slice(1);
    const to255 = (s)=> parseInt(s.length===3 ? s.repeat(2) : s, 16) / 255;
    const r = to255(h.slice(0, h.length===3?1:2));
    const g = to255(h.slice(h.length===3?1:2, h.length===3?2:4));
    const b = to255(h.slice(h.length===3?2:4));
    const srgb = [r,g,b].map(v => v <= 0.03928 ? v/12.92 : Math.pow((v+0.055)/1.055, 2.4));
    return 0.2126*srgb[0] + 0.7152*srgb[1] + 0.0722*srgb[2];
  }

  function contrastRatio(bg, fg){
    const L1 = Math.max(luminance(bg), luminance(fg));
    const L2 = Math.min(luminance(bg), luminance(fg));
    if(L1===0 && L2===0) return 1;
    return (L1 + 0.05) / (L2 + 0.05);
  }

  function updateContrastNotice(){
    const bg = $('#foodord_back_to_top_bg')?.value || '#ffffff';
    const icon = $('#foodord_back_to_top_icon')?.value || '#333333';
    const ratio = contrastRatio(bg, icon);
    const container = document.querySelector('.foodord-preview-header');
    if(!container) return;
    let note = container.querySelector('.foodord-contrast-note');
    if(!note){
      note = document.createElement('span');
      note.className = 'foodord-contrast-note';
      note.style.marginLeft = '8px';
      container.appendChild(note);
    }
    note.textContent = `Contrast: ${ratio.toFixed(2)}:1`;
    note.dataset.status = ratio < 3 ? 'low' : 'ok';
  }

  function updatePreview(){
    const bg = $('#foodord_back_to_top_bg')?.value || '';
    const hover = $('#foodord_back_to_top_hover')?.value || '';
    const icon = $('#foodord_back_to_top_icon')?.value || '';
    const btn = document.querySelector('[data-role="preview-button"]');
    if(!btn) return;
    if(bg){ btn.style.setProperty('--button-color', bg); btn.style.backgroundColor = bg; } else { btn.style.removeProperty('--button-color'); btn.style.backgroundColor = ''; }
    if(hover){ btn.style.setProperty('--button-hover-color', hover); } else { btn.style.removeProperty('--button-hover-color'); }
    if(icon){ btn.style.color = icon; } else { btn.style.color = ''; }
    updateContrastNotice();
  }

  function attachReset(){
    const defaults = {
      'foodord_back_to_top_bg': '#ffffff',
      'foodord_back_to_top_hover': '#f5f5f5',
      'foodord_back_to_top_icon': '#333333'
    };
    
    document.querySelectorAll('.foodord-reset').forEach((btn)=>{
      const target = btn.getAttribute('data-target');
      on(btn, 'click', () => {
        const colorEl = document.getElementById(target);
        const textEl = document.getElementById(target + '_text');
        const defaultValue = defaults[target] || '';
        
        if(colorEl){ colorEl.value = defaultValue; }
        if(textEl){ 
          textEl.value = defaultValue; 
          textEl.classList.remove('foodord-invalid'); 
        }
        updatePreview();
      });
    });
  }

  function init(){
    // Initialize WordPress Color Picker if jQuery is available
    if (typeof jQuery !== 'undefined' && jQuery.fn.wpColorPicker) {
      jQuery('.wr-color-picker').wpColorPicker({
        change: function() {
          updatePreview();
        },
        clear: function() {
          updatePreview();
        }
      });
    } else {
      // Fallback to custom color inputs
      syncPair('#foodord_back_to_top_bg', '#foodord_back_to_top_bg_text');
      syncPair('#foodord_back_to_top_hover', '#foodord_back_to_top_hover_text');
      syncPair('#foodord_back_to_top_icon', '#foodord_back_to_top_icon_text');
    }
    attachReset();
    updatePreview();
  }

  // Auto hide only success notices after saving (after 5 seconds)
  function autoHideNotices() {
    const successNotices = document.querySelectorAll('.notice.notice-success.is-dismissible');
    if (successNotices.length > 0) {
      successNotices.forEach(function(notice) {
        setTimeout(function() {
          notice.classList.add('notice-fade-out');
          setTimeout(function() {
            notice.remove();
          }, 500);
        }, 5000);
      });
    }
  }

  if(document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded', function() {
      init();
      setTimeout(autoHideNotices, 1000);
    });
  } else {
    init();
    setTimeout(autoHideNotices, 1000);
  }
})();
