"use client";

import { useEffect, useRef } from "react";

/**
 * Drop-in AdSense unit.
 *
 * SETUP:
 * 1. Add your publisher id to app/layout.tsx (the <Script> tag with
 *    ca-pub-XXXXXXXXXXXXXXXX — replace the placeholder there).
 * 2. Create an ad unit in your AdSense dashboard and copy its slot id.
 * 3. Use it anywhere: <AdSlot slotId="1234567890" />
 *
 * Until AdSense approves the site, this renders a labeled placeholder
 * box instead of a blank/broken space, so layout and spacing stay
 * correct for review.
 */
export default function AdSlot({
  slotId,
  format = "auto",
  className = "",
  label = "Advertisement",
}: {
  slotId?: string;
  format?: string;
  className?: string;
  label?: string;
}) {
  const insRef = useRef<HTMLModElement>(null);
  const pushed = useRef(false);

  useEffect(() => {
    if (!slotId || pushed.current) return;
    try {
      // @ts-ignore
      (window.adsbygoogle = window.adsbygoogle || []).push({});
      pushed.current = true;
    } catch (e) {
      // AdSense script not loaded yet (e.g. site not approved) — ignore.
    }
  }, [slotId]);

  if (!slotId) {
    return (
      <div
        className={`flex min-h-[100px] w-full items-center justify-center rounded-2xl border border-dashed border-brand/30 bg-brand-softer text-xs uppercase tracking-wide text-heading/40 ${className}`}
      >
        {label} slot — add NEXT ad unit id
      </div>
    );
  }

  return (
    <ins
      ref={insRef}
      className={`adsbygoogle block ${className}`}
      style={{ display: "block" }}
      data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
      data-ad-slot={slotId}
      data-ad-format={format}
      data-full-width-responsive="true"
    />
  );
}
