

import io.github.bonigarcia.seljup.SeleniumJupiter;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(SeleniumJupiter.class)
class BookSearchTest {

    @Test
    @DisplayName("Search for 'Harry Potter' and verify J.K. Rowling book appears")
    void testSearchBook(ChromeDriver driver) {
        driver.get("https://cover-bookstore.onrender.com");

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        //Locate search bar
        WebElement searchBox = wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector("[data-testid='book-search-input']")));

        searchBox.sendKeys("Harry Potter");
        searchBox.sendKeys(Keys.ENTER);

        //wait
        wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(
                By.cssSelector("[data-testid='book-search-item']")));

        List<WebElement> results = driver.findElements(By.cssSelector("[data-testid='book-search-item']"));

        System.out.println("Found " + results.size() + " results:");

        boolean found = false;
        //each book card found
        for (WebElement bookCard : results) {
            WebElement img = bookCard.findElement(By.tagName("img"));
            String title = img.getAttribute("alt");
            String cardText = bookCard.getText();

            System.out.println(title + " | Info: " + cardText);

            if (title.toLowerCase().contains("harry potter and the sorcerer")
                    && cardText.toLowerCase().contains("j.k. rowling")) {
                found = true;
                break;
            }
        }

        assertTrue(found, "Expected to find 'Harry Potter and the Sorcerer's Stone' by J.K. Rowling.");
    }
}
