'use client';

import { useEffect } from 'react';
import Script from 'next/script';

const MIDTRANS_SCRIPT_URL =
  'https://api.midtrans.com/v2/assets/js/midtrans-new-3ds.min.js';

interface MidtransScriptLoaderProps {
  clientKey?: string;
}

export default function MidtransScriptLoader({ clientKey: channelClientKey }: MidtransScriptLoaderProps) {
  const environment =
    (process.env.NEXT_PUBLIC_MIDTRANS_ENVIRONMENT || 'sandbox').toLowerCase() ===
    'production'
      ? 'production'
      : 'sandbox';
  const clientKey =
    channelClientKey?.trim() || process.env.NEXT_PUBLIC_MIDTRANS_CLIENT_KEY || '';

  useEffect(() => {
    if (!clientKey) {
      console.error('NEXT_PUBLIC_MIDTRANS_CLIENT_KEY is not configured');
    }
  }, [clientKey]);

  return (
    <Script
      id="midtrans-script"
      src={MIDTRANS_SCRIPT_URL}
      strategy="afterInteractive"
      data-environment={environment}
      data-client-key={clientKey}
      onLoad={() => window.dispatchEvent(new CustomEvent('midtransLoaded'))}
      onError={(error) => console.error('Failed to load Midtrans script:', error)}
    />
  );
}
