// Waitress / Floor — per-item view. Each ready item has its own "Served" action.
function WaitressScreen() {
  const { orders, advanceItem, rewindItem } = usePOS();
  useTick(1000);
  const [historyOpen, setHistoryOpen] = React.useState(false);

  const statusOf = (it, o) => it.status || (it.station === "bar" ? o.barStatus : o.kitchenStatus) || "new";

  // Orders that have at least one item ready to run. Oldest first.
  const readyOrders = orders
    .filter((o) => o.status !== "closed")
    .map((o) => ({
      order: o,
      ready: o.items
        .map((it, idx) => ({ it, idx, status: statusOf(it, o) }))
        .filter((x) => x.status === "ready"),
      pending: o.items
        .map((it, idx) => ({ it, idx, status: statusOf(it, o) }))
        .filter((x) => x.status === "new" || x.status === "cooking"),
    }))
    .filter((g) => g.ready.length > 0 || g.pending.length > 0)
    .sort((a, b) => (a.order.createdAt?.seconds || 0) - (b.order.createdAt?.seconds || 0));

  const readyCount = readyOrders.reduce((s, g) => s + g.ready.length, 0);
  const withReady = readyOrders.filter((g) => g.ready.length > 0);
  // Show every order that still has cooking/new items — even if some items in
  // that same order are already ready. The waitress needs to know more food
  // is still coming for that table.
  const stillPending = readyOrders.filter((g) => g.pending.length > 0);

  return (
    <div className="waitress">
      <header className="waitress-head">
        <div>
          <div className="eyebrow mono">FLOOR</div>
          <h2>{readyCount} item{readyCount === 1 ? "" : "s"} ready to run</h2>
        </div>
        <div className="waitress-head-right">
          <div className="floor-legend">
            <span><i className="dot dot-ready" /> Ready</span>
            <span><i className="dot dot-pending" /> Preparing</span>
          </div>
          <button className="kiosk-signout mono" onClick={() => setHistoryOpen(true)} title="View history">History</button>
          <button className="kiosk-signout mono" onClick={() => firebase.auth().signOut()} title="Sign out">Sign out</button>
        </div>
      </header>

      <div className="waitress-cols">
        <section>
          <div className="col-title mono">READY · RUN NOW</div>
          <div className="run-list">
            {withReady.length === 0 && <div className="cart-empty"><p>Nothing waiting.</p></div>}
            {withReady.map(({ order, ready }) => (
              <article className="run-card" key={order.id}>
                <header>
                  <Mono className="run-short">{order.shortId}</Mono>
                  <span className="run-table mono">Table {order.table}</span>
                  {ready.length > 1 && (
                    <button
                      className="btn-primary btn-sm"
                      style={{ marginLeft: "auto" }}
                      onClick={() => advanceItem(order.id, ready.map((r) => r.idx), "served")}
                      title="Mark every ready item as served"
                    >
                      All served ✓
                    </button>
                  )}
                </header>
                <div className="run-customer">{order.customer}</div>
                <ul className="run-items">
                  {ready.map(({ it, idx }) => (
                    <li
                      key={idx}
                      className={"run-item run-item-station-" + (it.station || "kitchen") + " kds-item-clickable"}
                      onClick={(e) => { if (e.target.closest("button")) return; advanceItem(order.id, idx, "served"); }}
                      onContextMenu={(e) => { e.preventDefault(); rewindItem(order.id, idx); }}
                      title="Click to serve · right-click to send back"
                    >
                      <Mono className="run-item-qty">{it.qty}×</Mono>
                      <div className="run-item-body">
                        <div>{it.name}</div>
                        {it.mods && it.mods.length > 0 && <div className="muted mono" style={{ fontSize: 11 }}>{it.mods.join(" · ")}</div>}
                        {it.notes && <div className="mono" style={{ fontSize: 11 }}>📝 {it.notes}</div>}
                      </div>
                      <button className="btn-primary btn-sm" onClick={(e) => { e.stopPropagation(); advanceItem(order.id, idx, "served"); }}>
                        Served ✓
                      </button>
                    </li>
                  ))}
                </ul>
                <footer>
                  <Mono className="muted">waiting {timeSince(order.createdAt)}</Mono>
                </footer>
              </article>
            ))}
          </div>
        </section>

        <section>
          <div className="col-title mono">PREPARING</div>
          <div className="run-list">
            {stillPending.length === 0 && <div className="muted mono" style={{ padding: 12 }}>Nothing being prepared.</div>}
            {stillPending.map(({ order, pending, ready }) => (
              <article className="run-card prep-card" key={order.id}>
                <header>
                  <Mono className="run-short">{order.shortId}</Mono>
                  <span className="run-table mono">Table {order.table}</span>
                  {ready.length > 0 && (
                    <span className="mono" style={{ fontSize: 11, color: "#8c5ab4", marginLeft: 8 }}>
                      · {ready.length} ready
                    </span>
                  )}
                  <Mono className="muted" style={{ marginLeft: "auto" }}>{timeSince(order.createdAt)}</Mono>
                </header>
                <div className="run-customer">{order.customer}</div>
                <ul className="run-items">
                  {pending.map(({ it, status }, i) => (
                    <li key={i} className={"run-item run-item-station-" + (it.station || "kitchen")}>
                      <Mono className="run-item-qty">{it.qty}×</Mono>
                      <div className="run-item-body">
                        <div>{it.name}</div>
                        {it.mods && it.mods.length > 0 && <div className="muted mono" style={{ fontSize: 11 }}>{it.mods.join(" · ")}</div>}
                      </div>
                      <StatusPill status={status}>{status}</StatusPill>
                    </li>
                  ))}
                </ul>
              </article>
            ))}
          </div>
        </section>
      </div>
      {historyOpen && window.HistorySheet && (
        <window.HistorySheet onClose={() => setHistoryOpen(false)} />
      )}
    </div>
  );
}

