import { useEffect, useRef } from "react";

type AdFormat = "auto" | "fluid" | "rectangle" | "horizontal" | "vertical";

interface AdSenseProps {
  slot: string;
  format?: AdFormat;
  responsive?: boolean;
  className?: string;
  style?: Record<string, string>;
  layout?: string;
  layoutKey?: string;
}

export default function AdSense({
  slot,
  format = "auto",
  responsive = true,
  className = "",
  style,
  layout,
  layoutKey,
}: AdSenseProps) {
  const adRef = useRef<HTMLModElement>(null);
  const pushed = useRef(false);

  useEffect(() => {
    if (pushed.current) return;
    try {
      const adsbygoogle = (window as any).adsbygoogle || [];
      adsbygoogle.push({});
      pushed.current = true;
    } catch (e) {
    }
  }, []);

  return (
    <div className={`ad-container ${className}`} data-testid={`ad-slot-${slot}`}>
      <ins
        ref={adRef}
        className="adsbygoogle"
        style={style || { display: "block" }}
        data-ad-client="ca-pub-4465464714854276"
        data-ad-slot={slot}
        data-ad-format={format}
        data-full-width-responsive={responsive ? "true" : undefined}
        {...(layout ? { "data-ad-layout": layout } : {})}
        {...(layoutKey ? { "data-ad-layout-key": layoutKey } : {})}
      />
    </div>
  );
}

export function ArticleCardAd() {
  return (
    <div className="bg-card rounded-md border border-card-border h-full flex flex-col overflow-hidden">
      <AdSense
        slot="auto"
        format="fluid"
        layoutKey="-6t+ed+2i-1n-4w"
        style={{ display: "block" }}
        className="flex-1 min-h-[280px]"
      />
    </div>
  );
}

export function InArticleAd() {
  return (
    <AdSense
      slot="auto"
      format="fluid"
      layout="in-article"
      style={{ display: "block", textAlign: "center" }}
      className="my-8"
    />
  );
}

export function SidebarAd() {
  return (
    <div className="bg-card rounded-md border border-card-border p-4 mt-6">
      <AdSense
        slot="auto"
        format="auto"
      />
    </div>
  );
}
