import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } 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']}>
      <AppCenter />
    </MemoryRouter>,
  );
}

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

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

  it('renders the empty state after clearing built-in apps', () => {
    renderAppCenter();

    expect(screen.getByText('暂无应用')).toBeVisible();
    expect(screen.getByText('全部 · 0')).toBeVisible();
    expect(screen.queryByTestId('app-center-item-product-center')).not.toBeInTheDocument();
    expect(screen.queryByTestId('app-center-item-nianxx-play')).not.toBeInTheDocument();
    expect(window.electron.openExternal).not.toHaveBeenCalled();
  });

  it('keeps the cleared state in English without exposing deleted app keys', async () => {
    await i18n.changeLanguage('en');
    resetAppCenterStore();

    renderAppCenter();

    expect(screen.getByText('No apps yet')).toBeVisible();
    expect(screen.getByText('All · 0')).toBeVisible();
    expect(screen.queryByTestId('app-center-item-product-center')).not.toBeInTheDocument();
    expect(screen.queryByTestId('app-center-item-nianxx-play')).not.toBeInTheDocument();
    expect(screen.queryByText('items.productCenter.name')).not.toBeInTheDocument();
    expect(screen.queryByText('items.nianxxPlay.name')).not.toBeInTheDocument();
  });
});
