"use client";
// src/analytics/AnalyticsBootstrap.tsx
import { useCallback, useEffect, useMemo, useRef } from "react";
function AnalyticsBootstrap(config) {
  useAnalytics(config);
  return null;
}
function useAnalytics(config) {
  const siteId = config?.siteId ?? null;
  const siteSlug = config?.siteSlug ?? "";
  const endpoint = config?.endpoint ?? "/api/analytics/collect";
  const sessionCookieName = config?.sessionCookieName ?? "builder_analytics_session";
  const disabled = config?.disabled ?? false;
  const activeConfig = useMemo(() => {
    if (!siteId || disabled) {
      return null;
    }
    return { siteId, siteSlug, endpoint, sessionCookieName };
  }, [disabled, endpoint, sessionCookieName, siteId, siteSlug]);
  const stateRef = useRef({
    client: null,
    queue: []
  });
  const configRef = useRef(null);
  configRef.current = activeConfig;
  const enqueue = useCallback((action) => {
    if (!configRef.current) return;
    const state = stateRef.current;
    if (state.client) {
      action(state.client);
      return;
    }
    state.queue.push(action);
  }, []);
  useEffect(() => {
    const state = stateRef.current;
    if (!activeConfig) {
      if (state.client) {
        state.client.destroy();
        state.client = null;
      }
      state.queue = [];
      return;
    }
    const configSnapshot = activeConfig;
    let disposed = false;
    async function start() {
      try {
        const client = createMinimalAnalyticsClient({
          siteId: configSnapshot.siteId,
          siteSlug: configSnapshot.siteSlug,
          endpoint: configSnapshot.endpoint,
          sessionCookieName: configSnapshot.sessionCookieName
        });
        if (disposed) return;
        state.client = client;
        if (state.queue.length > 0) {
          const pending = state.queue.splice(0);
          for (const action of pending) action(client);
        }
        await client.track({
          eventType: "page_view",
          metadata: { path: window.location.pathname }
        });
      } catch (error) {
        console.warn("[analytics] Failed to initialize client", error);
      }
    }
    start();
    return () => {
      disposed = true;
      if (state.client) {
        state.client.destroy();
        state.client = null;
      }
      state.queue = [];
    };
  }, [activeConfig]);
  const trackEvent = useCallback(
    (event) => {
      enqueue((client) => void client.track(event));
    },
    [enqueue]
  );
  const trackCtaClick = useCallback(
    (metadata) => {
      enqueue((client) => void client.trackCtaClick(metadata));
    },
    [enqueue]
  );
  const trackFormSubmit = useCallback(
    (metadata) => {
      enqueue((client) => void client.trackFormSubmit(metadata));
    },
    [enqueue]
  );
  return useMemo(
    () => ({ trackEvent, trackCtaClick, trackFormSubmit }),
    [trackEvent, trackCtaClick, trackFormSubmit]
  );
}
function createMinimalAnalyticsClient(config) {
  let sessionId = null;
  const cookies = document.cookie.split(";");
  for (const cookie of cookies) {
    const [name, value] = cookie.trim().split("=");
    if (name === config.sessionCookieName) {
      sessionId = value ?? null;
      break;
    }
  }
  if (!sessionId) {
    sessionId = generateSessionId();
    const expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3);
    document.cookie = `${config.sessionCookieName}=${sessionId}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
  }
  const track = async (event) => {
    try {
      await fetch(config.endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          siteId: config.siteId,
          siteSlug: config.siteSlug,
          sessionId,
          eventType: event.eventType,
          metadata: {
            ...event.metadata,
            userAgent: navigator.userAgent,
            referrer: document.referrer,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          }
        })
      });
    } catch (error) {
      console.warn("[analytics] Failed to track event", error);
    }
  };
  const trackCtaClick = async (metadata) => {
    await track({
      eventType: "cta_click",
      metadata
    });
  };
  const trackFormSubmit = async (metadata) => {
    await track({
      eventType: "form_submit",
      metadata
    });
  };
  const destroy = () => {
  };
  return {
    track,
    trackCtaClick,
    trackFormSubmit,
    destroy
  };
}
function generateSessionId() {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
}
export {
  AnalyticsBootstrap,
  useAnalytics
};
