// Waitress — sees ready orders, marks served. Customer Display — order summary + QR.
function WaitressScreen() {
  const { orders, closeOrder } = usePOS();
  useTick(1000);

  const ready = orders.filter((o) => {
    if (o.status === "closed") return false;
    const bar = o.barStatus;
    const kit = o.kitchenStatus;
    const barReady = !bar || bar === "ready" || bar === "served";
    const kitReady = !kit || kit === "ready" || kit === "served";
    return barReady && kitReady && (bar === "ready" || kit === "ready");
  });

  const pending = orders.filter((o) => {
    if (o.status === "closed") return false;
    if (ready.includes(o)) return false;
    return (o.barStatus && o.barStatus !== "served") || (o.kitchenStatus && o.kitchenStatus !== "served");
  });

  return (
    <div className="waitress">
      <header className="waitress-head">
        <div>
          <div className="eyebrow mono">FLOOR</div>
          <h2>{ready.length} ready to run</h2>
        </div>
        <div className="floor-legend">
          <span><i className="dot dot-ready" /> Ready</span>
          <span><i className="dot dot-pending" /> Preparing</span>
        </div>
      </header>

      <div className="waitress-cols">
        <section>
          <div className="col-title mono">READY · RUN NOW</div>
          <div className="run-list">
            {ready.length === 0 && <div className="cart-empty"><p>Nothing waiting.</p></div>}
            {ready.map((o) => (
              <article className="run-card" key={o.id + (o._bump || 0)}>
                <header>
                  <Mono className="run-short">{o.shortId}</Mono>
                  <span className="run-table mono">Table {o.table}</span>
                </header>
                <div className="run-customer">{o.customer}</div>
                <ul className="run-items">
                  {o.items.map((it, i) => (
                    <li key={i}><Mono>{it.qty}×</Mono> {it.name}</li>
                  ))}
                </ul>
                <footer>
                  <Mono className="muted">waiting {timeSince(o.createdAt)}</Mono>
                  <button className="btn-primary" onClick={() => closeOrder(o.id)}>Served ✓</button>
                </footer>
              </article>
            ))}
          </div>
        </section>

        <section>
          <div className="col-title mono">PREPARING</div>
          <div className="pending-list">
            {pending.map((o) => (
              <div className="pending-row" key={o.id}>
                <Mono className="pending-short">{o.shortId}</Mono>
                <span className="pending-table mono">T{o.table}</span>
                <div className="pending-items">{o.items.map((i) => i.qty + "× " + i.name).join(", ")}</div>
                <div className="pending-pills">
                  {o.barStatus && o.barStatus !== "served" && <StatusPill status={o.barStatus}>bar · {o.barStatus}</StatusPill>}
                  {o.kitchenStatus && o.kitchenStatus !== "served" && <StatusPill status={o.kitchenStatus}>kit · {o.kitchenStatus}</StatusPill>}
                </div>
                <Mono className="muted">{timeSince(o.createdAt)}</Mono>
              </div>
            ))}
          </div>
        </section>
      </div>
    </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: "Kedai Rona", password: "" });
  useTick(1000);

  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 || "Kedai Rona", password: d.password || "" });
      }
    });
  }, []);

  const last = live || receiptOrder;

  return (
    <div className="display">
      <div className="display-frame">
        <header className="display-head">
          <div className="display-brand">
            <div className="brand-mark mono">KON</div>
            <div>
              <div className="brand-name">Kedai Oma Nana</div>
              <div className="muted mono">Specialty coffee · Brunch · Since 2019</div>
            </div>
          </div>
          <div className="display-clock mono">{fmtClock()}</div>
        </header>

        <div className="display-body">
          <section className="display-order">
            <div className="eyebrow mono">YOUR ORDER · {last ? last.shortId : "—"}</div>
            <ul className="display-items">
              {(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-pay">
            {live?.payment?.method === "qris" && live.payment.ready ? (
              <React.Fragment>
                <div className="eyebrow mono">SCAN TO PAY · QRIS</div>
                <QRPlaceholder size={280} />
                <div className="display-pay-amount">
                  <span>Pay this amount</span>
                  <Mono>{money(live.payment.amount)}</Mono>
                </div>
                <div className="muted mono">Any QRIS-enabled wallet · GoPay · OVO · Dana · ShopeePay</div>
              </React.Fragment>
            ) : (
              <div className="display-pay-idle">
                <div className="eyebrow mono">PAYMENT</div>
                <div className="display-pay-hint mono">Awaiting checkout…</div>
                <div className="muted mono" style={{ marginTop: 8 }}>The cashier will start payment when your order is ready.</div>
              </div>
            )}
          </section>
        </div>

        <footer className="display-foot mono">
          <span>Thank you · Terima kasih</span>
          <span className="display-wifi">
            <StarlinkMark />
            <span>Wi-Fi: <strong>{wifi.ssid}</strong></span>
            <span>·</span>
            <span>Password: <strong>{wifi.password || "ask staff"}</strong></span>
          </span>
        </footer>
      </div>
    </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="IBM Plex Sans, sans-serif" fontSize="11" fontWeight="600" fill="currentColor" letterSpacing="0.5">
          Starlink
        </text>
      </svg>
    </span>
  );
}

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