import { DashboardPage } from "../dashboard.page";
import { Browser, BrowserContext, expect, Page } from '@playwright/test'
import { tableSearchUniqueSnapshot, headingAndCreateButton, tipsBlock, emptyState, haveRecord, caseUpdateUIHeader, caseUpdateUIBody, caseUpdateUIFooter, caseDetailLackInfo, caseDetailFullInfo } from "./case.snapshot";
import { LoginPage } from "../login.page";
import { RequestPage } from "../request/request.page";
import { verifyScreenshot } from "../../utils/screenshot";

export class CasePage extends DashboardPage {
    personalSearch: `//input[@class='form-control' and @placeholder='Search...']` | undefined;

    constructor(page: Page) {
        super(page);
    }

    actionType = [
        { name: "Letter of Protection", expectedRequests: 2 },
        { name: "Medical Bill", expectedRequests: 1 },
        { name: "Prescription", expectedRequests: 1 },
        { name: "Others", expectedRequests: 1 },
        { name: "Transfer", expectedRequests: 1 }
    ]

    statusTests = [
        { detail: 'Open', expectedStatus: 'Open' },
        { detail: 'In Progress', expectedStatus: 'In Progress' },
        { detail: 'On Hold', expectedStatus: 'On Hold' },
        { detail: 'Closed', expectedStatus: 'Closed' },
        { detail: 'Dropped', expectedStatus: 'Closed' },
        { detail: 'Cancelled', expectedStatus: 'Closed' },
        { detail: 'Declined', expectedStatus: 'Closed' },
        { detail: 'Transferred', expectedStatus: 'Closed' },
        { detail: 'Referred', expectedStatus: 'Closed' },
        { detail: 'Unknown', expectedStatus: 'Unknown' }
    ];

    infoPrev = ["full_name_client", "birthday_client", "address_client", "email_client", "phone_client", "text-description-case"];

    caseUpdateForm = [
        {
            inputName: "service_from",
            type: "input",
        },
        {
            inputName: "service_to",
            type: "input",
        },
        {
            inputName: "reference_id",
            type: "input"
        },
        {
            inputName: "description",
            type: "textarea"
        },
    ]

    get caseProps() {
        return {
            filterProperties: [
                {
                    name: 'case_id',
                    type: 'input'
                },
                {
                    name: 'patient',
                    type: 'input'
                }
            ],
            threeDotDropdownMenus: {
                customizedColumn: 'Customized Columns',
            },
            requestsColumns: [
                {
                    name: '#',
                    default: true,
                    tableDisplayName: '#'
                },
                {
                    name: 'Request',
                    default: true,
                    tableDisplayName: 'Request'
                },
                {
                    name: 'Status',
                    default: true,
                    tableDisplayName: 'Status'
                },
                {
                    name: 'Status Details',
                    default: true,
                    tableDisplayName: 'Status Details'
                },
                {
                    name: 'Star It',
                    default: true,
                    tableDisplayName: 'Star It'
                },
                {
                    name: 'Patient Name',
                    default: false,
                    tableDisplayName: 'Patient Name'
                },
                {
                    name: 'Shared From',
                    default: true,
                    tableDisplayName: 'Shared From'
                },
                {
                    name: 'Creator',
                    default: true,
                    tableDisplayName: 'Creator'
                },
                {
                    name: 'Directed To',
                    default: true,
                    tableDisplayName: 'Directed To'
                },
                {
                    name: 'Submit User',
                    default: false,
                    tableDisplayName: 'Submitted User'
                },
                {
                    name: 'Date',
                    default: false,
                    tableDisplayName: 'Date'
                },
                {
                    name: 'Updated',
                    default: false,
                    tableDisplayName: 'Updated'
                },
                {
                    name: 'Actions',
                    default: true,
                    tableDisplayName: 'Actions'
                }

            ],
            customizedColumns: [
                {
                    name: 'Pin',
                    default: true,
                    tableDisplayName: 'Pin'
                },
                {
                    name: 'Case #',
                    default: true,
                    tableDisplayName: 'Case #'
                },
                {
                    name: 'Patient Name',
                    default: true,
                    tableDisplayName: 'Patient Name'
                },
                {
                    name: 'DOI',
                    default: true,
                    tableDisplayName: 'DOI'
                },
                {
                    name: 'Status',
                    default: true,
                    tableDisplayName: 'Status'
                },
                {
                    name: 'Client DOB',
                    default: false,
                    tableDisplayName: 'Client DOB'
                },
                {
                    name: 'Category',
                    default: false,
                    tableDisplayName: 'Category'
                },
                {
                    name: 'Service From',
                    default: false,
                    tableDisplayName: 'Service From'
                },
                {
                    name: 'Service To',
                    default: false,
                    tableDisplayName: 'Service To'
                },
                {
                    name: 'Alias',
                    default: false,
                    tableDisplayName: 'Alias'
                },
                {
                    name: 'Case Name',
                    default: false,
                    tableDisplayName: 'Case Name'
                },
                {
                    name: 'Assignee',
                    default: false,
                    tableDisplayName: 'Assignee'
                },
                {
                    name: 'Date',
                    default: false,
                    tableDisplayName: 'Date'
                },
                {
                    name: 'Updated',
                    default: false,
                    tableDisplayName: 'Updated'
                }
            ]
        }
    }

