// Kitchen Display — bar + kitchen station tickets, animated transitions
const KDS_URGENT_SEC = 15 * 60; // 15 minutes

// Play a short two-beep notification using the Web Audio API.
function playKdsAlert() {
  try {
    const Ctx = window.AudioContext || window.webkitAudioContext;
    if (!Ctx) return;
    const ctx = new Ctx();
    const beep = (t) => {
      const o = ctx.createOscillator();
      const g = ctx.createGain();
      o.type = "sine"; o.frequency.value = 880;
      g.gain.setValueAtTime(0.0001, t);
      g.gain.exponentialRampToValueAtTime(0.35, t + 0.02);
      g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
      o.connect(g).connect(ctx.destination);
      o.start(t); o.stop(t + 0.25);
    };
    const now = ctx.currentTime;
    beep(now); beep(now + 0.35);
    setTimeout(() => ctx.close && ctx.close(), 1200);
  } catch (_) { /* audio blocked — silent */ }
}

function KitchenScreen() {
  const { orders, advance } = usePOS();
  useTick(1000);
  const [station, setStation] = React.useState("kitchen"); // 'kitchen' | 'bar' | 'all'
  const alerted = React.useRef(new Set());

  const visible = orders.filter((o) => {
    if (o.status === "closed") return false;
    const s = station === "kitchen" ? o.kitchenStatus : station === "bar" ? o.barStatus : (o.kitchenStatus || o.barStatus);
    return s && s !== "served";
  });

  // Trigger sound the moment a ticket crosses 15 minutes (only once per ticket).
  React.useEffect(() => {
    visible.forEach((o) => {
      const ms = tsToMs(o.createdAt);
      if (!ms) return;
      const ageSec = Math.floor((Date.now() - ms) / 1000);
      const status = station === "bar" ? o.barStatus : o.kitchenStatus;
      if (ageSec >= KDS_URGENT_SEC && status !== "ready" && !alerted.current.has(o.id)) {
        alerted.current.add(o.id);
        playKdsAlert();
      }
    });
  });

  return (
    <div className="kds">
      <header className="kds-head">
        <div>
          <div className="eyebrow mono">KITCHEN DISPLAY</div>
          <h2>{visible.length} active ticket{visible.length === 1 ? "" : "s"}</h2>
        </div>
        <div className="station-toggle">
          {[
            { id: "kitchen", label: "Kitchen" },
            { id: "bar", label: "Bar" },
            { id: "all", label: "Both" },
          ].map((s) => (
            <button
              key={s.id}
              className={"station-tab" + (station === s.id ? " active" : "")}
              onClick={() => setStation(s.id)}
            >{s.label}</button>
          ))}
        </div>
      </header>

      <div className="kds-board">
        {visible.length === 0 && (
          <div className="kds-empty">
            <div className="empty-mark">✓</div>
            <p>All caught up.</p>
          </div>
        )}
        {visible.map((o) => (
          <KitchenTicket key={o.id} order={o} station={station} advance={advance} />
        ))}
      </div>
    </div>
  );
}

function KitchenTicket({ order, station, advance }) {
  const stationKey = station === "bar" ? "bar" : station === "kitchen" ? "kitchen" : (order.kitchenStatus ? "kitchen" : "bar");
  const items = order.items.filter((i) => i.station === stationKey);
  if (!items.length && station !== "all") return null;

  const status = stationKey === "bar" ? order.barStatus : order.kitchenStatus;
  const nextMap = { new: "cooking", cooking: "ready", ready: "served" };
  const next = nextMap[status];

  const createdMs = tsToMs(order.createdAt);
  const ageSec = createdMs ? Math.floor((Date.now() - createdMs) / 1000) : 0;
  const urgent = ageSec >= KDS_URGENT_SEC && status !== "ready";

  return (
    <article className={"kds-card kds-" + status + (urgent ? " urgent" : "")} key={order._bump}>
      <header className="kds-card-head">
        <div className="kds-id">
          <Mono className="kds-short">{order.shortId}</Mono>
          <div className="muted mono">{order.table === "Bar" ? "Bar" : "Table " + order.table}</div>
        </div>
        <StatusPill status={status}>{status}</StatusPill>
      </header>
      <div className="kds-customer mono">{order.customer}</div>

      <ul className="kds-items">
        {items.map((it, i) => (
          <li key={i}>
            <Mono className="kds-qty">{it.qty}×</Mono>
            <div className="kds-item-body">
              <div className="kds-name">{it.name}</div>
              {it.mods.length > 0 && <div className="kds-mods mono">{it.mods.join(" · ")}</div>}
              {it.notes && <div className="kds-note mono">📝 {it.notes}</div>}
            </div>
          </li>
        ))}
      </ul>

      <footer className="kds-foot">
        <Mono className={"kds-timer " + (urgent ? "alert" : "")}>{timeSince(order.createdAt)}</Mono>
        <button className="btn-ghost-sm print-only-hide" onClick={() => printKitchenTicket(order, stationKey, items)}>Print</button>
        {next && (
          <button className="btn-advance" onClick={() => advance(order.id, stationKey, next)}>
            {next === "served" ? "Mark served" : "→ " + next}
          </button>
        )}
      </footer>
    </article>
  );
}

// Build a printable kitchen ticket DOM offscreen, print, then clean up.
function printKitchenTicket(order, station, items) {
  const settings = getPrinterSettings();
  const root = document.createElement("div");
  root.className = "printable ticket-print";
  root.innerHTML = `
    <div class="pr-center pr-brand">${station.toUpperCase()} TICKET</div>
    <div class="pr-rule"></div>
    <div class="pr-short">#${order.shortId}</div>
    <div class="pr-center">${order.table === "Bar" ? "Bar" : "Table " + order.table} · ${order.customer || ""}</div>
    <div class="pr-rule"></div>
    ${items.map((it) => `
      <div class="pr-line"><span class="qty">${it.qty}×</span>${it.name}${it.sku ? " (" + it.sku + ")" : ""}</div>
      ${it.mods && it.mods.length ? `<div class="pr-mod">${it.mods.join(" · ")}</div>` : ""}
      ${it.notes ? `<div class="pr-note">* ${it.notes}</div>` : ""}
    `).join("")}
    <div class="pr-rule"></div>
    <div class="pr-center" style="font-size:10px">${new Date().toLocaleString("en-GB", { timeZone: "Asia/Jakarta" })} WIB</div>
  `;
  document.body.appendChild(root);
  // Temporarily hide other .printable elements (e.g. receipt) so only this prints.
  const others = document.querySelectorAll(".printable");
  others.forEach((el) => { if (el !== root) el.dataset._wasPrintable = "1", el.classList.remove("printable"); });
  printPaper(settings.paperWidth);
  setTimeout(() => {
    others.forEach((el) => { if (el.dataset._wasPrintable === "1") { el.classList.add("printable"); delete el.dataset._wasPrintable; } });
    root.remove();
  }, 800);
}

Object.assign(window, { KitchenScreen, printKitchenTicket });
