'use client'

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

interface MatomoAnalyticsProps {
  siteId: string;
  matomoUrl: string;
}

function MatomoTracker({ siteId, matomoUrl }: MatomoAnalyticsProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    // Initialize Matomo
    const _paq = (window as any)._paq = (window as any)._paq || [];
    
    // Track page view
    _paq.push(['setCustomUrl', window.location.href]);
    _paq.push(['setDocumentTitle', document.title]);
    _paq.push(['trackPageView']);
    
    // Enable link tracking
    _paq.push(['enableLinkTracking']);
    
    // Set up Matomo tracker
    if (!(window as any).MatomoInitialized) {
      _paq.push(['setTrackerUrl', `${matomoUrl}/matomo.php`]);
      _paq.push(['setSiteId', siteId]);
      
      // Create script element
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src = `${matomoUrl}/matomo.js`;
      
      const firstScript = document.getElementsByTagName('script')[0];
      firstScript.parentNode?.insertBefore(script, firstScript);
      
      (window as any).MatomoInitialized = true;
    }
  }, [pathname, searchParams, siteId, matomoUrl]);

  return null;
}

export function MatomoAnalytics({ siteId, matomoUrl }: MatomoAnalyticsProps) {
  return (
    <Suspense fallback={null}>
      <MatomoTracker siteId={siteId} matomoUrl={matomoUrl} />
    </Suspense>
  );
}

// Helper function to track events
export function trackEvent(category: string, action: string, name?: string, value?: number) {
  const _paq = (window as any)._paq = (window as any)._paq || [];
  _paq.push(['trackEvent', category, action, name, value]);
}

// Helper function to track e-commerce
export function trackEcommerce(productName: string, price: number, quantity: number = 1) {
  const _paq = (window as any)._paq = (window as any)._paq || [];
  _paq.push(['addEcommerceItem',
    productName, // Product name
    productName, // Product SKU
    'Filament', // Product category
    price,
    quantity
  ]);
  _paq.push(['trackEcommerceOrder',
    Date.now().toString(), // Order ID
    price * quantity // Total value
  ]);
}