import { verify } from "crypto";
import { test, expect } from "../../../fixtures/index";
import { ContactPage } from "../../../pom/contact/contact.page";
import { LoginPage } from "../../../pom/login.page";
import { RequestPage } from "../../../pom/request/request.page";
import { BusinessPage } from "../../../pom/business/business.page";
import { randomDate } from "../../../pom/utils/utlisFunc";
import { randomString, randomText } from "../../../utils/array";
import { verifyScreenshot } from "../../../utils/screenshot";

test.describe("Features for contact tests", async () => {
    let loginPage: LoginPage;
    let contactPage: ContactPage;

    test.beforeEach(async ({ page, conf }) => {
        loginPage = new LoginPage(page);
        contactPage = new ContactPage(page);
        contactPage.loadBusinessNames(
            conf.data.business_singular,
            conf.data.business_plural
        );

        await test.step("Navigate to login page", async () => {
            await loginPage.open();
            await page.waitForLoadState('networkidle');
        });

        await test.step("Perform login authentication", async () => {
            await loginPage.login(conf.data.username, conf.data.password);
            await expect(loginPage.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });
        });

        if (conf.data.not_redirect) {
            return;
        }

        await test.step("Navigate to contact page", async () => {
            await contactPage.open();
            await page.waitForLoadState('networkidle');
        });
    });

    test("CONTACT_007 - Verify contact pin/unpin functionality", {
        tag: ["@CONTACT_007", "@contact", "@function"]
    }, async ({ conf, apiHelper }) => {
        let contactID: string;
        const firstName = `${randomText(5)}${randomString(5)}`;
        const lastName = `${randomText(5)}${randomString(8)}`;
        const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
        const contactName = `${capitalize(firstName)} ${capitalize(lastName)}`;

        await test.step("Precondition: Create 2 new contacts", async () => {
            const createContactResponse1 = await apiHelper.createContact({
                first_name: firstName,
                last_name: lastName,
                address_1: "123 Main St"
            });
            contactID = createContactResponse1.contact_id;
        });

        await test.step("Search for existing contact", async () => {
            await contactPage.contactLoc.searchInput.fill(contactName);
            await expect(contactPage.contactLoc.searchInput).toHaveValue(contactName);
            await expect(contactPage.contactLoc.nameInrow(contactName).first()).toBeVisible();
        });

        await test.step("Pin contact and verify pinned state", async () => {
            await contactPage.waitForSecond(1);

            const pinButton = contactPage.contactLoc.btnPin.first();
            await expect(pinButton).toBeVisible();
            await pinButton.click();

            await expect(contactPage.contactLoc.btnUnPin.first()).toBeVisible({ timeout: 5_000 });
            await expect(contactPage.contactLoc.singleBoxContactPin(contactName)).toBeVisible();
        });

        await test.step("Unpin contact and verify unpinned state", async () => {
            const unpinButton = contactPage.contactLoc.btnUnPin.first();
            await expect(unpinButton).toBeVisible();
            await unpinButton.click();

            await expect(contactPage.contactLoc.btnPin.first()).toBeVisible({ timeout: 5_000 });
            await expect(contactPage.contactLoc.singleBoxContactPin(contactName)).not.toBeVisible();
        });

        await test.step("Teardown - Archive contacts", async () => {
            await apiHelper.archiveContact(contactID);
        });
    });

    test("CONTACT_009 - Verify contact archive and unarchive functionality", {
        tag: ["@CONTACT_009", "@contact", "@function"],
    }, async ({ conf, updateContactPage }) => {
        const contactName = conf.data.contact_exist;

        await test.step("Archive contact and verify archived state", async () => {
            await updateContactPage.dashboardLoc.modal.button.archive.click();
            await updateContactPage.dashboardLoc.modal.button.acceptArchive.click();

            await expect(updateContactPage.contactLoc.updating.msgArchiveSucess).toBeVisible({ timeout: 10_000 });
            await expect(updateContactPage.dashboardLoc.modal.headerModal("Contact Detail")).not.toBeVisible();
            await expect(updateContactPage.contactLoc.updating.headerWarningContact).toBeVisible();

            await updateContactPage.dashboardLoc.btnClosePopupNotification.click();
            await updateContactPage.dashboardLoc.detail.button.back.click();
            await updateContactPage.waitForSecond(2);
            await expect(updateContactPage.dashboardLoc.table.noResult.first()).toBeVisible();
        });

        await test.step("Navigate to archived contacts and verify contact exists", async () => {
            await updateContactPage.dashboardLoc.table.tabInTable("Archived").click();
            await expect(updateContactPage.contactLoc.updating.contactAlreadyExits(contactName).first()).toBeVisible({ timeout: 5_000 });
        });

        await test.step("Unarchive contact and verify restored state", async () => {
            await updateContactPage.contactLoc.updating.contactAlreadyExits(contactName).first().click();
            await updateContactPage.dashboardLoc.buttonUpdate.click();
            await expect(updateContactPage.dashboardLoc.modal.headerModal("Contact Detail")).toBeVisible();

            await updateContactPage.dashboardLoc.modal.button.unArchive.click();
            await expect(updateContactPage.contactLoc.updating.msgUnArchiveSucess).toBeVisible({ timeout: 1_000 });
            await expect(updateContactPage.dashboardLoc.modal.headerModal("Contact Detail")).not.toBeVisible();
            await expect(updateContactPage.contactLoc.updating.headerWarningContact).not.toBeVisible();

            await updateContactPage.dashboardLoc.btnClosePopupNotification.click();
            await updateContactPage.dashboardLoc.detail.button.back.click();
            await updateContactPage.waitForSecond(2);
            await expect(updateContactPage.dashboardLoc.table.noResult.first()).toBeVisible();
        });
    });

    test("CONTACT_022 - Verify contact group email count filtering", {
        tag: ["@CONTACT_022", "@contact", "@validate"]
    }, async ({ conf }) => {
        const contactGroupName = conf.data.contact_group;

        await test.step("Navigate to Contact Group page and search", async () => {
            await contactPage.dashboardLoc.buttonByText("Contact Group").click();
            await expect(contactPage.contactLoc.contactGroup.heading("Contact Groups")).toBeVisible();

            await contactPage.search(contactGroupName);
            await expect(contactPage.dashboardLoc.table.itemInRow(contactGroupName).first()).toBeVisible();
        });

        await test.step("Verify total email count matches contact list", async () => {
            const totalEmailElement = contactPage.contactLoc.contactGroup.totalEmail;
            await expect(totalEmailElement).toBeVisible();
            const totalEmailText = await totalEmailElement.textContent();
            const totalEmailCount = parseInt(totalEmailText?.trim() || "0");

            await totalEmailElement.click();
            await expect(contactPage.contactLoc.contactGroup.heading("Contacts")).toBeVisible();

            const contactData = await contactPage.getDataTable();
            const prescriptionContactsCount = contactData.filter(item =>
                item.includes("Prescription")
            ).length;

            expect(totalEmailCount).toBe(prescriptionContactsCount);
        });
    });

    test("CONTACT_024 - Verify suggested contact modal workflow", {
        tag: ["@CONTACT_024", "@contact", "@function"]
    }, async ({ page, conf }) => {
        const contactPageInstance = new ContactPage(page);
        let requestPage: RequestPage;
        const uniqueEmail = await contactPageInstance.getRanmdomEmail(conf.data.email);
        const caseId = conf.data.case;

        await test.step("Share request with new contact not in system", async () => {
            requestPage = new RequestPage(contactPageInstance.page);
            await requestPage.open();
            await requestPage.getDetailCase(caseId);
            await expect(requestPage.dashboardLoc.buttonByText("Share")).toBeVisible();
            await requestPage.waitForSecond(1);
            await requestPage.dashboardLoc.buttonByText("Share").click();
            await expect(requestPage.dashboardLoc.modal.headerModal("Share with others")).toBeVisible();

            const emailInput = requestPage.requestLoc.create.inputByPlaceholder("Type or select an email address").first();
            await emailInput.type(uniqueEmail, { delay: 100 });

            const newContactDropdown = requestPage.requestLoc.create.dropdownMemberShareNew(uniqueEmail);
            await expect(newContactDropdown).toBeVisible();
            await newContactDropdown.click();

            await requestPage.dashboardLoc.buttonByText("Done").first().click();
        });

        await test.step("Verify suggested contact modal appears", async () => {
            const contactPageForModal = new ContactPage(requestPage.page);
            await contactPageForModal.open();

            await expect(contactPageForModal.dashboardLoc.modal.headerModal("Suggested Contacts")).toBeVisible();
            await expect(contactPageForModal.dashboardLoc.common.spanText(uniqueEmail)).toBeVisible();
        });

        await test.step("Add suggested contact and verify in contact list", async () => {
            const contactPageForVerification = new ContactPage(requestPage.page);

            await contactPageForVerification.dashboardLoc.buttonByText("Save").first().click();
            await contactPageForVerification.search(uniqueEmail);
            await expect(contactPageForVerification.contactLoc.nameInrow(uniqueEmail).first()).toBeVisible();
        });
    });

    test("CONTACT_025 - Verify add tag in contact's detail", {
        tag: ["@CONTACT_025", "@contact", "@validate"]
    }, async ({ conf }) => {
        await test.step("Navigate to contact detail", async () => {
            await contactPage.getDetailCase(conf.data.email_already_exist);
        });

        await test.step("Verify add tags with tag count greater than 9 (invalid)", async () => {
            await contactPage.addMultipleTags(10);
            await contactPage.saveTags();
            await expect(contactPage.dashboardLoc.tag.errorMaxTag).toBeVisible();
        });

        await test.step("Verify when add < 9 tag (valid)", async () => {
            await contactPage.removeOneTag();
            await contactPage.saveTags();
            await expect(contactPage.dashboardLoc.msgSuccess.first()).toBeVisible();
            await contactPage.dashboardLoc.btnClosePopupNotification.click();
            await expect(contactPage.dashboardLoc.tag.btnSaveTag).not.toBeVisible();

            const tagCount = await contactPage.getTagCount();
            expect(tagCount).toBe(9);
        });

        await test.step("Clear all tag", async () => {
            await contactPage.clearAllTags();
            await contactPage.saveTags();
            await expect(contactPage.dashboardLoc.msgSuccess.first()).toBeVisible();
            await contactPage.dashboardLoc.btnClosePopupNotification.click();
            await expect(contactPage.dashboardLoc.tag.btnSaveTag).not.toBeVisible();

            const tagCount = await contactPage.getTagCount();
            expect(tagCount).toBe(0);
        });
    });

    test("CONTACT_028 - Change work type", {
        tag: ["@CONTACT_028", "@contact", "@function"]
    }, async ({ apiHelper }) => {
        let contactID: string = "";
        let totalActiveEntries: number = 0;
        let totalReferenceEntries: number = 0;
        const firstName = `${randomText(5)}${randomString(5)}`;
        const lastName = `${randomText(5)}${randomString(5)}`;
        const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
        const fullName = `${capitalize(firstName)} ${capitalize(lastName)}`;

        await test.step("Preconditon: Create new contact", async () => {
            totalActiveEntries = await contactPage.getTotalEntriesByTabs("contact-members", "0,1", false);
            totalReferenceEntries = await contactPage.getTotalEntriesByTabs("contact-members", "2", false);
            const createContactResponse = await apiHelper.createContact({
                first_name: firstName,
                last_name: lastName
            });

            contactID = createContactResponse.contact_id;
            expect(totalActiveEntries + 1).toBe(await contactPage.getTotalEntriesByTabs("contact-members", "0,1", false));
        });

        await test.step("Change client to referrence", async () => {
            await contactPage.getDetailCase(fullName);
            await expect(contactPage.dashboardLoc.detail.workType("Active")).toBeVisible();

            // Change work type to reference
            await contactPage.dashboardLoc.detail.workType("Active").click();
            await expect(contactPage.dashboardLoc.detail.optionWorkType("Reference")).toBeVisible();
            await contactPage.dashboardLoc.detail.optionWorkType("Reference").click();
            await expect(contactPage.dashboardLoc.detail.workType("Reference")).toBeVisible();
            await contactPage.waitForSecond(1);
        });

        await test.step("Verify client in list client", async () => {
            await contactPage.open();

            //Veriy total entries changed 
            expect(totalActiveEntries).toBe(await contactPage.getTotalEntriesByTabs("contact-members", "0,1", false));
            expect(totalReferenceEntries + 1).toBe(await contactPage.getTotalEntriesByTabs("contact-members", "2", false));

            //Veriy in tab Active
            await contactPage.dashboardLoc.table.tabInTable("Active").click();
            await contactPage.search(fullName);
            await expect(contactPage.dashboardLoc.table.itemInRow(fullName)).not.toBeVisible();

            //Verify in tab Reference
            await contactPage.dashboardLoc.table.tabInTable("Reference").click();
            await contactPage.search(fullName);
            await expect(contactPage.dashboardLoc.table.itemInRow(fullName)).toBeVisible();
        });

        await test.step("Change client back to active", async () => {
            await contactPage.dashboardLoc.table.itemInRow(fullName).click();
            await expect(contactPage.dashboardLoc.detail.workType("Reference")).toBeVisible();
            // Change work type to active
            await contactPage.dashboardLoc.detail.workType("Reference").click();
            await expect(contactPage.dashboardLoc.detail.optionWorkType("Active")).toBeVisible();
            await contactPage.dashboardLoc.detail.optionWorkType("Active").click();
            await expect(contactPage.dashboardLoc.detail.workType("Active")).toBeVisible();
            await contactPage.waitForSecond(1);
        });

        await test.step("Verify client back to active in list client", async () => {
            await contactPage.open();

            //Veriy total entries changed
            expect(totalActiveEntries + 1).toBe(await contactPage.getTotalEntriesByTabs("contact-members", "0,1", false))
            expect(totalReferenceEntries).toBe(await contactPage.getTotalEntriesByTabs("contact-members", "2", false));

            //Veriy in tab Active
            await contactPage.dashboardLoc.table.tabInTable("Active").click();
            await contactPage.search(fullName);
            await expect(contactPage.dashboardLoc.table.itemInRow(fullName)).toBeVisible();

            //Verify in tab Reference
            await contactPage.dashboardLoc.table.tabInTable("Reference").click();
            await contactPage.search(fullName);
            await expect(contactPage.dashboardLoc.table.itemInRow(fullName)).not.toBeVisible();
        });

        await test.step("Teardown: Archive contact", async () => {
            await apiHelper.archiveContact(contactID);
        });
    });

    test("CONTACT_029 - Verify tab view all ", {
        tag: ['@CONTACT_029', '@contact', '@function']
    }, async ({ conf }) => {
        let totalBeforeSearch: number = 0;
        let totalAfterSearch: number = 0;
        const tabs = [
            { name: "All", types: "0,1,2" },
            { name: "Active", types: "0,1" },
            { name: "Reference", types: "2" }
        ];

        await test.step("Verify total in tab", async () => {
            // Fetch all API totals
            const apiTotals = await Promise.all(
                tabs.map(tab => contactPage.getTotalEntriesByTabs("contact-members", tab.types, false))
            );
            expect(apiTotals[0]).toBe(apiTotals[1] + apiTotals[2]);

            // Fetch UI totals
            await contactPage.waitAllRequestCompeleted();
            const uiTotals = await Promise.all(
                tabs.map(tab => contactPage.dashboardLoc.common.spanCountByTab(tab.name).innerText().then(Number))
            );
            expect(uiTotals[0]).toBe(uiTotals[1] + uiTotals[2]);
            totalBeforeSearch = uiTotals[0];
            // Verify each tab shows correct total in table and compare API vs UI
            for (let i = 0; i < tabs.length; i++) {
                await contactPage.dashboardLoc.table.tabInTable(tabs[i].name).click();
                await expect(contactPage.dashboardLoc.table.entriesTotal).toContainText(`${uiTotals[i]}`);
                expect(uiTotals[i]).toBe(apiTotals[i]);
            }
        });

        await test.step("Verify when search and change tab", async () => {
            await contactPage.search(conf.data.email_already_exist);
            await contactPage.waitAllRequestCompeleted();

            const apiTotals = await Promise.all(
                tabs.map(tab => contactPage.getTotalEntriesByTabs("contact-members", tab.types, false, "s=test%40gmail.com"))
            );
            expect(apiTotals[0]).toBe(apiTotals[1] + apiTotals[2]);

            await contactPage.waitForSecond(2); // Wait for UI to update after search

            const uiTotals = await Promise.all(
                tabs.map(tab => contactPage.dashboardLoc.common.spanCountByTab(tab.name).innerText().then(Number))
            );
            expect(uiTotals[0]).toBe(uiTotals[1] + uiTotals[2]);
            totalAfterSearch = uiTotals[0];
            expect(totalAfterSearch).toBeLessThan(totalBeforeSearch);

            // Verify each tab shows correct total in table and compare API vs UI
            for (let i = 0; i < tabs.length; i++) {
                await contactPage.dashboardLoc.table.tabInTable(tabs[i].name).click();
                await expect(contactPage.dashboardLoc.search.inputSearch).toHaveValue(conf.data.email_already_exist);
                await expect(contactPage.dashboardLoc.table.entriesTotal).toContainText(`${uiTotals[i]}`);
                expect(uiTotals[i]).toBe(apiTotals[i]);
            }
        });
    });
});

