document.addEventListener('DOMContentLoaded',()=>document.querySelectorAll('[data-pcec]').forEach(root=>{
  const form=root.querySelector('.pcec__form'),config=JSON.parse(root.querySelector('.pcec__config').textContent),s=config.settings,testMode=config.mode==='test',bothServices=s.service_scope==='both',firstStep=bothServices?1:2,totalSteps=bothServices?6:5;let step=firstStep;
  const field=n=>form.elements.namedItem(n),num=n=>Math.max(0,Number(field(n)?.value||0)),checked=n=>Boolean(field(n)?.checked),value=n=>field(n)?.value||'';
  const money=n=>`${s.currency_symbol}${Math.round(n).toLocaleString()} ${s.currency}`;
  const regional=text=>s.language==='en_US'?String(text).replaceAll('Colours','Colors').replaceAll('colours','colors').replaceAll('Colour','Color').replaceAll('colour','color').replaceAll('Storeys','Stories').replaceAll('storeys','stories').replaceAll('Storey','Story').replaceAll('storey','story').replaceAll('Moulding','Molding').replaceAll('moulding','molding'):String(text);
  const projectType=()=>bothServices?(value('project_type')||'interior'):(s.service_scope==='exterior'?'exterior':'interior');
  const rooms=()=>Array.from(root.querySelectorAll('.pcec__room')).map((row,i)=>{const get=n=>row.querySelector(`[data-room-field="${n}"]`);return{name:get('name').value||`Room ${i+1}`,length:Number(get('length').value||0),width:Number(get('width').value||0),height:get('height').value,type:get('type').value,accent:Boolean(get('accent')?.checked)};}).filter(r=>r.length>0&&r.width>0);
  const specialty=()=>Array.from(form.querySelectorAll('input[name="specialty"]:checked')).filter(el=>el.closest(projectType()==='interior'?'.pcec__interior':'.pcec__exterior')).map(el=>el.value);
  const project=()=>{const exterior=projectType()==='exterior';return{project_type:projectType(),rooms:rooms(),walls:checked('walls'),ceilings:checked('ceilings'),trim:checked('trim'),baseboards:checked('baseboards'),door_casings:checked('door_casings'),window_casings:checked('window_casings'),crown:checked('crown'),door_slabs:checked('door_slabs'),doors:num('doors'),windows:num('windows'),crown_length:num('crown_length'),interior_doors:num('interior_doors'),accent_walls:rooms().filter(room=>room.accent).length,condition:value('condition')||'normal',occupancy:value('occupancy')||'empty',colours:value(exterior?'exterior_colours':'colours')||'one',colour_change:value(exterior?'exterior_colour_change':'colour_change')||'similar',stairwell:value('stairwell')||'none',premium:checked(exterior?'premium_exterior':'premium'),specialty:specialty(),exterior_area:num('exterior_area'),exterior_storeys:value('exterior_storeys')||'two',exterior_surface:value('exterior_surface')||'vinyl_metal',exterior_access:value('exterior_access')||'easy',exterior_doors:num('exterior_doors'),garage_doors:num('garage_doors')};};
  const addRoom=()=>{const list=root.querySelector('[data-rooms]');if(list.children.length>=12)return;list.append(root.querySelector('[data-room-template]').content.cloneNode(true));updateRoomSummary();};
  const updateRoomSummary=()=>{const rs=rooms(),wall=rs.reduce((sum,r)=>{const h={h8:8,h9:9,h10:10,h11_12:11.5,vaulted:12}[r.height]||8;return sum+2*(r.length+r.width)*h;},0);root.querySelector('[data-room-summary]').textContent=rs.length?`${rs.length} room${rs.length===1?'':'s'} · approximately ${Math.round(wall).toLocaleString()} sq. ft. of wall surface`:'';root.querySelectorAll('.pcec__remove-room').forEach(b=>b.hidden=root.querySelectorAll('.pcec__room').length===1);};
  addRoom();
  const updateTrimOptions=()=>{const options=root.querySelector('[data-trim-options]');if(options)options.hidden=projectType()!=='interior'||!checked('trim');};
  updateTrimOptions();
  root.addEventListener('input',e=>{if(e.target.closest('.pcec__room'))updateRoomSummary();});
  root.addEventListener('change',e=>{if(e.target.matches('input[name="trim"]'))updateTrimOptions();});
  root.addEventListener('click',e=>{if(e.target.closest('.pcec__add-room'))addRoom();const remove=e.target.closest('.pcec__remove-room');if(remove){remove.closest('.pcec__room').remove();updateRoomSummary();}});
  const show=n=>{step=n;root.querySelectorAll('.pcec__step').forEach(el=>{let active=Number(el.dataset.step)===n;if(active&&n===2)active=el.classList.contains(`pcec__${projectType()}`);el.classList.toggle('is-active',active);});root.querySelectorAll('.pcec__interior').forEach(el=>{if(!el.classList.contains('pcec__step')&&!el.hasAttribute('data-trim-options'))el.hidden=projectType()!=='interior';});root.querySelectorAll('.pcec__exterior').forEach(el=>{if(!el.classList.contains('pcec__step'))el.hidden=projectType()!=='exterior';});updateTrimOptions();const visibleStep=bothServices?n:n-1;root.querySelectorAll('.pcec__progress span').forEach((el,i)=>el.classList.toggle('is-active',i<Math.min(visibleStep,totalSteps)));root.scrollIntoView({behavior:'smooth',block:'start'});};
  const validate=()=>{const active=Array.from(root.querySelectorAll('.pcec__step.is-active'))[0],message=active?.querySelector('.pcec__validation');let error='';if(bothServices&&step===1&&!value('project_type'))error='Choose interior or exterior painting to continue.';if(step===2&&projectType()==='interior'&&!rooms().length)error='Enter the length and width for at least one room.';if(step===2&&projectType()==='exterior'&&num('exterior_area')<100)error='Enter an approximate home size of at least 100 sq. ft.';if(step===3&&projectType()==='interior'&&!checked('walls')&&!checked('ceilings')&&!checked('trim'))error='Choose at least one surface to paint.';if(message)message.textContent=error;return!error;};
  const calculate=()=>{const p=project(),lines=[],add=(label,amount,fixed=false)=>{if(amount>0)lines.push({label:regional(label),amount,fixed});};let minimum=0;
    if(p.project_type==='interior'){let walls=0,ceilings=0,trim=0,heightExtra=0;p.rooms.forEach(r=>{const h={h8:8,h9:9,h10:10,h11_12:11.5,vaulted:12}[r.height]||8,perimeter=2*(r.length+r.width),rw=perimeter*h*Number(s.interior_wall_rate),rc=r.length*r.width*Number(s.ceiling_rate);if(p.walls)walls+=rw;if(p.ceilings)ceilings+=rc;if(p.trim&&p.baseboards)trim+=perimeter*Number(s.trim_rate);heightExtra+=((p.walls?rw:0)+(p.ceilings?rc:0))*Number(s.height_adjustments[r.height]||0)/100;});add('Interior wall painting',walls);add('Ceiling painting',ceilings);add('Baseboards',trim);const base=walls+ceilings+trim;add('Ceiling height and access',heightExtra);add('Surface preparation',base*Number(s.condition_adjustments[p.condition]||0)/100);add('Work-space protection',base*Number(s.occupancy_adjustments[p.occupancy]||0)/100);add('Multiple colours',base*Number(s.colour_adjustments[p.colours]||0)/100);add('Colour coverage allowance',(walls+ceilings)*Number(s.colour_change_adjustments[p.colour_change]||0)/100);if(p.trim&&p.door_casings)add('Door frames and casings',p.doors*Number(s.door_rate),true);if(p.trim&&p.window_casings)add('Window casings',p.windows*Number(s.window_casing_rate),true);if(p.trim&&p.crown)add('Crown moulding',p.crown_length*Number(s.crown_rate),true);if(p.trim&&p.door_slabs)add('Interior door slabs',p.interior_doors*Number(s.interior_door_rate),true);add('Accent walls',p.accent_walls*Number(s.accent_wall_rate),true);if(p.stairwell==='one')add('One-storey stairwell',Number(s.one_storey_stairwell),true);if(p.stairwell==='two')add('Two-storey stairwell',Number(s.two_storey_stairwell),true);if(p.premium)add('Premium paint allowance',base*Number(s.premium_adjustment)/100);minimum=Number(s.minimum_interior);
    }else{const base=p.exterior_area*Number(s.exterior_rate);add('Exterior painting',base);add('Exterior surface adjustment',base*Number(s.exterior_surface_adjustments[p.exterior_surface]||0)/100);add('Storey and height access',base*Number(s.exterior_storey_adjustments[p.exterior_storeys]||0)/100);add('Site accessibility',base*Number(s.exterior_access_adjustments[p.exterior_access]||0)/100);add('Surface preparation',base*Number(s.condition_adjustments[p.condition]||0)/100);add('Multiple colours',base*Number(s.colour_adjustments[p.colours]||0)/100);add('Colour coverage allowance',base*Number(s.colour_change_adjustments[p.colour_change]||0)/100);add('Exterior doors',p.exterior_doors*Number(s.exterior_door_rate),true);add('Garage doors',p.garage_doors*Number(s.garage_door_rate),true);if(p.premium)add('Premium exterior coating allowance',base*Number(s.premium_adjustment)/100);minimum=Number(s.minimum_exterior);}
    let total=lines.reduce((sum,l)=>sum+l.amount,0);if(total<minimum){add('Minimum project allowance',minimum-total,true);total=minimum;}const spread=Number(s.estimate_range)/100;lines.forEach(l=>{l.low=l.fixed?l.amount:l.amount*(1-spread);l.high=l.fixed?l.amount:l.amount*(1+spread);});let low=lines.reduce((sum,l)=>sum+l.low,0),high=lines.reduce((sum,l)=>sum+l.high,0);if(Number(s.include_tax)&&Number(s.tax_rate)>0){const rate=Number(s.tax_rate)/100,tax={label:`${s.tax_label} (${Number(s.tax_rate).toFixed(2)}%)`,amount:total*rate,low:low*rate,high:high*rate};lines.push(tax);total+=tax.amount;low+=tax.low;high+=tax.high;}root.querySelector('[data-range]').textContent=`${money(low)} – ${money(high)}`;root.querySelector('[data-midpoint]').textContent=money(total);root.querySelector('[data-lines]').innerHTML=lines.map(l=>`<tr><td>${l.label}</td><td>${l.fixed||Math.abs(l.high-l.low)<1?money(l.amount):`${money(l.low)} – ${money(l.high)}`}</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.`;root.querySelector('[data-specialty-note]').hidden=!p.specialty.length;return{lines,total,low,high};};
  root.addEventListener('click',e=>{if(e.target.closest('.pcec__next')&&validate())show(Math.min(5,step+1));if(e.target.closest('.pcec__back'))show(Math.max(firstStep,step-1));if(e.target.closest('.pcec__estimate')&&validate()){calculate();show(6);}if(e.target.closest('.pcec__edit'))show(2);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'),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}),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;}});
  show(firstStep);
}));


