import type { TrailCardData } from "../data/queries";
import { TrailCard } from "./TrailCard";
import { TrailCardWalkers } from "./TrailCardWalkers";
import { HomeEmptyState } from "./HomeEmptyState";
import "./HomeTrailsList.css";

type Props = {
  trails: TrailCardData[];
};

// Reorder items for CSS columns masonry: [1,2,3,4,5,6] -> [1,3,5,2,4,6]
// CSS columns fills top-to-bottom, so left column gets first half of DOM.
// We put odd-ranked items first (left col), then even-ranked (right col).
// Visual order reads left-to-right: 1,2 / 3,4 / 5,6
// Tab order follows DOM: 1 -> 3 -> 5 -> 2 -> 4 -> 6 (column-wise)
// On mobile, CSS order property restores original ranking.
function interleaveForMasonry<T>(items: T[]): { item: T; originalIndex: number }[] {
  const result: { item: T; originalIndex: number }[] = [];
  for (let i = 0; i < items.length; i += 2) {
    result.push({ item: items[i], originalIndex: i });
  }
  for (let i = 1; i < items.length; i += 2) {
    result.push({ item: items[i], originalIndex: i });
  }
  return result;
}

export function HomeTrailsList({ trails }: Props) {
  if (trails.length === 0) {
    return (
      <HomeEmptyState message="no trails are trending right now" buttonText="start a new trail" />
    );
  }

  const reordered = interleaveForMasonry(trails);

  return (
    <div className="HomeTrailsList-grid">
      {reordered.map(({ item: trail, originalIndex }) => (
        <div key={trail.uri} style={{ "--original-index": originalIndex } as React.CSSProperties}>
          <TrailCard
            rkey={trail.rkey}
            creatorHandle={trail.creatorHandle}
            title={trail.title}
            description={trail.description}
            accentColor={trail.accentColor}
            backgroundColor={trail.backgroundColor}
            creator={trail.creator}
            stopsCount={trail.stopsCount}
            walkersSlot={<TrailCardWalkers trailUri={trail.uri} />}
          />
        </div>
      ))}
    </div>
  );
}
