import { useEffect } from 'react';

// Extend window interface for gtag and fbq
declare global {
  interface Window {
    gtag?: (...args: any[]) => void;
    fbq?: (...args: any[]) => void;
    dataLayer?: any[];
  }
}

export function useAnalytics() {
  const trackPageView = (url: string) => {
    // 1. Google Analytics 4
    if (window.gtag) {
      window.gtag('config', process.env.NEXT_PUBLIC_GA_TRACKING_ID || 'G-MOCK-ID', {
        page_path: url,
      });
    }
    // 2. Facebook Pixel
    if (window.fbq) {
      window.fbq('track', 'PageView');
    }
    console.log(`[Analytics] Track PageView: ${url}`);
  };

  const trackProductView = (productId: string, name: string, price: number) => {
    if (window.gtag) {
      window.gtag('event', 'view_item', {
        currency: 'INR',
        value: price,
        items: [{ item_id: productId, item_name: name, price }],
      });
    }
    if (window.fbq) {
      window.fbq('track', 'ViewContent', {
        content_ids: [productId],
        content_name: name,
        value: price,
        currency: 'INR',
      });
    }
    console.log(`[Analytics] Track ProductView: ${name} (₹${price})`);
  };

  const trackAddToCart = (productId: string, name: string, price: number, quantity: number = 1) => {
    if (window.gtag) {
      window.gtag('event', 'add_to_cart', {
        currency: 'INR',
        value: price * quantity,
        items: [{ item_id: productId, item_name: name, price, quantity }],
      });
    }
    if (window.fbq) {
      window.fbq('track', 'AddToCart', {
        content_ids: [productId],
        content_name: name,
        value: price * quantity,
        currency: 'INR',
      });
    }
    console.log(`[Analytics] Track AddToCart: ${name} x${quantity}`);
  };

  const trackCheckout = (step: number, cartTotal: number) => {
    if (window.gtag) {
      window.gtag('event', 'begin_checkout', {
        currency: 'INR',
        value: cartTotal,
      });
    }
    if (window.fbq) {
      window.fbq('track', 'InitiateCheckout', {
        value: cartTotal,
        currency: 'INR',
      });
    }
    console.log(`[Analytics] Track InitiateCheckout Step ${step}: Total ₹${cartTotal}`);
  };

  const trackPurchase = (orderId: string, grandTotal: number, items: any[]) => {
    if (window.gtag) {
      window.gtag('event', 'purchase', {
        transaction_id: orderId,
        value: grandTotal,
        currency: 'INR',
        items: items.map((i) => ({
          item_id: i.id || i.bookId,
          item_name: i.title || i.book?.title,
          price: Number(i.price || i.book?.price),
          quantity: i.quantity,
        })),
      });
    }
    if (window.fbq) {
      window.fbq('track', 'Purchase', {
        value: grandTotal,
        currency: 'INR',
        content_type: 'product',
        contents: items.map((i) => ({
          id: i.id || i.bookId,
          quantity: i.quantity,
        })),
      });
    }
    console.log(`[Analytics] Track Purchase Order: ${orderId} (₹${grandTotal})`);
  };

  return {
    trackPageView,
    trackProductView,
    trackAddToCart,
    trackCheckout,
    trackPurchase,
  };
}
