// ============================================================
// CHART REVIEW — fill the form → generate → verify mocked output.
// ============================================================

const { test, expect, E2E_BASE, mockAI } = require('../fixtures');

async function openTab(page) {
  await page.goto(E2E_BASE + '/');
  await page.waitForSelector('button.tab-btn', { timeout: 15000 });
  const vp = page.viewportSize();
  if (vp && vp.width <= 768) {
    await page.click('#btn-menu-toggle').catch(() => {});
  }
  await page.click('button.tab-btn[data-tab="chart"]');
  await page.waitForFunction(() => {
    const el = document.getElementById('chart-tab');
    return el && el.classList.contains('active') && el.innerHTML.trim().length > 100;
  }, { timeout: 15000 });
}

test.describe('Chart Review — generation workflow', () => {

  test('minimum form → generate → mocked analysis renders in output card', async ({ authedPage: _, page }) => {
    await mockAI(page);
    await openTab(page);

    await page.fill('#cr-age', '8 years');
    await page.selectOption('#cr-gender', 'Male');
    await page.fill('#cr-pmh', 'Hypothyroidism, asthma');

    // The chart template already renders one visit row with a .visit-content
    // contenteditable. Fill it so the client-side "at least one visit" guard
    // doesn't block the generate call.
    const firstVisit = page.locator('.visit-content').first();
    await firstVisit.click();
    await page.keyboard.type('Annual well visit. Growth stable. No acute concerns.');

    const [resp] = await Promise.all([
      page.waitForResponse('**/api/generate-chart-review', { timeout: 15000 }),
      page.click('#cr-generate-btn'),
    ]);
    expect(resp.status()).toBe(200);
    await expect(page.locator('#cr-output')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('#cr-review-text')).toContainText('MOCK chart review');
  });

  test('load popover opens/closes when its buttons are clicked', async ({ authedPage: _, page }) => {
    await openTab(page);
    await page.click('#btn-chart-load');
    await expect(page.locator('#chart-load-popover')).not.toHaveClass(/hidden/, { timeout: 3000 });
    await page.locator('#chart-load-popover .enc-pop-close').click();
    await expect(page.locator('#chart-load-popover')).toHaveClass(/hidden/);
  });
});
