import Script from 'next/script';

interface UmamiScriptProps {
  /**
   * Custom website ID to override the environment variable
   */
  websiteId?: string;
  /**
   * Custom script URL to override the environment variable
   */
  scriptUrl?: string;
}

/**
 * Umami Analytics Script Component
 *
 * Loads the Umami analytics script only when a website ID is available.
 * Uses Next.js Script component with 'afterInteractive' strategy for optimal performance.
 *
 * @example
 * ```tsx
 * // Uses environment variables automatically
 * <UmamiScript />
 *
 * // Or provide custom values
 * <UmamiScript websiteId="custom-id" scriptUrl="https://custom.analytics.com/script.js" />
 * ```
 */
export default function UmamiScript({ websiteId, scriptUrl }: UmamiScriptProps) {
  // Use provided website ID or fall back to environment variable
  const finalWebsiteId = websiteId ?? process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID;
  
  // If no website ID is available, don't render the script
  if (!finalWebsiteId) {
    if (process.env.NODE_ENV === 'development') {
      console.warn('[Umami] NEXT_PUBLIC_UMAMI_WEBSITE_ID is not set. Analytics will be disabled.');
    }
    return null;
  }

  // Use provided script URL or fall back to environment variable or default
  const finalScriptUrl = scriptUrl ??
    process.env.NEXT_PUBLIC_UMAMI_SCRIPT_URL ??
    'https://analytics.infra.mintel.me/script.js';

  return (
    <Script
      id="umami-analytics"
      src={finalScriptUrl}
      data-website-id={finalWebsiteId}
      strategy="afterInteractive"
      defer
      // Add error handling for script loading failures
      onError={(error) => {
        console.error('[Umami] Failed to load analytics script:', error);
      }}
    />
  );
}

