// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';

vi.mock('../../lib/use-scanner-sound.js', () => ({
  useScannerSound: () => ({ playSuccess: vi.fn() }),
}));

vi.mock('../../lib/use-scanner-flash.js', () => ({
  useScannerFlash: () => ({
    flashSupported: false,
    flashOn: false,
    toggleFlash: vi.fn(),
  }),
}));

vi.mock('../../components/scanner/ScannerScanPeek.js', () => ({
  default: () => <div data-testid="scanner-scan-peek" />,
}));

vi.mock('../../components/scanner/ScannerCountPill.js', () => ({
  default: () => <div data-testid="scanner-count-pill" />,
}));

vi.mock('../../components/scanner/ScannerDisambiguation.js', () => ({
  default: () => null,
}));

import ScannerCamera from '../../components/scanner/ScannerCamera.js';

function createCameraFixture() {
  return {
    videoRef: { current: document.createElement('video') },
    canvasRef: { current: document.createElement('canvas') },
    detectionCanvasRef: { current: document.createElement('canvas') },
    isStreaming: true,
    trackedCards: [],
    videoMetrics: { width: 1280, height: 720 },
    startCamera: vi.fn(),
    streamRef: { current: null },
    facingMode: 'environment',
    switchFacingMode: vi.fn(),
  };
}

function renderCamera(overrides = {}) {
  const props = {
    queue: { scannedCards: [], addingCardIds: new Set() },
    camera: createCameraFixture(),
    identification: { disambiguation: null },
    onBack: vi.fn(),
    onOpenCheckout: vi.fn(),
    latestPeekCard: null,
    cartCount: 0,
    ...overrides,
  };

  return render(<ScannerCamera {...props} />);
}

describe('ScannerCamera workstation variant', () => {
  afterEach(() => cleanup());

  it('keeps mobile overlay chrome visible in the default variant', () => {
    const { container } = renderCamera({ variant: 'default' });

    expect(screen.getByRole('button', { name: 'Leave scanner' })).toBeTruthy();
    expect(screen.getByTestId('scanner-scan-peek')).toBeTruthy();
    expect(screen.getByTestId('scanner-count-pill')).toBeTruthy();
    expect(screen.queryByText('Auto-detect ON')).toBeNull();
    expect(container.querySelector('.md\\:hidden')).toBeNull();
  });

  it('marks overlay chrome for md+ hiding and shows the Auto-detect badge in workstation mode', () => {
    const { container } = renderCamera({
      variant: 'workstation',
      autoDetectOn: true,
    });

    expect(container.querySelector('.md\\:hidden')).toBeTruthy();
    expect(screen.getByText('Auto-detect ON')).toBeTruthy();
    expect(screen.getByRole('status').textContent).toContain('Auto-detect ON');
    expect(screen.getByText('LIVE')).toBeTruthy();
  });

  it('shows Auto-detect OFF when autoDetectOn is false', () => {
    renderCamera({
      variant: 'workstation',
      autoDetectOn: false,
    });

    expect(screen.getByText('Auto-detect OFF')).toBeTruthy();
  });
});
