/* eslint-disable */
// Ad slots, premium banner placements across the site.
//
// Two components:
//   <AdSlot format="leaderboard" position="news-top" />
//   <AdCarousel format="medium-rectangle" position="article-sidebar" />
//
// All slots are CMS-driven: a single AD_INVENTORY array below holds the live
// banners. Format names follow the IAB standard so any agency can deliver
// creative that fits.
//
// When AD_INVENTORY has no banner for a slot, the component renders an
// elegant placeholder advertising the slot itself (a paid-position recruiter
// for the partnerships team). This converts unsold inventory into sales pipeline.

const AD_FORMATS = {
  // [width, height, label-key]
  'leaderboard':       { w: 728, h: 90,  label: 'Leaderboard · 728×90' },
  'billboard':         { w: 970, h: 250, label: 'Billboard · 970×250' },
  'medium-rectangle':  { w: 300, h: 250, label: 'Medium rectangle · 300×250' },
  'large-rectangle':   { w: 336, h: 280, label: 'Large rectangle · 336×280' },
  'half-page':         { w: 300, h: 600, label: 'Half page · 300×600' },
  'mobile-banner':     { w: 320, h: 100, label: 'Mobile banner · 320×100' },
};

// AD_INVENTORY_DEFAULT — hardcoded fallback used when /data/ads.json hasn't loaded yet.
// The live inventory is fetched from /data/ads.json at page load (see below).
const AD_INVENTORY_DEFAULT = [
  {
    "id": "confirmation-home-mid",
    "format": "billboard",
    "position": "home-mid",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-billboard.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "confirmation-home-pre-tiers",
    "format": "leaderboard",
    "position": "home-pre-tiers",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-leaderboard.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "confirmation-news-top",
    "format": "leaderboard",
    "position": "news-top",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-leaderboard.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "confirmation-jobs-top",
    "format": "leaderboard",
    "position": "jobs-top",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-leaderboard.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "confirmation-article-mid",
    "format": "large-rectangle",
    "position": "article-mid",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-large-rectangle.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "gim-cpa-home-mid",
    "format": "billboard",
    "position": "home-mid",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-billboard.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cpa-home-pre-tiers",
    "format": "leaderboard",
    "position": "home-pre-tiers",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-leaderboard.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cpa-news-top",
    "format": "leaderboard",
    "position": "news-top",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-leaderboard.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cpa-jobs-top",
    "format": "leaderboard",
    "position": "jobs-top",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-leaderboard.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cpa-article-mid",
    "format": "large-rectangle",
    "position": "article-mid",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-large-rectangle.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cia-home-mid",
    "format": "billboard",
    "position": "home-mid",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-billboard.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  },
  {
    "id": "gim-cia-home-pre-tiers",
    "format": "leaderboard",
    "position": "home-pre-tiers",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-leaderboard.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  },
  {
    "id": "gim-cia-news-top",
    "format": "leaderboard",
    "position": "news-top",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-leaderboard.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  },
  {
    "id": "gim-cia-jobs-top",
    "format": "leaderboard",
    "position": "jobs-top",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-leaderboard.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  },
  {
    "id": "gim-cia-article-mid",
    "format": "large-rectangle",
    "position": "article-mid",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-large-rectangle.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  },
  {
    "id": "confirmation-directory-top",
    "format": "leaderboard",
    "position": "directory-top",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-leaderboard.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "confirmation-courses-top",
    "format": "leaderboard",
    "position": "courses-top",
    "advertiser": "Confirmation.com",
    "image": "assets/imagery/ads/confirmation-leaderboard.jpg",
    "href": "https://www.confirmation.com",
    "alt": "Confirmation.com, The trusted audit confirmations platform",
    "active": true
  },
  {
    "id": "gim-cpa-directory-top",
    "format": "leaderboard",
    "position": "directory-top",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-leaderboard.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cpa-courses-top",
    "format": "leaderboard",
    "position": "courses-top",
    "advertiser": "GIM CPA",
    "image": "assets/imagery/ads/gim-cpa-leaderboard.jpg",
    "href": "https://gim.cpa/cpa-opleiding",
    "alt": "GIM CPA opleiding, Internationally recognised on Curaçao",
    "active": true
  },
  {
    "id": "gim-cia-directory-top",
    "format": "leaderboard",
    "position": "directory-top",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-leaderboard.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  },
  {
    "id": "gim-cia-courses-top",
    "format": "leaderboard",
    "position": "courses-top",
    "advertiser": "GIM CIA",
    "image": "assets/imagery/ads/gim-cia-leaderboard.jpg",
    "href": "https://gim.cpa/cia-opleiding",
    "alt": "GIM CIA opleiding, Become a Certified Internal Auditor",
    "active": true
  }
];

