// Bakes live input values into their sibling .pv span before printing (so text doesn't clip
// at a fixed .f width the way a raw <input> would), then clears them after. One DOM, one
// rendering — see app.css's @media print block for the corresponding display swap.
//
// Operates on #print-sheet (not the passed-in screen `form`): the print worksheet lives
// outside #plan-form on purpose, so its inputs are addressed by container id instead.

export function initPrint({ beforePrint }) {
  document.getElementById("btn-print").addEventListener("click", () => window.print());

  window.addEventListener("beforeprint", () => {
    beforePrint?.(); // re-sync the print worksheet's inputs from state.plan before baking
    bakeValues();
  });
  window.addEventListener("afterprint", () => clearBaked());
}

function printSheet() {
  return document.getElementById("print-sheet");
}

function bakeValues() {
  for (const el of printSheet().querySelectorAll("input.ws-input, textarea.ws-input")) {
    if (el.type === "radio" || el.type === "checkbox") continue;
    const pv = el.nextElementSibling;
    if (pv && pv.classList.contains("pv")) pv.textContent = el.value || "";
  }
}

function clearBaked() {
  for (const pv of printSheet().querySelectorAll(".pv")) pv.textContent = "";
}
