// controls.js — Volume (L), Temperature (K), moles

window.simulationParams = {
  T: 300,
  V: 0.5,
  nA: 0.00,
  nB: 0.00,
  nG: 0.00,
  atomSize: 5
};

window.thermoState = {
  isExothermic: true,
  showKc: false,
  showQc: false       
};

window.kineticsState = {
  catalyst: false,
  inert: false
};

document.querySelectorAll('input[name="catalystMode"]').forEach(radio => {
  radio.addEventListener("change", e => {
    window.kineticsState.catalyst = (e.target.value === "on");
    updateVessel();   // ⬅️ ΥΠΟΧΡΕΩΤΙΚΟ
  });
});



const emptyBtn = document.getElementById("emptyBtn");
if (emptyBtn) {
  emptyBtn.addEventListener("pointerdown", e => {
    e.preventDefault();

    if (window.ParticlesSim?.setRunning)
      window.ParticlesSim.setRunning(false);

    window.simulationParams.nA = 0;
    window.simulationParams.nB = 0;
    window.simulationParams.nG = 0;

    if (window.ParticlesSim?.reset)
      window.ParticlesSim.reset({ keepInventory:false });

    
    setTimeout(() => {
      window._lastQcValue = null;
      updateQcDisplay(null);
    }, 0);
  });
}








// staged values (what will be added)
window.stagedMoles = { A:0, B:0, G:0 };

document.querySelectorAll('input[name="thermoType"]').forEach(radio=>{
  radio.addEventListener("change", e=>{
    window.thermoState.isExothermic = (e.target.value === "exo");

    const emptyBtn = document.getElementById("emptyBtn");
    if (emptyBtn) {
      emptyBtn.dispatchEvent(new PointerEvent("pointerdown"));
    }

  
    window._lastQcValue = null;
    updateQcDisplay(null);

    window.dispatchEvent(new Event("thermochange"));
    updateKcDisplay();
  });
});






const showKcChk = document.getElementById("showKcChk");
const kcBox = document.getElementById("kcBox");

if (showKcChk) {
showKcChk.addEventListener("change", e=>{
  window.thermoState.showKc = e.target.checked;
  updateKcDisplay();
});

}

const showQcChk = document.getElementById("showQcChk");

if (showQcChk) {
  showQcChk.addEventListener("change", e => {
    window.thermoState.showQc = e.target.checked;
    updateQcDisplay(window._lastQcValue ?? null);
  });
}



const optionsBtn   = document.getElementById("optionsBtn");
const optionsPanel = document.getElementById("optionsPanel");

if (optionsBtn && optionsPanel) {
optionsBtn.addEventListener("pointerdown", e => {
  e.preventDefault();
  optionsPanel.classList.toggle("hidden");
});

}


const fullscreenBtn = document.getElementById("fullscreenBtn");

fullscreenBtn.addEventListener("pointerdown", e => {
  e.preventDefault();
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
  } else {
    document.exitFullscreen();
  }
});


function setControlsLocked(locked){

  /* =========================
     PANEL – ΧΗΜΙΚΕΣ ΜΕΤΑΒΟΛΕΣ
  ========================= */

  // Βέλη steppers (▲ ▼)
  document
    .querySelectorAll("#panel .arrow")
    .forEach(el => el.classList.toggle("disabled", locked));

  // Προσθήκη / Αφαίρεση
  ["addBtn","removeBtn"].forEach(id=>{
    const el = document.getElementById(id);
    if(el) el.classList.toggle("disabled", locked);
  });

  // ΆΔΕΙΑΣΜΑ → ΚΛΕΙΔΩΜΕΝΟ ΟΤΑΝ ΤΡΕΧΕΙ
  const emptyBtn = document.getElementById("emptyBtn");
  if (emptyBtn) emptyBtn.classList.toggle("disabled", locked);

  // ❗ startBtn ΔΕΝ αγγίζεται ΠΟΤΕ

  /* =========================
     OPTIONS PANEL
  ========================= */

  // Radio & checkbox (exo/endo, Kc)
  document
    .querySelectorAll("#optionsPanel input")
    .forEach(el=>{
      el.disabled = locked;
      el.classList.toggle("disabled", locked);
    });
      // Radio καταλύτη (κλειδωμένο όσο τρέχει η προσομοίωση)
  document
    .querySelectorAll('input[name="catalystMode"]')
    .forEach(el => {
      el.disabled = locked;
      el.classList.toggle("disabled", locked);
    });
      // Radio αδρανούς αερίου (κλειδωμένο όσο τρέχει η προσομοίωση)
  document
    .querySelectorAll('input[name="inertMode"]')
    .forEach(el => {
      el.disabled = locked;
      el.classList.toggle("disabled", locked);
    });


}


