/**
 * Plausible Analytics Adapter
 * Decoupled implementation
 */

import type {
  AnalyticsAdapter,
  AnalyticsEvent,
  AnalyticsConfig,
} from "./interfaces";

export class PlausibleAdapter implements AnalyticsAdapter {
  private domain: string;
  private scriptUrl: string;

  constructor(config: AnalyticsConfig) {
    this.domain = config.domain || "";
    this.scriptUrl = config.scriptUrl || "";
  }

  async track(event: AnalyticsEvent): Promise<void> {
    if (typeof window === "undefined") return;

    const w = window as any;
    if (w.plausible) {
      w.plausible(event.name, {
        props: event.props,
      });
    }
  }

  async page(path: string, props?: Record<string, any>): Promise<void> {
    await this.track({
      name: "Pageview",
      props: { path, ...props },
    });
  }

  getScriptTag(): string {
    return `<script defer data-domain="${this.domain}" src="${this.scriptUrl}"></script>`;
  }
}