    checkboxArchiveList = [this.caseLoc.checkboxArchiveMe, this.caseLoc.checkboxArchiveTeam];

    get caseLoc() {
        return {
            // Link case
            bannerCaseRelevant: this.genLoc("//div[@class='box-is-this-relevant mb-3']"),
            bannerNewCaseCreated: this.genLoc("//div[@class='box-request-link-case mb-3']"),
            svgBannerNewCaseCreated: this.genLoc("//div[@class='box-request-link-case mb-3']//span[@class='svg']"),

            // Case New
            itemBoldUnread: this.genLoc("//tr[contains(@class,'not_field_read fw-bold')]"),
            itemReaded: this.genLoc("//tr[contains(@class,'row-data-table read')]"),
            itemAcceptedButUnRead: this.genLoc("//tr[contains(@class,'row-data-table')]"),
            caseIDNew: (caseID: string) => this.genLoc(`//a[contains(.,'${caseID}')]/descendant::span[text()='${caseID}']`),

            shareRequest: {
                tableActivityRequest: this.genLoc("//h2[text()='Request Activity']//ancestor::div[contains(@class,'card bd-none bx-shadow')]"),
                modalPromote: this.genLoc("//h2[text()='Enhance this Request?']/ancestor::div[contains(@class,'modal-body')]"),
                buttonPromote: this.genLoc("//div[@class='request-action-icon']"),
                tableShareRequest: this.genLoc("//div[contains(@class,'tips-content')]")
            },

            linkcase: {
                bannerNewBusinessAddon: this.genLoc("//div[contains(@class,'box-case-have-new-business-add-on')]"),
                newRequestID: this.genLoc("//div[contains(@class, 'card-header') and .//h2[text()='Request Activity']]//following-sibling::div[contains(@class, 'table-responsive')]/table/descendant::a[1]"),
                caseIDLinked: this.genLoc("//tr[contains(@class,'row-data-table')]/td[2]/descendant::span"),
                newCaseID: this.genLoc("//tr[contains(@class,'not_field_read fw-bold')]/td[2]/descendant::span"),
                bannerCreatedCaseSuccess: this.genLoc("//div[@class='case-confirm-banner']")
            },

            caseDOI: this.genLoc("//div[@class='list-info-items']/span[1]"),

            linkToCase: (caseID: string) => this.genLoc(`//a[contains(.,'#${caseID}')]`),
            linkToCaseID: (caseID: string) => this.genLoc(`//a[contains(text(),'#${caseID}')]`),
            btnCloseModal: this.genLoc("//button[text()='Close' and @data-user-tracking]"),
            checkboxArchiveMe: this.genLoc("//input[contains(@id,'checkbox-user_state#is_archived')]"),
            checkboxArchiveTeam: this.genLoc("//input[contains(@id,'checkbox-business_state#is_archived')]"),
            inputArchive: this.genLoc("//input[@name='is_archived']"),
            boxSelectArchive: (option: string) => this.genLoc(`//div[@class='autocomplete-option' and contains(.,'${option}')]`),
            create: {
                tagBusinessCreate: (businessName: string) => this.genLoc(`//div[contains(@class,'date-option') and contains(.,'${businessName}')]`),
                optionBusiness: (option: string) => this.genLoc(`//li[contains(.,'${option}')]`),
                btnCreate: this.genLoc("//button[text()='Create']"),
                btnCreateCase: this.genLoc("//button[text()='Create Case']"),
                msgCreateSuccess: this.genLoc("//p[text()='Added New Successfully!']"),
                detail: {
                    noOptionsCategory: this.genLoc("//div[@class='no-options']"),
                    inputCreateClientName: (name: string) => this.genLoc(`//input[@name='${name}']`),
                    inputByPlaceHolder: (placeholder: string) => this.genLoc(`//input[@placeholder="${placeholder}"]`),
                    createActive: this.genLoc("//button[@class='dropdown-item' and contains(.,'Add')] "),
                    description: this.genLoc("//textarea[@name='description']"),
                    doi: this.genLoc("//input[@name='date_of_injury']"),
                    bussiness: this.genLoc("(//input[@placeholder='Select or type a name'])[2]"),
                    boxTextBusinessByName: (name: string) => this.genLoc(`//div[contains(@class,'box-text box-text-business')]/div[text()='${name}']`),
                    categoryInput: this.genLoc("//input[@id='autocomplete_category_id']"),
                    optionCategory: (optionName: string) => this.genLoc(`//div[contains(@class,'title-option') and text()='${optionName}']`)
                },
                preview: {
                    infoClient: (name: string) => this.genLoc(`//p[contains(@class,'${name}')]`)
                }
            },
            detail: {
                inputUploadfile: this.genLoc("//input[@id='attachmentsObjectTypeDetailInput']"),
                listRequestTags: this.genLoc("//div[@class='list-request-tag']"),
                statusDetailRequestActivityTable: (requestDetail: string) => this.genLoc(`//a[text()='${requestDetail}']/preceding::h2[text()='Activity']`),
                modalFinalCaseReview: {
                    rowInTable: this.genLoc("//table[@class='table table-hover align-middle mb-0']/tbody/tr"),
                    textFilter: this.genLoc(`//h3[text()='Final Case Review']/following::span[@class='dropdown-option-icon']/following-sibling::span`),
                    btnSelectFilterRequestType: this.genLoc("//h3[text()='Final Case Review']/following::li[@class='dropdown-select__filter-selected cursor-pointer']"),
                    optionInSelectFilter: (requestType: string) => this.genLoc(`//h3[text()='Final Case Review']/following::li[@class='dropdown-select__select-option cursor-pointer']/following::span[text()='${requestType}']`),
                    firstRequestID: this.genLoc("//table[@class='table table-hover align-middle mb-0']/descendant::tr[2]/td[1]"),
                    btnSelectStatusdetailFirst: this.genLoc("//table[@class='table table-hover align-middle mb-0']/descendant::tr[2]/td[5]/div"),
                    selectOption: (option: string) => this.genLoc(`//span[text()='${option}']/ancestor::li`)
                },
                requestsInTableActivity: this.genLoc("//h2[text()='Request Activity']/following::table/tbody/tr"),
                btnCancelFinalCaseReview: this.genLoc("//button[@class='btn btn-cancel me-auto']"),
                btnSubmitAssignee: this.genLoc("//button[@data-test-id='btn-modal-assignee-member-submit']"),
                btnCloseModalUpdate: this.genLoc("//button[@data-test-id='btn-modal-case-new-edit-cancel']"),
                requestTableNoResult: this.genLoc("//div[text()='Start your request today.']"),
                dataIntable: (tableName: string, caseID: string) => this.genLoc(`//h2[text()='${tableName}']/following::a[text()='${caseID}']`),
                dropdownOption: (action: string) => this.genLoc(`//span[@class='dropdown-item cursor-pointer' and text()='${action}']`),
                btnClosePopup: this.genLoc("//button[@class='my-snackbar__close']"),
                noDataRequest: this.genLoc("//div[contains(text(),'Start your request today.')]"),
                noLegal: this.genLoc("//a[@data-user-tracking='BTN_SHOW_LEGAL_CONTACTS_MODAL']"),
                businessContact: this.genLoc("//p[contains(@class,'business-contact-name')]"),
                buttonActivity: this.genLoc("//button[@data-user-tracking='BTN_SHOW_REQUEST_ACTIVITY_MODAL']"),
                buttonUpdateCase: this.genLoc("//button[@data-user-tracking='BTN_SHOW_UPDATE_CASE_MODAL']"),
                boxClientNameActive: (clientName: string) => this.genLoc(`//div[@class='box-text box-text-business' and contains(.,'${clientName}')]`),
                textNoRequest: this.genLoc("//p[contains(.,'to submit your request or inquiries for this case now!')]"),
                requestExist: (requestID: string) => this.genLoc(`//a[contains(text(),'${requestID}')]`),
                requestExitInRequestTable: (requestID: string) => this.genLoc(`//div[contains(@class, 'card-header') and .//h2[text()='Request Activity']]//following-sibling::div[contains(@class, 'table-responsive')]//table//tr[td/a[@href='/requests/${requestID}']]`),
                discussionCase: this.genLoc("//div[contains(@class,'case-discussion-menu-icon')]/parent::div"),
                teamDiscussion: this.genLoc("//img[@alt='Team Discussion']"),

                discussion: {
                    inputMsg: this.genLoc("//input[@placeholder='Message']"),
                    contentMsg: (message: string) => this.genLoc(`//div[@class='content-message' and text()='${message}']`)
                },

                update: {
                    fieldForm: (type: string, name: string) => this.genLoc(`//${type}[@name='${name}']`),
                    msgArchive: this.genLoc("//p[text()='This case has been archived']"),
                    msgUnArchive: this.genLoc("//p[text()='This case has been unarchived']"),
                    boxHeaderArchive: this.genLoc("//div[@class='box-notification-archive']"),
                    btnUnArchive: this.genLoc("//a[text()='unarchiving.']"),
                },
                activity: {
                    spanInActivity: this.genLoc("(//div[@class='box-history-left']/div)[1]/p/span"),
                    listActivity: this.genLoc("//div[@class='box-modal-activity-history activity-history']"),
                    buttonClose: this.genLoc("//div[@class='box-btn-reset-apply-filter']/button[text()='Close']")
                },
                addLegalModal: {
                    btnAddSuggest: (nameBusiness: string) => this.genLoc(`//p[contains(text(),'Add suggested:')]/span[text()='${nameBusiness}']`),
                    counselAdd: (email: string) => this.genLoc(`//span[@class="date-option" and text()="${email}"]`),
                    inputByPlaceholder: (placeholder: string) => this.genLoc(`//input[@placeholder="${placeholder}"]`),
                    btnSubmit: this.genLoc("//button[text()='Submit']"),
                    msgSuccess: this.genLoc("//p[text()='Updated Successfully!']")
                },
                transfer: {
                    boxOption: (value: string) => this.genLoc(`//div[contains(@class,'title-option') and contains(text(),'${value}')]/ancestor::div[@class='autocomplete-option']`),
                    msgArchive: this.genLoc("//p[text()='This case has been archived']"),
                    radioCheckArchive: this.genLoc("//input[@id='radio-action-action2']")
                },

                //Status
                statusDetailsOption: (statusDetail: string) => this.genLoc(`//span[text()='${statusDetail}']/ancestor::li[@class='dropdown-select__select-option cursor-pointer']`),
                statusDetailsInput: this.genLoc("//li[@class='dropdown-select__filter-selected cursor-pointer']"),
                statusDisplay: this.genLoc("//span[contains(@class,'status-rq')]/span[2]"),

                //Assignee
                inputSearchMember: this.genLoc("//input[@name='assignee_id' and @placeholder='Search...']"),
                optionMember: this.genLoc("//div[contains(@class,'autocomplete-option')]"),
                btnAssignee: this.genLoc("//span[text()='Assignee:']/parent::div[contains(@class,'case-tour-step-two btn-update-case')]"),
                optionSearchExist: (email: string) => this.genLoc(`//div[@class='autocomplete-option']/div/span[text()='${email}']`),
                fullnameAssignee: this.genLoc("//span[contains(@class,'assignee-full-name')]"),

                //Dive deeper
                firstSuggestBusiness: this.genLoc("//div[contains(@class,'recommend-items')]/div[position()=1]/p"),
                labelByStepCreateRequest: (step: number) => this.genLoc(`//label[@class='select-step-value select-step-${step} cl-gray']`),
                btnCreateNewRequest: this.genLoc("//a[@data-user-tracking='BTN_SUBMIT_NEW_REQUEST_WITH_BUSINESS']"),
                listBusinesses: this.genLoc("//a[contains(@class,'logo-contact')]"),
                singleBusinesses: (name: string) => this.genLoc(`//a[contains(@class,'logo-contact') and @data-tooltip-content='${name}']`),
                btnDropDownActionBySingleBusiness: (name: string) => this.genLoc(`//a[contains(@class,'logo-contact') and @data-tooltip-content='${name}']`),
                btnDropdownBusiness: this.genLoc("//div[contains(@class,'dropdown action-case-participant')]"),
                btnInDropdownBusiness: (name: string) => this.genLoc(`//span[@data-user-tracking='${name}']`),
                popupSwal: this.genLoc("//div[@class='swal2-popup swal2-modal swal2-show']"),
                btnCofirmArchive: this.genLoc("//button[@class='swal2-confirm swal2-styled']"),
                btnViewArchivedBusiness: this.genLoc("//p[contains(text(),'View archived business')]"),
                listArchiveRequests: this.genLoc("(//h2[text()='Archived Request']/following::table)[1]/tbody/tr"),
                listLinkArchiveRequests: this.genLoc("(//h2[text()='Archived Request']/following::table)[1]/tbody/tr"),
                requestHadStarIt: (requestID: string) => this.genLoc(`//a[@href="/requests/${requestID}"]/*[name()='svg']`),
                keyFocus: (type: string) => this.genLoc(`//p[contains(text(),'${type}')]/ancestor::div[contains(@class,'request-type-items request-type-items-flip')]`),
                btnStarItInModalFocus: (caseID: string) => this.genLoc(`((((//span[@class='cl-gray d-block text-ellipsis cursor-pointer']/*[name()='svg'])/preceding::a[text()='${caseID}'])[2])/ancestor::tr)/descendant::span[@class='cl-gray d-block text-ellipsis cursor-pointer']/*[name()='svg']`),
                headingTableRequest: (headerName: string) => this.genLoc(`//thead/tr/th[normalize-space(span)='${headerName}']`),
                threeDotCustomizeColumnRequest: this.genLoc("//h2[text()='Request Activity']/following::div[@class='dropdown d-flex align-items-center']"),
                listRequestOfBusiness: this.genLoc("//h2[text()='Request Activity']/following::table[1]/tbody/tr"),
                radioCheckAddNew: this.genLoc("//input[@name='action_move_request' and @value='add_new']"),
                inputAddNewDOI: this.genLoc("//div[@class='box-add-new-case']/descendant::input[@id='date_time_date_of_injury']"),
                inputMoveRequest: this.genLoc("(//input[@name='move_to_case_id'])[1]"),

                //Quick summary
                dataRequestType: (type: string) => this.genLoc(`//div[@data-tooltip-content='${type}']`),
                textSummaryDisplay: this.genLoc("//p[contains(@class,'request-type-name')]")
            },

            buttonByText: (name: string) => this.genLoc(`//button[text()='${name}']`),
            paginationInfo: this.genLoc(`//div[@id='root']/descendant::div[@class='card-body border-bottom p-3']`),
            bulkEditBtn: this.genLoc(`//button[contains(text(),  'Bulk Edit')]`),
            filterBtn: this.genLoc(`//button[contains(text(),  'Filter')]`),
            caseRow: this.genLoc(`//table[contains(@class, 'table-business-client')]//tbody`),
            personalSearch: this.genLoc(`//input[@class='form-control' and @placeholder='Search...']`),
            msgNoResultFound: this.genLoc(`//div[contains(text(), 'No matching results found. Try again.') or contains(text(), 'Create a new case')]`),
            tableHeadingColumn: (name: string) => this.genLoc(`//table//thead//th[contains(normalize-space(), '${name}')]`),
            perPageInput: this.genLoc(`//input[@name='per_page']`),
            entriesTotal: this.genLoc(`//div[contains(@class, 'pagination-in-business')]`),
            inputSearch: this.genLoc(`//div[contains(@class, 'personal-search')]//input[@placeholder='Search...']`),
            // tableHeadingColumn: (name: string) =>
            //     this.genLoc(`//th[contains(@class, 'title-table') and contains(normalize-space(), '${name}')]`).first(),
            pinIcon: (caseNumber: string) =>
                this.genLoc(`//td[normalize-space()='${caseNumber}']/preceding-sibling::td/div/div[contains(@data-tooltip-content, 'Click here to pin')]`),
            pinnedIcon: (caseNumber: string) =>
                this.genLoc(`//a[normalize-space()='${caseNumber}']/ancestor::tr//div[@data-tooltip-content='Click here to unpin!']`),
            firstCaseNumber: (caseNumber: string) =>
                this.genLoc(`//div[contains(@class, 'pin-card')]//a[contains(@href, "/cases/${caseNumber}")]`),
        }
    }

