import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { AppCenter } from '@/pages/AppCenter';
import { useAppCenterStore } from '@/stores/app-center';
import i18n from '@/i18n';

function renderAppCenter() {
  return render(
    <MemoryRouter initialEntries={['/app-center']}>
      <Routes>
        <Route path="/app-center" element={<AppCenter />} />
        <Route path="/app-center/product-center" element={<div data-testid="product-center-route" />} />
      </Routes>
    </MemoryRouter>,
  );
}

function resetAppCenterStore() {
  useAppCenterStore.setState({
    items: [],
    selectedItemId: null,
    selectedTagKey: 'all',
    initialized: false,
  });
}

describe('App Center', () => {
  beforeEach(async () => {
    await i18n.changeLanguage('zh');
    vi.clearAllMocks();
    resetAppCenterStore();
  });

  it('lists Travel Resource Ordering and opens it inside the desktop route', () => {
    renderAppCenter();

    expect(screen.getByTestId('app-center-item-product-center')).toHaveTextContent('旅游资源订购');
    expect(screen.getByTestId('app-center-item-product-center')).toHaveTextContent('旅游资源底价订购');

    fireEvent.click(screen.getByTestId('app-center-item-product-center'));

    expect(screen.getByTestId('product-center-route')).toBeVisible();
    expect(window.electron.openExternal).not.toHaveBeenCalled();
  });

  it('covers built-in apps in English without exposing translation keys', async () => {
    await i18n.changeLanguage('en');
    resetAppCenterStore();

    renderAppCenter();

    expect(screen.getByTestId('app-center-item-product-center')).toHaveTextContent('Travel Resource Ordering');
    expect(screen.getByTestId('app-center-item-nianxx-play')).toHaveTextContent('Quick Video Creation');
    expect(screen.queryByText('items.productCenter.name')).not.toBeInTheDocument();
    expect(screen.queryByText('items.nianxxPlay.name')).not.toBeInTheDocument();
  });
});