test("CONTACT_032 - Verify confirm business, contact in banner 1", {
    tag: ['@CONTACT_032', '@contact', '@function']
}, async ({ adminBusiness, apiHelper, conf, browser }) => {
    test.setTimeout(200_000);
    const { adminPage, businessName, memberEmail, fullNameUser } = adminBusiness;
    const loginPage = new LoginPage(adminPage.page);
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    const dob = await randomDate();

    await test.step("Verify login with new user", async () => {
        await loginPage.open();
        await loginPage.login(memberEmail, "123123123");
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });
    });

    await test.step("User A create new client, case, request and share to user B", async () => {
        await apiHelper.createFullRequest({
            first_name: firstName,
            last_name: lastName,
            birthday: dob,
            category_id: conf.data.category_id,
            message_text: '<p>Request from User A - Existing client (automation OFF)</p>',
            intent_type: conf.data.intent_type,
            request_type_id: conf.data.request_type_id,
            emails: [conf.data.user_receive],
            send_email_notification: 0,
            switch: conf.data.switch
        });

        if (adminPage.page && adminPage.page.context()) {
            await adminPage.page.context().close();
        }
    });

    let contactPageB: ContactPage;

    await test.step("User B: Login to system and navigate to contact page", async () => {
        const contextB = await browser.newContext();
        const pageB = await contextB.newPage();
        const loginPageB = new LoginPage(pageB);
        contactPageB = new ContactPage(pageB);
        await pageB.addLocatorHandler(contactPageB.dashboardLoc.closeNotification, async () => {
            await contactPageB.dashboardLoc.closeNotification.click();
        });

        await loginPageB.open();
        await loginPageB.login(conf.data.user_receive, conf.data.password);
        await expect(loginPageB.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });

        await contactPageB.open();
        await contactPageB.search(memberEmail)
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();
    });

    await test.step("User B: Goto contact detail and confirm contact", async () => {
        // Accept this contact
        await contactPageB.waitForSecond(1);
        await contactPageB.dashboardLoc.table.itemInRow(memberEmail).first().click();
        await expect(contactPageB.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-contact-first.png', contactPageB.dashboardLoc.detail.bannerHaveNewAddOn, [], 0.01);

        await contactPageB.dashboardLoc.buttonByText("Yes, Keep").click();
        await expect(contactPageB.dashboardLoc.detail.bannerHaveNewAddOn).not.toBeVisible();

        //Verify in list contact
        await contactPageB.open();
        await contactPageB.dashboardLoc.table.tabInTable("Active").click();
        await contactPageB.search(memberEmail);
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });

        await expect(contactPageB.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).not.toBeVisible();

        await contactPageB.dashboardLoc.table.tabInTable("Reference").click();
        await expect(contactPageB.dashboardLoc.table.noResult.first()).toBeVisible();
    });

    await test.step("User B: Goto business detail and confirm business", async () => {
        const businessPage = new BusinessPage(contactPageB.page);
        await businessPage.open();
        await businessPage.search(businessName);

        // Verify show icon New
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).toBeVisible();
        await expect(businessPage.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();

        // Goto detail business
        await businessPage.waitForSecond(1);
        await businessPage.dashboardLoc.table.itemInRow(businessName).first().click();

        // Verify show banner and click confirm
        await expect(businessPage.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-business-first.png', businessPage.dashboardLoc.detail.bannerHaveNewAddOn, [], 0.01);

        await businessPage.dashboardLoc.buttonByText("Yes, Keep").click();
        await expect(businessPage.dashboardLoc.detail.bannerHaveNewAddOn).not.toBeVisible();

        // Verify in list business
        await businessPage.open();
        await businessPage.search(businessName);

        await expect(businessPage.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).not.toBeVisible();

        await businessPage.dashboardLoc.table.tabInTable("Reference").click();
        await expect(businessPage.dashboardLoc.table.noResult.first()).toBeVisible();
    });
});

