import { Page } from "@playwright/test";

export const allowAllCookies = async (page: Page) => {
    const popupLocator = page.locator("//button[contains(text(), 'Allow all')]");
    await page.addLocatorHandler(popupLocator, async () => {
        await popupLocator.click();
    })
}

export const closeNewsletterPopup = async (page: Page) => {
    await page.addLocatorHandler(
        page.locator('//div[@class="Avada-ContinueShoppingText"]'),
        async (locator) => {
            await locator.click();
        }
    );
}

export const closeWheel = async (page: Page) => {
    const popupLocator = page.locator("//div[contains(@class, 'om-wheel-position')]").first();
    await page.addLocatorHandler(popupLocator, async () => {
        await page.waitForTimeout(1500); // wait for popup stable
        const closeMessages = ["Non, merci !", "No, thanks!"];
        const closeButtonXPath = closeMessages.map((message) => `contains(text(), '${message}')`);
        const closeMsg = await page.locator(`//span[${closeButtonXPath.join(' or ')}]`).all();
        for (const button of closeMsg) {
            if (await button.isVisible()) {
                await button.click();
            }
        }

        const closeButtons = await page.locator("//div[contains(@class, 'om-popup-close')]").all();
        for (const button of closeButtons) {
            if (await button.isVisible()) {
                await button.click();
            }
        }
    });

}

export const handlePopupDiscount = async (page: Page) => {
    const popupLocator = page.locator("//div[@id='pge_c9Q0tcaMTu']/div[@class='om-global-close-button om-popup-close om-popup-close-v2']").first();
    await page.addLocatorHandler(popupLocator, async () => {
        await page.waitForTimeout(1500); // wait for popup stable
        await popupLocator.click();
    });
}

export const authorizedShoppayPopup = async (page: Page) => {
    const popupLocator = page.locator("//section[@data-testid='authorize-modal']");
    await page.addLocatorHandler(popupLocator, async () => {
        await page.locator("//button[@data-testid='authorize-modal-close-button']").click();
    });
}