import { test, expect } from "@playwright/test";

test.beforeEach(async ({ page }) => {
  await page.goto("http://localhost:3420/");
});

test("rountrip receive and send", async ({ page }) => {
    // Click the receive button
    await page.click("text=Receive");
  
    // Expect the url to conain receive
    await expect(page).toHaveURL(/.*receive/);
  
    // At least one h1 should show "0 sats"
    await expect(page.locator("h1")).toContainText(["0 SATS"]);
  
    // At least one h2 should show "0 USD"
    await expect(page.locator("h2")).toContainText(["$0 USD"]);
  
    // Click the 100k button
    await page.click("text=100k");
  
    // Now the h1 should show "10,000 sats"
    await expect(page.locator("h1")).toContainText(["100,000 SATS"]);
  
    // Click the "Set Amount" button
    await page.click("text=Set Amount");
  
    // There should be a button with the text "Continue" and it should not be disabled
    const continueButton = await page.locator("button", { hasText: "Continue" });
    await expect(continueButton).not.toBeDisabled();
  
    // Wait one second
    // TODO: figure out how to not get an error without waiting
    await page.waitForTimeout(1000);
  
    continueButton.click();
  
    await expect(
        page.getByText("Keep Mutiny open to complete the payment.")
    ).toBeVisible();
  
    // Locate an SVG inside a div with id "qr"
    const qrCode = await page.locator("#qr > svg");
  
    await expect(qrCode).toBeVisible();
  
    const value = await qrCode.getAttribute("value");
  
    // The SVG's value property includes "bitcoin:t"
    expect(value).toContain("bitcoin:t");

    const lightningInvoice = value?.split("lightning=")[1];

    // Post the lightning invoice to the server
    const _response = await fetch("https://faucet.mutinynet.com/api/lightning", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            bolt11: lightningInvoice
        })
    });

    // Wait for an h1 to appear in the dom that says "Payment Received"
    await page.waitForSelector("text=Payment Received", { timeout: 30000 });

    // Click the "Nice" button
    await page.click("text=Nice");

    // Now we send
    await page.click("text=Send");

    // In the textarea with the placeholder "bitcoin:..." type refund@lnurl-staging.mutinywallet.com
    const sendInput = await page.locator("textarea");
    await sendInput.fill("refund@lnurl-staging.mutinywallet.com");

    await page.click("text=Continue");

    await page.click("text=Set Amount");

    await page.click("text=10k");

    await page.click("text=Set Amount");

    await page.click("text=Confirm Send");

    // Wait for an h1 to appear in the dom that says "Payment Received"
    await page.waitForSelector("text=Payment Sent", { timeout: 30000 });
  });
  
