<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;
}

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

.rightRailAd__frame {
  min-height: 520px;
  padding: 14px;
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(255, 255, 255, 0.02);
}

.rightRailAd__slot {
  width: 100%;
  min-height: 490px;
}
</style>
