import { type Locator, type Page } from '@playwright/test';
import { BasePage } from './BasePage';
import { IClaimDetails } from '@business-logic/types/CustomerDetails';


export class InsuranceCompanyPage extends BasePage {
    readonly page: Page;
    readonly insuranceInputBox: Locator;
    readonly payOnMyOwnLink: Locator;

    url = process.env['BASE_URL']! + '/fmg/?fmgPage=insurance-company';

    constructor(page: Page) {
        super(page);
        this.page = page;
        this.insuranceInputBox = this.page.getByRole('textbox', { name: 'Enter your insurance company' });
        this.payOnMyOwnLink = this.page.getByRole('link', { name: 'Pay on my own' });

        // this.validateURL(this.url);
    }

    async enterInsuranceCompany(company: string): Promise<void> {

        await this.insuranceInputBox.fill(company);
        try {
            // First attempt: Try to find and click an exact match
            await this.page.getByText(company, { exact: true })
                .locator('xpath=ancestor::div[contains(@class, "ui-menu-item-wrapper")]')
                .click({ timeout: 2000 }); // Short timeout for quick fallback
        } catch (error) {
            // Fallback: If exact match fails, select the first option containing the text
            const options = this.page.locator('div.ui-menu-item-wrapper', { hasText: company });
            const count = await options.count();
            
            if (count === 0) {
                throw new Error(`No insurance company options found containing "${company}"`);
            } else if (count === 1) {
                // If only one option, click it
                await options.click();
            } else {
                // If multiple options, click the first one
                await options.first().click();
                console.log(`Selected first match for "${company}" from ${count} options`);
            }
        }
    }
}