    get caseSnapshot() {
        return {
            tableSearchUniqueSnapshot: (searchValue: string, clientName: string) => tableSearchUniqueSnapshot(searchValue, clientName),
            caseDetailLackInfo: (patientId: string, doi?: string) => caseDetailLackInfo(patientId, doi),
            caseDetailFullInfo: caseDetailFullInfo,
            headingAndCreateButton: headingAndCreateButton,
            tipsBlock: tipsBlock,
            emptyState: emptyState,
            haveRecord: haveRecord,
            caseUpdateUIHeader: caseUpdateUIHeader,
            caseUpdateUIBody: caseUpdateUIBody,
            caseUpdateUIFooter: caseUpdateUIFooter
        }
    }
    async open() {
        await this.page.goto('cases');
    }

    async switchToAttachmentLayout(layout: 'list' | 'grid') {
        // In grid view → button tooltip = "List layout" (click to go to list)
        // In list view → button tooltip = "Grid layout" (click to go to grid)
        const btnToSwitchToList = this.dashboardLoc.detail.btnLayoutToggle('List layout');
        const btnToSwitchToGrid = this.dashboardLoc.detail.btnLayoutToggle('Grid layout');

        if (layout === 'list') {
            if (await btnToSwitchToList.isVisible()) {
                await btnToSwitchToList.click();
            }
        } else {
            if (await btnToSwitchToGrid.isVisible()) {
                await btnToSwitchToGrid.click();
                await this.waitForSecond(4); // Wait for load image
            }
        }
        await this.dashboardLoc.detail.tabName("Attachment").hover();
    }

