// ============================================================
// ENCOUNTER SAVE/LOAD — save an encounter draft, then load it back
// and verify the transcript + label repopulate.
// ============================================================

const { test, expect, E2E_BASE, mockAI, getAuthToken } = 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="encounter"]');
  await page.waitForFunction(() => {
    const el = document.getElementById('encounter-tab');
    return el && el.classList.contains('active') && el.innerHTML.trim().length > 100;
  }, { timeout: 15000 });
}

// Purge all saved encounters for the test user so each run starts clean.
async function wipeSaved(request) {
  const token = await getAuthToken(request);
  const auth = { Authorization: 'Bearer ' + token };
  const r = await request.get(E2E_BASE + '/api/encounters', { headers: auth });
  if (!r.ok()) return;
  const d = await r.json().catch(() => ({ items: [] }));
  for (const it of (d.items || d.encounters || [])) {
    await request.delete(E2E_BASE + '/api/encounters/' + it.id, { headers: auth }).catch(() => {});
  }
}

test.describe('Encounter — save + load saved drafts', () => {
  test.beforeEach(async ({ request }) => {
    await wipeSaved(request);
  });

  test.afterAll(async ({ request }) => {
    await wipeSaved(request);
  });

  test('save → load popover lists the saved draft → loading repopulates transcript', async ({ authedPage: _, page }) => {
    await mockAI(page);
    await openTab(page);

    // Build a distinct transcript + label so we can verify round-trip
    const label = 'TEST-ENC-' + Date.now();
    const transcript = 'Unique transcript content: acute pharyngitis with fever.';

    await page.fill('#enc-age', '7 years');
    await page.selectOption('#enc-gender', 'Male');
    await page.locator('#enc-transcript').click();
    await page.keyboard.type(transcript);
    await page.fill('#enc-label', label);

    await page.click('#btn-enc-save');
    // Wait for save toast / API round-trip — watch for a save request
    await page.waitForResponse(res =>
      /\/api\/encounters/.test(res.url()) && res.request().method() === 'POST',
      { timeout: 10000 }
    );

    // Clear the form and open load popover
    await page.click('#btn-enc-new');
    // Transcript should now be empty after 'new'
    await expect.poll(async () =>
      (await page.locator('#enc-transcript').innerText()).trim(),
    { timeout: 3000 }).toBe('');

    await page.click('#btn-enc-load');
    await expect(page.locator('#enc-load-popover')).not.toHaveClass(/hidden/, { timeout: 5000 });
    // The saved label appears in the popover list
    await expect(page.locator('#enc-load-popover')).toContainText(label, { timeout: 5000 });

    // Click the row for this encounter
    await page.locator('#enc-load-popover').getByText(label).first().click();
    // Wait for the transcript contenteditable to repopulate
    await expect.poll(async () =>
      (await page.locator('#enc-transcript').innerText()),
    { timeout: 5000 }).toContain('acute pharyngitis');
  });
});
