'use client';

import { useEffect, useRef } from 'react';

declare global {
  interface Window {
    adsbygoogle?: unknown[];
  }
}

/**
 * Mounts one AdSense unit.
 *
 * A client component because AdSense needs to run in the browser, but
 * kept as small as possible: everything else about an ad slot — whether
 * it renders at all, its label, its spacing — is decided on the server
 * by AdSlot.
 *
 * The reserved height is the Core Web Vitals requirement. An ad that
 * loads into unreserved space pushes the article down as the reader is
 * reading it, which is both the worst kind of layout shift and the
 * fastest way to make a site feel like an ad farm.
 */
export function AdUnit({
  client,
  slot,
  format = 'auto',
  minHeight,
}: {
  client: string;
  slot: string;
  format?: string;
  minHeight: number;
}) {
  const pushed = useRef(false);

  useEffect(() => {
    // React 18 strict mode mounts twice in development. Pushing the same
    // slot twice makes AdSense log "already have ads in them" and leave
    // the unit blank.
    if (pushed.current) return;
    pushed.current = true;

    try {
      (window.adsbygoogle = window.adsbygoogle ?? []).push({});
    } catch {
      // A blocked or failed script must never break the page around it.
    }
  }, []);

  return (
    <ins
      className="adsbygoogle"
      style={{ display: 'block', minHeight, width: '100%' }}
      data-ad-client={client}
      data-ad-slot={slot}
      data-ad-format={format}
      data-full-width-responsive="true"
    />
  );
}
