'use client';

/**
 * Cloudflare Turnstile Captcha Widget
 * Handles mounting, lifecycle, auto-cleanup, and verification status display.
 */

import React, { useEffect, useRef } from 'react';
import { ShieldCheck } from 'lucide-react';

declare global {
  interface Window {
    turnstile?: {
      render: (
        container: string | HTMLElement,
        params: {
          sitekey: string;
          theme?: 'light' | 'dark' | 'auto';
          callback?: (token: string) => void;
          'error-callback'?: () => void;
          'expired-callback'?: () => void;
          size?: 'normal' | 'compact' | 'flexible';
        }
      ) => string;
      reset: (widgetId?: string) => void;
      remove: (widgetId?: string) => void;
    };
  }
}

export interface TurnstileWidgetProps {
  containerId: string;
  onVerify: (token: string) => void;
  onExpire: () => void;
  isVerified: boolean;
  isAr?: boolean;
}

export function TurnstileWidget({
  containerId,
  onVerify,
  onExpire,
  isVerified,
  isAr = false,
}: TurnstileWidgetProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);

  useEffect(() => {
    let isMounted = true;
    const siteKey =
      process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || '1x00000000000000000000AA';

    const renderCaptcha = () => {
      if (!window.turnstile || !containerRef.current || !isMounted) return;

      if (widgetIdRef.current) {
        try {
          window.turnstile.remove(widgetIdRef.current);
        } catch {}
        widgetIdRef.current = null;
      }

      containerRef.current.innerHTML = '';

      try {
        const wId = window.turnstile.render(containerRef.current, {
          sitekey: siteKey,
          theme: 'auto',
          size: 'normal',
          callback: (token: string) => {
            if (isMounted) onVerify(token);
          },
          'error-callback': () => {
            if (isMounted) onExpire();
          },
          'expired-callback': () => {
            if (isMounted) onExpire();
          },
        });
        widgetIdRef.current = wId;
      } catch (err) {
        console.warn('[Turnstile] Render error:', err);
      }
    };

    if (!window.turnstile) {
      let script = document.getElementById('cf-turnstile-script') as HTMLScriptElement;
      if (!script) {
        script = document.createElement('script');
        script.id = 'cf-turnstile-script';
        script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
        script.async = true;
        script.defer = true;
        document.head.appendChild(script);
      }
      script.addEventListener('load', renderCaptcha);
      return () => {
        isMounted = false;
        script.removeEventListener('load', renderCaptcha);
        if (widgetIdRef.current && window.turnstile) {
          try {
            window.turnstile.remove(widgetIdRef.current);
          } catch {}
        }
      };
    } else {
      const timer = setTimeout(renderCaptcha, 120);
      return () => {
        isMounted = false;
        clearTimeout(timer);
        if (widgetIdRef.current && window.turnstile) {
          try {
            window.turnstile.remove(widgetIdRef.current);
          } catch {}
        }
      };
    }
  }, [containerId, onVerify, onExpire]);

  return (
    <div className="w-full">
      <div
        className={`transition-all duration-300 ${
          isVerified ? 'hidden' : 'flex justify-center min-h-[65px] my-2'
        }`}
      >
        <div ref={containerRef} id={containerId} />
      </div>

      {isVerified && (
        <div className="flex items-center justify-center gap-1.5 text-[11px] text-emerald-600 dark:text-emerald-400 font-medium py-1">
          <ShieldCheck className="w-3.5 h-3.5" />
          <span>{isAr ? 'تم التحقق الأمني بنجاح' : 'Security check complete'}</span>
        </div>
      )}
    </div>
  );
}
