/* OLIS KYC Modal - Wrapper around KYCForm with API integration */
(function () {


  const { Button, Card } = window.OLISDesignSystem_ba3bd8;
  const Icon = window.Icon;
  const i18n = window.i18nConfig;

  function KYCModal({ onClose }) {
    const [isLoading, setIsLoading] = React.useState(false);
    const [error, setError] = React.useState(null);

    const handleFormSubmit = async (formData) => {
      setIsLoading(true);
      setError(null);

      try {
        const response = await fetch('/api/kyc', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            ...formData,
            language: i18n.locale,
          }),
        });

        if (!response.ok) {
          throw new Error('Failed to submit application');
        }

        const result = await response.json();

        // Show success message with reference number
        if (result.success && result.referenceNumber) {
          console.log('✅ KYC Submitted:', result.referenceNumber);
          // Could show a success screen or close modal
          // For now, keep form visible with success state
        }
      } catch (err) {
        console.error('KYC Submit Error:', err);
        setError(err.message || 'Failed to submit application. Please try again.');
      } finally {
        setIsLoading(false);
      }
    };

    return (
      <div
        className="olis-modal-bg"
        onClick={onClose}
        style={{
          position: 'fixed',
          inset: 0,
          background: 'rgba(3,8,6,0.72)',
          backdropFilter: 'blur(6px)',
          display: 'grid',
          placeItems: 'center',
          zIndex: 100,
          padding: 20,
          animation: 'olisFade .2s ease forwards',
        }}
      >
        <Card
          padding={30}
          glow
          style={{
            width: 'min(560px, 100%)',
            maxHeight: '90vh',
            overflowY: 'auto',
          }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Close Button */}
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 20 }}>
            <button
              onClick={onClose}
              style={{
                background: 'none',
                border: 'none',
                color: 'var(--text-muted)',
                cursor: 'pointer',
                fontSize: 24,
              }}
            >
              ×
            </button>
          </div>

          {/* Error Message */}
          {error && (
            <div
              style={{
                background: 'rgba(220, 38, 38, 0.1)',
                border: '1px solid rgb(220, 38, 38)',
                borderRadius: 'var(--radius-md)',
                padding: 12,
                marginBottom: 20,
                fontSize: 13,
                color: 'rgb(127, 29, 29)',
              }}
            >
              {error}
            </div>
          )}

          {/* Loading Overlay */}
          {isLoading && (
            <div
              style={{
                position: 'absolute',
                inset: 0,
                background: 'rgba(255,255,255,0.7)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 101,
                borderRadius: 'var(--radius-lg)',
              }}
            >
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 32, marginBottom: 8 }}>⏳</div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>Submitting...</div>
              </div>
            </div>
          )}

          {/* KYC Form Component */}
          <window.OLISKYCForm onClose={onClose} onComplete={handleFormSubmit} />
        </Card>
      </div>
    );
  }

  Object.assign(window, { OLISKYCModal: KYCModal });
})();
