document.addEventListener('DOMContentLoaded', () => document.querySelectorAll('[data-pcec]').forEach(root => {
  const form = root.querySelector('.pcec__form');
  const config = JSON.parse(root.querySelector('.pcec__config').textContent);
  const s = config.settings;
  const testMode = config.mode === 'test';
  let step = 1;
  const field = name => form.elements.namedItem(name);
  const number = name => Math.max(0, Number(field(name)?.value || 0));
  const checked = name => Boolean(field(name)?.checked);
  const money = value => `${s.currency_symbol}${Math.round(value).toLocaleString()} ${s.currency}`;
  const show = next => {
    step = next;
    root.querySelectorAll('.pcec__step').forEach(el => el.classList.toggle('is-active', Number(el.dataset.step) === step));
    root.querySelectorAll('.pcec__progress span').forEach((el, i) => el.classList.toggle('is-active', i < Math.min(step, 6)));
    root.scrollIntoView({behavior:'smooth', block:'start'});
  };
  const project = () => ({
    material: field('material')?.value || '', area: number('painting_area'),
    pitch: field('pitch')?.value || 'standard', stories: field('stories')?.value || 'two',
    complexity: field('complexity')?.value || 'average', access: field('access')?.value || 'open', tearoff_layers: number('tearoff_layers'),
    vents: number('vents'), skylights: number('skylights'), chimneys: number('chimneys'),
    permit: checked('permit'), disposal: checked('disposal'),
    ventilation_upgrade: checked('ventilation_upgrade')
  });
  const validate = () => {
    const message = root.querySelector(`.pcec__step[data-step="${step}"] .pcec__validation`);
    if (step === 1 && !field('material')?.value) { if(message) message.textContent='Choose a painting system to continue.'; return false; }
    if (step === 2 && number('painting_area') < 100) { if(message) message.textContent='Enter an estimated painting area of at least 100 sq ft.'; return false; }
    if(message) message.textContent=''; return true;
  };
  const calculate = () => {
    const p=project(), lines=[];
    const complexityWaste={simple:-4,average:0,complex:4,very_complex:8}[p.complexity]||0;
    const sizeWaste=p.area<1500?2:(p.area>3500?-1:0);
    const wastePercent=Math.max(5,Math.min(25,Number(s.waste_percent||12)+complexityWaste+sizeWaste));
    const adjustedArea=p.area*(1+wastePercent/100);
    const base=adjustedArea*Number(s.material_rates[p.material]||0); lines.push({label:`${config.materials[p.material]} (${Math.round(p.area).toLocaleString()} sq ft painting)`,amount:base});
    const envelope=(Number(s.pitch_factors[p.pitch]||1)*Number(s.stories_factors[p.stories]||1)*Number(s.complexity_factors[p.complexity]||1)*Number(s.access_factors[p.access]||1));
    if(Math.abs(envelope-1)>.001) lines.push({label:'Pitch, height, painting shape and access adjustment',amount:base*(envelope-1)});
    if(p.disposal&&p.tearoff_layers) lines.push({label:`Tear-off, disposal and cleanup (${p.tearoff_layers} layer${p.tearoff_layers===1?'':'s'})`,amount:adjustedArea*Number(s.tearoff_per_sqft)*p.tearoff_layers});
    lines.push({label:'Underlayment and required eave / ice protection',amount:adjustedArea*Number(s.underlayment_per_sqft)});
    [['vents','vent','Painting vents'],['skylights','skylight','Skylights'],['chimneys','chimney','Chimneys']].forEach(([key,rate,label])=>{if(p[key]) lines.push({label:`${label} (${p[key]})`,amount:p[key]*Number(s.addon_rates[rate])});});
    if(p.ventilation_upgrade) lines.push({label:'Ventilation system upgrade allowance',amount:Number(s.addon_rates.vent)*4});
    if(['complex','very_complex'].includes(p.complexity)) lines.push({label:'Additional flashing allowance for complex painting transitions',amount:Number(s.flashing_allowance)});
    if(p.permit) lines.push({label:'Permit handling allowance',amount:Number(s.permit_allowance)});
    let total=Math.max(Number(s.minimum_job),lines.reduce((sum,l)=>sum+l.amount,0));
    const before=lines.reduce((sum,l)=>sum+l.amount,0); if(total>before) lines.push({label:'Minimum project adjustment',amount:total-before});
    if(Number(s.include_tax)&&Number(s.tax_rate)>0){const tax=total*Number(s.tax_rate)/100; lines.push({label:`${s.tax_label} (${Number(s.tax_rate).toFixed(2)}%)`,amount:tax}); total+=tax;}
    const spread=Number(s.range_percent)/100; const calc={lines,total,low:total*(1-spread),high:total*(1+spread)};
    root.querySelector('[data-range]').textContent=`${money(calc.low)} – ${money(calc.high)}`; root.querySelector('[data-midpoint]').textContent=money(total);
    root.querySelector('[data-lines]').innerHTML=lines.map(l=>`<tr><td>${l.label}</td><td>${money(l.amount)}</td></tr>`).join('');
    root.querySelector('[data-tax-note]').textContent=Number(s.include_tax)&&Number(s.tax_rate)>0?`${s.tax_label} is included.`:`${s.tax_label} is not included.`;
    return calc;
  };
  root.addEventListener('click', e => {
    if(e.target.closest('.pcec__next')&&validate()) show(Math.min(6,step+1));
    if(e.target.closest('.pcec__back')) show(step===7?1:Math.max(1,step-1));
    if(e.target.closest('.pcec__estimate')) { if(validate()){calculate();show(7);} }
    if(e.target.closest('.pcec__print')) window.print();
  });
  form.addEventListener('submit', async e => {
    e.preventDefault(); if(testMode) return; const message=root.querySelector('.pcec__submit-message'); const submit=root.querySelector('.pcec__email'); submit.disabled=true; message.textContent='Saving your estimate…';
    const body=new FormData(form); body.set('action','pcec_submit'); body.set('nonce',config.nonce); body.set('estimate',JSON.stringify(project()));
    try { const response=await fetch(config.ajaxUrl,{method:'POST',credentials:'same-origin',body}); const result=await response.json(); if(!result.success) throw new Error(result.data?.message||'Could not send the estimate.'); message.textContent=result.data.message; if(result.data.redirect) window.location.assign(result.data.redirect); }
    catch(error){message.textContent=error.message;} finally{submit.disabled=false;}
  });
}));
