import React from 'react';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';

const navigateMock = vi.fn();
const backMock = vi.fn();

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

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, fallback?: string) => fallback ?? key,
  }),
  initReactI18next: {
    type: '3rdParty',
    init: () => undefined,
  },
}));

vi.mock('react-hot-toast', () => ({
  default: {
    error: vi.fn(),
    success: vi.fn(),
  },
}));

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

vi.mock('../components/Primitives', () => ({
  MobileCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  CTAButton: ({ label }: { label: string }) => <button type="button">{label}</button>,
  SkeletonCard: () => <div>Loading...</div>,
}));

vi.mock('../components/FormControls', () => ({
  MobileField: ({ label, children }: { label: string; children: React.ReactNode }) => (
    <div>
      <span>{label}</span>
      {children}
    </div>
  ),
  MobileColorInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
  MobileFileInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
  MobileInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
  MobileSelect: ({ children, ...props }: React.SelectHTMLAttributes<HTMLSelectElement>) => (
    <select {...props}>{children}</select>
  ),
}));

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

vi.mock('../hooks/useBackNavigation', () => ({
  useBackNavigation: () => backMock,
}));

vi.mock('../theme', () => ({
  ADMIN_COLORS: {
    primary: '#ff5a5f',
    accent: '#6d28d9',
  },
  ADMIN_GRADIENTS: { softCard: 'linear-gradient(180deg, #fff, #f3f4f6)' },
  useAdminTheme: () => ({
    textStrong: '#0f172a',
    muted: '#64748b',
    subtle: '#94a3b8',
    border: '#e2e8f0',
    primary: '#ff5a5f',
    accentSoft: '#f5f3ff',
    danger: '#dc2626',
    surfaceMuted: '#f8fafc',
    surface: '#ffffff',
    backdrop: '#0f172a',
    dangerBg: '#fee2e2',
    dangerText: '#b91c1c',
    glassSurface: 'rgba(255,255,255,0.8)',
    glassSurfaceStrong: 'rgba(255,255,255,0.9)',
    glassBorder: 'rgba(226,232,240,0.7)',
    glassShadow: 'rgba(15,23,42,0.14)',
    appBackground: 'linear-gradient(180deg, #f7fafc, #eef3f7)',
  }),
}));

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/react-native-web-lite', () => ({
  Pressable: ({ children, onPress }: { children: React.ReactNode; onPress?: () => void }) => (
    <button type="button" onClick={onPress}>
      {children}
    </button>
  ),
}));

vi.mock('tamagui', () => ({
  Slider: Object.assign(
    ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
    {
      Track: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
      TrackActive: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
      Thumb: () => <div />,
    }
  ),
}));

const getEventMock = vi.fn();
const updateEventMock = vi.fn();
const getTenantFontsMock = vi.fn();
const getTenantSettingsMock = vi.fn();
const trackOnboardingMock = vi.fn();

vi.mock('../../api', () => ({
  TenantEvent: {},
  TenantFont: {},
  WatermarkSettings: {},
  getEvent: (...args: unknown[]) => getEventMock(...args),
  updateEvent: (...args: unknown[]) => updateEventMock(...args),
  getTenantFonts: (...args: unknown[]) => getTenantFontsMock(...args),
  getTenantSettings: (...args: unknown[]) => getTenantSettingsMock(...args),
  trackOnboarding: (...args: unknown[]) => trackOnboardingMock(...args),
}));

import MobileBrandingPage from '../BrandingPage';

const baseEvent = {
  id: 9,
  name: 'Demo Event',
  slug: 'demo-event',
  event_date: null,
  event_type_id: 1,
  event_type: null,
  status: 'draft' as const,
  settings: {},
};

describe('MobileBrandingPage', () => {
  beforeEach(() => {
    getTenantFontsMock.mockResolvedValue([]);
    getTenantSettingsMock.mockResolvedValue({ settings: {} });
  });

  it('hides custom branding controls when default branding is active', async () => {
    getEventMock.mockResolvedValueOnce({
      ...baseEvent,
      settings: { branding: { use_default_branding: true } },
    });

    render(<MobileBrandingPage />);

    await waitFor(() => {
      expect(screen.getByText('Branding Source')).toBeInTheDocument();
    });

    expect(screen.queryByText('Theme')).toBeNull();
    expect(screen.queryByText('Colors')).toBeNull();
  });

  it('shows custom branding controls when event branding is active', async () => {
    getEventMock.mockResolvedValueOnce({
      ...baseEvent,
      settings: { branding: { use_default_branding: false } },
    });

    render(<MobileBrandingPage />);

    await waitFor(() => {
      expect(screen.getByText('Branding Source')).toBeInTheDocument();
    });

    expect(screen.getByText('Theme')).toBeInTheDocument();
    expect(screen.getByText('Colors')).toBeInTheDocument();
  });

  it('offers an upgrade CTA when branding is locked', async () => {
    getEventMock.mockResolvedValueOnce({
      ...baseEvent,
      package: { branding_allowed: false, watermark_allowed: false },
      settings: { branding_allowed: false, watermark_allowed: false },
    });

    render(<MobileBrandingPage />);

    await waitFor(() => {
      expect(screen.getByText('Unlock branding')).toBeInTheDocument();
    });

    expect(screen.getByText('Upgrade package')).toBeInTheDocument();
  });

  it('offers an upgrade CTA on the watermark tab when disabled', async () => {
    getEventMock.mockResolvedValueOnce({
      ...baseEvent,
      package: { branding_allowed: true, watermark_allowed: false },
      settings: { branding_allowed: true, watermark_allowed: false },
    });

    render(<MobileBrandingPage />);

    await waitFor(() => {
      expect(screen.getByText('Branding Source')).toBeInTheDocument();
    });

    fireEvent.click(screen.getByText('Wasserzeichen'));

    await waitFor(() => {
      expect(screen.getByText('Upgrade to Premium')).toBeInTheDocument();
    });
  });
});
