// insertion table for equal split
const insertionTable = {2:0.8,4:1.2,8:1.5,16:1.8,32:2.2};

// ratio loss table
const ratioLossTable = {
  "1:99":{M:20.2,N:0.24},"2:98":{M:17.19,N:0.29},"3:97":{M:15.43,N:0.33},
  "4:96":{M:14.18,N:0.38},"5:95":{M:13.21,N:0.42},"6:94":{M:12.42,N:0.47},
  "7:93":{M:11.75,N:0.52},"8:92":{M:11.17,N:0.56},"9:91":{M:10.66,N:0.61},
  "10:90":{M:10.2,N:0.66},"12:88":{M:9.41,N:0.76},"15:85":{M:8.44,N:0.91},
  "18:82":{M:7.65,N:1.06},"20:80":{M:7.19,N:1.16},"22:78":{M:6.78,N:1.28},
  "25:75":{M:6.22,N:1.45},"28:72":{M:5.73,N:1.63},"30:70":{M:5.43,N:1.75},
  "35:65":{M:4.76,N:2.07},"40:60":{M:4.18,N:2.42},"45:55":{M:3.71,N:2.88},
  "50:50":{M:3.21,N:3.21}
};

// generate ratio options
const raRatioSelect = typeof document !== "undefined" ? document.getElementById("raRatio") : null;
if(raRatioSelect){
  Object.keys(ratioLossTable).forEach(r => {
    const opt=document.createElement("option");
    opt.value=r;opt.textContent=r;raRatioSelect.appendChild(opt);
  });
  raRatioSelect.value="20:80";
}

// Equal split calculation
function computeEqual(){
  const input=parseFloat(document.getElementById("eqInput").value)||0;
  const N=parseInt(document.getElementById("eqSplit").value)||2;
  const ins=insertionTable[N]||0;
  const idealLoss=10*Math.log10(N);
  const totalLoss=idealLoss+ins;
  const out=input-totalLoss;
  document.getElementById("eqResult").innerHTML=`Input: ${input} dBm<br>Splitter 1:${N} (loss ${totalLoss.toFixed(2)} dB)<br><strong>Output per-port: ${out.toFixed(2)} dBm</strong>`;
}

// Ratio calculation
function computeRatio(){
  const input=parseFloat(document.getElementById("raInput").value)||0;
  const ratio=document.getElementById("raRatio").value;
  const split=parseInt(document.getElementById("raSplit").value)||2;
  const loss=ratioLossTable[ratio];

  let outM=input-loss.M;
  let outN=input-loss.N;

  const ins2=insertionTable[split]||0;
  const ideal2=10*Math.log10(split);
  const total2=ideal2+ins2;
  const outNsplit=outN-total2;

  document.getElementById("raResult").innerHTML=`Input: ${input} dBm<br>Splitter Rasio ${ratio}<br>
    <div class='result-blue'>🔹 Port Biru (M): ${outM.toFixed(2)} dBm (langsung ke pelanggan)</div>
    <div class='result-orange'>🔸 Port Orange/Merah (N): ${outN.toFixed(2)} dBm (sebelum splitter lanjutan)<br>
    ⮡ Setelah splitter 1:${split} → ${outNsplit.toFixed(2)} dBm / port</div>`;
}

// Tab switcher
if(typeof document !== "undefined"){
  const tabs=document.querySelectorAll(".tab-button");
  tabs.forEach(btn=>{
    btn.addEventListener("click",()=>{
      document.querySelectorAll(".tab-button").forEach(b=>b.classList.remove("active"));
      document.querySelectorAll(".tab-content").forEach(c=>c.classList.remove("active"));
      btn.classList.add("active");
      document.getElementById(btn.dataset.tab).classList.add("active");
    });
  });
}
