/**
 * Cart Recovery Entry Point
 *
 * Initializes all cart recovery frontend modules including
 * customer info capture and heartbeat tracking.
 *
 * @package EDD\Pro\CartRecovery
 * @since 3.6.5
 */

import * as CustomerInfo from './cart-recovery/customer-info';
import * as Heartbeat from './cart-recovery/heartbeat';
import { HEARTBEAT_INTERVAL } from './cart-recovery/heartbeat';

/**
 * Initializes cart recovery modules based on page context
 *
 * - Customer info capture: Always on checkout pages
 * - Heartbeat: Only when there's an active cart being tracked
 *
 * @return {void}
 */
const initCartRecovery = () => {
	// Always initialize customer info capture on checkout pages
	// This needs to run even before a cart is created
	CustomerInfo.init();

	// Initialize heartbeat if we already have a tracked cart
	const hasTrackedCart = globalThis.eddCartRecovery?.hasTrackedCart ?? false;
	if ( hasTrackedCart ) {
		Heartbeat.init();
	} else {
		// No tracked cart yet — start the heartbeat once customer info is captured,
		// which creates the tracked cart server-side.
		document.addEventListener(
			'edd_acr_customer_captured',
			() => setTimeout( () => Heartbeat.init(), HEARTBEAT_INTERVAL ),
			{ once: true }
		);
	}
};

// Auto-initialize when DOM is ready
if ( document.readyState === 'loading' ) {
	document.addEventListener( 'DOMContentLoaded', initCartRecovery );
} else {
	// DOM is already ready
	initCartRecovery();
}

// Export modules for testing purposes
export { CustomerInfo } from './cart-recovery/customer-info';
export { Heartbeat } from './cart-recovery/heartbeat';
