import GalleryAdCard from '@/components/media/GalleryAdCard';
import type { GalleryAd } from '@/types/gallery-ads';
import { getOrCreateSessionId } from '@/lib/media-public-api';

interface AdBannerProps {
  ads: GalleryAd[];
  /** Maximum number of ads to display (default: 1) */
  maxAds?: number;
  /** Placement identifier for session-stable rotation */
  placement?: string;
}

/** Simple deterministic hash for session-stable selection */
function hashCode(str: string): number {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const ch = str.charCodeAt(i);
    hash = ((hash << 5) - hash + ch) | 0; // Convert to 32-bit int
  }
  return Math.abs(hash);
}

/**
 * Select ads using weighted session-stable rotation.
 * Lower position = higher weight. Same session+placement always returns the same ads.
 */
function selectAds(ads: GalleryAd[], maxAds: number, placement: string): GalleryAd[] {
  if (ads.length <= maxAds) return ads;

  const sessionId = getOrCreateSessionId();
  const seed = hashCode(sessionId + ':' + placement);

  const maxPosition = Math.max(...ads.map((a) => a.position ?? 0));
  const selected: GalleryAd[] = [];
  const remaining = [...ads];

  for (let i = 0; i < maxAds && remaining.length > 0; i++) {
    // Build weights: lower position = higher weight
    const weights = remaining.map((ad) => maxPosition - (ad.position ?? 0) + 1);
    const totalWeight = weights.reduce((sum, w) => sum + w, 0);

    // Use a different hash offset per slot so multi-ad displays don't repeat
    const pick = (seed + i * 7919) % totalWeight;
    let cumulative = 0;
    let chosenIdx = 0;
    for (let j = 0; j < weights.length; j++) {
      cumulative += (weights[j] ?? 0);
      if (pick < cumulative) {
        chosenIdx = j;
        break;
      }
    }

    const chosen = remaining[chosenIdx];
    if (chosen) selected.push(chosen);
    remaining.splice(chosenIdx, 1);
  }

  return selected;
}

/**
 * Renders GalleryAdCard(s) in a centered container.
 * Intended for use on public pages between content sections.
 */
export default function AdBanner({ ads, maxAds = 1, placement }: AdBannerProps) {
  if (ads.length === 0) return null;

  const displayAds = placement ? selectAds(ads, maxAds, placement) : ads.slice(0, maxAds);

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        gap: 16,
        margin: '24px auto',
        maxWidth: maxAds > 1 ? 800 : 400,
        flexWrap: 'wrap',
      }}
    >
      {displayAds.map((ad) => (
        <div key={ad.id} style={{ flex: '1 1 300px', maxWidth: 400 }}>
          <GalleryAdCard ad={ad} />
        </div>
      ))}
    </div>
  );
}
