import { render } from 'solid-js/web';
import { HashRouter, Route } from '@solidjs/router';
import { AppProvider } from '@util/context';
import { routes } from '@util/routes';
import Layout from '@/Layout';
import * as packedge from '../shared/packedge.js';
import './styles.css';

// PackEdge feature-adoption snapshot: once per day, listing which features are
// enabled. Requires analytics consent (track() self-gates) - install/uninstall
// counts are handled server-side via lifecycle hooks. Never blocks the UI.
(function sendTelemetry() {
	try {
		const v = window?.ajaxpress_admin_vars || {};
		const lic = v.license || {};

		const DAY = 24 * 60 * 60 * 1000;
		const last = parseInt(localStorage.getItem('ajaxpress_pkg_features_at') || '0', 10);
		if (Date.now() - last > DAY) {
			const settings = v.settings || {};
			const enabled = Object.keys(settings).filter((k) => settings[k] === true);
			const sent = packedge.track('feature_used', {
				enabled_count: enabled.length,
				enabled: enabled.slice(0, 50),
				licensed: lic.status === 'active',
			}, { licenseKey: lic.key });
			// Only stamp the throttle if it actually sent (i.e. consent given),
			// so it fires promptly once the user opts in.
			if (sent) localStorage.setItem('ajaxpress_pkg_features_at', String(Date.now()));
		}
	} catch (e) {
		/* telemetry must never break the admin */
	}
})();

const Image = (name = '') => {
	const baseUrl = window?.ajaxpress_admin_vars?.plugin?.url || '';
	return baseUrl + 'public/images/' + name;
};

window.ajaxpressImage = Image;

// Prevent SolidJS router from intercepting external navigation links
document.addEventListener('click', (e) => {
	// If click is inside AjaxPress app, let router handle it
	if (e.target.closest('#ajaxpress-app')) return;

	const link = e.target.closest('a');
	if (!link) return; // Non-link clicks pass through

	const href = link.getAttribute('href');

	// Only stop propagation for real navigation links (not JS-handled links like menu toggles)
	// JS-handled links typically have href="#", "javascript:", or no href
	if (href && href !== '#' && !href.startsWith('#') && !href.startsWith('javascript:')) {
		e.stopImmediatePropagation();
	}
}, true); // Capture phase - runs first

const App = () => {
	return (
		<HashRouter root={(props) => (
			<AppProvider>
				<Layout>{props.children}</Layout>
			</AppProvider>
		)}>
			{routes.map((route) => (
				<Route path={route.path} component={route.component} />
			))}
		</HashRouter>
	);
};

document.addEventListener('DOMContentLoaded', () => {
	const root = document.getElementById('ajaxpress-app');
	if (root) {
		render(() => <App />, root);
	}
});
