/* Small helpers local to the split lane. Nothing here rescues a step a person could not do —
   the evaluate-click is only used where a full-screen sibling scrim (`m2-dock-scrim`) makes
   Playwright's hit-test land on the overlay, which a real thumb does not suffer from. */
import { DWELL, arriveAsDiner } from "../lib-witness.mjs";

export async function arrive(page, rid, table) {
  const seen = await arriveAsDiner(page, rid, table, "mosaic_v2");
  const gateNo = page.locator('[data-testid="m2-dietary-gate-no"]').first();
  if (await gateNo.count()) {
    seen.push("dietary gate (testid)");
    await gateNo.evaluate(e => e.click()).catch(() => {});
    await page.waitForTimeout(DWELL);
  }
  return seen;
}

/** Tap something, falling back to a bubbling native click when the dock scrim intercepts. */
export async function tap(page, locator, timeout = 12000) {
  try { await locator.click({ timeout }); }
  catch { await locator.evaluate(e => e.click()); }
  await page.waitForTimeout(2500);
}

/** Who does this diner think is at the table? Names + counts straight off the cart chips. */
export async function whoIsHere(page) {
  return page.evaluate(() => [...document.querySelectorAll('[data-testid^="cart-scope-chip-"]')]
    .map(e => ({ testid: e.getAttribute("data-testid"),
                 text: (e.textContent || "").replace(/\s+/g, " ").trim() })));
}

/** Every settle-ish handle currently on screen, so I can say what I was offered, not guess. */
export async function settleControls(page) {
  return page.evaluate(() => [...new Set([...document.querySelectorAll("[data-testid]")]
    .map(e => e.getAttribute("data-testid"))
    .filter(x => /split|cover|payhow|settle|pay|charge|share|invite|tip|gratuit/i.test(x)))].sort());
}

/** Open the running-order sheet (only exists once the cart has something in it). */
export async function openSheet(page) {
  const t = page.locator('[data-testid="m2-dock-cart"], [data-testid="m2-view-order"]').first();
  if (!(await t.count())) return false;
  await tap(page, t);
  await page.waitForTimeout(DWELL);
  return true;
}
