'use client';

import { Suspense, useEffect, useRef } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

const ENDPOINT =
  (typeof process !== 'undefined' && process.env.NEXT_PUBLIC_RMP_ADS_API
    ? process.env.NEXT_PUBLIC_RMP_ADS_API
    : 'https://advertising.relevantmediaproperties.com') + '/api/analytics/pageview';

const ARTICLE_PREFIXES = ['/news/', '/articles/', '/article/', '/blog/'];
const SKIP_PREFIXES = ['/admin', '/api', '/login', '/client-login', '/wp-admin', '/marketplace/admin'];

function getSessionId(): string {
  try {
    let sid = sessionStorage.getItem('rmp_analytics_sid');
    if (!sid) {
      sid =
        typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
          ? crypto.randomUUID()
          : `as_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
      sessionStorage.setItem('rmp_analytics_sid', sid);
    }
    return sid;
  } catch {
    return `as_${Date.now()}`;
  }
}

function utmParams(): Record<string, string | null> {
  if (typeof window === 'undefined') return {};
  const p = new URLSearchParams(window.location.search);
  const out: Record<string, string | null> = {};
  for (const k of ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term']) {
    out[k] = p.get(k);
  }
  return out;
}

function fireView(propertySlug: string, pathname: string) {
  if (typeof window === 'undefined') return;
  if (SKIP_PREFIXES.some((p) => pathname.startsWith(p))) return;

  const isArticle = ARTICLE_PREFIXES.some((p) => pathname.startsWith(p));
  const articleSlug = isArticle ? pathname.split('/').filter(Boolean).pop() || null : null;
  const utm = utmParams();

  const payload = JSON.stringify({
    propertySlug,
    pagePath: pathname,
    pageUrl: window.location.href,
    articleSlug,
    referrer: document.referrer || null,
    sessionId: getSessionId(),
    eventType: 'view',
    utmSource: utm.utm_source,
    utmMedium: utm.utm_medium,
    utmCampaign: utm.utm_campaign,
    utmContent: utm.utm_content,
    utmTerm: utm.utm_term,
  });

  try {
    if (typeof navigator.sendBeacon === 'function') {
      const ok = navigator.sendBeacon(ENDPOINT, new Blob([payload], { type: 'application/json' }));
      if (ok) return;
    }
  } catch {
    /* fall through */
  }

  fetch(ENDPOINT, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: payload,
    keepalive: true,
    mode: 'cors',
  }).catch(() => undefined);
}

function BeaconInner({ propertySlug }: { propertySlug: string }) {
  const pathname = usePathname() || '';
  const searchParams = useSearchParams();
  const lastKey = useRef('');

  useEffect(() => {
    if (!propertySlug || !pathname) return;
    const key = `${pathname}?${searchParams?.toString() || ''}`;
    if (lastKey.current === key) return;
    lastKey.current = key;
    fireView(propertySlug, pathname);
  }, [pathname, searchParams, propertySlug]);

  return null;
}

/** Mount in root layout — tracks all public routes → advertising pageview API → adv.page_view_events. */
export default function SiteAnalyticsBeacon({ propertySlug }: { propertySlug: string }) {
  if (!propertySlug) return null;
  return (
    <Suspense fallback={null}>
      <BeaconInner propertySlug={propertySlug} />
    </Suspense>
  );
}
