// Presentational card for one trip. Port of the Angular
// TripCardComponent with two deliberate design changes:
//
// 1. The @Input('trip') was typed as `any`; here the prop is the Trip
//    interface, so the compiler verifies every field access.
// 2. The Angular version stashed the trip code in localStorage and
//    navigated to a fixed /edit-trip URL. That made edit links
//    unbookmarkable and coupled two components through shared browser
//    state. The React version encodes the code in the route itself
//    (/edit-trip/:tripCode), which is the standard SPA pattern.
//
// The original template also bound trip.description with [innerHTML],
// which renders unsanitized markup — a stored XSS vector if a trip
// description ever contains a script payload. React escapes
// interpolated text by default, so rendering {trip.description} as
// plain text closes that hole.
import { Link } from 'react-router-dom';
import { Trip } from '../models/trip';
import { useAuth } from '../context/AuthContext';

interface TripCardProps {
  trip: Trip;
}

// Format the perPerson value the way Angular's currency pipe did.
function formatCurrency(value: string): string {
  const amount = Number(value);
  if (Number.isNaN(amount)) {
    return value;
  }
  return amount.toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD'
  });
}

export default function TripCard({ trip }: TripCardProps) {
  const { isLoggedIn } = useAuth();

  return (
    <div className="card">
      <div className="card-header">{trip.name}</div>
      <img
        src={`/assets/images/${trip.image}`}
        alt="trip thumbnail"
        className="card-img-top"
      />
      <div className="card-body">
        <h6 className="card-subtitle mb-2 text-muted">{trip.resort}</h6>
        <p className="card-subtitle mt-3 mb-3 text-muted">
          {trip.length} only {formatCurrency(trip.perPerson)} per person
        </p>
        <p className="card-text">{trip.description}</p>
        {isLoggedIn && (
          <Link
            to={`/edit-trip/${trip.code}`}
            className="btn btn-info"
            role="button"
          >
            Edit Trip
          </Link>
        )}
      </div>
    </div>
  );
}
