import { expect } from "@playwright/test"
import { Navigation } from "./Navigation.js"
import { isDesktopViewPort } from "../Utils/isDesktopViewport.js"

export class ProductsPage {

    constructor(page) {
        this.page = page
        this.addButtons = page.locator('[data-qa="product-button"]')
        this.sortDropdown = page.locator('[data-qa="sort-dropdown"]')
        this.productTitle = page.locator('[data-qa="product-title"]')
    }

    visit = async () => {
        await this.page.goto("/")
    }



    addProductToBasket = async (productIndex) => {
        const specificAddButton = this.addButtons.nth(productIndex)
        await specificAddButton.waitFor()

        await expect(specificAddButton).toHaveText("Add to Basket")
        const navigation = new Navigation(this.page)

        // only desktop viewport
        let basketCountBefore
        if (isDesktopViewPort(this.page)) {
            basketCountBefore = await navigation.getBasketCount()
        }

        await specificAddButton.click()

        await expect(specificAddButton).toHaveText("Remove from Basket")

        // only desktop viewport
        if(isDesktopViewPort(this.page)) {
            const basketCountAfter = await navigation.getBasketCount()
            expect(basketCountAfter).toBeGreaterThan(basketCountBefore)
        }

    }

    sortByCheapest = async () => {
        await this.sortDropdown.waitFor()
        await this.productTitle.first().waitFor()
        const productTitleBefore = await this.productTitle.allInnerTexts()

        await this.sortDropdown.selectOption("price-asc")
        const productTitleAfter = await this.productTitle.allInnerTexts()

        expect(productTitleAfter).not.toEqual(productTitleBefore)
    }

}