// AdSense ad slot system.
//
// When ads are enabled but no publisher/slot IDs are configured, renders
// a visible test placeholder so admins can see exactly where ads appear.
// Once real IDs are set, the placeholders are replaced with live AdSense units.

(function () {
  let _adsScriptLoaded = false;
  let _adsScriptLoading = false;

  function loadAdSenseScript(clientId) {
    if (_adsScriptLoaded || _adsScriptLoading || !clientId) return;
    _adsScriptLoading = true;
    const s = document.createElement('script');
    s.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=' + clientId;
    s.async = true;
    s.crossOrigin = 'anonymous';
    s.onload = () => { _adsScriptLoaded = true; _adsScriptLoading = false; };
    s.onerror = () => { _adsScriptLoading = false; };
    document.head.appendChild(s);
  }

  let _cssInjected = false;
  function injectCss() {
    if (_cssInjected) return;
    _cssInjected = true;
    const s = document.createElement('style');
    s.textContent = `
      .mm-ad-slot { position:relative; border-radius:8px; background:var(--id-surface-alt); border:1px solid var(--id-border); overflow:hidden; }
      .mm-ad-label { position:absolute; top:4px; right:8px; font-size:9px; letter-spacing:.1em; text-transform:uppercase; color:var(--id-text-muted); opacity:.6; pointer-events:none; z-index:1; }
      .mm-ad-slot ins { min-height:inherit; }
      .mm-ad-test {
        display:flex; align-items:center; justify-content:center; gap:8px;
        width:100%; color:var(--id-text-muted); font-size:12px; font-weight:600;
        letter-spacing:.04em; text-transform:uppercase;
        border:2px dashed var(--id-border); border-radius:8px;
        background:repeating-linear-gradient(135deg, transparent, transparent 10px, var(--id-border) 10px, var(--id-border) 11px);
        opacity:.7;
      }
      .mm-ad-test-icon { font-size:18px; }
    `;
    document.head.appendChild(s);
  }

  const SLOT_LABELS = {
    leaderboard: 'Leaderboard Ad (728 x 90)',
    ingrid:      'In-Grid Native Ad (fluid)',
    modal:       'Modal Ad (728 x 90)',
    footer:      'Footer Ad (728 x 90)',
  };

  const HORIZONTAL = { format: 'horizontal', style: { display: 'block', width: '100%', minHeight: 90, textAlign: 'center' } };
  const SLOT_CONFIG = {
    leaderboard: HORIZONTAL,
    ingrid:      { format: 'fluid', style: { display: 'block', width: '100%', minHeight: 250 } },
    modal:       HORIZONTAL,
    footer:      HORIZONTAL,
  };

  function isPremiumUser() {
    const ents = window.MM_USER_ENTITLEMENTS || [];
    return ents.includes('premium') || ents.includes('pro');
  }

  function AdSlot({ slot, style: extraStyle }) {
    const ref = React.useRef(null);
    const pushed = React.useRef(false);
    const [visible, setVisible] = React.useState(false);
    const [adsConfig, setAdsConfig] = React.useState(window.MM_ADS_CONFIG || null);

    React.useEffect(() => {
      if (adsConfig) return;
      const onCfg = () => setAdsConfig(window.MM_ADS_CONFIG);
      window.addEventListener('mm-ads-ready', onCfg);
      return () => window.removeEventListener('mm-ads-ready', onCfg);
    }, [adsConfig]);

    React.useEffect(() => {
      const el = ref.current;
      if (!el) return;
      const io = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting) { setVisible(true); io.disconnect(); }
      }, { rootMargin: '200px' });
      io.observe(el);
      return () => io.disconnect();
    }, []);

    // Push live ad unit once visible and fully configured
    React.useEffect(() => {
      if (pushed.current || !visible || !adsConfig?.enabled) return;
      if (!adsConfig.clientId || !adsConfig.slots?.[slot]) return;
      if (!window.MMConsent?.has('advertising') || isPremiumUser()) return;

      loadAdSenseScript(adsConfig.clientId);
      pushed.current = true;

      const tryPush = () => {
        try { (window.adsbygoogle = window.adsbygoogle || []).push({}); } catch {}
      };
      let retryId, timeoutId;
      if (window.adsbygoogle) tryPush();
      else {
        retryId = setInterval(() => {
          if (!window.adsbygoogle) return;
          clearInterval(retryId);
          tryPush();
        }, 500);
        timeoutId = setTimeout(() => clearInterval(retryId), 10000);
      }
      return () => { clearInterval(retryId); clearTimeout(timeoutId); };
    }, [visible, adsConfig, slot]);

    // Gate: ads must be enabled
    if (!adsConfig?.enabled) return null;
    // Gate: premium users never see ads
    if (isPremiumUser()) return null;

    injectCss();
    const cfg = SLOT_CONFIG[slot] || HORIZONTAL;
    const containerStyle = { ...cfg.style, ...(extraStyle || {}) };
    const hasRealConfig = adsConfig.clientId && adsConfig.slots?.[slot];
    const hasConsent = window.MMConsent?.has('advertising');
    const isTestMode = !hasRealConfig;

    // --- Test placeholder: ads enabled but no IDs configured yet ---
    if (isTestMode) {
      return (
        <div ref={ref} className="mm-ad-slot" data-slot={slot} style={containerStyle}>
          <div className="mm-ad-test" style={{ height: cfg.style.minHeight || 90 }}>
            <span className="mm-ad-test-icon">&#x1f4e2;</span>
            <span>{SLOT_LABELS[slot] || 'Ad Slot: ' + slot}</span>
          </div>
          <div className="mm-ad-label">Test</div>
        </div>
      );
    }

    // --- No consent: show nothing (GDPR) ---
    if (!hasConsent) return null;

    // --- Live ad ---
    return (
      <div ref={ref} className="mm-ad-slot" data-slot={slot} style={containerStyle}>
        {visible && (
          <ins className="adsbygoogle"
               style={{ display: 'block' }}
               data-ad-client={adsConfig.clientId}
               data-ad-slot={adsConfig.slots[slot]}
               data-ad-format={cfg.format === 'fluid' ? 'fluid' : 'auto'}
               data-full-width-responsive="true" />
        )}
        <div className="mm-ad-label">Ad</div>
      </div>
    );
  }

  window.AdSlot = AdSlot;
})();
