// Thermal printer helper — uses window.print() and a CSS-only stylesheet.
// Works with any USB/Bluetooth thermal printer that has an OS driver
// (Windows, macOS, Linux, Android via Chrome's "Print" dialog).

const PRINTER_DEFAULTS = { paperWidth: "80", autoPrintReceipt: false, autoPrintKitchen: false };

function getPrinterSettings() {
  try {
    return { ...PRINTER_DEFAULTS, ...(JSON.parse(localStorage.getItem("pos.printer") || "{}")) };
  } catch (_) { return { ...PRINTER_DEFAULTS }; }
}
function savePrinterSettings(s) {
  localStorage.setItem("pos.printer", JSON.stringify(s));
}

// Print whatever is inside an element with class "printable". The caller
// renders the printable markup (anywhere in the DOM), then calls this.
function printPaper(paperWidth) {
  const w = paperWidth || getPrinterSettings().paperWidth || "80";
  document.body.classList.toggle("print-58", w === "58");
  document.body.classList.toggle("print-80", w !== "58");
  // Give the browser a tick to apply the class
  requestAnimationFrame(() => {
    window.print();
    setTimeout(() => {
      document.body.classList.remove("print-58", "print-80");
    }, 500);
  });
}

// React hook returning [settings, update]
function usePrinterSettings() {
  const [s, setS] = React.useState(getPrinterSettings);
  const update = (patch) => {
    const next = { ...s, ...patch };
    setS(next); savePrinterSettings(next);
  };
  return [s, update];
}

Object.assign(window, { printPaper, getPrinterSettings, savePrinterSettings, usePrinterSettings });
