(function () {
  'use strict';
  var root = document.getElementById('htCalculator');
  if (!root) return;

  var materialRates = {
    akrilik: [{label:'3 mm', value:'3', rate:15000},{label:'5 mm', value:'5', rate:18000},{label:'10 mm', value:'10', rate:25000}],
    galvanis: [{label:'0,5 mm', value:'0.5', rate:25000},{label:'0,7 mm', value:'0.7', rate:30000}],
    stainless_hairline: [{label:'0,6 mm', value:'0.6', rate:30000},{label:'0,8 mm', value:'0.8', rate:38000}],
    stainless_mirror: [{label:'0,6 mm', value:'0.6', rate:35000},{label:'0,8 mm', value:'0.8', rate:45000}],
    kuningan: [{label:'0,6 mm', value:'0.6', rate:45000},{label:'0,8 mm', value:'0.8', rate:55000}],
    lainnya: [{label:'Harga manual', value:'manual', rate:0}]
  };
  var ids = ['htText','htCount','htHeight','htMaterial','htThickness','htFinishing','htDifficulty','htBaseRate','htLighting','htLightRate','htProduction','htInstall','htTransport','htOther','htProfitMethod','htMargin','htRounding'];
  var fields = {};
  ids.forEach(function (id) { fields[id] = document.getElementById(id); });
  var moneyIds = ['htBaseRate','htLightRate','htProduction','htInstall','htTransport','htOther'];
  var storageKey = 'kalkulator_huruf_timbul_v2';
  var restoring = false;

  function number(value) { var parsed=Number(String(value==null?'':value).replace(/[^0-9,-]/g,'').replace(',','.')); return isFinite(parsed)?parsed:0; }
  function rupiah(value) { return 'Rp'+Math.round(value||0).toLocaleString('id-ID'); }
  function countLetters(text) { return String(text||'').replace(/[^A-Za-z0-9À-ÿ]/g,'').length; }
  function formatMoney(input) { input.value=Math.round(number(input.value)).toLocaleString('id-ID'); }
  function valueOf(id) { return number(fields[id].value); }
  function selectedText(select) { return select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '-'; }

  function populateThickness(savedValue) {
    var choices=materialRates[fields.htMaterial.value]||materialRates.lainnya;
    fields.htThickness.innerHTML='';
    choices.forEach(function(item){ var option=document.createElement('option'); option.value=item.value; option.textContent=item.label; option.dataset.rate=item.rate; fields.htThickness.appendChild(option); });
    if (savedValue && choices.some(function(item){return item.value===savedValue;})) fields.htThickness.value=savedValue;
    updateRecommendedRate();
  }
  function updateRecommendedRate() {
    var option=fields.htThickness.options[fields.htThickness.selectedIndex];
    var rate=option?number(option.dataset.rate):0;
    if (rate>0) { fields.htBaseRate.value=Math.round(rate).toLocaleString('id-ID'); fields.htBaseRate.readOnly=false; }
    fields.htBaseRate.readOnly=false;
    calculate();
  }

  function calculate() {
    var count=Math.max(1,Math.round(valueOf('htCount'))), height=Math.max(0,valueOf('htHeight')), baseRate=valueOf('htBaseRate');
    var baseLetterCost=count*height*baseRate;
    var finishingRate=Math.max(0,valueOf('htFinishing'))/100, difficultyRate=Math.max(0,valueOf('htDifficulty'))/100;
    var finishingCost=baseLetterCost*finishingRate, difficultyCost=baseLetterCost*difficultyRate;
    var letterCost=baseLetterCost+finishingCost+difficultyCost;
    var lightCost=fields.htLighting.value==='0'?0:count*valueOf('htLightRate');
    var production=valueOf('htProduction'), install=valueOf('htInstall'), transport=valueOf('htTransport'), other=valueOf('htOther');
    var subtotal=letterCost+lightCost+production+install+transport+other;
    var percent=Math.max(0,Math.min(99,valueOf('htMargin')))/100;
    var rawTotal=fields.htProfitMethod.value==='margin' ? subtotal/(1-percent) : subtotal*(1+percent);
    var rounding=Math.max(1,valueOf('htRounding')), total=Math.ceil(rawTotal/rounding)*rounding, profit=total-subtotal;

    document.getElementById('htJobName').textContent=fields.htText.value.trim()||'TANPA NAMA PEKERJAAN';
    document.getElementById('htSpecSummary').textContent=count+' huruf • '+height+' cm';
    document.getElementById('htMaterialSummary').textContent=selectedText(fields.htMaterial)+' • '+selectedText(fields.htThickness);
    document.getElementById('htProfitHint').textContent=fields.htProfitMethod.value==='margin'
      ? 'Margin adalah persentase keuntungan dari harga jual akhir.'
      : 'Markup adalah persentase tambahan yang dihitung dari HPP.';
    document.getElementById('htLetterCost').textContent=rupiah(letterCost);
    document.getElementById('htLightCost').textContent=rupiah(lightCost);
    document.getElementById('htProductionCost').textContent=rupiah(production);
    document.getElementById('htInstallCost').textContent=rupiah(install);
    document.getElementById('htTransportCost').textContent=rupiah(transport);
    document.getElementById('htOtherCost').textContent=rupiah(other);
    document.getElementById('htSubtotal').textContent=rupiah(subtotal);
    document.getElementById('htProfit').textContent=rupiah(profit);
    document.getElementById('htGrandTotal').textContent=rupiah(total);
    document.getElementById('htPerLetter').textContent=rupiah(total/count);
    var additions=[];
    if(finishingRate) additions.push('finishing '+(finishingRate*100)+'%');
    if(difficultyRate) additions.push('kesulitan '+(difficultyRate*100)+'%');
    document.getElementById('htFormula').textContent=count+' huruf × '+height+' cm × '+rupiah(baseRate)+' = '+rupiah(baseLetterCost)+(additions.length?' + '+additions.join(' + ')+' = '+rupiah(letterCost):'')+'. '+selectedText(fields.htProfitMethod)+' '+(percent*100)+'%.';
    if(!restoring) save();
  }
  function save(){ try{var data={}; ids.forEach(function(id){data[id]=fields[id].value;}); localStorage.setItem(storageKey,JSON.stringify(data));}catch(e){} }
  function restore(){
    restoring=true;
    var data={}; try{data=JSON.parse(localStorage.getItem(storageKey)||'{}');}catch(e){}
    if(data.htMaterial) fields.htMaterial.value=data.htMaterial;
    populateThickness(data.htThickness);
    ids.forEach(function(id){if(id!=='htMaterial'&&id!=='htThickness'&&Object.prototype.hasOwnProperty.call(data,id)) fields[id].value=data[id];});
    restoring=false;
  }

  restore();
  moneyIds.forEach(function(id){fields[id].addEventListener('input',function(){formatMoney(fields[id]);calculate();});formatMoney(fields[id]);});
  ids.filter(function(id){return moneyIds.indexOf(id)===-1;}).forEach(function(id){fields[id].addEventListener('input',calculate);fields[id].addEventListener('change',calculate);});
  fields.htText.addEventListener('input',function(){var count=countLetters(fields.htText.value);if(count>0)fields.htCount.value=count;calculate();});
  fields.htMaterial.addEventListener('change',function(){populateThickness();});
  fields.htThickness.addEventListener('change',updateRecommendedRate);
  fields.htLighting.addEventListener('change',function(){fields.htLightRate.disabled=fields.htLighting.value==='0';calculate();});
  document.getElementById('htReset').addEventListener('click',function(){if(!window.confirm('Reset seluruh nilai Kalkulator Huruf Timbul?'))return;localStorage.removeItem(storageKey);window.location.reload();});
  document.getElementById('htPrint').addEventListener('click',function(){window.print();});
  fields.htLightRate.disabled=fields.htLighting.value==='0';
  calculate();
})();