// Customer-facing display, full screen, shows live cart from cashier + QR
function CustomerDisplayScreen() {
  const { receiptOrder, db } = usePOS();
  const [live, setLive] = React.useState(null);
  const [wifi, setWifi] = React.useState({ ssid: "", password: "" });
  useTick(1000);
  const itemsRef = React.useRef(null);

  React.useEffect(() => {
    return db.collection("displays").doc("main").onSnapshot((doc) => {
      if (!doc.exists) return setLive(null);
      const d = doc.data();
      if (!d.items || !d.items.length || d.status === "idle") return setLive(null);
      setLive(d);
    });
  }, []);

  React.useEffect(() => {
    return db.collection("displays").doc("wifi").onSnapshot((doc) => {
      if (doc.exists) {
        const d = doc.data();
        setWifi({ ssid: d.ssid || "", password: d.password || "" });
      }
    });
  }, []);

  const last = live || receiptOrder;

  // Auto-shrink the items list when it would overflow its column. Computes
  // a CSS scale factor so the whole display fits without scrolling — the QR
  // stays on screen no matter how long the order is.
  React.useLayoutEffect(() => {
    const items = itemsRef.current;
    if (!items) return;
    items.style.setProperty("--display-scale", "1");
    const needed = items.scrollHeight;
    const available = items.clientHeight;
    if (available > 0 && needed > available) {
      const scale = Math.max(0.55, available / needed);
      items.style.setProperty("--display-scale", String(scale));
    }
  });

  return (
    <div className="display">
      <div className="display-frame">
        <header className="display-head">
          <div className="display-brand">
            <div className="brand-mark mono">{window.STORE_MARK}</div>
            <div>
              <div className="brand-name">{window.STORE_NAME}</div>
              <div className="muted mono">Specialty coffee · Brunch · Since 2019</div>
            </div>
          </div>
          <div className="display-head-right">
            <div className="display-clock mono">{fmtClock()}</div>
            <button className="display-signout mono" onClick={() => firebase.auth().signOut()} title="Sign out">Sign out</button>
          </div>
        </header>

        <section className="display-order">
          <div className="eyebrow mono">YOUR ORDER · {last ? last.shortId : "—"}</div>
          <ul className="display-items" ref={itemsRef}>
            {(last ? last.items : []).map((it, i) => (
              <li key={i}>
                <Mono className="d-qty">{it.qty}×</Mono>
                <div className="d-line">
                  <span>{it.name}</span>
                  {it.mods && it.mods.length > 0 && <span className="d-mods mono">{it.mods.join(" · ")}</span>}
                </div>
                <Mono className="d-sub">{money((it.price + (it.modPrice || 0)) * it.qty)}</Mono>
              </li>
            ))}
            {(!last || !last.items.length) && <li className="muted">No active order</li>}
          </ul>
          {last && last.uniqueCode > 0 && (
            <div className="display-code-row">
              <span className="eyebrow mono">UNIQUE CODE (QRIS)</span>
              <Mono>+{money(last.uniqueCode)}</Mono>
            </div>
          )}
          <div className="display-total">
            <span className="eyebrow mono">TOTAL</span>
            <Mono className="display-total-num">{money(last ? last.total : 0)}</Mono>
          </div>
        </section>

        <section className="display-bottom">
          <div className="display-pay">
            {live?.payment?.method === "qris" && live.payment.ready ? (
              <QrisDynamic amount={live.payment.amount} maxSize={200} />
            ) : (
              <div className="display-pay-idle">
                <div className="display-pay-hint mono">Awaiting checkout…</div>
              </div>
            )}
          </div>
          <div className="display-wifi-panel">
            <div className="wifi-head">
              <StarlinkMark />
              <div className="eyebrow mono">FREE WI-FI</div>
            </div>
            <div className="wifi-network">
              <div className="muted mono">NETWORK</div>
              <div className="wifi-network-name">{wifi.ssid}</div>
            </div>
            <div className="wifi-pw">
              <div className="muted mono">PASSWORD</div>
              <div className="wifi-pw-value mono">{wifi.password || "ask staff"}</div>
            </div>
            <div className="wifi-thanks mono">Thank you · Terima kasih</div>
          </div>
        </section>
      </div>
    </div>
  );
}

