// ============================================================
// hCaptcha — wiederverwendbare Komponente für alle Formulare
// ============================================================
// Globale Konfiguration (in HTML vor diesem Script setzen):
//   <script>window.HCAPTCHA_SITEKEY = "echter-key-hier";</script>
// Default: hCaptcha-Test-Sitekey (validiert immer als success).
// ============================================================

window.HCAPTCHA_SITEKEY = window.HCAPTCHA_SITEKEY || '30e8eca0-0168-40e0-8562-d5ae48b2041c';

window.HCaptchaBox = function HCaptchaBox({ onVerify, lang, theme }) {
  const ref = React.useRef(null);
  const widgetIdRef = React.useRef(null);
  const onVerifyRef = React.useRef(onVerify);
  React.useEffect(() => { onVerifyRef.current = onVerify; }, [onVerify]);

  React.useEffect(() => {
    let cancelled = false;
    let attempts = 0;

    const tryRender = () => {
      if (cancelled) return;
      if (!ref.current) return;
      if (widgetIdRef.current !== null) return;

      if (window.hcaptcha && typeof window.hcaptcha.render === 'function') {
        try {
          widgetIdRef.current = window.hcaptcha.render(ref.current, {
            sitekey: window.HCAPTCHA_SITEKEY,
            hl: (lang || 'de').slice(0, 2),
            theme: theme || 'light',
            size: 'normal',
            callback: (token) => { if (onVerifyRef.current) onVerifyRef.current(token); },
            'expired-callback': () => { if (onVerifyRef.current) onVerifyRef.current(null); },
            'error-callback':   () => { if (onVerifyRef.current) onVerifyRef.current(null); }
          });
        } catch (e) {
          // schon gerendert oder Skript-Fehler — ignorieren
          console.warn('[hcaptcha] render skipped:', e.message);
        }
      } else if (attempts < 50) {
        attempts++;
        setTimeout(tryRender, 200);
      }
    };
    tryRender();

    return () => {
      cancelled = true;
      if (widgetIdRef.current !== null && window.hcaptcha) {
        try { window.hcaptcha.reset(widgetIdRef.current); } catch (e) {}
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="ce-hcaptcha-wrap" aria-label="hCaptcha">
      <div ref={ref}></div>
    </div>
  );
};
