/**
 * 바즈(VADS) React 컴포넌트 v1 — 복붙 설치 파일 (의존성 없음, npm 불필요)
 * 소재는 서버(/api/offer)에서 내려받음 — 오퍼 추가/수정에 이 파일 수정 불필요.
 *
 * 설치 프롬프트 (Lovable/Bolt/Claude Code에 붙여넣기 — 대시보드에서 내 코드가 삽입된 버전 제공):
 * ────────────────────────────────────────────────────
 *   https://vibeadvertise.ai/sdk/VadsAd.jsx 의 내용을 가져와서
 *   src/components/VadsAd.jsx 파일로 그대로 추가하고 <VadsAd pub="발급받은코드" slot="위치이름" />을 사용해.
 *   위치는 앱 흐름에 가장 자연스러운 곳을 네가 판단해서 골라줘 —
 *   사용자가 결과나 완료를 확인한 직후 자리가 보통 반응이 가장 좋아.
 *   위치이름(slot)은 "result", "sidebar"처럼 자리를 설명하는 짧은 영문으로 (위치별 리포트 기준).
 *   규칙: 화면당 광고 1개, 광고 배지와 min-height는 유지.
 * ────────────────────────────────────────────────────
 *
 * 완성형:  <VadsAd pub="vp..." slot="result" />
 * 헤드리스: <VadsAd pub="vp..." slot="result" render={(ad, onClick) => (
 *            <MyCard title={ad.title} desc={ad.desc} img={ad.img} onClick={onClick} />
 *          )} />   ← 배지·측정·클릭 래핑은 컴포넌트가 계속 담당
 */
import { useEffect, useRef, useState } from 'react';

const VADS_BASE = 'https://vibeadvertise.ai';

function beacon(data) {
  try { navigator.sendBeacon(VADS_BASE + '/e', JSON.stringify(data)); } catch (e) {}
}

export default function VadsAd({ pub, slot = 'fixed', render }) {
  const ref = useRef(null);
  const [ad, setAd] = useState(null);
  const [noFill, setNoFill] = useState(false);

  useEffect(() => {
    let alive = true;
    fetch(`${VADS_BASE}/api/offer?pub=${encodeURIComponent(pub)}`)
      .then((r) => r.json())
      .then((d) => { if (!alive) return; d && d.ok ? setAd(d) : setNoFill(true); })
      .catch(() => alive && setNoFill(true));
    return () => { alive = false; };
  }, [pub]);

  useEffect(() => {
    const el = ref.current;
    if (!el || !ad) return;
    let counted = false, timer = null;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (counted) return;
        if (entry.intersectionRatio >= 0.5) {
          timer = setTimeout(() => {
            counted = true;
            beacon({ t: 'imp', vpub: pub, slot, offer: ad.id, cid: ad.cid, url: location.href });
          }, 1000);
        } else if (timer) { clearTimeout(timer); timer = null; }
      });
    }, { threshold: [0, 0.5] });
    io.observe(el);
    return () => { io.disconnect(); if (timer) clearTimeout(timer); };
  }, [pub, slot, ad]);

  if (noFill) return null; // no-fill → 렌더링 안 함

  const onClick = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (!ad) return;
    const vck = 'v' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
    beacon({ t: 'click', vck, vpub: pub, slot, offer: ad.id, cid: ad.cid, url: location.href });
    const sep = ad.url.includes('?') ? '&' : '?';
    window.location.href = `${ad.url}${sep}vck=${vck}&vpb=${pub}`;
  };

  // 로딩 중에도 공간 예약 (CLS 제로)
  if (!ad) return <div ref={ref} style={{ minHeight: 96 }} />;

  // 헤드리스: 렌더링은 앱이, 배지·측정·클릭은 우리가
  if (render) {
    return (
      <div ref={ref} style={{ position: 'relative', minHeight: 96 }}>
        {render(ad, onClick)}
        <span style={{ position: 'absolute', top: 4, right: 8, fontSize: 10, opacity: 0.5, pointerEvents: 'none' }}>광고</span>
      </div>
    );
  }

  // 완성형 카드 (테마는 부모에서 상속)
  return (
    <div ref={ref} style={{ minHeight: 96 }}>
      <a href={ad.url} onClick={onClick} style={{
        position: 'relative', display: 'flex', gap: 12, alignItems: 'center', padding: 12,
        border: '1px solid rgba(128,128,128,.25)', borderRadius: 12,
        textDecoration: 'none', color: 'inherit', fontFamily: 'inherit',
      }}>
        {ad.img && <img src={ad.img} alt="" style={{ width: 72, height: 72, borderRadius: 8, objectFit: 'cover' }} />}
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: 'block', fontWeight: 600 }}>{ad.title}</span>
          <span style={{ display: 'block', fontSize: 13, opacity: 0.75 }}>{ad.desc}</span>
        </span>
        <span style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap' }}>{ad.cta} ›</span>
        <span style={{ position: 'absolute', top: 4, right: 8, fontSize: 10, opacity: 0.5 }}>광고</span>
      </a>
    </div>
  );
}
