import type { TripSummary } from "../lib/types";

function formatDate(d: string) {
  const date = new Date(d + "T12:00:00");
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function TripCard({ trip, onSelect }: { trip: TripSummary; onSelect: () => void }) {
  const dateRange = trip.dates.length === 1
    ? formatDate(trip.dates[0])
    : `${formatDate(trip.dates[0])} — ${formatDate(trip.dates[trip.dates.length - 1])}`;

  return (
    <div class="trip-card" onClick={onSelect}>
      <div class="trip-card-title">{trip.title}</div>
      <div class="trip-card-subtitle">{trip.subtitle}</div>
      <div class="trip-card-meta">
        <span>{dateRange}</span>
        {trip.travelers.length > 0 && <>
          <span class="trip-card-dot" />
          <span>{trip.travelers.join(", ")}</span>
        </>}
      </div>
      {trip.notes && <div class="trip-card-notes">{trip.notes}</div>}
    </div>
  );
}

export function TripIndex({ trips, onSelect }: {
  trips: TripSummary[];
  onSelect: (id: string) => void;
}) {
  return (
    <div class="trip-index">
      <h1 class="trip-index-heading">Trips</h1>
      {trips.length === 0 && (
        <div class="empty-state">No trips yet.</div>
      )}
      <div class="trip-index-list">
        {trips.map(t => (
          <TripCard key={t.id} trip={t} onSelect={() => onSelect(t.id)} />
        ))}
      </div>
    </div>
  );
}