test("CONTACT_033 - Verify reject business, contact in banner 1", {
    tag: ['@CONTACT_033', '@contact', '@function']
}, async ({ adminBusiness, apiHelper, conf, browser }) => {
    test.setTimeout(200_000);
    const { adminPage, businessName, memberEmail, fullNameUser } = adminBusiness;
    const loginPage = new LoginPage(adminPage.page);
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    const dob = await randomDate();

    await test.step("Verify login with new user", async () => {
        await loginPage.open();
        await loginPage.login(memberEmail, "123123123");
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });
    });

    await test.step("User A create new client, case, request and share to user B", async () => {
        await apiHelper.createFullRequest({
            first_name: firstName,
            last_name: lastName,
            birthday: dob,
            category_id: conf.data.category_id,
            message_text: '<p>Request from User A - Existing client (automation OFF)</p>',
            intent_type: conf.data.intent_type,
            request_type_id: conf.data.request_type_id,
            emails: [conf.data.user_receive],
            send_email_notification: 0,
            switch: conf.data.switch
        });

        if (adminPage.page && adminPage.page.context()) {
            await adminPage.page.context().close();
        }
    });

    let contactPageB: ContactPage;

    await test.step("User B: Login to system and navigate to contact page", async () => {
        const contextB = await browser.newContext();
        const pageB = await contextB.newPage();
        const loginPageB = new LoginPage(pageB);
        contactPageB = new ContactPage(pageB);
        await pageB.addLocatorHandler(contactPageB.dashboardLoc.closeNotification, async () => {
            await contactPageB.dashboardLoc.closeNotification.click();
        });

        await loginPageB.open();
        await loginPageB.login(conf.data.user_receive, conf.data.password);
        await expect(loginPageB.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });

        await contactPageB.open();
        await contactPageB.search(memberEmail)
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();
    });

    await test.step("User B: Goto contact detail and reject contact", async () => {
        // Reject this contact
        await contactPageB.waitForSecond(1);
        await contactPageB.dashboardLoc.table.itemInRow(memberEmail).first().click();
        await expect(contactPageB.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-contact-first.png', contactPageB.dashboardLoc.detail.bannerHaveNewAddOn, [], 0.01);

        await contactPageB.dashboardLoc.buttonByText("No, Move").click();
        await expect(contactPageB.dashboardLoc.detail.bannerHaveNewAddOn).not.toBeVisible();

        //Verify in list contact
        await contactPageB.open();
        await contactPageB.dashboardLoc.table.tabInTable("Active").click();
        await contactPageB.search(memberEmail);
        await expect(contactPageB.dashboardLoc.table.noResult.first()).toBeVisible();

        await contactPageB.dashboardLoc.table.tabInTable("Reference").click();
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });

        await expect(contactPageB.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).not.toBeVisible();
    });

    await test.step("User B: Goto business detail and reject business", async () => {
        const businessPage = new BusinessPage(contactPageB.page);
        await businessPage.open();
        await businessPage.search(businessName);

        // Verify show icon New
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).toBeVisible();
        await expect(businessPage.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();

        // Goto detail business
        await businessPage.waitForSecond(1);
        await businessPage.dashboardLoc.table.itemInRow(businessName).first().click();

        // Verify show banner and click confirm
        await expect(businessPage.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-business-first.png', businessPage.dashboardLoc.detail.bannerHaveNewAddOn, [], 0.01);

        await businessPage.dashboardLoc.buttonByText("No, Move").click();
        await expect(businessPage.dashboardLoc.detail.bannerHaveNewAddOn).not.toBeVisible();

        // Verify in list business
        await businessPage.open();
        await businessPage.search(businessName);
        await businessPage.dashboardLoc.table.tabInTable("Active").click();
        await expect(businessPage.dashboardLoc.table.noResult.first()).toBeVisible();

        await businessPage.dashboardLoc.table.tabInTable("Reference").click();
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).not.toBeVisible();
    });
});

