"use client";

import { useEffect } from "react";
import { track } from "@/lib/analytics";

/** Calendly / Cal.com embed. Both post a message when a meeting is booked, which becomes a Schedule event. */
export default function BookingEmbed({ url, title }: { url: string; title: string }) {
  useEffect(() => {
    const onMessage = (e: MessageEvent) => {
      const fromCalendly = e.origin.endsWith("calendly.com") && (e.data as { event?: string })?.event === "calendly.event_scheduled";
      const fromCal = e.origin.endsWith("cal.com") && JSON.stringify(e.data ?? "").includes("bookingSuccessful");
      if (fromCalendly || fromCal) track({ name: "Schedule", provider: fromCalendly ? "calendly" : "cal.com" });
    };
    window.addEventListener("message", onMessage);
    return () => window.removeEventListener("message", onMessage);
  }, []);
  return <iframe src={url} title={title} className="h-[640px] w-full" loading="lazy" />;
}
