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-tabs2", async ({ browser }) => {
  const jr = journal("w004-tabs2");
  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 });

    for (const tab of ["Service", "Bill", "Guests"]) {
      await jr.step("WAITER", `Tap ${tab} on my table sheet and look`, async id => {
        /* Find the exact label, then confirm what is really under that point before tapping. */
        const spot = await w.evaluate(t => {
          const el = [...document.querySelectorAll("button,[role=tab],div,span,a")]
            .find(e => e.textContent.trim() === t && e.getClientRects().length);
          if (!el) return null;
          el.scrollIntoView({ block: "center" });
          const r = el.getBoundingClientRect();
          const x = Math.round(r.x + r.width / 2), y = Math.round(r.y + r.height / 2);
          const hit = document.elementFromPoint(x, y);
          return { x, y, hitText: hit ? hit.textContent.trim().slice(0, 30) : null,
                   hitTag: hit ? hit.tagName : null, ownText: el.textContent.trim() };
        }, tab);
        if (!spot) throw new Error(`no "${tab}" label on screen at all`);
        if (!spot.hitText || !spot.hitText.includes(tab))
          throw new Error(`something else is on top of "${tab}": <${spot.hitTag}> "${spot.hitText}"`);
        await w.mouse.click(spot.x, spot.y);
        await w.waitForTimeout(DWELL);
        await expect(w.getByText(`Table #${T}`).first(),
                     `the sheet must still be open on ${tab}`).toBeVisible({ timeout: 15000 });
        const sheet = await w.evaluate(t => {
          const h = [...document.querySelectorAll("*")].find(e => e.textContent.trim() === `Table #${t}`);
          let n = h; for (let i = 0; i < 6 && n; i++) n = n.parentElement;
          return n ? n.innerText.replace(/\s+/g, " ").slice(0, 900) : null;
        }, T);
        const ids = await w.evaluate(() => [...new Set([...document.querySelectorAll("[data-testid]")]
          .map(e => e.getAttribute("data-testid")))]);
        out[tab] = { sheet, serveLike: ids.filter(x => /serve|deliver|ready|done|complete|fire|bump/i.test(x)) };
        await look(w, jr, "waiter", id, `${tab} tab`);
        return `${tab}: serve controls = ${out[tab].serveLike.join(", ") || "NONE"}. ${(sheet || "").slice(0, 320)}`;
      });
    }
  } 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", "Service / Bill / Guests tabs of the table sheet.");
    await closeRole(cW, jr, "waiter");
  }
});