const helpBtn = document.getElementById("helpBtn");

if(helpBtn){
helpBtn.addEventListener("pointerdown", e => {
  e.preventDefault();
  window.open("files/system/help.html", "_blank");
});

}


function updateKcDisplay(){
  const kcValEl = document.getElementById("kcValue");
  const kcBox   = document.getElementById("kcBox");

  if (!kcValEl || !kcBox) return;

  if (!window.thermoState.showKc) {
    kcBox.style.display = "none";
    return;
  }

  const T = window.simulationParams.T;

  // ΜΙΑ ΠΗΓΗ ΑΛΗΘΕΙΑΣ
  kcValEl.textContent = window.KcFromT(T).toFixed(2);
  kcBox.style.display = "block";
}

function updateQcDisplay(qc){
  const qcValEl = document.getElementById("qcValue");
  const qcBox   = document.getElementById("qcBox");
  if (!qcValEl || !qcBox) return;

  // αποθήκευση τελευταίας τιμής
  window._lastQcValue = qc;

  if (!window.thermoState.showQc) {
    qcBox.style.display = "none";
    return;
  }

  if (qc === null || !isFinite(qc)) {
    qcValEl.textContent = "—";
  } else {
    qcValEl.textContent = qc.toFixed(2);
  }

  qcBox.style.display = "block";
}

window.updateQcDisplay = updateQcDisplay;


// ⬅️ ΚΑΝ' ΤΟ GLOBAL
window.updateQcDisplay = updateQcDisplay;



function makeStepper({valueEl, upBtn, downBtn, values, decimals=0, onChange}){
  let idx = 0;

  function snapIndexFromValue(v){
    let best = 0, bestErr = Infinity;
    for(let i=0;i<values.length;i++){
      const err = Math.abs(values[i]-v);
      if(err < bestErr){ bestErr = err; best = i; }
    }
    return best;
  }

  function render(){
    valueEl.textContent = values[idx].toFixed(decimals);
    if(onChange) onChange(values[idx]);
  }

  function setValue(v){
    idx = snapIndexFromValue(+v || 0);
    render();
  }






  // init from displayed legend value
  setValue(parseFloat(valueEl.textContent));

upBtn.addEventListener("pointerdown", e=>{
  e.preventDefault();
  if(idx < values.length-1){ idx++; render(); }
});

downBtn.addEventListener("pointerdown", e=>{
  e.preventDefault();
  if(idx > 0){ idx--; render(); }
});


  // expose controller for external resets
  valueEl._stepper = { setValue };
}


