// ============================================================
// MODEL SELECTOR — each tab has its own <select.tab-model-select>
// populated by window._buildModelOptions. Verify the dropdowns
// render across tabs that should have one.
// ============================================================

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

async function openTab(page, name) {
  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="${name}"]`);
  await page.waitForFunction((t) => {
    const el = document.getElementById(t + '-tab');
    return el && el.classList.contains('active') && el.innerHTML.trim().length > 100;
  }, name, { timeout: 15000 });
}

test.describe('Per-tab model selector', () => {
  const tabsWithModelPicker = ['encounter', 'dictation', 'chart', 'soap', 'hospital', 'sickvisit', 'wellvisit'];

  for (const tab of tabsWithModelPicker) {
    test(`${tab}: model picker renders and has at least one option`, async ({ authedPage: _, page }) => {
      await openTab(page, tab);
      // Well Visit has four sub-panels each with their own picker; three of
      // them are hidden until you switch to that sub-tab, so visibility is
      // unreliable. Instead: require that the active tab contains at least
      // one picker AND that at least one picker inside the tab has >0
      // options populated by window._buildModelOptions.
      const pickers = page.locator(`#${tab}-tab select.tab-model-select`);
      await expect.poll(async () => pickers.count(), { timeout: 10000 })
        .toBeGreaterThan(0);
      await expect.poll(async () => {
        return await pickers.evaluateAll(list => list.reduce((max, el) =>
          Math.max(max, el.options ? el.options.length : 0), 0));
      }, { timeout: 10000 }).toBeGreaterThan(0);
    });
  }
});
