import {
  createElement,
  useEffect,
  useRef,
  type HTMLAttributes,
  type ReactElement,
} from "react";

import { initAkintu } from "../loader.js";

export interface AkintuEmbedProps extends HTMLAttributes<HTMLElement> {
  apiKey: string;
  apiBaseUrl?: string | undefined;
}

export interface AkintuInlineProps extends HTMLAttributes<HTMLDivElement> {
  apiKey: string;
  apiBaseUrl?: string | undefined;
  context: string;
}

/**
 * Renders inert custom-element markup during SSR and initializes it only after
 * hydration. The apiKey is consumed by the effect and is never spread to HTML.
 */
export function AkintuEmbed({
  apiKey,
  apiBaseUrl,
  ...htmlProps
}: AkintuEmbedProps): ReactElement {
  const elementRef = useRef<HTMLElement>(null);
  useEffect(() => {
    const element = elementRef.current;
    if (element === null) return;
    void initAkintu({
      apiKey,
      apiBaseUrl,
      root: element.ownerDocument,
    });
  }, [apiKey, apiBaseUrl]);

  return createElement("akintu-embed", {
    ...htmlProps,
    ref: elementRef,
  });
}

/**
 * Renders the contextual mount container expected by the shared loader. The
 * remote inlineEnabled flag remains authoritative after hydration.
 */
export function AkintuInline({
  apiKey,
  apiBaseUrl,
  context,
  ...htmlProps
}: AkintuInlineProps): ReactElement {
  const containerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const container = containerRef.current;
    if (container === null) return;
    void initAkintu({
      apiKey,
      apiBaseUrl,
      root: container.ownerDocument,
    });
  }, [apiKey, apiBaseUrl, context]);

  return createElement("div", {
    ...htmlProps,
    ref: containerRef,
    "data-akintu-context": context,
  });
}