window.addEventListener("load", ()=>{

  const rows = document.querySelectorAll("#panel .row.compact");

  const rowVT = rows[0];
  const vtValues = rowVT.querySelectorAll(".value");
  const vtArrows = rowVT.querySelectorAll(".arrow");


const removeBtn = document.getElementById("removeBtn");
if(removeBtn){
  removeBtn.addEventListener("pointerdown", e => {
  e.preventDefault();

    // πάγωμα
    if(window.ParticlesSim?.setRunning) window.ParticlesSim.setRunning(false);

    const dA = window.stagedMoles?.A || 0;
    const dB = window.stagedMoles?.B || 0;
    const dG = window.stagedMoles?.G || 0;

    // ενημέρωση totals (με clamp στο 0)
    window.simulationParams.nA = Math.max(0, (window.simulationParams.nA || 0) - dA);
    window.simulationParams.nB = Math.max(0, (window.simulationParams.nB || 0) - dB);
    window.simulationParams.nG = Math.max(0, (window.simulationParams.nG || 0) - dG);

    // αφαίρεση στο simulation
    if(window.ParticlesSim?.removeMoles){
      window.ParticlesSim.removeMoles(dA, dB, dG);
    }

    // μηδένισε τα steppers όπως στην προσθήκη
    const rows = document.querySelectorAll("#panel .row.compact");
    const rowAB = rows[1];
    if(rowAB){
      const vals = rowAB.querySelectorAll(".value");
      if(vals[0]?._stepper) vals[0]._stepper.setValue(0);
      if(vals[1]?._stepper) vals[1]._stepper.setValue(0);
    }
    const rowG = Array.from(rows).find(r => r.textContent.includes("nΓ"));
    if(rowG){
      const vg = rowG.querySelector(".value");
      if(vg?._stepper) vg._stepper.setValue(0);
    }
    window.stagedMoles = {A:0,B:0,G:0};
 });

}





  // Volume (L)
  makeStepper({
    valueEl: vtValues[0],
    upBtn: vtArrows[0],
    downBtn: vtArrows[1],
    values: [0.5,0.6,0.7,0.8,0.9,1.0],
    decimals: 3,
    onChange: v => {
      window.simulationParams.V = v;
      if(window.updateVessel) window.updateVessel();
      // adapt current microstate to new volume (no reset)
      if(window.ParticlesSim?.adaptVolume){
        requestAnimationFrame(()=>window.ParticlesSim.adaptVolume());
      }
    }
  });

  // Temperature (K)
  makeStepper({
    valueEl: vtValues[1],
    upBtn: vtArrows[2],
    downBtn: vtArrows[3],
    values: [300,310,320,330,340,350],
    decimals: 0,
onChange: v => {
  window.simulationParams.T = v;
  if(window.ParticlesSim?.adaptTemperature){
    window.ParticlesSim.adaptTemperature();
  }
  updateKcDisplay();   // ⬅️ ΝΕΟ
}

  });

  const rowN = rows[1];
  const nValues = rowN.querySelectorAll(".value");
  const nArrows = rowN.querySelectorAll(".arrow");

    const molSteps = [0.000, 0.050, 0.100, 0.150, 0.200];


  makeStepper({
    valueEl: nValues[0],
    upBtn: nArrows[0],
    downBtn: nArrows[1],
    values: molSteps,
    decimals: 3,
    onChange: v => window.stagedMoles.A = v
  });

  makeStepper({
    valueEl: nValues[1],
    upBtn: nArrows[2],
    downBtn: nArrows[3],
    values: molSteps,
    decimals: 3,
    onChange: v => window.stagedMoles.B = v
  });


  // Γ
  const rowG = Array.from(document.querySelectorAll("#panel .row.compact"))
    .find(r => r.textContent.includes("nΓ"));
  if(rowG){
    const gValue = rowG.querySelector(".value");
    const gArrows = rowG.querySelectorAll(".arrow");
    makeStepper({
      valueEl: gValue,
      upBtn: gArrows[0],
      downBtn: gArrows[1],
      values: molSteps,
      decimals: 3,
      onChange: v => window.stagedMoles.G = v
    });
  }
});


window.addEventListener("load", ()=>{
  const addBtn = document.getElementById("addBtn");
  if(!addBtn) return;

  addBtn.addEventListener("pointerdown", e => {
  e.preventDefault();

    // freeze time (pause reaction), but DO NOT reset V or T
    if(window.ParticlesSim?.setRunning) window.ParticlesSim.setRunning(false);

    const dA = window.stagedMoles.A || 0;
    const dB = window.stagedMoles.B || 0;
    const dG = window.stagedMoles.G || 0;

    // update totals in simulationParams (state of "vessel inventory")
    window.simulationParams.nA += dA;
    window.simulationParams.nB += dB;
    window.simulationParams.nG += dG;

    // add particles without recreating vessel; also re-baseline ICE at current time
    window._addingNow = true;
    if(window.ParticlesSim?.addMoles){
      window.ParticlesSim.addMoles(dA, dB, dG);
    } else if(window.ParticlesSim?.reset){
      // fallback (older builds)
      window.ParticlesSim.reset();
    }

    

    
// clear ONLY the staged mol inputs (and internal stepper state)
const rows = document.querySelectorAll("#panel .row.compact");
const rowAB = rows[1];
if(rowAB){
  const vals = rowAB.querySelectorAll(".value");
  if(vals[0]?._stepper) vals[0]._stepper.setValue(0);
  if(vals[1]?._stepper) vals[1]._stepper.setValue(0);
}
const rowG = rows[2];
if(rowG){
  const vg = rowG.querySelector(".value");
  if(vg?._stepper) vg._stepper.setValue(0);
}
window.stagedMoles = {A:0,B:0,G:0};

  });

  updateKcDisplay();

});

document.querySelectorAll('input[name="catalystMode"]').forEach(radio => {
  radio.addEventListener("change", e => {
    window.kineticsState.catalyst = (e.target.value === "on");
  });
});

document.querySelectorAll('input[name="inertMode"]').forEach(radio => {
  radio.addEventListener("change", e => {
    window.kineticsState.inert = (e.target.value === "on");

    if (window.ParticlesSim?.setInert) {
      window.ParticlesSim.setInert(window.kineticsState.inert);
    }
  });
});


setInterval(()=>{
  setControlsLocked(!!window.controlsLocked);
}, 100);