/**
 * AIForAll Component Tests
 * 
 * 測試目標：
 * 1. 元件能正確渲染
 * 2. 元件能正確呼叫廠商 aiForAll.js
 * 3. 元件卸載時能正確 cleanup
 */

import React from 'react';
import { render, waitFor, cleanup as rtlCleanup } from '@testing-library/react';
import AIAForAll from '@/components/aia/aia-for-all';
import * as vendorAIForAll from '@vendor-web/js/components/aiForAll.js';

// Mock 廠商 aiForAll.js
jest.mock('@vendor-web/js/components/aiForAll.js', () => ({
  aiForAll: jest.fn(),
}));

describe('AIForAll Component', () => {
  let mockCleanup: jest.Mock;

  beforeEach(() => {
    mockCleanup = jest.fn();
    (vendorAIForAll.aiForAll as jest.Mock).mockReturnValue(mockCleanup);
  });

  afterEach(() => {
    rtlCleanup();
    jest.clearAllMocks();
  });

  it('應該渲染 aiForAll 結構', () => {
    const { container, getByText } = render(<AIAForAll />);

    expect(container.querySelector('.aiForAll')).toBeInTheDocument();
    expect(getByText('AI For All')).toBeInTheDocument();
    expect(container.querySelector('.aiForAll-container')).toBeInTheDocument();
  });

  it('應該呼叫廠商 aiForAll 初始化函式', async () => {
    render(<AIAForAll />);

    await waitFor(() => {
      expect(vendorAIForAll.aiForAll).toHaveBeenCalledTimes(1);
      expect(vendorAIForAll.aiForAll).toHaveBeenCalledWith(
        expect.any(HTMLElement)
      );
    });
  });

  it('應該在元件卸載時呼叫 cleanup 函式', async () => {
    const { unmount } = render(<AIAForAll />);

    await waitFor(() => {
      expect(vendorAIForAll.aiForAll).toHaveBeenCalled();
    });

    unmount();

    expect(mockCleanup).toHaveBeenCalledTimes(1);
  });

  it('應該能處理廠商 JS 未返回 cleanup 的情況', async () => {
    (vendorAIForAll.aiForAll as jest.Mock).mockReturnValue(undefined);

    const { unmount } = render(<AIAForAll />);

    // 不應該拋出錯誤
    expect(() => unmount()).not.toThrow();
  });

  it('應該渲染所有行業清單項目', () => {
    const { getAllByText, getByText } = render(<AIAForAll />);

    // 測試幾個關鍵行業項目（使用 getAllByText 因為有多個匹配）
    expect(getAllByText(/utomobile/).length).toBeGreaterThan(0);
    expect(getAllByText(/iotechnology/).length).toBeGreaterThan(0);
    expect(getAllByText(/inance/).length).toBeGreaterThan(0);
    expect(getAllByText(/ealthcare/).length).toBeGreaterThan(0);
    
    // 確認標題存在
    expect(getByText('AI For All')).toBeInTheDocument();
  });
});