    async getRowCount(): Promise<number> {
        return this.caseLoc.caseRow.count();
    }

    async search(keyword: string) {
        await this.caseLoc.personalSearch.fill(keyword);
    }

    async gotoArchive(caseID: string): Promise<void> {
        await this.go(`cases/${caseID}?view_participant_archived=true`)
    }

    async fillDataCreateClient(infoClient: { birthday: string, phone: string, address: string }, email: string): Promise<void> {
        await this.caseLoc.create.detail.inputCreateClientName("birthday").fill(infoClient.birthday);
        await this.caseLoc.create.detail.inputCreateClientName("phone_number").first().fill(infoClient.phone);
        await this.caseLoc.create.detail.inputCreateClientName("email_address").first().fill(email);
        await this.caseLoc.create.detail.inputCreateClientName("address_1").first().fill(infoClient.address);

        await this.caseLoc.create.btnCreate.first().click();
    }

    async fillCaseDetail(detail: { business: string, category: string, description: string }, clientName: string, doi?: string, createNewBusiness?: boolean): Promise<void> {
        await this.caseLoc.create.detail.doi.fill(doi || "");

        if (!createNewBusiness) {
            await this.caseLoc.create.detail.bussiness.type(detail.business);
            await this.caseLoc.create.detail.boxTextBusinessByName(detail.business).click();
            await this.dashboardLoc.modal.headerModalh2("Preview").click();
        }
        await this.caseLoc.create.detail.categoryInput.click();
        await this.waitForSecond(1.5);
        await this.caseLoc.create.detail.noOptionsCategory.waitFor({ state: "hidden" });
        await this.caseLoc.create.detail.categoryInput.clear();
        await this.caseLoc.create.detail.categoryInput.type(detail.category, { delay: 50 });
        await this.caseLoc.create.detail.optionCategory(detail.category).waitFor({ state: "visible" });
        await this.caseLoc.create.detail.optionCategory(detail.category).click();
        await this.caseLoc.create.detail.description.fill(detail.description);

        await this.caseLoc.create.detail.inputByPlaceHolder("Select or type a name").first().click();
        await this.caseLoc.create.detail.inputByPlaceHolder("Select or type a name").first().type(clientName, { delay: 100 });
    }

