package com.example.e2e;

import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

/**
 * End-to-end example covering {@link com.example.views.FormView}: rendering,
 * binder validation and the two form buttons. Captions are English — see
 * {@link PlaywrightTestBase#openPage()} for why.
 */
class FormViewPlaywrightTest extends PlaywrightTestBase {

    @BeforeEach
    void openFormView() {
        navigate("formular");
    }

    @Test
    void form_rendersItsFieldsAndTheReadOnlyAge() {
        assertThat(page.getByText("Registration")).isVisible();
        assertThat(field("First name")).isVisible();
        assertThat(field("Last name")).isVisible();
        assertThat(field("Email")).isVisible();
        // preset on the bean and bound read-only
        assertThat(field("Age")).hasValue("37");
        assertThat(field("Age")).not().isEditable();
    }

    @Test
    void save_withoutRequiredFields_showsErrorNotification() {
        button("Save").click();

        assertThat(notification()).containsText("Please check your entries");
    }

    @Test
    void save_withInvalidEmail_showsErrorNotification() {
        field("First name").fill("Max");
        field("Last name").fill("Mustermann");
        field("Email").fill("not-an-email");

        button("Save").click();

        assertThat(notification()).containsText("Please check your entries");
    }

    @Test
    void save_withValidInput_showsSuccessNotification() {
        field("First name").fill("Max");
        field("Last name").fill("Mustermann");
        field("Email").fill("max@example.com");

        button("Save").click();

        assertThat(notification()).containsText("Saved: Max Mustermann");
    }

    @Test
    void reset_clearsTheEnteredValues() {
        field("First name").fill("Max");
        field("Last name").fill("Mustermann");

        button("Reset").click();

        assertThat(field("First name")).hasValue("");
        assertThat(field("Last name")).hasValue("");
    }

    /** The input inside the Vaadin field carrying {@code label}. */
    private Locator field(String label) {
        return page.getByLabel(label, new Page.GetByLabelOptions().setExact(true));
    }

    private Locator button(String caption) {
        return page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(caption).setExact(true));
    }

    private Locator notification() {
        return page.locator("vaadin-notification-card");
    }
}
