import { createRoot, hydrateRoot } from "react-dom/client";
import App from "./App";
import "./index.css";

// Type declarations for gtag
declare function gtag(command: string, action: string, params?: Record<string, any>): void;

interface LargestContentfulPaintEntry extends PerformanceEntry {
  renderTime: number;
  loadTime: number;
}

interface LayoutShiftEntry extends PerformanceEntry {
  hadRecentInput: boolean;
  value: number;
}

interface PerformanceEventEntry extends PerformanceEntry {
  duration: number;
}

// Core Web Vitals monitoring for SEO
function initCoreWebVitals() {
  // Report Web Vitals to Google Analytics
  if (typeof window !== 'undefined' && 'PerformanceObserver' in window) {
    // Listen for Largest Contentful Paint (LCP)
    const observer = new PerformanceObserver((list) => {
      list.getEntries().forEach((entry) => {
        if (entry.entryType === 'largest-contentful-paint') {
          const lcpEntry = entry as unknown as LargestContentfulPaintEntry;
          const lcp = lcpEntry.renderTime || lcpEntry.loadTime;
          if (typeof gtag !== 'undefined') {
            gtag('event', 'page_view', {
              'web_vitals_lcp': Math.round(lcp),
              'metric_id': entry.name,
              'metric_value': Math.round(lcp)
            });
          }
        }
      });
    });
    observer.observe({ entryTypes: ['largest-contentful-paint'] });

    // Cumulative Layout Shift (CLS)
    let clsValue = 0;
    const clsObserver = new PerformanceObserver((list) => {
      list.getEntries().forEach((entry) => {
        const shiftEntry = entry as unknown as LayoutShiftEntry;
        if (!shiftEntry.hadRecentInput) {
          clsValue += shiftEntry.value;
          if (typeof gtag !== 'undefined') {
            gtag('event', 'page_view', {
              'web_vitals_cls': parseFloat(clsValue.toFixed(3)),
              'metric_id': entry.name,
              'metric_value': parseFloat(clsValue.toFixed(3))
            });
          }
        }
      });
    });
    clsObserver.observe({ entryTypes: ['layout-shift'] });

    // First Input Delay (FID) / Interaction to Next Paint (INP)
    const inpObserver = new PerformanceObserver((list) => {
      list.getEntries().forEach((entry) => {
        const eventEntry = entry as unknown as PerformanceEventEntry;
        if (typeof gtag !== 'undefined') {
          gtag('event', 'page_view', {
            'web_vitals_inp': Math.round(eventEntry.duration),
            'metric_id': entry.name,
            'metric_value': Math.round(eventEntry.duration)
          });
        }
      });
    });
    inpObserver.observe({ entryTypes: ['event'] });
  }
}

// Enhanced GA4 Event Tracking
function initEnhancedGA4Events() {
  // Track time on page
  let startTime = Date.now();
  window.addEventListener('beforeunload', () => {
    const timeOnPage = Math.round((Date.now() - startTime) / 1000);
    if (typeof gtag !== 'undefined') {
      gtag('event', 'page_duration', {
        'duration_seconds': timeOnPage,
        'page_path': window.location.pathname
      });
    }
  });

  // Track scroll depth
  let maxScrollDepth = 0;
  window.addEventListener('scroll', () => {
    const scrollDepth = Math.round(
      (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
    );
    if (scrollDepth > maxScrollDepth) {
      maxScrollDepth = scrollDepth;
      if (maxScrollDepth % 25 === 0 && typeof gtag !== 'undefined') {
        gtag('event', 'scroll_depth', {
          'scroll_depth': maxScrollDepth,
          'page_path': window.location.pathname
        });
      }
    }
  });

  // Track form interactions
  document.addEventListener('focusin', (e) => {
    const target = e.target as HTMLElement;
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
      if (typeof gtag !== 'undefined') {
        gtag('event', 'form_focus', {
          'form_id': target.id || 'unknown',
          'input_type': (target as HTMLInputElement).type || 'unknown',
          'page_path': window.location.pathname
        });
      }
    }
  });

  // Track button clicks
  document.addEventListener('click', (e) => {
    const target = e.target as HTMLElement;
    if (target.tagName === 'BUTTON' || target.getAttribute('role') === 'button') {
      if (typeof gtag !== 'undefined') {
        gtag('event', 'button_click', {
          'button_text': target.textContent?.trim() || 'unknown',
          'button_id': target.id || 'unknown',
          'page_path': window.location.pathname
        });
      }
    }
  });

  // Track form submissions
  document.addEventListener('submit', (e) => {
    const form = e.target as HTMLFormElement;
    if (typeof gtag !== 'undefined') {
      gtag('event', 'form_submit', {
        'form_id': form.id || 'unknown',
        'form_name': form.name || 'unknown',
        'page_path': window.location.pathname
      });
    }
  });
}

// Initialize tracking when DOM is ready
if (typeof window !== 'undefined') {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      initCoreWebVitals();
      initEnhancedGA4Events();
    });
  } else {
    initCoreWebVitals();
    initEnhancedGA4Events();
  }
}

const rootEl = document.getElementById("root")!;
if (rootEl.hasChildNodes()) {
  hydrateRoot(rootEl, <App />);
} else {
  createRoot(rootEl).render(<App />);
}
