import { test, expect, type Page } from "@playwright/test";
import { login } from "./auth";

async function readable(page: Page) {
    expect(await page.locator("body").innerText()).not.toMatch(
        /P1-\d|Phase 1 browser|PROFILE-\d|Browser Test Teacher/,
    );
    expect(
        await page.evaluate(
            () => document.documentElement.scrollWidth <= innerWidth + 1,
        ),
    ).toBeTruthy();
}

test("demo role selector fills credentials for every role and signs in normally", async ({
    page,
}, info) => {
    await page.goto("/login");
    const selector = page.getByLabel("Demo role", { exact: true });
    for (const email of [
        "admin",
        "enrollment",
        "registrar",
        "finance-staff",
        "finance",
        "teacher",
        "dean",
        "department",
        "student",
    ]) {
        await selector.selectOption(email + "@school.test");
        await expect(
            page.getByLabel("Email address", { exact: true }),
        ).toHaveValue(email + "@school.test");
        await expect(page.getByLabel("Password", { exact: true })).toHaveValue(
            "SchoolDemo2026!",
        );
    }
    await selector.selectOption("teacher@school.test");
    await page.screenshot({
        path: `design/implementation/simulation-demo-login-${info.project.name}.png`,
    });
    await page.getByRole("button", { name: "Sign in", exact: true }).click();
    await expect(
        page.getByRole("heading", {
            name: "My teaching overview",
            exact: true,
        }),
    ).toBeVisible();
});

test("simulation shows named Students, actual subjects and separate school-year details", async ({
    page,
}, info) => {
    const errors: string[] = [];
    page.on("pageerror", (error) => errors.push(error.message));
    await login(page, "registrar");
    await page.goto("/enrollment-records?search=Miguel%20Santos");
    await page.getByRole("link", { name: "View record", exact: true }).click();
    await expect(
        page.getByRole("heading", { name: "Miguel Santos", exact: true }),
    ).toBeVisible();
    const details = page.locator("section.panel").filter({
        has: page.getByRole("heading", {
            name: "Enrollment details",
            exact: true,
        }),
    });
    await expect(details).toContainText("BS Information Technology");
    await expect(details).toContainText("2026–2027");
    await expect(details).toContainText("First Semester");
    await expect(details).toContainText("1st Year");
    await expect(details).toContainText("BSIT 1-A");
    await expect(
        page.getByText("Computer Programming 1", { exact: false }).first(),
    ).toBeVisible();
    await readable(page);
    await page.screenshot({
        path: `design/implementation/simulation-enrollment-${info.project.name}.png`,
        fullPage: true,
    });
    await page.goto("/schedule");
    await expect(page.getByLabel("School year", { exact: true })).toHaveValue(
        "2026–2027",
    );
    await page
        .getByLabel("Enrollment period", { exact: true })
        .selectOption({ label: "First Semester" });
    await expect(
        page.getByText("Computer Programming 1", { exact: false }).first(),
    ).toBeVisible();
    await expect(
        page.getByText("Computer Programming 2", { exact: false }),
    ).toHaveCount(0);
    await readable(page);
    await page.screenshot({
        path: `design/implementation/simulation-schedule-${info.project.name}.png`,
        fullPage: true,
    });
    await page
        .getByLabel("Enrollment period", { exact: true })
        .selectOption({ label: "Full School Year" });
    await expect(
        page.getByText("Mathematics 7", { exact: false }).first(),
    ).toBeVisible();
    await readable(page);
    expect(errors).toEqual([]);
});

test("school-year setup uses one coverage choice and generates the semester name", async ({
    page,
}, info) => {
    await login(page, "admin");
    await page.goto("/setup");
    await page
        .getByRole("tab", { name: "School years & grades", exact: true })
        .click();
    const form = page.locator("form").filter({
        has: page.getByRole("button", {
            name: "Add school year / semester",
            exact: true,
        }),
    });
    await form.getByLabel("School year", { exact: true }).fill("2027-2028");
    await form
        .getByLabel("Coverage", { exact: true })
        .selectOption("semester_1");
    await expect(form.locator('input[name="name"]')).toHaveValue(
        "First Semester · 2027–2028",
    );
    await expect(form.locator('input[name="kind"]')).toHaveValue("semester");
    await expect(
        form.getByLabel("Classes start", { exact: true }),
    ).toBeVisible();
    await expect(form.getByLabel("Period name", { exact: true })).toHaveCount(
        0,
    );
    await readable(page);
    await form.scrollIntoViewIfNeeded();
    await page.screenshot({
        path: `design/implementation/simulation-school-years-${info.project.name}.png`,
    });
});

