// ─── AdSense ad unit ─────────────────────────
// Reusable <AdSlot/>. Publisher ID is read from the loader <script> in
// index.html. The ad-unit slot defaults to the GradeCheck Result unit, so
// the gated <AdSlot/> in app.jsx (free / signed-out users only) shows a real ad.

const ADSENSE_CLIENT = (() => {
  try {
    const s = document.querySelector('script[src*="adsbygoogle.js"]');
    const m = s && s.src.match(/client=(ca-pub-\d+)/);
    return m ? m[1] : "";
  } catch { return ""; }
})();

const DEFAULT_AD_SLOT = "7292821172"; // GradeCheck Result Ad

function AdSlot({ slot, format = "auto", layout, className = "", style }) {
  const adSlot = slot || DEFAULT_AD_SLOT;
  const configured = !!ADSENSE_CLIENT && !!adSlot;

  React.useEffect(() => {
    if (!configured) return;
    if (typeof window === "undefined" || !window.adsbygoogle) return;
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (e) {
      /* AdSense not ready / blocked — fail silently */
    }
  }, [configured, adSlot]);

  if (!configured) return null;

  return (
    <div className={"ad-slot " + className} style={style}>
      <ins
        className="adsbygoogle"
        style={{ display: "block" }}
        data-ad-client={ADSENSE_CLIENT}
        data-ad-slot={adSlot}
        data-ad-format={format}
        data-full-width-responsive="true"
        {...(layout ? { "data-ad-layout": layout } : {})}
      ></ins>
    </div>
  );
}

window.AdSlot = AdSlot;
