"use client";

import type { WalkCardData } from "@/data/queries";
import { HomeWalkingPill } from "./HomeWalkingPill";
import { abandonWalk } from "@/data/actions";
import { WalkingList } from "@/app/WalkingList";

type Props = {
  walks: WalkCardData[];
  canDelete?: boolean;
};

export function HomeWalkingList({ walks, canDelete = true }: Props) {
  const abandonAction = async (walkUri: string) => {
    await abandonWalk(walkUri);
  };

  return (
    <WalkingList>
      {walks.map((walk) => {
        // Find current: last visited stop that still exists
        let currentStopIndex = 0;
        for (let i = walk.visitedStops.length - 1; i >= 0; i--) {
          const idx = walk.stops.findIndex((s) => s.tid === walk.visitedStops[i]);
          if (idx !== -1) {
            currentStopIndex = idx;
            break;
          }
        }

        // Find furthest: max index of any visited stop that still exists
        let furthestStopIndex = 0;
        for (const tid of walk.visitedStops) {
          const idx = walk.stops.findIndex((s) => s.tid === tid);
          if (idx > furthestStopIndex) {
            furthestStopIndex = idx;
          }
        }

        const currentStep = walk.stops[currentStopIndex];

        const dots = walk.stops.map((_stop, idx: number) => {
          if (idx === currentStopIndex) return "current";
          if (idx <= furthestStopIndex) return "completed";
          return "upcoming";
        }) as Array<"completed" | "current" | "upcoming">;

        const walkUri = `at://${walk.walkerDid}/app.sidetrail.walk/${walk.walkRkey}`;

        return (
          <HomeWalkingPill
            key={walkUri}
            title={walk.title}
            subtitle={currentStep?.title || `stop ${currentStopIndex + 1}`}
            accentColor={walk.accentColor}
            backgroundColor={walk.backgroundColor}
            linkTo={`/@${walk.trailCreatorHandle}/trail/${walk.trailRkey}`}
            dots={dots}
            deleteAction={canDelete ? () => abandonAction(walkUri) : undefined}
            deleteLabel={canDelete ? "abandon trail" : undefined}
          />
        );
      })}
    </WalkingList>
  );
}
