// Component tests for TripCard using React Testing Library.
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import TripCard from '../components/TripCard';
import { AuthProvider } from '../context/AuthContext';
import { saveToken } from '../context/token-storage';
import { Trip } from '../models/trip';

const sampleTrip: Trip = {
  _id: '1',
  code: 'GALR210214',
  name: 'Gale Reef',
  length: '4 nights / 5 days',
  start: '2026-02-14T08:00:00.000Z',
  resort: 'Emerald Bay, 3 stars',
  perPerson: '799.00',
  image: 'reef1.jpg',
  description: 'Gale Reef Sed et augue lorem.'
};

function renderCard() {
  return render(
    <AuthProvider>
      <MemoryRouter>
        <TripCard trip={sampleTrip} />
      </MemoryRouter>
    </AuthProvider>
  );
}

function buildToken(payload: object): string {
  const encode = (part: object) =>
    btoa(JSON.stringify(part)).replace(/=+$/, '');
  return `${encode({ alg: 'none' })}.${encode(payload)}.signature`;
}

describe('TripCard', () => {
  beforeEach(() => {
    localStorage.clear();
  });

  test('renders the trip name, resort, and formatted price', () => {
    renderCard();
    expect(screen.getByText('Gale Reef')).toBeInTheDocument();
    expect(screen.getByText('Emerald Bay, 3 stars')).toBeInTheDocument();
    expect(
      screen.getByText(/4 nights \/ 5 days only \$799\.00 per person/)
    ).toBeInTheDocument();
  });

  test('renders the description as plain text (no HTML injection)', () => {
    render(
      <AuthProvider>
        <MemoryRouter>
          <TripCard
            trip={{ ...sampleTrip, description: '<img src=x onerror=alert(1)>' }}
          />
        </MemoryRouter>
      </AuthProvider>
    );
    // The payload must appear as literal text, not become a DOM element.
    expect(
      screen.getByText('<img src=x onerror=alert(1)>')
    ).toBeInTheDocument();
  });

  test('hides the Edit Trip link when logged out', () => {
    renderCard();
    expect(screen.queryByText('Edit Trip')).not.toBeInTheDocument();
  });

  test('shows the Edit Trip link routed to the trip code when logged in', () => {
    saveToken(buildToken({ exp: Date.now() / 1000 + 3600, email: 'a@b.c', name: 'A' }));
    renderCard();
    const editLink = screen.getByText('Edit Trip');
    expect(editLink).toBeInTheDocument();
    expect(editLink.closest('a')).toHaveAttribute(
      'href',
      '/edit-trip/GALR210214'
    );
  });
});