    async fillLegalContact(business: string, userRecive: string) {
        await this.waitForSecond(2);
        await this.caseLoc.detail.noLegal.click({ force: true });
        await this.caseLoc.detail.addLegalModal.btnAddSuggest(business).click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the attorney's name.").click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the attorney's name.").fill(userRecive);
        await this.caseLoc.detail.addLegalModal.counselAdd(userRecive).click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the case manager's name.").click();
        await this.caseLoc.detail.addLegalModal.inputByPlaceholder("Enter the case manager's name.").fill(userRecive);
        await this.caseLoc.detail.addLegalModal.counselAdd(userRecive).click();
    }

    async getNewestActivity(): Promise<string> {
        await this.waitForSecond(2);
        await this.caseLoc.detail.buttonActivity.waitFor({ state: 'visible' });
        await this.caseLoc.detail.buttonActivity.click({ force: true });
        const textActivity = await this.caseLoc.detail.activity.listActivity.first().innerText();
        await this.caseLoc.detail.activity.buttonClose.click();
        return textActivity.replace(/\s+/g, ' ').trim();
    }

    async changeStarFocus(caseID: string): Promise<void> {
        await this.caseLoc.detail.keyFocus("Medical Bill").scrollIntoViewIfNeeded();
        await this.waitForSecond(1.5);
        await this.caseLoc.detail.keyFocus("Medical Bill").hover();
        await this.caseLoc.detail.keyFocus("Medical Bill").locator("//div[@class='edit-request open-modal-verify cursor-pointer']").click();
        await this.caseLoc.detail.btnStarItInModalFocus(caseID).click({ force: true });
        await this.dashboardLoc.buttonByText("Confirm").click();
        await this.dashboardLoc.msgSuccess.waitFor({ state: 'visible' });
        await this.dashboardLoc.btnClosePopupNotification.click();
    }

