import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import './styles/fonts.css';
import './styles/theme.css';
import App from './App';

// Capture referral code from URL on app load
// This ensures referral tracking works even for block/AJAX checkout flows
(function captureReferralCode() {
    const params = new URLSearchParams(window.location.search);
    const ref = params.get('ref');
    console.log('[WooNooW] captureReferralCode - URL search:', window.location.search, ', ref:', ref);

    if (ref && ref.trim() !== '') {
        // Store in localStorage as backup
        try {
            localStorage.setItem('woonoow_ref', ref);
            console.log('[WooNooW] Stored ref in localStorage:', ref);
        } catch (e) {
            // localStorage may be blocked
            console.log('[WooNooW] localStorage blocked:', e);
        }

        // Also set cookie for PHP backend to read
        // Cookie expires in 30 days, path is root
        const expires = new Date();
        expires.setDate(expires.getDate() + 30);
        const cookieStr = `woonoow_ref=${encodeURIComponent(ref)}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
        document.cookie = cookieStr;
        console.log('[WooNooW] Set cookie:', cookieStr);
    } else {
        // Check if ref exists in localStorage from previous visit
        try {
            const storedRef = localStorage.getItem('woonoow_ref');
            if (storedRef) {
                console.log('[WooNooW] Found stored ref in localStorage:', storedRef);
                // Re-set the cookie from localStorage
                const expires = new Date();
                expires.setDate(expires.getDate() + 30);
                document.cookie = `woonoow_ref=${encodeURIComponent(storedRef)}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
                console.log('[WooNooW] Re-set cookie from localStorage:', storedRef);
            }
        } catch (e) {
            console.log('[WooNooW] Could not read localStorage:', e);
        }
    }
})();

const el = document.getElementById('woonoow-customer-app');
if (el) {
  createRoot(el).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
} else {
  console.warn('[WooNooW Customer] Root element #woonoow-customer-app not found.');
}
