// Ad slot system — canonical Red Goggles spec.
//
// Behavior modes:
//   "design"  — show labeled placeholder boxes at full size (dev visualization)
//   "live"    — render <ins class="adsbygoogle">; label is hidden until
//               Google sets data-ad-status="filled". Pre-approval / unfilled
//               pageviews show reserved empty space, per portfolio spec.
//
// In production set mode: "live" + per-slot ad-unit IDs in
// window.__AD_CONFIG.slots. Empty slot IDs are safe — the page renders
// reserved empty space rather than broken ad chrome.

const AD_CONFIG = (typeof window !== 'undefined' && window.__AD_CONFIG) || {};
const AD_MODE = AD_CONFIG.mode || (AD_CONFIG.publisherId ? 'live' : 'design');

const AD_SIZES = {
  leaderboard:           { w: 728, h: 90,  desc: '728 × 90' },
  mrec:                  { w: 300, h: 250, desc: '300 × 250' },
  halfpage:              { w: 300, h: 600, desc: '300 × 600' },
  'mobile-banner':       { w: 320, h: 50,  desc: '320 × 50' },
  'large-mobile-banner': { w: 320, h: 100, desc: '320 × 100' },
};

const ADSENSE_FORMATS = {
  leaderboard:           'horizontal',
  mrec:                  'rectangle',
  halfpage:              'vertical',
  'mobile-banner':       'horizontal',
  'large-mobile-banner': 'horizontal',
};

function AdSlot({ size, slotId, label, className = '', style = {} }) {
  const dims = AD_SIZES[size] || {};
  const insRef = React.useRef(null);
  const slotConfigured = AD_CONFIG.publisherId && AD_CONFIG.slots && AD_CONFIG.slots[slotId];

  // Push to adsbygoogle in live mode when a real slot ID is configured
  React.useEffect(() => {
    if (AD_MODE !== 'live' || !slotConfigured) return;
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (e) {
      console.warn('[ads] push failed', slotId, e);
    }
  }, [slotConfigured, slotId]);

  return (
    <aside
      className={`ad-slot ad-${size} ${className}`}
      data-ad-slot={slotId}
      data-ad-size={size}
      data-ad-mode={AD_MODE}
      style={style}
      aria-label="Advertisement"
    >
      <span className="ad-slot-label">
        <span className="ad-label-text">Advertisement</span>
        <span className="ad-label-dim">{dims.desc}</span>
      </span>
      <div
        className="ad-slot-inner"
        style={{ aspectRatio: `${dims.w} / ${dims.h}`, maxWidth: dims.w }}
      >
        {AD_MODE === 'live' ? (
          slotConfigured && (
            <ins
              ref={insRef}
              className="adsbygoogle"
              style={{ display: 'block', width: '100%', height: '100%' }}
              data-ad-client={AD_CONFIG.publisherId}
              data-ad-slot={AD_CONFIG.slots[slotId]}
              data-ad-format={ADSENSE_FORMATS[size] || 'auto'}
              data-full-width-responsive="true"
            />
          )
        ) : (
          // Design-mode placeholder. NOT shown in production.
          <div className="ad-placeholder-content">
            <div className="ad-placeholder-logo">
              <svg viewBox="0 0 32 32" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5">
                <rect x="3" y="6" width="26" height="20" rx="2" />
                <path d="M3 12h26M9 6v20" />
              </svg>
            </div>
            <div className="ad-placeholder-text">
              {label || `Programmatic ${dims.desc} · served at runtime`}
            </div>
          </div>
        )}
      </div>
    </aside>
  );
}

// Responsive pair — render desktop+mobile sizes, CSS hides whichever
// doesn't apply to the current viewport.
function ResponsiveAd({ desktop, mobile, slotId, label }) {
  return (
    <>
      <AdSlot size={desktop} slotId={slotId} className="desktop-only" label={label} />
      <AdSlot size={mobile} slotId={slotId} className="ad-mobile-only" label={label} />
    </>
  );
}

function StickyMobileAd({ slotId }) {
  const [dismissed, setDismissed] = React.useState(() => {
    try { return sessionStorage.getItem('ad-sticky-dismissed') === '1'; }
    catch { return false; }
  });
  if (dismissed) return null;
  const dismiss = () => {
    setDismissed(true);
    try { sessionStorage.setItem('ad-sticky-dismissed', '1'); } catch {}
  };
  return (
    <div className="sticky-mobile-ad">
      <button
        className="sticky-mobile-ad-close"
        onClick={dismiss}
        aria-label="Dismiss ad"
      >×</button>
      <AdSlot size="mobile-banner" slotId={slotId} />
    </div>
  );
}

window.AdSlot = AdSlot;
window.ResponsiveAd = ResponsiveAd;
window.StickyMobileAd = StickyMobileAd;
