// 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'
  });
}

// Format the ISO start date for display (e.g. "Feb 14, 2021").
// Rendering the date matters for Enhancement Two: the listing can be
// sorted by start date, so the sort key must be visible on the card.
function formatStartDate(isoDate: string): string {
  const date = new Date(isoDate);
  if (Number.isNaN(date.getTime())) {
    return '';
  }
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    timeZone: 'UTC'
  });
}

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>
        {formatStartDate(trip.start) && (
          <p className="card-subtitle mb-2 text-muted">
            Departs {formatStartDate(trip.start)}
          </p>
        )}
        <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>
  );
}
