import { getAdSlot } from '@/lib/api';
import { AdUnit } from './AdUnit';

export type AdSlotKey =
  | 'home_sidebar'
  | 'home_top_feed'
  | 'home_between_sections'
  | 'home_mobile_feed'
  | 'article_middle'
  | 'article_bottom';

/**
 * Reserved height per slot, so the ad cannot push content as it loads.
 *
 * Layout shift is the one advertising failure that damages both Core Web
 * Vitals and the reading experience at the same time, so every slot
 * reserves its space up front. Values match the formats each position
 * actually serves.
 */
const MIN_HEIGHT: Record<AdSlotKey, number> = {
  home_sidebar: 250,
  home_top_feed: 90,
  home_between_sections: 90,
  home_mobile_feed: 100,
  article_middle: 90,
  article_bottom: 100,
};

/**
 * The single advertising component. No ad markup appears anywhere else,
 * so a provider change is one edit here.
 *
 * Rules from docs/DESIGN.md section 7, enforced in code rather than by
 * convention:
 *  - renders null when disabled or unconfigured, so there is never an
 *    empty reserved box or a collapsing layout
 *  - always carries a visible ADVERTISEMENT label
 *  - 56px clear space comes from .ad-slot, not from callers
 *  - reserves its height, so nothing moves when the ad arrives
 *
 * Placement rules (after the hero, never between title and summary) are
 * the caller's responsibility — this component cannot know where it sits.
 */
export async function AdSlot({
  slotKey,
  label = 'Advertisement',
}: {
  slotKey: AdSlotKey;
  label?: string;
}) {
  const slot = await getAdSlot(slotKey);

  // Nothing configured: render nothing at all. No placeholder, no
  // reserved box, no "advertisement" label over empty space.
  if (!slot?.enabled || !slot.provider || !slot.unit_id) return null;

  const client = process.env.NEXT_PUBLIC_ADSENSE_CLIENT;

  // Configured in the database but no publisher id in the environment:
  // still render nothing rather than a broken unit.
  if (slot.provider === 'adsense' && !client) return null;

  return (
    <aside className="ad-slot" aria-label={label}>
      <span className="ad-label">{label}</span>
      {slot.provider === 'adsense' && client ? (
        <AdUnit
          client={client}
          slot={slot.unit_id}
          minHeight={MIN_HEIGHT[slotKey]}
          format={slotKey === 'home_sidebar' ? 'rectangle' : 'auto'}
        />
      ) : (
        // Another provider configured but not implemented. Render
        // nothing rather than guess at its markup.
        null
      )}
    </aside>
  );
}
