document.addEventListener('DOMContentLoaded', () => document.querySelectorAll('[data-rfec]').forEach(root => {
  const form = root.querySelector('.rfec__form');
  const config = JSON.parse(root.querySelector('.rfec__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('.rfec__step').forEach(el => el.classList.toggle('is-active', Number(el.dataset.step) === step));
    root.querySelectorAll('.rfec__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 || '', style: field('style')?.value || 'standard', area: number('roof_area'),
    pitch: field('pitch')?.value || 'standard', waste_percent: number('waste_percent'), stories: field('stories')?.value || 'two',
    complexity: field('complexity')?.value || 'average', access: field('access')?.value || 'open', tearoff_layers: number('tearoff_layers'),
    decking_sheets: number('decking_sheets'), vents: number('vents'), skylights: number('skylights'), chimneys: number('chimneys'),
    underlayment: checked('underlayment'), flashing: checked('flashing'), permit: checked('permit'), disposal: checked('disposal'),
    ventilation_upgrade: checked('ventilation_upgrade')
  });
  const validate = () => {
    const message = root.querySelector(`.rfec__step[data-step="${step}"] .rfec__validation`);
    if (step === 1 && !field('material')?.value) { if(message) message.textContent='Choose a roofing system to continue.'; return false; }
    if (step === 2 && number('roof_area') < 100) { if(message) message.textContent='Enter an estimated roof area of at least 100 sq ft.'; return false; }
    if(message) message.textContent=''; return true;
  };
  const calculate = () => {
    const p=project(), lines=[], adjustedArea=p.area*(1+p.waste_percent/100);
    const base=adjustedArea*Number(s.material_rates[p.material]||0); lines.push({label:`${config.materials[p.material]} (${Math.round(adjustedArea).toLocaleString()} sq ft incl. waste)`,amount:base});
    const envelope=(Number(s.pitch_factors[p.pitch]||1)*Number(s.profile_factors[p.style]||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, system tier, height, complexity 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});
    if(p.underlayment) lines.push({label:'Enhanced underlayment / ice protection',amount:adjustedArea*Number(s.underlayment_per_sqft)});
    if(p.decking_sheets) lines.push({label:`Decking replacement allowance (${p.decking_sheets} sheets)`,amount:p.decking_sheets*Number(s.decking_sheet)});
    [['vents','vent','Roof 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(p.flashing) lines.push({label:'Additional flashing allowance',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('.rfec__next')&&validate()) show(Math.min(6,step+1));
    if(e.target.closest('.rfec__back')) show(step===7?1:Math.max(1,step-1));
    if(e.target.closest('.rfec__estimate')) { if(validate()){calculate();show(7);} }
    if(e.target.closest('.rfec__print')) window.print();
  });
  form.addEventListener('submit', async e => {
    e.preventDefault(); if(testMode) return; const message=root.querySelector('.rfec__submit-message'); const submit=root.querySelector('.rfec__email'); submit.disabled=true; message.textContent='Saving your estimate…';
    const body=new FormData(form); body.set('action','rfec_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;}
  });
}));
