(function(){
  const servicesWrapper = document.getElementById('services-wrapper');
  const addServiceBtn = document.getElementById('add-service-btn');
  const servicesStateEl = document.getElementById('services-json');
  const grandTotalEl = document.getElementById('grand-total');
  const previewForm = document.getElementById('preview-config-form');

  function parseMoney(value){
    const clean = String(value || '').replace(/[^\d,.-]/g,'');
    if(!clean) return 0;
    if(clean.includes(',') && clean.includes('.')) return Number(clean.replace(/\./g,'').replace(',', '.')) || 0;
    return Number(clean.replace(',', '.')) || 0;
  }

  function formatMoney(value){
    return value.toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
  }

  function formatMoneyInput(value){
    const digits = String(value || '').replace(/\D/g,'');
    if(!digits) return '';
    const num = Number(digits) / 100;
    return 'R$ ' + num.toLocaleString('pt-BR',{minimumFractionDigits:2, maximumFractionDigits:2});
  }

  function applyPhoneMask(value){
    const digits = String(value || '').replace(/\D/g,'').slice(0,11);
    if(digits.length <= 10){
      return digits.replace(/(\d{0,2})(\d{0,4})(\d{0,4}).*/, (_,a,b,c) => {
        let out = '';
        if(a) out += '(' + a;
        if(a.length === 2) out += ') ';
        if(b) out += b;
        if(c) out += '-' + c;
        return out;
      });
    }
    return digits.replace(/(\d{0,2})(\d{0,5})(\d{0,4}).*/, (_,a,b,c) => {
      let out = '';
      if(a) out += '(' + a;
      if(a.length === 2) out += ') ';
      if(b) out += b;
      if(c) out += '-' + c;
      return out;
    });
  }

  function escapeHtml(value){
    return String(value ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  function defaultService(){
    return {name:'',description:'',quantity:'1',unit_price:'0,00'};
  }

  function initMasks(scope){
    const root = scope || document;
    root.querySelectorAll('.phone-mask').forEach((input) => {
      if(input.dataset.maskReady === '1') return;
      input.dataset.maskReady = '1';
      input.addEventListener('input', (e) => { e.target.value = applyPhoneMask(e.target.value); });
      input.value = applyPhoneMask(input.value);
    });

    root.querySelectorAll('.money-mask, .price-input').forEach((input) => {
      if(input.dataset.maskReady === '1') return;
      input.dataset.maskReady = '1';
      input.addEventListener('input', (e) => {
        e.target.value = formatMoneyInput(e.target.value);
        if (servicesWrapper) syncFromDom();
      });
      input.addEventListener('blur', (e) => {
        e.target.value = formatMoneyInput(e.target.value);
        if (servicesWrapper) syncFromDom();
      });
      input.value = formatMoneyInput(input.value || '');
    });
  }

  let services = [];
  if(servicesStateEl){
    try { services = JSON.parse(servicesStateEl.value || '[]'); } catch(e){ services = []; }
    if(!Array.isArray(services)) services = [];
  }

  function serviceTemplate(service,index){
    return `
      <div class="service-card" data-index="${index}">
        <div class="service-header">
          <h3>Serviço ${index+1}</h3>
          <div class="service-tools">
            <button class="icon-btn duplicate-btn" type="button">Duplicar</button>
            <button class="icon-btn remove-btn" type="button">Remover</button>
          </div>
        </div>
        <div class="form-grid">
          <div class="field field-span-2">
            <label>Nome do serviço</label>
            <input name="service_name[]" type="text" value="${escapeHtml(service.name || '')}" placeholder="Ex.: Limpeza completa do ar-condicionado">
          </div>
          <div class="field field-span-2">
            <label>Descrição do serviço</label>
            <textarea name="service_description[]" rows="4" placeholder="Detalhe o que será executado">${escapeHtml(service.description || '')}</textarea>
          </div>
          <div class="field">
            <label>Quantidade</label>
            <input name="service_quantity[]" class="quantity-input" type="number" min="0" step="0.01" value="${escapeHtml(service.quantity || '1')}">
          </div>
          <div class="field">
            <label>Valor unitário</label>
            <input name="service_unit_price[]" class="price-input" type="text" value="${escapeHtml(service.unit_price || '0,00')}" placeholder="0,00">
          </div>
          <div class="field">
            <label>Subtotal</label>
            <input type="text" class="subtotal-output" value="R$ 0,00" readonly>
          </div>
        </div>
      </div>`;
  }

  function updateServicesJson(){
    if(servicesStateEl){ servicesStateEl.value = JSON.stringify(services); }
  }

  function recalcTotals(){
    if(!servicesWrapper) return;
    let grandTotal = 0;
    Array.from(servicesWrapper.querySelectorAll('.service-card')).forEach((card) => {
      const q = Number(String(card.querySelector('.quantity-input').value || '0').replace(',', '.')) || 0;
      const v = parseMoney(card.querySelector('.price-input').value || '0');
      const subtotal = q * v;
      grandTotal += subtotal;
      card.querySelector('.subtotal-output').value = formatMoney(subtotal);
    });
    if(grandTotalEl) grandTotalEl.textContent = formatMoney(grandTotal);
  }

  function syncFromDom(){
    if(!servicesWrapper) return;
    services = Array.from(servicesWrapper.querySelectorAll('.service-card')).map((card) => ({
      name: card.querySelector('[name="service_name[]"]').value,
      description: card.querySelector('[name="service_description[]"]').value,
      quantity: card.querySelector('[name="service_quantity[]"]').value,
      unit_price: card.querySelector('[name="service_unit_price[]"]').value,
    }));
    updateServicesJson();
    recalcTotals();
  }

  function bindServiceEvents(){
    if(!servicesWrapper) return;
    servicesWrapper.querySelectorAll('.duplicate-btn').forEach((btn) => btn.addEventListener('click', (e) => {
      const idx = Number(e.currentTarget.closest('.service-card').dataset.index);
      const copy = JSON.parse(JSON.stringify(services[idx] || defaultService()));
      services.splice(idx + 1, 0, copy);
      renderServices();
    }));

    servicesWrapper.querySelectorAll('.remove-btn').forEach((btn) => btn.addEventListener('click', (e) => {
      const idx = Number(e.currentTarget.closest('.service-card').dataset.index);
      services.splice(idx, 1);
      renderServices();
    }));

    servicesWrapper.querySelectorAll('input, textarea').forEach((el) => el.addEventListener('input', syncFromDom));
  }

  function renderServices(){
    if(!servicesWrapper) return;
    if(services.length === 0){
      servicesWrapper.innerHTML = '<div class="empty-state"><p>Nenhum serviço adicionado ainda.</p><button type="button" class="btn btn-primary" id="inner-empty-add">Adicionar primeiro serviço</button></div>';
      const innerBtn = document.getElementById('inner-empty-add');
      if(innerBtn) innerBtn.addEventListener('click', () => { services.push(defaultService()); renderServices(); });
      if(grandTotalEl) grandTotalEl.textContent = formatMoney(0);
      updateServicesJson();
      return;
    }

    servicesWrapper.innerHTML = services.map(serviceTemplate).join('');
    bindServiceEvents();
    initMasks(servicesWrapper);
    recalcTotals();
    updateServicesJson();
  }

  if(addServiceBtn){
    addServiceBtn.addEventListener('click', () => { services.push(defaultService()); renderServices(); });
  }

  initMasks(document);
  if(servicesWrapper){ renderServices(); }

  if(previewForm){
    const model = document.getElementById('preview_model');
    const picker = document.getElementById('preview_color');
    const intensity = document.getElementById('preview_intensity');
    const swatch = document.getElementById('preview_swatch');
    const presets = document.querySelectorAll('.color-preset[data-color]');
    const colorMoreBtn = document.getElementById('color-more-btn');
    const applyPreviewBtn = document.getElementById('apply-preview-btn');
    let previewSubmitTimer = null;

    function mixColorWithWhite(hexColor, intensityValue){
      const hex = String(hexColor || '#1e3a5f').replace('#','');
      const r = parseInt(hex.slice(0,2),16);
      const g = parseInt(hex.slice(2,4),16);
      const b = parseInt(hex.slice(4,6),16);
      const f = Math.max(30, Math.min(100, Number(intensityValue || 100))) / 100;
      const mix = (c) => Math.round(c*f + 255*(1-f));
      return `#${mix(r).toString(16).padStart(2,'0')}${mix(g).toString(16).padStart(2,'0')}${mix(b).toString(16).padStart(2,'0')}`;
    }

    function refreshPreviewControls(){
      if(!picker || !intensity) return;
      const mixed = mixColorWithWhite(picker.value, intensity.value);
      if(swatch) swatch.style.background = mixed;
      presets.forEach((p) => p.classList.toggle('active', p.dataset.color.toLowerCase() === picker.value.toLowerCase()));
    }

    function submitPreviewForm(delay){
      window.clearTimeout(previewSubmitTimer);
      previewSubmitTimer = window.setTimeout(() => {
        if (typeof previewForm.requestSubmit === 'function') {
          previewForm.requestSubmit();
        } else {
          previewForm.submit();
        }
      }, delay || 0);
    }

    if(model){
      model.addEventListener('change', () => submitPreviewForm(80));
      model.addEventListener('input', () => submitPreviewForm(80));
      model.addEventListener('blur', () => refreshPreviewControls());
    }
    if(intensity){
      intensity.addEventListener('input', refreshPreviewControls);
      intensity.addEventListener('change', () => submitPreviewForm(120));
      intensity.addEventListener('touchend', () => submitPreviewForm(120), {passive:true});
    }
    if(picker){
      picker.addEventListener('input', refreshPreviewControls);
      picker.addEventListener('change', () => submitPreviewForm(80));
    }
    presets.forEach((btn) => btn.addEventListener('click', () => {
      if(!picker) return;
      picker.value = btn.dataset.color;
      refreshPreviewControls();
      submitPreviewForm(60);
    }));
    if(colorMoreBtn && picker) colorMoreBtn.addEventListener('click', () => picker.click());
    if(applyPreviewBtn) applyPreviewBtn.addEventListener('click', () => submitPreviewForm(0));
    refreshPreviewControls();
  }
})();