// Real QRIS dynamic QR — converts the configured static MPM-S payload into
// a dynamic MPM-D one with the actual transaction amount, then renders it
// via the qrious lib. Auto-sizes to the available container space, so the
// QR is always crisp and never clipped. Falls back to placeholder if QRIS
// isn't configured.
function QrisDynamic({ amount, reference, maxSize = 280 }) {
  const wrapRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const [size, setSize] = React.useState(maxSize);
  const staticPayload = (window.QRIS_CONFIG || {}).staticPayload || "";

  React.useEffect(() => {
    if (!wrapRef.current) return;
    const measure = () => {
      if (!wrapRef.current) return;
      const w = wrapRef.current.clientWidth;
      const h = wrapRef.current.clientHeight;
      const next = Math.max(80, Math.min(maxSize, Math.floor(Math.min(w, h))));
      setSize(next);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(wrapRef.current);
    return () => ro.disconnect();
  }, [maxSize]);

  React.useEffect(() => {
    if (!canvasRef.current || !window.QRious || !window.QRIS || !staticPayload) return;
    const dyn = window.QRIS.staticToDynamic(staticPayload, amount, reference);
    new window.QRious({
      element: canvasRef.current,
      value: dyn,
      size,
      foreground: "#1C1B1F",
      background: "#ffffff",
      level: "M",
    });
  }, [amount, reference, size, staticPayload]);

  if (!staticPayload || !window.QRious) return <QRPlaceholder size={maxSize} />;
  return (
    <div ref={wrapRef} className="qr-wrap">
      <canvas ref={canvasRef} />
    </div>
  );
}

// Minimal QR placeholder — a grid of monospaced cells, not a real QR
function QRPlaceholder({ size = 240 }) {
  const cells = 21;
  const cellSize = size / cells;
  const pattern = React.useMemo(() => {
    const m = [];
    for (let y = 0; y < cells; y++) {
      const row = [];
      for (let x = 0; x < cells; x++) {
        const corner = (x < 7 && y < 7) || (x > cells - 8 && y < 7) || (x < 7 && y > cells - 8);
        const innerCorner = (x > 0 && x < 6 && y > 0 && y < 6) || (x > cells - 7 && x < cells - 1 && y > 0 && y < 6) || (x > 0 && x < 6 && y > cells - 7 && y < cells - 1);
        const dotCorner = (x > 1 && x < 5 && y > 1 && y < 5) || (x > cells - 6 && x < cells - 2 && y > 1 && y < 5) || (x > 1 && x < 5 && y > cells - 6 && y < cells - 2);
        let v;
        if (corner) v = !innerCorner || dotCorner ? 1 : 0;
        else v = Math.random() > 0.55 ? 1 : 0;
        row.push(v);
      }
      m.push(row);
    }
    return m;
  }, []);
  return (
    <div className="qr-ph" style={{ width: size, height: size }}>
      {pattern.map((row, y) => row.map((v, x) => (
        v ? <span key={x + "-" + y} style={{
          left: x * cellSize, top: y * cellSize, width: cellSize, height: cellSize,
        }} /> : null
      )))}
    </div>
  );
}

// Minimal Starlink-style mark: dish + arc, monoline.
function StarlinkMark() {
  return (
    <span className="starlink-mark" title="Powered by Starlink">
      <svg viewBox="0 0 64 24" width="64" height="20" aria-hidden="true">
        <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
          <ellipse cx="8" cy="14" rx="6" ry="2.2" />
          <line x1="8" y1="14" x2="8" y2="20" />
          <line x1="4" y1="20" x2="12" y2="20" />
          <path d="M3 9 Q8 4 13 9" />
          <path d="M5 6 Q8 2 11 6" />
        </g>
        <text x="18" y="17" fontFamily="Roboto, sans-serif" fontSize="11" fontWeight="600" fill="currentColor" letterSpacing="0.5">
          Starlink
        </text>
      </svg>
    </span>
  );
}

Object.assign(window, { WaitressScreen, CustomerDisplayScreen, QRPlaceholder, QrisDynamic, StarlinkMark });
