'use client'

import { useEffect } from 'react'
import { KleapBadge } from './kleap-badge'
import { KleapAnalytics } from './kleap-analytics'

/**
 * Kleap Scripts Loader
 *
 * NOTE: Tailwind CDN is now loaded in layout.tsx <head> SSR (not here!)
 * This ensures it's available BEFORE React renders, fixing JIT class generation
 */
export function KleapScripts() {
  useEffect(() => {
    // Only load Kleap scripts when inside an iframe (Kleap environment)
    if (typeof window !== 'undefined' && window.parent !== window) {
      // Create script tags dynamically
      const scripts = [
        '/_kleap/kleap-shim.js',
        '/_kleap/kleap-nextjs-error-detector.js', // Next.js build error detection
        '/_kleap/kleap-component-selector-client.js',
        '/_kleap/kleap-react-tagger.js'
      ];

      scripts.forEach(src => {
        // Check if script is already loaded
        if (!document.querySelector(`script[src="${src}"]`)) {
          const script = document.createElement('script');
          script.src = src;
          script.defer = true;
          script.onerror = () => console.warn('Kleap script not found:', src);
          document.head.appendChild(script);
        }
      });
    }
  }, []);

  return (
    <>
      <KleapBadge />
      <KleapAnalytics />
    </>
  );
}
