import { useEffect, useRef } from "react";

type CalFn = ((...args: unknown[]) => void) & {
  loaded?: boolean;
  ns?: Record<string, CalFn>;
  q?: unknown[];
};
type CalWindow = Window & { Cal?: CalFn };

// Loads the Cal.com inline embed once and mounts it into #cal-inline.
// Fires onBooking(payload) when a booking is completed.
export function CalEmbed({
  calLink,
  onBooking,
  theme = "dark",
}: {
  calLink: string;
  onBooking?: (payload: unknown) => void;
  theme?: "dark" | "light" | "auto";
}) {
  const ref = useRef<HTMLDivElement>(null);
  const cbRef = useRef(onBooking);
  cbRef.current = onBooking;

  useEffect(() => {
    if (!calLink || typeof window === "undefined") return;
    const link = calLink
      .replace(/^https?:\/\/(app\.)?cal\.com\//i, "")
      .replace(/^\/+/, "")
      .split("?")[0];
    if (!link) return;

    // Cal.com official loader snippet (idempotent).
    (function (C: CalWindow, A: string, L: string) {
      const p = (a: CalFn, ar: unknown) => {
        (a.q ||= []).push(ar);
      };
      const d = C.document;
      C.Cal =
        C.Cal ||
        (function () {
          const cal: CalFn = function (this: unknown) {
            // eslint-disable-next-line prefer-rest-params
            const args = arguments as unknown as unknown[];
            const c = C.Cal!;
            if (!c.loaded) {
              c.ns = {};
              c.q = c.q || [];
              const s = d.createElement("script");
              s.src = A;
              d.head.appendChild(s);
              c.loaded = true;
            }
            if (args[0] === L) {
              const api: CalFn = function (this: unknown) {
                // eslint-disable-next-line prefer-rest-params
                p(api, arguments as unknown as unknown[]);
              } as CalFn;
              const ns = args[1] as string;
              api.q = api.q || [];
              if (typeof ns === "string") {
                c.ns![ns] = c.ns![ns] || api;
                p(c.ns![ns], args);
                p(c, ["initNamespace", ns]);
              } else {
                p(c, args);
              }
              return;
            }
            p(c, args);
          } as CalFn;
          return C.Cal;
        })();
    })(window as CalWindow, "https://app.cal.com/embed/embed.js", "init");

    const NS = "ponto-sched";
    const Cal = (window as CalWindow).Cal!;
    Cal("init", NS, { origin: "https://cal.com" });
    const nsApi = Cal.ns![NS];

    nsApi("inline", {
      elementOrSelector: ref.current,
      calLink: link,
      config: { layout: "month_view", theme },
    });
    nsApi("ui", {
      hideEventTypeDetails: false,
      layout: "month_view",
      theme,
    });
    nsApi("on", {
      action: "bookingSuccessful",
      callback: (e: unknown) => {
        try {
          cbRef.current?.((e as { detail?: unknown })?.detail ?? e);
        } catch {
          /* noop */
        }
      },
    });
  }, [calLink, theme]);

  return (
    <div
      ref={ref}
      id="cal-inline"
      className="w-full min-h-[640px] rounded-xl overflow-hidden bg-white/5"
    />
  );
}
