import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
const useEventDataMock = vi.fn();
const navigateMock = vi.fn();

vi.mock('react-router-dom', () => ({
  useNavigate: () => navigateMock,
}));

vi.mock('../context/EventDataContext', () => ({
  useEventData: () => useEventDataMock(),
}));

vi.mock('@tamagui/stacks', () => ({
  YStack: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  XStack: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('@tamagui/text', () => ({
  SizableText: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
}));

vi.mock('@tamagui/button', () => ({
  Button: ({ children, onPress, ...rest }: { children: React.ReactNode; onPress?: () => void }) => (
    <button type="button" onClick={onPress} {...rest}>
      {children}
    </button>
  ),
}));

vi.mock('lucide-react', () => ({
  Camera: () => <span>camera</span>,
  Sparkles: () => <span>sparkles</span>,
  Image: () => <span>image</span>,
  Star: () => <span>star</span>,
  Timer: () => <span>timer</span>,
  RefreshCw: () => <span>refresh</span>,
  Trophy: () => <span>trophy</span>,
  X: () => <span>x</span>,
}));

vi.mock('../components/AppShell', () => ({
  default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('../components/TaskHeroCard', () => ({
  default: ({ task }: { task: { title?: string } | null }) => (
    <div>
      <span>{task?.title}</span>
      <span>Let&apos;s go!</span>
    </div>
  ),
}));

vi.mock('../components/PhotoFrameTile', () => ({
  default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

vi.mock('@/guest/context/EventBrandingContext', () => ({
  useEventBranding: () => ({
    branding: { welcomeMessage: '' },
    isCustom: false,
  }),
  useOptionalEventBranding: () => ({
    branding: { welcomeMessage: '' },
    isCustom: false,
  }),
}));

vi.mock('../services/tasksApi', () => ({
  fetchTasks: vi.fn().mockResolvedValue([
    {
      id: 12,
      title: 'Capture the dancefloor',
      description: 'Find the happiest crew.',
      instructions: 'Look for the brightest smiles.',
      duration: 5,
      emotion: { slug: 'freude', name: 'Joy' },
    },
  ]),
}));

vi.mock('../services/emotionsApi', () => ({
  fetchEmotions: vi.fn().mockResolvedValue([{ slug: 'freude', name: 'Joy' }]),
}));

const fetchGalleryMock = vi.fn().mockResolvedValue({ data: [] });

vi.mock('../services/photosApi', () => ({
  fetchGallery: (...args: unknown[]) => fetchGalleryMock(...args),
}));

const translate = (key: string, options?: unknown, fallback?: string) => {
  if (typeof fallback === 'string') return fallback;
  if (typeof options === 'string') return options;
  return key;
};

vi.mock('@/guest/i18n/useTranslation', () => ({
  useTranslation: () => ({ t: translate, locale: 'de' }),
}));

vi.mock('@/guest/i18n/LocaleContext', () => ({
  useLocale: () => ({ locale: 'de' }),
}));

vi.mock('../hooks/usePollStats', () => ({
  usePollStats: () => ({
    stats: { onlineGuests: 0, tasksSolved: 0, guestCount: 0, likesCount: 0, latestPhotoAt: null },
  }),
}));

vi.mock('../lib/useStaggeredReveal', () => ({
  useStaggeredReveal: () => 5,
}));

vi.mock('@/hooks/use-appearance', () => ({
  useAppearance: () => ({ resolved: 'light' }),
}));

vi.mock('@/guest/hooks/useGuestTaskProgress', () => ({
  useGuestTaskProgress: () => ({ isCompleted: () => false }),
}));

import HomeScreen from '../screens/HomeScreen';

describe('HomeScreen', () => {
  beforeEach(() => {
    navigateMock.mockReset();
    fetchGalleryMock.mockReset();
  });

  it('shows task hero content when tasks are enabled', async () => {
    fetchGalleryMock.mockResolvedValueOnce({ data: [] });
    useEventDataMock.mockReturnValue({
      tasksEnabled: true,
      token: 'demo',
      event: { name: 'Demo Event' },
    });

    render(<HomeScreen />);

    expect(await screen.findByText('Capture the dancefloor')).toBeInTheDocument();
    expect(screen.getByText("Let's go!")).toBeInTheDocument();
  });

  it('shows capture-ready content when tasks are disabled', () => {
    fetchGalleryMock.mockResolvedValueOnce({ data: [] });
    useEventDataMock.mockReturnValue({
      tasksEnabled: false,
      token: 'demo',
      event: { name: 'Demo Event' },
    });

    render(<HomeScreen />);

    expect(screen.getByText('Capture ready')).toBeInTheDocument();
    expect(screen.getByText('Upload / Take photo')).toBeInTheDocument();
  });

  it('opens gallery lightbox from preview tile', async () => {
    fetchGalleryMock.mockResolvedValueOnce({
      data: [{ id: 42, thumbnail_url: '/storage/demo.jpg' }],
    });
    useEventDataMock.mockReturnValue({
      tasksEnabled: false,
      token: 'demo',
      event: { name: 'Demo Event' },
    });

    render(<HomeScreen />);

    const previewButton = await screen.findByRole('button', { name: /foto 42/i });
    fireEvent.click(previewButton);

    expect(navigateMock).toHaveBeenCalledWith('/e/demo/gallery?photo=42');
  });
});
