(function(){
  const money = n => (Number(n)||0).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
  const num = el => Number(el && el.value ? el.value : 0);
  const products = window.FQS_PRODUCTS || [];

  function initMethods(){
    const system = document.getElementById('systemType');
    const method = document.getElementById('calculationMethod');
    if(!system || !method) return;
    const current = method.dataset.current || document.querySelector('[name="calculation_method"]')?.value || '';
    const map = {
      'On-Grid Solar System':['Peak Load','Monthly Electricity Bill'],
      'Off-Grid Solar System':['Load Calculation','Monthly Electricity Bill'],
      'Hybrid Solar System':['Load Calculation','Monthly Electricity Bill'],
      'Solar Water Pumping System':['Water Pumping']
    };
    function render(){
      const old = method.value || current;
      method.innerHTML = '';
      (map[system.value] || []).forEach(v => {
        const o = document.createElement('option'); o.value = v; o.textContent = v; o.selected = old === v; method.appendChild(o);
      });
      updateBlocks();
    }
    system.addEventListener('change', render);
    method.addEventListener('change', updateBlocks);
    render();
  }

  function updateBlocks(){
    const method = document.getElementById('calculationMethod')?.value || '';
    document.querySelectorAll('.calc-block').forEach(b => b.style.display = b.dataset.method === method ? '' : 'none');
    const sys = document.getElementById('systemType')?.value || '';
    const sumSystem = document.getElementById('sumSystem');
    const sumMethod = document.getElementById('sumMethod');
    if(sumSystem) sumSystem.textContent = sys.replace(' Solar System','');
    if(sumMethod) sumMethod.textContent = method;
    calcAll();
  }

  function reindex(tableId, group){
    const rows = document.querySelectorAll(`#${tableId} tbody tr`);
    rows.forEach((tr,i)=>{
      const sl = tr.querySelector('.sl'); if(sl) sl.textContent = i+1;
      tr.querySelectorAll('input,select,textarea').forEach(el => {
        if(el.name) el.name = el.name.replace(new RegExp(`${group}\\[\\d+\\]`), `${group}[${i}]`);
      });
    });
  }

  function cloneRow(tableId, group, custom){
    const tbody = document.querySelector(`#${tableId} tbody`);
    if(!tbody || !tbody.rows.length) return;
    const tr = tbody.rows[tbody.rows.length-1].cloneNode(true);
    tr.querySelectorAll('input').forEach(i => {
      if(i.type === 'hidden') i.value = custom ? '1' : '0';
      else if(i.type === 'number') i.value = i.classList.contains('qty') ? '1' : '0';
      else i.value = '';
    });
    tr.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
    tr.dataset.custom = custom ? '1' : '0';
    tbody.appendChild(tr); reindex(tableId, group); calcAll();
  }

  function fillProduct(tr, id){
    const p = products.find(x => String(x.id) === String(id));
    if(!p) return;
    tr.querySelector('.category').value = p.product_category;
    tr.querySelector('.product-name').value = p.product_name;
    tr.querySelector('.description').value = p.description || '';
    tr.querySelector('.brand').value = p.brand || '';
    tr.querySelector('.model').value = p.model || '';
    tr.querySelector('.unit').value = p.unit || 'pcs';
    tr.querySelector('.unit-price').value = p.unit_price || 0;
    tr.querySelector('.custom-flag').value = 0;
    calcAll();
  }

  function calcLoads(){
    let connected = 0, energy = 0;
    document.querySelectorAll('#loadTable tbody tr').forEach(tr => {
      const inputs = tr.querySelectorAll('.load-num');
      const qty = num(inputs[0]), watt = num(inputs[1]), backup = num(inputs[2]);
      const total = qty*watt, wh = total*backup;
      connected += total; energy += wh;
      tr.querySelector('.total-watt').textContent = money(total);
      tr.querySelector('.watt-hour').textContent = money(wh);
    });
    const inv = connected*1.25, batteryWh = energy*1.25, batteryAh = batteryWh/12, panel = energy/4.5*1.25;
    setText('connectedLoad', money(connected)+' W'); setText('energyNeed', money(energy)+' Wh'); setText('loadInverter', money(inv)+' VA'); setText('loadBattery', money(batteryAh)+' Ah'); setText('loadPanel', money(panel)+' W');
    if(document.getElementById('calculationMethod')?.value === 'Load Calculation'){ setText('suggestInverter', money(inv)+' VA'); setText('suggestBattery', money(batteryAh)+' Ah'); setText('suggestPanel', money(panel)+' W'); }
  }

  function calcBill(){
    const bill = num(document.getElementById('monthlyBill')), rate = num(document.getElementById('electricityRate')), sun = num(document.getElementById('sunHour')) || 4.5;
    const monthly = rate ? bill/rate : 0, daily = monthly/30, solar = sun ? daily/sun : 0;
    setText('monthlyUnits', money(monthly)); setText('dailyUnits', money(daily)); setText('billSolar', money(solar)+' kW');
    if(document.getElementById('calculationMethod')?.value === 'Monthly Electricity Bill'){ setText('suggestInverter', money(solar)+' kW'); setText('suggestBattery','If applicable'); setText('suggestPanel', money(solar)+' kW'); }
  }

  function calcPeak(){
    const peak = num(document.getElementById('peakLoad')), safety = num(document.getElementById('safetyFactor')) || 25, kw = peak*(1+safety/100);
    setText('peakInverter', money(kw)+' kW'); setText('peakPanel', money(kw)+' kW');
    if(document.getElementById('calculationMethod')?.value === 'Peak Load'){ setText('suggestInverter', money(kw)+' kW'); setText('suggestBattery','N/A'); setText('suggestPanel', money(kw)+' kW'); }
  }

  function calcPump(){
    const hp = num(document.getElementById('pumpHp')), kw = hp*.746, panel = kw*1.5, inv = kw*1.25;
    setText('pumpPanel', money(panel)+' kW'); setText('pumpInverter', money(inv)+' kW');
    if(document.getElementById('calculationMethod')?.value === 'Water Pumping'){ setText('suggestInverter', money(inv)+' kW'); setText('suggestBattery','N/A'); setText('suggestPanel', money(panel)+' kW'); }
  }

  function calcItems(){
    let subtotal = 0;
    document.querySelectorAll('#productTable tbody tr').forEach(tr => {
      const total = num(tr.querySelector('.qty')) * num(tr.querySelector('.unit-price'));
      subtotal += total; tr.querySelector('.item-total').textContent = money(total);
    });
    const vat = subtotal * (num(document.getElementById('vatPercent'))/100);
    const grand = Math.max(0, subtotal + vat - num(document.getElementById('discountAmount')));
    setText('subtotalView', money(subtotal)); setText('vatView', money(vat)); setText('grandView', money(grand)); setText('suggestCost', money(grand));
    setVal('subtotalInput', subtotal); setVal('vatAmountInput', vat); setVal('grandTotalInput', grand);
  }

  function setText(id, text){ const el = document.getElementById(id); if(el) el.textContent = text; }
  function setVal(id, value){ const el = document.getElementById(id); if(el) el.value = value.toFixed(2); }
  function calcAll(){ calcLoads(); calcBill(); calcPeak(); calcPump(); calcItems(); reindex('productTable','items'); reindex('loadTable','loads'); }

  document.addEventListener('input', e => { if(e.target.matches('.load-num,.item-num,#vatPercent,#discountAmount,.bill-calc,.peak-calc,.pump-calc')) calcAll(); });
  document.addEventListener('change', e => { if(e.target.matches('.product-select')) fillProduct(e.target.closest('tr'), e.target.value); });
  document.addEventListener('click', e => {
    const rem = e.target.closest('.remove-row');
    if(rem){ const tr = rem.closest('tr'), tbody = tr.parentElement; if(tbody.rows.length > 1) tr.remove(); calcAll(); }
    if(e.target.closest('#addLoad')) cloneRow('loadTable','loads',false);
    if(e.target.closest('#addProduct')) cloneRow('productTable','items',false);
    if(e.target.closest('#addCustom')) cloneRow('productTable','items',true);
  });
  document.getElementById('quotationForm')?.addEventListener('submit', e => {
    const hasCustomer = document.getElementById('customerSelect')?.value || document.querySelector('[name="customer_name"]')?.value.trim();
    if(!hasCustomer){ e.preventDefault(); alert('Please select or enter customer information.'); return; }
    calcAll();
  });
  const chart = document.getElementById('monthlyChart');
  if(chart && window.Chart){ new Chart(chart,{type:'bar',data:{labels:JSON.parse(chart.dataset.labels||'[]'),datasets:[{label:'Monthly quotation amount',data:JSON.parse(chart.dataset.values||'[]'),backgroundColor:'#0b7a34'}]},options:{plugins:{legend:{display:false}},scales:{y:{beginAtZero:true}}}}); }
  initMethods(); calcAll();
})();