test("CONTACT_034 - Verify reject business, contact in banner 2", {
    tag: ['@CONTACT_034', '@contact', '@function']
}, async ({ adminBusiness, apiHelper, conf, browser }) => {
    test.setTimeout(200_000);
    const { adminPage, businessName, memberEmail, fullNameUser } = adminBusiness;
    const loginPage = new LoginPage(adminPage.page);
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    const dob = await randomDate();

    await test.step("Verify login with new user", async () => {
        await loginPage.open();
        await loginPage.login(memberEmail, "123123123");
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });
    });

    await test.step("User A create new client, case, request and share to user B", async () => {
        await apiHelper.createFullRequest({
            first_name: firstName,
            last_name: lastName,
            birthday: dob,
            category_id: conf.data.category_id,
            message_text: '<p>Request from User A - Existing client (automation OFF)</p>',
            intent_type: conf.data.intent_type,
            request_type_id: conf.data.request_type_id,
            emails: [conf.data.user_receive],
            send_email_notification: 0,
            switch: conf.data.switch
        });

        if (adminPage.page && adminPage.page.context()) {
            await adminPage.page.context().close();
        }
    });

    let contactPageB: ContactPage;

    await test.step("User B: Login to system and navigate to contact page", async () => {
        const contextB = await browser.newContext();
        const pageB = await contextB.newPage();
        const loginPageB = new LoginPage(pageB);
        contactPageB = new ContactPage(pageB);
        await pageB.addLocatorHandler(contactPageB.dashboardLoc.closeNotification, async () => {
            await contactPageB.dashboardLoc.closeNotification.click();
        });

        await loginPageB.open();
        await loginPageB.login(conf.data.user_receive, conf.data.password);
        await expect(loginPageB.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });

        await contactPageB.open();
        await contactPageB.search(memberEmail)
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();
    });

    await test.step("User B: Goto contact detail and reject contact", async () => {
        // Reject this contact
        await contactPageB.waitForSecond(1);
        await contactPageB.dashboardLoc.table.itemInRow(memberEmail).first().click();
        await expect(contactPageB.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await contactPageB.page.reload();
        await expect(contactPageB.dashboardLoc.detail.bannerRelevant).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-contact-second.png', contactPageB.dashboardLoc.detail.bannerRelevant, [], 0.01);

        await contactPageB.dashboardLoc.buttonByText("No, Move").click();
        await expect(contactPageB.dashboardLoc.detail.bannerRelevant).not.toBeVisible();

        //Verify in list contact
        await contactPageB.open();
        await contactPageB.dashboardLoc.table.tabInTable("Active").click();
        await contactPageB.search(memberEmail);
        await expect(contactPageB.dashboardLoc.table.noResult.first()).toBeVisible();
        await contactPageB.waitForSecond(1);

        await contactPageB.dashboardLoc.table.tabInTable("Reference").click();
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });
        await expect(contactPageB.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).not.toBeVisible();
    });

    await test.step("User B: Goto business detail and reject business", async () => {
        const businessPage = new BusinessPage(contactPageB.page);
        await businessPage.open();
        await businessPage.search(businessName);

        // Verify show icon New
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).toBeVisible();
        await expect(businessPage.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();

        // Goto detail business
        await businessPage.waitForSecond(1);
        await businessPage.dashboardLoc.table.itemInRow(businessName).first().click();

        // Verify show banner and click confirm
        await expect(businessPage.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await businessPage.page.reload();
        await expect(businessPage.dashboardLoc.detail.bannerRelevant).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-business-second.png', businessPage.dashboardLoc.detail.bannerRelevant, [], 0.01);

        await businessPage.dashboardLoc.buttonByText("No, Move").click();
        await expect(businessPage.dashboardLoc.detail.bannerRelevant).not.toBeVisible();

        // Verify in list business
        await businessPage.open();
        await businessPage.search(businessName);
        await businessPage.dashboardLoc.table.tabInTable("Active").click();
        await expect(businessPage.dashboardLoc.table.noResult.first()).toBeVisible();
        await businessPage.waitForSecond(1);

        await businessPage.dashboardLoc.table.tabInTable("Reference").click();
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).not.toBeVisible();
    });
});

