"use client";

import { useEffect, useRef } from "react";
import type { SupportedLocale } from "@/lib/i18n-config";
import {
  ADSENSE_CONTENT_FEED_LAYOUT_KEY,
  ADSENSE_PUBLISHER_ID,
} from "@/lib/adsense";

const adLabels: Record<SupportedLocale, string> = {
  en: "Advertisement",
  ja: "広告",
  ko: "광고",
  ru: "Реклама",
  vi: "Quảng cáo",
  zh: "广告",
};

type AdsenseContentAdProps = {
  className?: string;
  format?: "horizontal" | "in-article" | "in-feed" | "rectangle";
  locale: SupportedLocale;
  slot: string | null;
};

export function AdsenseContentAd({
  className = "",
  format = "in-article",
  locale,
  slot,
}: AdsenseContentAdProps) {
  const adRef = useRef<HTMLModElement | null>(null);
  const initializedRef = useRef(false);

  useEffect(() => {
    const ad = adRef.current;
    const shell = ad?.closest<HTMLElement>("[data-adsense-shell]");
    const hostname = window.location.hostname.toLowerCase();

    if (process.env.NODE_ENV === "development" || !ad || !shell || !slot || initializedRef.current) {
      return;
    }

    if (!["officialsite.kr", "www.officialsite.kr"].includes(hostname)) {
      shell.dataset.adsenseState = "unfilled";
      return;
    }

    initializedRef.current = true;
    shell.dataset.adsenseState = "loading";

    const syncStatus = () => {
      const status = ad.dataset.adStatus;

      if (status === "filled" || status === "unfilled") {
        shell.dataset.adsenseState = status;
      }
    };
    const observer = new MutationObserver(syncStatus);
    observer.observe(ad, { attributeFilter: ["data-ad-status"], attributes: true });

    const timeout = window.setTimeout(() => {
      if (!ad.dataset.adStatus) {
        shell.dataset.adsenseState = "timeout";
      }
    }, 12_000);

    try {
      const adsenseWindow = window as Window & {
        adsbygoogle?: Array<Record<string, never>>;
      };
      adsenseWindow.adsbygoogle = adsenseWindow.adsbygoogle ?? [];
      adsenseWindow.adsbygoogle.push({});
    } catch {
      shell.dataset.adsenseState = "unfilled";
    }

    return () => {
      window.clearTimeout(timeout);
      observer.disconnect();
    };
  }, [slot]);

  if (!slot) return null;

  const label = adLabels[locale];
  const isRectangle = format === "rectangle";
  const isFluid = format === "in-article" || format === "in-feed";
  const shellClassName = `adsense-content-shell my-10 w-full overflow-hidden sm:my-12 ${className}`;
  const adClassName = isRectangle
    ? "adsbygoogle block min-h-[250px] w-full"
    : format === "horizontal"
      ? "adsbygoogle block min-h-[90px] w-full sm:min-h-[110px]"
      : "adsbygoogle block min-h-[150px] w-full sm:min-h-[176px]";
  const previewClassName = isRectangle
    ? "min-h-[250px]"
    : format === "horizontal"
      ? "min-h-[90px] sm:min-h-[110px]"
      : "min-h-[150px] sm:min-h-[176px]";
  const header = (
    <p className="mb-2 text-[10px] font-medium uppercase tracking-[0.14em] text-[#98a3b3]">
      {label}
    </p>
  );

  if (process.env.NODE_ENV === "development") {
    return (
      <aside
        aria-label={`${label} preview`}
        className={shellClassName}
        data-adsense-shell
        data-adsense-state="preview"
      >
        {header}
        <div
          className={`flex items-center justify-center px-5 text-center ${previewClassName}`}
          data-adsense-preview
        >
          <div>
            <p className="text-[13px] font-semibold text-[#536987]">
              {format === "in-feed" ? "블로그 목록 인피드 광고 영역" : "콘텐츠 본문 광고 영역"}
            </p>
            <p className="mt-1.5 text-[11px] text-[#8a9ab1]">개발 환경에서는 실제 광고를 요청하지 않습니다.</p>
          </div>
        </div>
      </aside>
    );
  }

  return (
    <aside
      aria-label={label}
      className={shellClassName}
      data-adsense-shell
    >
      {header}
      <div className="overflow-hidden">
        <ins
          ref={adRef}
          className={adClassName}
          data-ad-client={ADSENSE_PUBLISHER_ID}
          data-ad-format={isFluid ? "fluid" : format}
          data-ad-layout={format === "in-article" ? "in-article" : undefined}
          data-ad-layout-key={format === "in-feed" ? ADSENSE_CONTENT_FEED_LAYOUT_KEY : undefined}
          data-ad-slot={slot}
          data-full-width-responsive="true"
          style={{ display: "block", textAlign: "center" }}
        />
      </div>
    </aside>
  );
}
