import { useState } from "preact/hooks";
import type { Trip, Place } from "../../lib/types";
import type { UserLocation } from "../../lib/use-location";
import { PlaceCard } from "../shared/PlaceCard";

function buildVisitOrder(trip: Trip): Map<string, number> {
  const order = new Map<string, number>();
  let idx = 0;
  for (const day of trip.days) {
    for (const stop of day.stops) {
      order.set(stop.name, idx++);
    }
  }
  return order;
}

export function LandmarksTab({ trip, location }: { trip: Trip; location: UserLocation | null }) {
  const [expandedIdx, setExpandedIdx] = useState<string | null>(null);
  const visitOrder = buildVisitOrder(trip);

  const all = trip.places.filter(p => p.category === "landmark" || p.category === "trail");
  const byName = new Map<string, Place>();
  for (const p of all) {
    const existing = byName.get(p.name);
    if (!existing || p.category === "trail") byName.set(p.name, p);
  }
  const landmarks = [...byName.values()]
    .sort((a, b) => {
      const dayA = (a.details as Record<string, unknown>)?.day as number ?? 99;
      const dayB = (b.details as Record<string, unknown>)?.day as number ?? 99;
      if (dayA !== dayB) return dayA - dayB;
      const orderA = visitOrder.get(a.name) ?? 999;
      const orderB = visitOrder.get(b.name) ?? 999;
      return orderA - orderB;
    });

  const byDay = new Map<number, Place[]>();
  for (const p of landmarks) {
    const day = (p.details as Record<string, unknown>)?.day as number ?? 0;
    const arr = byDay.get(day);
    if (arr) arr.push(p);
    else byDay.set(day, [p]);
  }

  return (
    <div class="food-tab">
      <div class="food-tab-header">
        <div class="itin-section-label">Landmarks</div>
        <div class="food-count">{landmarks.length} places</div>
      </div>

      {[...byDay.entries()].sort((a, b) => a[0] - b[0]).map(([day, items]) => (
        <div key={day} class="food-meal-section">
          <div class="food-meal-header">
            <div class="food-meal-label">Day {day}</div>
          </div>
          <div class="food-cards">
            {items.map(place => {
              const uid = day + ":" + place.name;
              return (
                <PlaceCard
                  key={uid}
                  place={place}
                  expanded={expandedIdx === uid}
                  onToggle={() => setExpandedIdx(expandedIdx === uid ? null : uid)}
                  location={location}
                />
              );
            })}
          </div>
        </div>
      ))}

      {landmarks.length === 0 && (
        <div class="empty-state">No landmarks found.</div>
      )}
    </div>
  );
}