test("batch-first enrollment and curriculum setup use plain school terms", async ({
    page,
}, info) => {
    const errors: string[] = [];
    page.on("pageerror", (e) => errors.push(e.message));
    await login(page, "registrar");
    await page.goto("/enrollments");
    await expect(
        page.getByRole("button", { name: "Open Enrollment", exact: true }),
    ).toBeVisible();
    await expect(
        page.getByRole("button", { name: "Start enrollment", exact: true }),
    ).toHaveCount(0);
    await expect(
        page.getByRole("link", { name: "View batch", exact: true }).first(),
    ).toBeVisible();
    await readable(page);
    await page.screenshot({
        path: `design/implementation/batch-enrollments-${info.project.name}.png`,
        fullPage: true,
    });
    await page
        .getByRole("button", { name: "Open Enrollment", exact: true })
        .click();
    const dialog = page.getByRole("dialog");
    await dialog
        .getByLabel("Branch", { exact: true })
        .selectOption({ label: "Main Campus" });
    await dialog
        .getByLabel("School level", { exact: true })
        .selectOption("college");
    await expect(
        dialog.getByLabel("School Year", { exact: true }).locator("option"),
    ).toContainText(["Choose School Year", "2026–2027"]);
    await readable(page);
    await page.screenshot({
        path: `design/implementation/open-enrollment-${info.project.name}.png`,
    });
    await page.keyboard.press("Escape");
    await login(page, "admin");
    await page.goto("/setup");
    await expect(
        page.getByRole("heading", { name: "Global Curricula", exact: true }),
    ).toBeVisible();
    await expect(
        page.getByRole("heading", { name: "Unit Types", exact: true }),
    ).toBeVisible();
    await page.getByText("Configure Lecture", { exact: true }).click();
    await expect(
        page.getByRole("spinbutton", { name: "Price (PHP)", exact: true }),
    ).toHaveAttribute("min", "0");
    await readable(page);
    expect(errors).toEqual([]);
});

test("College intake excludes Grade 11 and existing wrong draft offers removal", async ({
    page,
}, info) => {
    await login(page, "registrar");
    await page.goto("/enrollments");
    const batch = page
        .locator("tr:visible,article.subject-choice:visible")
        .filter({ hasText: "College" })
        .filter({ hasText: "Second Semester" })
        .filter({ hasText: "Main Campus" });
    test.skip(
        (await batch.count()) === 0,
        "No open College second-semester demonstration batch.",
    );
    await batch.getByRole("link", { name: "View batch", exact: true }).click();
    await expect(page).toHaveURL(/\/enrollment-batches\/\d+$/);
    const francis = page
        .locator("tr:visible,article.subject-choice:visible")
        .filter({ hasText: "Francis Bautista" });
    if (await francis.count()) {
        await expect(francis).toContainText("not eligible");
        await expect(
            francis.getByRole("link", { name: "Continue", exact: true }),
        ).toHaveCount(0);
        await francis
            .getByRole("button", { name: "Remove from batch", exact: true })
            .click();
        await expect(page.getByRole("dialog")).toContainText(
            "Francis Bautista",
        );
        await page.screenshot({
            path: `design/implementation/simulation-remove-ineligible-${info.project.name}.png`,
        });
        await page.keyboard.press("Escape");
    }
    await page
        .getByRole("button", { name: "Add Student", exact: true })
        .click();
    const dialog = page.getByRole("dialog");
    await dialog
        .getByLabel("Search Student", { exact: true })
        .fill("Francis Bautista");
    await expect(
        dialog
            .getByLabel("Student", { exact: true })
            .locator("option")
            .filter({ hasText: "Francis Bautista" }),
    ).toHaveCount(0);
    await readable(page);
    await page.screenshot({
        path: `design/implementation/simulation-eligible-students-${info.project.name}.png`,
    });
    await page.keyboard.press("Escape");
});