// Bootstrap inventory from JSON; fall back to hardcoded default.
window.AD_INVENTORY = [...AD_INVENTORY_DEFAULT];
fetch('/data/ads.json?_=' + Date.now())
  .then(r => r.ok ? r.json() : null)
  .then(data => {
    if (data && Array.isArray(data.inventory)) {
      window.AD_INVENTORY = data.inventory;
      window.dispatchEvent(new CustomEvent('cbm-ads-loaded'));
    }
  })
  .catch(() => {});

function pickBanners(format, position) {
  return (window.AD_INVENTORY || []).filter(
    b => b.active !== false && b.format === format && b.position === position
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// AdSlot, a single banner placement.
// Shows the live banner if available, otherwise an elegant placeholder.
// ─────────────────────────────────────────────────────────────────────────────
const AdSlot = ({ format = 'leaderboard', position = 'unspecified', hideOnMobile = false }) => {
  const t = (window.useT && window.useT()) || ((k) => k);
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    window.addEventListener('cbm-ads-loaded', forceUpdate);
    return () => window.removeEventListener('cbm-ads-loaded', forceUpdate);
  }, []);
  const f = AD_FORMATS[format] || AD_FORMATS.leaderboard;
  const banners = pickBanners(format, position);
  const banner = banners[0]; // single-shot AdSlot, for rotation, use AdCarousel.

  return (
    <div className={'cbm-adslot-rail' + (hideOnMobile ? ' cbm-adslot--hide-mobile' : '')}>
      <div
        className={'cbm-adslot cbm-adslot--' + format}
        data-position={position}
      >
      {banner ? (
        <a href={banner.href} target="_blank" rel="noopener sponsored" className="cbm-adslot__live">
          <img src={banner.image} alt={banner.alt || banner.advertiser} loading="lazy" />
        </a>
      ) : (
        <a
          className="cbm-adslot__placeholder"
          onClick={(e) => { e.preventDefault(); window.location.hash = '#/advertise'; }}
          href="#/advertise"
        >
          <div className="cbm-adslot__meta">
            <span className="cbm-adslot__label">{t('adslot_premium_slot')}</span>
            <span className="cbm-adslot__size">{f.label}</span>
          </div>
          <div className="cbm-adslot__cta">{t('adslot_cta')}</div>
        </a>
      )}
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// AdCarousel, auto-rotating banner carousel for one slot.
// Cycles through live banners every 6 seconds; pauses on hover; arrow + dot nav.
// ─────────────────────────────────────────────────────────────────────────────
const AdCarousel = ({ format = 'billboard', position = 'home-top', interval = 6000 }) => {
  const t = (window.useT && window.useT()) || ((k) => k);
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    window.addEventListener('cbm-ads-loaded', forceUpdate);
    return () => window.removeEventListener('cbm-ads-loaded', forceUpdate);
  }, []);
  const f = AD_FORMATS[format] || AD_FORMATS.billboard;
  const banners = pickBanners(format, position);
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  // Auto-advance when there's more than one banner.
  React.useEffect(() => {
    if (banners.length < 2 || paused) return;
    const tmr = setTimeout(() => setIdx(i => (i + 1) % banners.length), interval);
    return () => clearTimeout(tmr);
  }, [idx, banners.length, paused, interval]);

  const wrap = {};

  // Empty state, promote the slot itself.
  if (banners.length === 0) {
    return (
      <div className="cbm-adslot-rail" style={{display:'flex', justifyContent:'center', padding:'0 16px', boxSizing:'border-box', width:'100%', margin:'24px 0'}}>
        <div className="cbm-adslot cbm-adslot--carousel" data-position={position}
             style={{position:'relative', width:'100%', maxWidth:'970px', aspectRatio:'970 / 250', overflow:'hidden', background:'var(--cbm-silver-2)', borderRadius:'4px', boxSizing:'border-box'}}>
          <a
            className="cbm-adslot__placeholder"
            onClick={(e) => { e.preventDefault(); window.location.hash = '#/advertise'; }}
            href="#/advertise"
          >
            <div className="cbm-adslot__meta">
              <span className="cbm-adslot__label">{t('adslot_carousel_slot')}</span>
              <span className="cbm-adslot__size">{f.label} · {t('adslot_rotates')}</span>
            </div>
            <div className="cbm-adslot__cta">{t('adslot_cta')}</div>
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="cbm-adslot-rail" style={{display:'flex', justifyContent:'center', padding:'0 16px', boxSizing:'border-box', width:'100%', margin:'24px 0'}}>
      <div
        className="cbm-adslot cbm-adslot--carousel"
        data-position={position}
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
        style={{position:'relative', width:'100%', maxWidth:'970px', aspectRatio:'970 / 250', overflow:'hidden', background:'var(--cbm-silver-2)', borderRadius:'4px', boxSizing:'border-box'}}
      >
      <div className="cbm-adslot__track" style={{position:'absolute', inset:0}}>
        {banners.map((b, i) => (
          <a
            key={b.id}
            className={'cbm-adslot__slide' + (i === idx ? ' is-active' : '')}
            href={b.href}
            target="_blank"
            rel="noopener sponsored"
            aria-hidden={i !== idx}
            tabIndex={i === idx ? 0 : -1}
            style={{position:'absolute', inset:0, opacity: i === idx ? 1 : 0, transition:'opacity 280ms ease', pointerEvents: i === idx ? 'auto' : 'none'}}
          >
            <img src={b.image} alt={b.alt || b.advertiser} loading={i === 0 ? 'eager' : 'lazy'}
                 style={{display:'block', width:'100%', height:'100%', objectFit:'cover'}} />
          </a>
        ))}
      </div>
      {banners.length > 1 && (
        <>
          <button
            className="cbm-adslot__nav cbm-adslot__nav--prev"
            onClick={(e) => { e.stopPropagation(); setIdx(i => (i - 1 + banners.length) % banners.length); }}
            aria-label={t('adslot_prev')}
          >‹</button>
          <button
            className="cbm-adslot__nav cbm-adslot__nav--next"
            onClick={(e) => { e.stopPropagation(); setIdx(i => (i + 1) % banners.length); }}
            aria-label={t('adslot_next')}
          >›</button>
          <div className="cbm-adslot__dots">
            {banners.map((_, i) => (
              <button
                key={i}
                className={'cbm-adslot__dot' + (i === idx ? ' is-active' : '')}
                onClick={(e) => { e.stopPropagation(); setIdx(i); }}
                aria-label={`Banner ${i + 1}`}
              />
            ))}
          </div>
          <div className="cbm-adslot__progress" aria-hidden="true">
            {/* Re-key so animation restarts on each idx change; pause on hover via parent class */}
            <div
              key={idx + (paused ? '-p' : '')}
              className="cbm-adslot__progress-bar"
              style={{
                animationDuration: interval + 'ms',
                animationPlayState: paused ? 'paused' : 'running',
              }}
            />
          </div>
        </>
      )}
      <div className="cbm-adslot__badge">{t('adslot_sponsored')}</div>
      </div>
    </div>
  );
};

Object.assign(window, { AdSlot, AdCarousel, AD_FORMATS, pickBanners });
