'use client';

import { Children, isValidElement, type ReactNode } from 'react';
import { cn } from '@/lib/utils';

type StackSlot = 'min-order-banner' | 'sticky-cta' | 'cart-pill';

type MobileBottomStackProps = {
  /**
   * Slot children keyed by priority. Render priority (top-to-bottom on screen):
   *   1. `min-order-banner`  — required attention
   *   2. `sticky-cta`        — primary action
   *   3. `cart-pill`         — passive nav
   * Only the top two slots render; everything else is suppressed so the viewport
   * cannot stack more than 2 fixed elements above the BottomNav.
   */
  slots: Partial<Record<StackSlot, ReactNode>>;
  className?: string;
};

const PRIORITY_ORDER: StackSlot[] = ['min-order-banner', 'sticky-cta', 'cart-pill'];
const MAX_VISIBLE = 2;

export function MobileBottomStack({ slots, className }: MobileBottomStackProps) {
  const visible = PRIORITY_ORDER.filter((slot) => {
    const node = slots[slot];
    if (!node) return false;
    if (isValidElement(node)) return true;
    return Children.count(node) > 0;
  }).slice(0, MAX_VISIBLE);

  if (visible.length === 0) return null;

  return (
    <div
      className={cn(
        'pointer-events-none fixed inset-x-0 bottom-[var(--bottom-nav-offset,4rem)] z-30 flex flex-col gap-2 px-4 pb-2',
        'md:hidden',
        className,
      )}
      data-testid="mobile-bottom-stack"
    >
      {visible.map((slot) => (
        <div key={slot} className="pointer-events-auto" data-slot={slot}>
          {slots[slot]}
        </div>
      ))}
    </div>
  );
}
