const DOMAIN = 'narrowit.schmelczer.dev';
const ENDPOINT = '/status';
const IS_DEV = process.env.NODE_ENV !== 'production';

type EventOptions = {
  props?: Record<string, string | number | boolean>;
  revenue?: { currency: string; amount: number };
};

function sendEvent(name: string, options?: EventOptions) {
  if (IS_DEV) return;

  const payload: Record<string, unknown> = {
    n: name,
    u: window.location.href,
    d: DOMAIN,
    r: document.referrer || null,
  };
  if (options?.props) {
    payload.p = JSON.stringify(options.props);
  }
  if (options?.revenue) {
    payload.$ = JSON.stringify(options.revenue);
  }
  if (navigator.sendBeacon) {
    navigator.sendBeacon(
      ENDPOINT,
      new Blob([JSON.stringify(payload)], { type: 'application/json' })
    );
  } else {
    fetch(ENDPOINT, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
      keepalive: true,
    }).catch(() => {});
  }
}

let initialized = false;

/**
 * Tracks pageview on first call and returns a trackEvent function.
 * Tracks outbound link clicks automatically.
 */
export function initPlausible() {
  if (initialized) return;
  initialized = true;

  // Initial pageview
  sendEvent('pageview');

  // Track outbound link clicks
  document.addEventListener('click', (e) => {
    const link = (e.target as HTMLElement).closest?.('a');
    if (!link) return;
    const href = link.getAttribute('href');
    if (!href) return;
    try {
      const url = new URL(href, window.location.origin);
      if (url.hostname !== window.location.hostname) {
        sendEvent('Outbound Link: Click', { props: { url: href } });
      }
    } catch {
      // invalid URL, ignore
    }
  });
}

export function trackPageview(options?: EventOptions) {
  sendEvent('pageview', options);
}

export function trackEvent(name: string, options?: EventOptions) {
  sendEvent(name, options);
}
