// src/CaptchaFox.tsx
import { createEffect, createSignal, on, onCleanup } from "solid-js";

// ../internal/dist/index.mjs
var RetryError = class extends Error {
};
var backoff = (retryCount) => Math.exp(retryCount) * 150;
var withRetry = async (callback, { attempts = 4 } = {}) => {
  let error;
  for (let i = 0; i < attempts; i++) {
    try {
      return await callback();
    } catch (err) {
      error = err;
      await new Promise((r) => setTimeout(r, backoff(i)));
    }
  }
  throw new RetryError((error == null ? void 0 : error.message) ?? "Exhausted all retries");
};
var mountInstance;
var LOAD_FUNC_KEY = "captchaFoxOnLoad";
var SCRIPT_SRC = `https://cdn.captchafox.com/api.js?render=explicit&onload=${LOAD_FUNC_KEY}`;
async function loadScript({ nonce } = {}) {
  if (mountInstance && document.querySelector(`script[src="${SCRIPT_SRC}"]`)) {
    return mountInstance;
  }
  mountInstance = new Promise((resolve, reject) => {
    window[LOAD_FUNC_KEY] = resolve;
    const script = document.createElement("script");
    script.src = SCRIPT_SRC;
    script.async = true;
    script.defer = true;
    script.onerror = (e) => {
      script.remove();
      mountInstance = void 0;
      reject(e);
    };
    if (nonce) {
      script.nonce = nonce;
    }
    document.body.appendChild(script);
  });
  return mountInstance;
}
async function loadCaptchaScript(props = {}) {
  return withRetry(() => loadScript(props));
}
var isApiReady = () => typeof (window == null ? void 0 : window.captchafox) !== "undefined";

// src/CaptchaFox.tsx
var CaptchaFox = (props) => {
  const [widgetId, setWidgetId] = createSignal();
  let containerRef;
  if (typeof props.ref === "function") {
    props.ref({
      getResponse() {
        if (!isApiReady() || !widgetId()) {
          console.warn("[CaptchaFox] Widget has not been loaded");
          return "";
        }
        return window.captchafox.getResponse(widgetId());
      },
      reset() {
        if (!isApiReady() || !widgetId()) {
          console.warn("[CaptchaFox] Widget has not been loaded");
          return;
        }
        window.captchafox.reset(widgetId());
      },
      remove() {
        if (!isApiReady() || !widgetId()) {
          console.warn("[CaptchaFox] Widget has not been loaded");
          return;
        }
        setWidgetId("");
        window.captchafox.remove(widgetId());
      },
      execute: () => {
        if (!isApiReady() || !widgetId()) {
          return Promise.reject("[CaptchaFox] Widget has not been loaded");
        }
        return window.captchafox.execute(widgetId());
      }
    });
  }
  const renderCaptcha = async () => {
    if (!isApiReady()) {
      return;
    }
    window.captchafox?.remove(widgetId());
    if (!containerRef || containerRef.children.length === 1) {
      return;
    }
    const newWidgetId = await window.captchafox?.render(containerRef, {
      lang: props.lang,
      sitekey: props.sitekey,
      mode: props.mode,
      start: props.start,
      theme: props.theme,
      i18n: props.i18n,
      hideClose: props.hideClose,
      onError: props.onError,
      onFail: props.onFail,
      onClose: props.onClose,
      onVerify: props.onVerify,
      onExpire: props.onExpire,
      onChallengeChange: props.onChallengeChange,
      onChallengeOpen: props.onChallengeOpen
    });
    setWidgetId(newWidgetId);
    props.onLoad?.();
  };
  onCleanup(() => {
    if (!widgetId()) return;
    try {
      window.captchafox?.remove(widgetId());
    } catch (err) {
      console.error("[CaptchaFox] Error during cleanup:", err);
    }
  });
  createEffect(
    on(
      () => [props.sitekey, props.lang, props.mode, props.start, props.theme, props.hideClose],
      async () => {
        if (isApiReady()) {
          await renderCaptcha();
          return;
        }
        try {
          await loadCaptchaScript({ nonce: props.nonce });
          await renderCaptcha();
        } catch (err) {
          props.onError?.(err);
          console.error("[CaptchaFox] Could not load script:", err);
        }
      }
    )
  );
  return <div ref={containerRef} id={widgetId()} />;
};

// src/index.tsx
var CAPTCHA_RESPONSE_KEY = "cf-captcha-response";
export {
  CAPTCHA_RESPONSE_KEY,
  CaptchaFox
};
