import { test, expect } from "@playwright/test";
import { journal, look, signInWaiter, DWELL, roleContext, closeRole, account, HOUSE, table } from "../lib-witness.mjs";
import fs from "node:fs";
const T = table(10094);
test("w004-bill2", async ({ browser }) => {
  const jr = journal("w004-bill2");
  jr.target({ app: "waiter", restaurantId: HOUSE.restaurantId, table: T });
  const cW = await roleContext(browser, jr, "waiter", "Desktop Chrome");
  const w = await cW.newPage();
  const out = {};
  try {
    const a = account(HOUSE.waiter);
    await signInWaiter(w, a.email, a.password);
    await w.getByTestId("tab-tables").click({ timeout: 20000 }).catch(() => {});
    await w.waitForTimeout(3000);
    await w.getByTestId(`table-card-${T}`).click({ timeout: 25000 });
    await w.waitForTimeout(DWELL);
    await expect(w.getByText(`Table #${T}`).first()).toBeVisible({ timeout: 20000 });

    await jr.step("WAITER", "What exactly are the three tabs on this sheet", async id => {
      out.tabRow = await w.evaluate(() => {
        const hits = [];
        for (const e of document.querySelectorAll("*")) {
          const t = (e.textContent || "").trim();
          if (t.length && t.length < 12 && /^(guests|service|bill)$/i.test(t) && e.getClientRects().length) {
            const r = e.getBoundingClientRect();
            hits.push({ tag: e.tagName, cls: (e.className || "").toString().slice(0, 40),
                        text: JSON.stringify(t), x: Math.round(r.x), y: Math.round(r.y),
                        w: Math.round(r.width), h: Math.round(r.height), kids: e.children.length });
          }
        }
        return hits;
      });
      await look(w, jr, "waiter", id, "sheet with its tab row");
      return `tab-like elements: ${JSON.stringify(out.tabRow).slice(0, 700)}`;
    });

    await jr.step("WAITER", "Tap Bill and see what a waiter gets", async id => {
      const cand = (out.tabRow || []).filter(h => /bill/i.test(h.text)).sort((a, b) => b.w * b.h - a.w * a.h)[0];
      if (!cand) throw new Error("nothing on the sheet is labelled Bill");
      const x = cand.x + Math.round(cand.w / 2), y = cand.y + Math.round(cand.h / 2);
      const hit = await w.evaluate(([x, y]) => {
        const e = document.elementFromPoint(x, y);
        return e ? { tag: e.tagName, text: (e.textContent || "").trim().slice(0, 24) } : null;
      }, [x, y]);
      out.hit = hit;
      if (!hit || !/bill/i.test(hit.text)) throw new Error(`point (${x},${y}) is "${hit && hit.text}" not Bill`);
      await w.mouse.click(x, y);
      await w.waitForTimeout(DWELL);
      await expect(w.getByText(`Table #${T}`).first(), "sheet must still be open").toBeVisible({ timeout: 15000 });
      out.serveLike = await w.evaluate(() => [...new Set([...document.querySelectorAll("[data-testid]")]
        .map(e => e.getAttribute("data-testid")))].filter(x => /serve|deliver|ready|done|complete|fire|bump/i.test(x)));
      out.buttons = await w.evaluate(() => [...document.querySelectorAll("button,[role=button]")]
        .map(b => b.innerText.replace(/\s+/g," ").trim()).filter(Boolean).slice(0,30));
      await look(w, jr, "waiter", id, "Bill tab");
      return `Bill: serve controls = ${out.serveLike.join(", ") || "NONE"}; buttons = ${out.buttons.join(" | ").slice(0,300)}`;
    });
  } catch (e) { jr.note(`> Stopped: ${String(e.message || e).split("\n")[0]}`); }
  finally {
    fs.writeFileSync(`${jr.dir}/PROBE.json`, JSON.stringify(out, null, 1));
    jr.finish("SPINE_OK", "The Bill tab.");
    await closeRole(cW, jr, "waiter");
  }
});
