package ru.kovbasa.tests;

import com.microsoft.playwright.Locator;
import org.junit.jupiter.api.Test;
import ru.kovbasa.pages.ClickhousePage;

import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ClickhouseTeachersTest extends BaseTest {

    @Test
    void teachersCarouselAndPopup() {
        ClickhousePage clickhouse = new ClickhousePage(page(), config);
        clickhouse.open();

        Locator cards = clickhouse.getTeacherCards();
        cards.first().waitFor();
        assertTrue(cards.count() > 0, "Teacher cards should be visible");

        Locator activeCard = clickhouse.getActiveTeacherCard();
        String firstNameBefore = getCardName(activeCard);
        var scrollBefore = clickhouse.getTeachersScrollLeft();

        clickhouse.dragTeachersCarousel();

        activeCard = clickhouse.getActiveTeacherCard();
        String firstNameAfter = getCardName(activeCard);
        var scrollAfter = clickhouse.getTeachersScrollLeft();
        boolean scrolled = scrollBefore.isPresent() && scrollAfter.isPresent()
                && !scrollBefore.get().equals(scrollAfter.get());
        boolean nameChanged = !firstNameBefore.equals(firstNameAfter);
        assertTrue(scrolled || nameChanged,
                "Teacher list should be scrolled after drag");

        clickhouse.openTeacherPopup(activeCard);
        String popupName = clickhouse.getPopupTeacherName();
        assertTrue(!popupName.isEmpty()
                        && (popupName.contains(firstNameAfter)
                        || firstNameAfter.contains(popupName)),
                "Popup should match clicked teacher");

        clickhouse.clickPopupNext();
        String nextName = clickhouse.getPopupTeacherName();
        if (nextName.equals(popupName)) {
            clickhouse.dragTeachersCarousel();
            nextName = clickhouse.getPopupTeacherName();
        }
        assertNotEquals(popupName, nextName, "Next teacher should differ");

        clickhouse.clickPopupPrev();
        String prevName = clickhouse.getPopupTeacherName();
        int attempts = 0;
        while (!matches(prevName, popupName) && attempts < 2) {
            clickhouse.clickPopupPrev();
            prevName = clickhouse.getPopupTeacherName();
            attempts++;
        }
        assertTrue(matches(prevName, popupName),
                "Previous teacher should be opened");
    }

    private String getCardName(Locator card) {
        card.scrollIntoViewIfNeeded();
        Locator name = card.locator("h3, h4, [class*='name']").first();
        if (name.count() > 0) {
            String text = name.textContent();
            return text == null ? "" : text.trim();
        }
        String text = card.textContent();
        return text == null ? "" : text.trim();
    }

    private boolean matches(String a, String b) {
        return a.contains(b) || b.contains(a);
    }
}