    async clickButtonDropdownSelect(dropdown: string): Promise<void> {
        await this.caseLoc.detail.btnDropdownBusiness.waitFor({ state: 'visible' });
        await this.waitForSecond(2);
        await this.caseLoc.detail.btnDropdownBusiness.click({ force: true });
        await this.caseLoc.detail.btnInDropdownBusiness(dropdown).click();
    }

    async tearDownMoveToOldCase(caseID: string): Promise<void> {
        await this.clickButtonDropdownSelect("BTN_SHOW_MOVE_REQUEST_OF_BUSINESS_MODAL");
        await this.caseLoc.detail.inputMoveRequest.click();
        await this.caseLoc.detail.inputMoveRequest.type(caseID, { delay: 100 });
        await this.caseLoc.detail.transfer.boxOption(caseID).click();
        await this.caseLoc.buttonByText("Move").click();
    }

    // Login as another user in a new browser context and return the new RequestPage
    async loginInAnotherBrowser(browser: Browser, username: string, password: string): Promise<{ context: BrowserContext; page: Page; casePage: CasePage }> {
        const context = await browser.newContext();
        const page = await context.newPage();
        const loginPage = new LoginPage(page);
        await loginPage.open();
        await loginPage.login(username, password);
        await expect(loginPage.baseLoc.dashboardContainer).toBeVisible();
        return { context, page, casePage: new CasePage(page) };
    }

