// @vitest-environment happy-dom
/**
 * ProductSwitcher — auto-hides for single-tenant deployments and lists the
 * configured products otherwise.
 */

import { describe, it, expect, beforeAll, vi } from 'vitest';
import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import type { Product } from '@/lib/product-constants';

const useProduct = vi.fn();
vi.mock('@/lib/product-context', () => ({ useProduct: () => useProduct() }));

import { ProductSwitcher } from '@/components/product-switcher';

beforeAll(() => {
  (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
});

function render(products: readonly Product[]): { container: HTMLDivElement; root: Root } {
  useProduct.mockReturnValue({
    productId: products[0]?.id ?? 'x',
    setProductId: vi.fn(),
    products,
  });
  const container = document.createElement('div');
  document.body.appendChild(container);
  let root!: Root;
  act(() => {
    root = createRoot(container);
    root.render(createElement(ProductSwitcher));
  });
  return { container, root };
}

describe('ProductSwitcher', () => {
  it('renders nothing when there is zero or one product', () => {
    const none = render([]);
    expect(none.container.querySelector('select')).toBeNull();
    act(() => none.root.unmount());

    const one = render([{ id: 'solo', name: 'Solo' }]);
    expect(one.container.querySelector('select')).toBeNull();
    act(() => one.root.unmount());
  });

  it('renders a select with an option per product when there are multiple', () => {
    const { container, root } = render([
      { id: 'a', name: 'Alpha' },
      { id: 'b', name: 'Beta' },
    ]);
    const select = container.querySelector('select');
    expect(select).not.toBeNull();
    expect(select!.querySelectorAll('option')).toHaveLength(2);
    expect(container.textContent).toContain('Alpha');
    expect(container.textContent).toContain('Beta');
    act(() => root.unmount());
  });
});
