"use client";

import { useEffect, useRef } from "react";

interface ProofclawWidgetProps {
  agentId: string;
  theme?: "light" | "dark";
  compact?: boolean;
  badgeOnly?: boolean;
}

const SCRIPT_URL = "https://www.proofclaw.io/embed/widget.js";
let scriptLoaded = false;

function loadScript() {
  if (scriptLoaded) return;
  scriptLoaded = true;
  const s = document.createElement("script");
  s.src = SCRIPT_URL;
  s.async = true;
  document.head.appendChild(s);
}

export function ProofclawWidget({
  agentId,
  theme = "light",
  compact = false,
  badgeOnly = false,
}: ProofclawWidgetProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    loadScript();
    // Re-init widget when props change
    const el = ref.current;
    if (el) {
      el.removeAttribute("data-proofclaw-loaded");
      el.textContent = "";
    }
    const id = setTimeout(() => {
      // @ts-expect-error widget.js global
      if (typeof window !== "undefined" && window.__PROOFCLAW_INIT__) {
        // @ts-expect-error widget.js global
        window.__PROOFCLAW_INIT__();
      }
    }, 200);
    return () => clearTimeout(id);
  }, [agentId, theme, compact, badgeOnly]);

  return (
    <div
      ref={ref}
      data-proofclaw-agent={agentId}
      data-theme={theme}
      {...(compact ? { "data-compact": "1" } : {})}
      {...(badgeOnly ? { "data-badge-only": "1" } : {})}
    />
  );
}