    async addBusinessInDetail(businessName: string): Promise<void> {
        await this.dashboardLoc.detail.tabName("Summary/ Dive Deeper").click();
        await this.caseLoc.detail.listBusinesses.last().click();
        await this.dashboardLoc.modal.headerModal("Business").waitFor({ state: 'visible' });
        await this.dashboardLoc.modal.inputByID("autocomplete_business_provider_id").type(businessName, { delay: 100 });
        await this.caseLoc.create.detail.boxTextBusinessByName(businessName).waitFor({ state: 'visible' });
        await this.caseLoc.create.detail.boxTextBusinessByName(businessName).click();
        await this.dashboardLoc.buttonByText("Save").first().click();
        await this.dashboardLoc.msgAddBusinessInDetail.waitFor({ state: 'visible' });
        await this.dashboardLoc.btnClosePopupNotification.click();
    }

    async removeBusiness(businessName: string): Promise<void> {
        const businessBtn = this.caseLoc.detail.btnDropDownActionBySingleBusiness(businessName);
        await businessBtn.click();
        await businessBtn.waitFor({ state: 'visible' });
        // Wait for active class to be applied
        await this.page.waitForSelector(`[class*="active"]`);
        await this.caseLoc.detail.btnDropdownBusiness.click();
        await this.caseLoc.detail.dropdownOption("Remove").click();
        await this.dashboardLoc.msgRemoveBussinessSuccess.waitFor({ state: 'visible' });
        await this.dashboardLoc.btnClosePopupNotification.click();
        await businessBtn.waitFor({ state: 'hidden' });
    }

