"use client";
import { useMemo } from "react";
import AdImage from "./AdImage";
import { pickAds, rotateAll, type Ad } from "@/lib/ads";

// Renders the 300x600 at the top followed by EVERY 300x250 banner stacked
// vertically in a shuffled order. Both reads happen at render time so the
// centralized RMP cache (which populates async after module import) is
// picked up — using the module-level FIXED_300X600 constant captured the
// FALLBACK ad with its direct bmd.link click_url and bypassed the click
// logger entirely.
export default function SidebarAdStack({
  excludeSrcs = [],
  className = "",
  // When true, omit the leading 300x600 banner. Used on the homepage where
  // the 300x600 is rendered up in the FeaturedBento row instead, to keep
  // the article feed sidebar starting with the 300x250 stack.
  skipTop600 = false,
}: {
  excludeSrcs?: string[];
  className?: string;
  skipTop600?: boolean;
}) {
  const top600 = useMemo<Ad | null>(
    () => (skipTop600 ? null : pickAds("300x600", 1)[0] ?? null),
    [excludeSrcs.join("|"), skipTop600],
  );
  const rotating = useMemo<Ad[]>(
    () => rotateAll("300x250", new Set(excludeSrcs)),
    [excludeSrcs.join("|")],
  );

  return (
    <div className={`flex flex-col items-end gap-4 ${className}`}>
      {top600 && <AdImage ad={top600} priority />}
      {rotating.map((ad) => (
        <AdImage key={ad.src ?? ad.label} ad={ad} />
      ))}
    </div>
  );
}
