<script setup>
import { computed, nextTick, onMounted, ref } from 'vue'

const props = defineProps({
  className: {
    type: String,
    default: '',
  },
})

const adEl = ref(null)
const client = 'ca-pub-4516420168710424'
const slot = '1236919061'
const panelClass = computed(() => ['rightRailAd', props.className].filter(Boolean).join(' '))

function ensureAdScript() {
  if (typeof window === 'undefined' || typeof document === 'undefined') return Promise.resolve()
  const existing = document.querySelector(`script[data-ad-client="${client}"]`)
  if (existing) return Promise.resolve()

  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.async = true
    script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${client}`
    script.crossOrigin = 'anonymous'
    script.dataset.adClient = client
    script.onload = () => resolve()
    script.onerror = () => reject(new Error('adsense_load_failed'))
    document.head.appendChild(script)
  })
}

onMounted(async () => {
  if (typeof window === 'undefined') return
  try {
    await ensureAdScript()
    await nextTick()
    if (!adEl.value) return
    window.adsbygoogle = window.adsbygoogle || []
    if (!adEl.value.dataset.adsbygoogleStatus) {
      window.adsbygoogle.push({})
    }
  } catch (e) {
    // Keep the slot quiet when ad blockers or network policies block the script.
  }
})
</script>

<template>
  <section :class="panelClass">
    <div class="rightRailAd__eyebrow">Sponsored</div>
    <div class="rightRailAd__frame">
      <ins
        ref="adEl"
        class="adsbygoogle rightRailAd__slot"
        style="display:block"
        :data-ad-client="client"
        :data-ad-slot="slot"
        data-ad-format="auto"
        data-full-width-responsive="true"
      ></ins>
    </div>
  </section>
</template>

<style scoped>
.rightRailAd {
  display: grid;
  gap: 12px;
  padding-top: 78px;
}

.rightRailAd__eyebrow {
  font-size: 11px;
  letter-spacing: 0.14em;
  text-transform: uppercase;
  color: rgba(255, 255, 255, 0.34);
}

.rightRailAd__frame {
  width: min(100%, 300px);
  min-height: 600px;
  margin: 0 auto;
}

.rightRailAd__slot {
  display: block;
  width: 300px;
  max-width: 100%;
  min-height: 600px;
  margin: 0 auto;
}
</style>