test("CONTACT_035 - Verify confirm business, contact in banner 2", {
    tag: ['@CONTACT_035', '@contact', '@function']
}, async ({ adminBusiness, apiHelper, conf, browser }) => {
    test.setTimeout(200_000);
    const { adminPage, businessName, memberEmail, fullNameUser } = adminBusiness;
    const loginPage = new LoginPage(adminPage.page);
    const firstName = `${randomText(5)}${randomString(5)}`;
    const lastName = `${randomText(5)}${randomString(5)}`;
    const dob = await randomDate();

    await test.step("Verify login with new user", async () => {
        await loginPage.open();
        await loginPage.login(memberEmail, "123123123");
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });
    });

    await test.step("User A create new client, case, request and share to user B", async () => {
        await apiHelper.createFullRequest({
            first_name: firstName,
            last_name: lastName,
            birthday: dob,
            category_id: conf.data.category_id,
            message_text: '<p>Request from User A - Existing client (automation OFF)</p>',
            intent_type: conf.data.intent_type,
            request_type_id: conf.data.request_type_id,
            emails: [conf.data.user_receive],
            send_email_notification: 0,
            switch: conf.data.switch
        });

        if (adminPage.page && adminPage.page.context()) {
            await adminPage.page.context().close();
        }
    });

    let contactPageB: ContactPage;

    await test.step("User B: Login to system and navigate to contact page", async () => {
        const contextB = await browser.newContext();
        const pageB = await contextB.newPage();
        const loginPageB = new LoginPage(pageB);
        contactPageB = new ContactPage(pageB);
        await pageB.addLocatorHandler(contactPageB.dashboardLoc.closeNotification, async () => {
            await contactPageB.dashboardLoc.closeNotification.click();
        });

        await loginPageB.open();
        await loginPageB.login(conf.data.user_receive, conf.data.password);
        await expect(loginPageB.baseLoc.dashboardContainer).toBeVisible({ timeout: 15_000 });

        await contactPageB.open();
        await contactPageB.search(memberEmail)
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();
    });

    await test.step("User B: Goto contact detail and confirm contact", async () => {
        // Accept this contact
        await contactPageB.waitForSecond(1);
        await contactPageB.dashboardLoc.table.itemInRow(memberEmail).first().click();
        await expect(contactPageB.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await contactPageB.page.reload();
        await expect(contactPageB.dashboardLoc.detail.bannerRelevant).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-contact-second.png', contactPageB.dashboardLoc.detail.bannerRelevant, [], 0.01);

        await contactPageB.dashboardLoc.buttonByText("Yes, Keep").click();
        await expect(contactPageB.dashboardLoc.detail.bannerRelevant).not.toBeVisible();

        //Verify in list contact
        await contactPageB.open();
        await contactPageB.dashboardLoc.table.tabInTable("Active").click();
        await contactPageB.search(memberEmail);
        await expect(contactPageB.dashboardLoc.table.itemInRow(memberEmail).first()).toBeVisible({ timeout: 15_000 });
        await expect(contactPageB.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(contactPageB.dashboardLoc.table.iconNew(memberEmail)).not.toBeVisible();

        await contactPageB.dashboardLoc.table.tabInTable("Reference").click();
        await expect(contactPageB.dashboardLoc.table.noResult.first()).toBeVisible();
    });

    await test.step("User B: Goto business detail and confirm business", async () => {
        const businessPage = new BusinessPage(contactPageB.page);
        await businessPage.open();
        await businessPage.search(businessName);

        // Verify show icon New
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).toBeVisible();
        await expect(businessPage.dashboardLoc.table.itemBoldUnread.first()).toBeVisible();

        // Goto detail business
        await businessPage.waitForSecond(1);
        await businessPage.dashboardLoc.table.itemInRow(businessName).first().click();

        // Verify show banner and click confirm
        await expect(businessPage.dashboardLoc.detail.bannerHaveNewAddOn).toBeVisible({ timeout: 15_000 });
        await businessPage.page.reload();
        await expect(businessPage.dashboardLoc.detail.bannerRelevant).toBeVisible({ timeout: 15_000 });
        await verifyScreenshot('banner-confirm-business-second.png', businessPage.dashboardLoc.detail.bannerRelevant, [], 0.01);

        await businessPage.dashboardLoc.buttonByText("Yes, Keep").click();
        await expect(businessPage.dashboardLoc.detail.bannerRelevant).not.toBeVisible();

        // Verify in list business
        await businessPage.open();
        await businessPage.search(businessName);
        await expect(businessPage.dashboardLoc.table.itemInRow(businessName).first()).toBeVisible({ timeout: 15_000 });
        await expect(businessPage.dashboardLoc.table.itemRead.first()).toBeVisible();
        await expect(businessPage.dashboardLoc.table.iconNew(businessName)).not.toBeVisible();

        await businessPage.dashboardLoc.table.tabInTable("Reference").click();
        await expect(businessPage.dashboardLoc.table.noResult.first()).toBeVisible();
    });
});