    async loginAndSearchCase(requestPage: RequestPage, browser: any, username: string, password: string, searchTerm: string, caseLinked?: boolean): Promise<{ casePage: CasePage; caseID: string }> {
        const { requestPage: requestPageB } = await requestPage.loginInAnotherBrowser(
            browser,
            username,
            password
        );
        const casePage = new CasePage(requestPageB.page);
        await casePage.open();
        await casePage.search(searchTerm);
        await casePage.waitForSecond(3);

        const caseID = caseLinked ? await casePage.caseLoc.linkcase.caseIDLinked.innerText() : await casePage.caseLoc.linkcase.newCaseID.first().innerText();
        return { casePage, caseID };
    }

    /**
     * User B: Verify case unread và screenshot
     */
    async verifyCaseUnread(caseId: string, clientName: string, doi: string) {
        await expect(this.caseLoc.itemBoldUnread.first()).toBeVisible();
        await this.resetToDefaultColumn(this.caseProps.customizedColumns, 1);
        await verifyScreenshot('new-case-unread.png', this.caseLoc.itemBoldUnread.first(), [this.caseLoc.caseIDNew(caseId), this.dashboardLoc.common.aText(clientName), this.dashboardLoc.common.aText(doi)], 0.02);
    }

    /**
     * User B: Open case detail và verify Banner 1 hoặc Banner 2
     */
    async openCaseAndVerifyBanner(caseId: string, bannerType: 'banner1' | 'banner2' = 'banner1') {
        await this.caseLoc.caseIDNew(caseId).click();
        await this.dashboardLoc.detail.tabName("Summary/ Dive Deeper").click();
        await expect(this.caseLoc.linkcase.bannerCreatedCaseSuccess).toBeVisible();

        if (bannerType === 'banner2') {
            await this.page.reload();
            await expect(this.caseLoc.linkcase.bannerCreatedCaseSuccess).toBeVisible();
            await expect(this.dashboardLoc.common.divText("Keep this Case in Active?")).toBeVisible();
            await verifyScreenshot('banner-case-relevant.png', this.caseLoc.bannerCaseRelevant, [], 0.02);
        } else {
            await verifyScreenshot('banner-new-case-created.png', this.caseLoc.bannerNewCaseCreated, [this.caseLoc.svgBannerNewCaseCreated], 0.02);
        }
    }

    /**
     * User B: Accept hoặc Reject case via Banner và lấy requestId
     */
    async handleCaseBanner(action: 'accept' | 'reject'): Promise<string> {
        const buttonText = action === 'accept' ? "Yes, Keep" : "No, Move";
        await this.waitForSecond(1);
        await this.dashboardLoc.buttonByText(buttonText).click({ force: true });
        await expect(this.dashboardLoc.msgSuccess).toBeVisible();
        await expect(this.caseLoc.linkcase.bannerCreatedCaseSuccess).not.toBeVisible();
        return await this.caseLoc.linkcase.newRequestID.innerText();
    }

    /**
     * Verify case ở tab Active hoặc Reference sau khi accept/reject
     */
    async verifyCaseInTab(caseId: string, clientName: string, doi: string, tab: 'active' | 'reference') {
        await this.open();
        await this.search(caseId);

        if (tab === 'reference') {
            await expect(this.dashboardLoc.table.noResult).toBeVisible();
            await this.dashboardLoc.common.divText("Reference").click();
            await this.search(caseId);
        }

        await expect(this.caseLoc.caseIDNew(caseId)).toBeVisible();
        if (tab === 'active') {
            await this.resetToDefaultColumn(this.caseProps.customizedColumns, 1);
            await verifyScreenshot('new-case-read.png', this.caseLoc.itemReaded, [this.caseLoc.caseIDNew(caseId), this.dashboardLoc.common.aText(clientName), this.dashboardLoc.common.aText(doi)], 0.02);
        }
    }
}