"use client";

import dynamic from "next/dynamic";
import { TripPoint } from "@/lib/api";
import { useMapsConfig } from "@/lib/useMapsConfig";
import { useLocale } from "@/i18n/LocaleProvider";
import { EmptyState } from "@/components/ui";

const MapboxTripMap = dynamic(
  () => import("@/components/MapboxTripMap").then((m) => m.MapboxTripMap),
  { ssr: false, loading: () => <div className="h-full w-full animate-pulse rounded-card bg-surface-raised" /> },
);

/**
 * The trip path, provider-agnostic at this boundary.
 *
 * <p>Two states are honest rather than broken: no map key configured, and a trip that recorded no
 * positions at all. The second is real - a ride whose vehicle never reported while moving has no
 * path to draw, and saying so beats an empty map that looks like a failure.
 */
export function TripMap({
  track,
  start,
  end,
  className = "h-[360px] w-full overflow-hidden rounded-card border border-line",
}: {
  track: TripPoint[];
  start: { lat: number; lng: number } | null;
  end: { lat: number; lng: number } | null;
  className?: string;
}) {
  const { t } = useLocale();
  const { config, loading } = useMapsConfig();

  if (loading) {
    return <div className={`${className} animate-pulse bg-surface-raised`} />;
  }
  if (!config?.apiKey) {
    return (
      <div className={`${className} flex items-center justify-center p-6`}>
        <EmptyState icon={<span className="text-xl">🗺️</span>} title={t("fleetMap.noKeyTitle")} />
      </div>
    );
  }
  if (track.length === 0 && !start && !end) {
    return (
      <div className={`${className} flex items-center justify-center p-6`}>
        <EmptyState
          icon={<span className="text-xl">📍</span>}
          title={t("trips.noTrack")}
          description={t("trips.noTrackBody")}
        />
      </div>
    );
  }

  return (
    <MapboxTripMap
      token={config.apiKey}
      track={track}
      start={start}
      end={end}
      className={className}
    />
  );
}
