import { test, expect } from '@playwright/test';
import { switchToUser, getTestUserData, importUserFromAccount } from './testUtils';

test('New offers for another user', async ({ page }) => {
  await page.goto('./');

  // Get the auto-created DID from the HomeView
  await page.waitForLoadState('networkidle');
  const autoCreatedDid = await page.getAttribute('#Content', 'data-active-did');
  
  if (!autoCreatedDid) {
    throw new Error('Auto-created DID not found in HomeView');
  }

  await page.getByTestId('closeOnboardingAndFinish').click();
  // Wait for onboarding dialog to fully close and settings to persist
  await expect(page.locator('.dialog-overlay')).toBeHidden({ timeout: 5000 });
  await expect(page.getByTestId('newDirectOffersActivityNumber')).toBeHidden();

  // Become User Zero
  await importUserFromAccount(page, "00");

  // As User Zero, add the auto-created DID as a contact
  await page.goto('./contacts');
  await page.getByPlaceholder('URL or DID, Name, Public Key').fill(autoCreatedDid + ', A Friend');
  await expect(page.locator('button > svg.fa-plus')).toBeVisible();
  await page.locator('button > svg.fa-plus').click();
  await expect(page.locator('div[role="alert"] h4:has-text("Success")')).toBeVisible(); // wait for info alert to be visible…
  await page.getByRole('alert').filter({ hasText: 'Success' }).getByRole('button').click(); // …and dismiss it
  await expect(page.getByRole('alert').filter({ hasText: 'Success' })).toBeHidden(); // ensure alert is gone
  // Wait for register prompt alert to be ready before clicking
  await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('div[role="alert"] button');
    return Array.from(buttons).some(button => button.textContent?.includes('No'));
  }, { timeout: 5000 });
  // Use a more robust approach to click the button
  await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('div[role="alert"] button');
    const noButton = Array.from(buttons).find(button => button.textContent?.includes('No'));
    if (noButton) {
      (noButton as HTMLElement).click();
      return true;
    }
    return false;
  }, { timeout: 5000 });
  // Wait for export data prompt alert to be ready before clicking
  await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('div[role="alert"] button');
    return Array.from(buttons).some(button => button.textContent?.includes('No, Not Yet'));
  }, { timeout: 5000 });
  // Use a more robust approach to click the button
  await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('div[role="alert"] button');
    const noButton = Array.from(buttons).find(button => button.textContent?.includes('No, Not Yet'));
    if (noButton) {
      (noButton as HTMLElement).click();
      return true;
    }
    return false;
  }, { timeout: 5000 });

  // show buttons to make offers directly to people
  await page.getByRole('button').filter({ hasText: /See Actions/i }).click();

  // make an offer directly to user 1
  // Generate a random string of 3 characters, skipping the "0." at the beginning
  const randomString1 = Math.random().toString(36).substring(2, 5);
  await page.getByTestId('offerButton').click();
  await page.getByTestId('inputDescription').fill(`help of ${randomString1} from #000`);
  await page.getByTestId('inputOfferAmount').locator('input').fill('1');
  await page.getByRole('button', { name: 'Sign & Send' }).click();
  await expect(page.getByText('That offer was recorded.')).toBeVisible();
  await page.getByRole('alert').filter({ hasText: 'Success' }).getByRole('button').click(); // dismiss info alert
  await expect(page.getByRole('alert').filter({ hasText: 'Success' })).toBeHidden(); // ensure alert is gone

  // Handle backup seed modal if it appears (following 00-noid-tests.spec.ts pattern)
  try {
    // Wait for backup seed modal to appear
    await page.waitForFunction(() => {
      const alert = document.querySelector('div[role="alert"]');
      return alert && alert.textContent?.includes('Backup Your Identifier Seed');
    }, { timeout: 3000 });
    
    // Dismiss backup seed modal
    await page.getByRole('button', { name: 'No, Remind me Later' }).click();
    await expect(page.locator('div[role="alert"]').filter({ hasText: 'Backup Your Identifier Seed' })).toBeHidden();
  } catch (error) {
    // Backup modal might not appear, that's okay
    console.log('Backup seed modal did not appear, continuing...');
  }

  // make another offer to user 1
  const randomString2 = Math.random().toString(36).substring(2, 5);
  await page.getByTestId('offerButton').click();
  await page.getByTestId('inputDescription').fill(`help of ${randomString2} from #000`);
  await page.getByTestId('inputOfferAmount').locator('input').fill('3');
  await page.getByRole('button', { name: 'Sign & Send' }).click();
  await expect(page.getByText('That offer was recorded.')).toBeVisible();
  await page.getByRole('alert').filter({ hasText: 'Success' }).getByRole('button').click(); // dismiss info alert
  await expect(page.getByRole('alert').filter({ hasText: 'Success' })).toBeHidden(); // ensure alert is gone

  // Switch back to the auto-created DID (the "another user") to see the offers
  await switchToUser(page, autoCreatedDid);
  await page.goto('./');
  let offerNumElem = page.getByTestId('newDirectOffersActivityNumber');
  await expect(offerNumElem).toHaveText('2');

  // click on the number of new offers to go to the list page
  await offerNumElem.click();

  await expect(page.getByText('New Offers To You', { exact: true })).toBeVisible();
  await page.getByTestId('showOffersToUser').locator('div > svg.fa-chevron-right').click();

  await expect(page.getByText('The offers are marked as read')).toBeVisible();
  await page.getByRole('alert').filter({ hasText: 'Info' }).getByRole('button').click(); // dismiss info alert

  await page.waitForTimeout(1000);

  // note that they show in reverse chronologicalorder
  await expect(page.getByText(`help of ${randomString2} from #000`)).toBeVisible();
  await expect(page.getByText(`help of ${randomString1} from #000`)).toBeVisible();

  // click on the latest offer to keep it as "unread"
  await page.hover(`li:has-text("help of ${randomString2} from #000")`);
  // await page.locator('li').filter({ hasText: `help of ${randomString2} from #000` }).click();
  // await page.locator('div').filter({ hasText: /keep all above/ }).click();
  // now find the "Click to keep all above as new offers" after that list item and click it
  const liElem = page.locator('li').filter({ hasText: `help of ${randomString2} from #000` });
  await liElem.hover();
  const keepAboveAsNew = await liElem.locator('div').filter({ hasText: /keep all above/ });

  await keepAboveAsNew.click();

  await expect(page.getByText('All offers above that line are marked as unread.')).toBeVisible();
  await page.getByRole('alert').filter({ hasText: 'Info' }).getByRole('button').click(); // dismiss info alert

  // now see that only one offer is shown as new
  await page.goto('./');
  offerNumElem = page.getByTestId('newDirectOffersActivityNumber');
  await expect(offerNumElem).toHaveText('1');
  await offerNumElem.click();
  await expect(page.getByText('New Offer To You', { exact: true })).toBeVisible();
  await page.getByTestId('showOffersToUser').locator('div > svg.fa-chevron-right').click();

  await expect(page.getByText('The offers are marked as read')).toBeVisible();
  await page.getByRole('alert').filter({ hasText: 'Info' }).getByRole('button').click(); // dismiss info alert

  // now see that no offers are shown as new
  await page.goto('./');
  // wait until the list with ID listLatestActivity has at least one visible item
  await page.locator('#listLatestActivity li').first().waitFor({ state: 'visible' });
  await expect(page.getByTestId('newDirectOffersActivityNumber')).toBeHidden();
});
