'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { firePixelEvent } from './firePixelEvent';

type RouteRule = {
  pattern: RegExp;
  getParams: (match: RegExpMatchArray) => { contentName: string; contentCategory: string };
};

function slugToTitle(slug: string): string {
  return slug
    .split('-')
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

// Checked in order — first match wins. More specific patterns come first.
const ROUTE_RULES: RouteRule[] = [
  {
    pattern: /^\/services\/(.+)$/,
    getParams: ([, slug]) => ({ contentName: slugToTitle(slug), contentCategory: 'Service' }),
  },
  {
    pattern: /^\/locations\/(.+)$/,
    getParams: ([, slug]) => ({ contentName: slugToTitle(slug), contentCategory: 'Location' }),
  },
  {
    pattern: /^\/services$/,
    getParams: () => ({ contentName: 'Services', contentCategory: 'Services' }),
  },
  {
    pattern: /^\/locations$/,
    getParams: () => ({ contentName: 'Locations', contentCategory: 'Locations' }),
  },
  {
    pattern: /^\/portal$/,
    getParams: () => ({ contentName: 'Member Portal', contentCategory: 'Pricing' }),
  },
  {
    pattern: /^\/service-menu$/,
    getParams: () => ({ contentName: 'Service Menu', contentCategory: 'Pricing' }),
  },
  {
    pattern: /^\/faq$/,
    getParams: () => ({ contentName: 'FAQ', contentCategory: 'FAQ' }),
  },
  {
    pattern: /^\/contact$/,
    getParams: () => ({ contentName: 'Contact', contentCategory: 'Contact' }),
  },
];

type Props = {
  /** External booking URL. When set, fires InitiateCheckout on any click targeting that URL. */
  bookingUrl?: string | null;
};

/**
 * Single client-side tracker placed once in KeystoneRootLayout.
 * - Fires ViewContent on every route change for known page patterns.
 * - Fires InitiateCheckout whenever a visitor clicks a link to the external booking URL.
 *
 * Portal booking tab tracking is handled directly inside PortalPage via PortalTabTracker
 * since intent is only established when the Booking tab is explicitly opened.
 */
export function MetaPixelTracker({ bookingUrl }: Props) {
  const pathname = usePathname();

  useEffect(() => {
    for (const rule of ROUTE_RULES) {
      const match = pathname.match(rule.pattern);
      if (match) {
        const { contentName, contentCategory } = rule.getParams(match);
        firePixelEvent('ViewContent', { contentName, contentCategory });
        break;
      }
    }
  }, [pathname]);

  useEffect(() => {
    if (!bookingUrl) return;

    const handleClick = (e: MouseEvent) => {
      const anchor = (e.target as Element).closest('a');
      if (anchor?.href?.startsWith(bookingUrl)) {
        firePixelEvent('InitiateCheckout');
      }
    };

    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, [bookingUrl]);

  return null;
}
