const PLAUSIBLE_API = import.meta.env.VITE_PLAUSIBLE_API || 'http://localhost/api/event';
const DOMAIN = import.meta.env.VITE_PLAUSIBLE_DOMAIN || 'myapp-dev';

const sendEvent = (payload) => {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), 5000);

  fetch(PLAUSIBLE_API, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
    signal: controller.signal,
  })
    .catch((e) => console.error('Plausible error:', e))
    .finally(() => clearTimeout(timeout));
};

export const trackPageView = (pathname) => {
  if (!pathname) return;

  sendEvent({
    domain: DOMAIN,
    url: `${window.location.origin}${pathname}`,
    referrer: document.referrer,
    screenWidth: window.innerWidth,
    name: 'pageview',
  });
};

export const trackEvent = (eventName, properties = {}) => {
  if (!eventName) return;

  sendEvent({
    domain: DOMAIN,
    url: window.location.href,
    referrer: document.referrer,
    screenWidth: window.innerWidth,
    name: eventName,
    props: properties,
  });
};
