/**
 * Dashboard Activity card — React island.
 *
 * Replaces the static "Weekly Statistics" card with a live view that refreshes
 * from `agentic/v1/dashboard-stats`, adds a Week/Month period toggle, and shows
 * the ecosystem agent counts. The rest of the dashboard remains server-rendered.
 */
import { createRoot, useEffect, useState, Fragment } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';

const REFRESH_MS = 30000;

function getConfig() {
	return window.agenticDashboard || {};
}

function buildUrl( page, extra ) {
	const cfg = getConfig();
	const base = cfg.adminUrl || '';
	let url = `${ base }admin.php?page=${ page }`;
	if ( extra ) {
		url += extra;
	}
	return url;
}

function formatInt( value ) {
	return Number( value || 0 ).toLocaleString();
}

function Metric( { value, label, href } ) {
	return (
		<div className="agentic-metric">
			<div className="agentic-metric-value">{ value }</div>
			<div className="agentic-metric-label">
				{ href ? <a href={ href }>{ label }</a> : label }
			</div>
		</div>
	);
}

function ActivityCard() {
	const cfg = getConfig();
	const isPro = !! cfg.isPro;
	const [ period, setPeriod ] = useState( 'week' );
	const [ data, setData ] = useState( null );
	const [ error, setError ] = useState( false );

	useEffect( () => {
		let cancelled = false;

		const load = () => {
			apiFetch( {
				path: `agentic/v1/dashboard-stats?period=${ period }`,
			} )
				.then( ( res ) => {
					if ( ! cancelled ) {
						setData( res );
						setError( false );
					}
				} )
				.catch( () => {
					if ( ! cancelled ) {
						setError( true );
					}
				} );
		};

		load();
		const timer = setInterval( load, REFRESH_MS );
		return () => {
			cancelled = true;
			clearInterval( timer );
		};
	}, [ period ] );

	const activity = data?.activity || {};
	const agents = data?.agents || {};
	const usageLink = isPro
		? buildUrl( 'agentic-costs' )
		: buildUrl( 'agentic-audit-log' );

	return (
		<Fragment>
			<div className="agentic-card-header agentic-flex-between">
				<h2>{ __( 'Activity', 'agent-builder' ) }</h2>
				<div className="agentic-period-toggle">
					<button
						type="button"
						className={ `button button-small${
							'week' === period ? ' button-primary' : ''
						}` }
						onClick={ () => setPeriod( 'week' ) }
					>
						{ __( 'Week', 'agent-builder' ) }
					</button>
					<button
						type="button"
						className={ `button button-small${
							'month' === period ? ' button-primary' : ''
						}` }
						onClick={ () => setPeriod( 'month' ) }
					>
						{ __( 'Month', 'agent-builder' ) }
					</button>
				</div>
			</div>

			{ error && (
				<p className="agentic-status-error">
					{ __( 'Could not load activity.', 'agent-builder' ) }
				</p>
			) }

			<div className="agentic-metrics-grid">
				<Metric
					value={ formatInt( activity.actions ) }
					label={ __( 'Total Actions', 'agent-builder' ) }
					href={ buildUrl( 'agentic-audit-log' ) }
				/>
				<Metric
					value={ formatInt( activity.tokens ) }
					label={ __( 'Tokens Used', 'agent-builder' ) }
					href={ usageLink }
				/>
				{ Number( activity.cost ) > 0 && (
					<Metric
						value={ '$' + Number( activity.cost ).toFixed( 4 ) }
						label={
							isPro
								? __( 'Est. Cost', 'agent-builder' )
								: __( 'Estimated Usage', 'agent-builder' )
						}
						href={ usageLink }
					/>
				) }
				<Metric
					value={ formatInt( agents.active ) }
					label={ __( 'Active Agents', 'agent-builder' ) }
					href={ buildUrl( 'agentic-agents' ) }
				/>
				<Metric
					value={ formatInt( agents.uploaded ) }
					label={ __( 'Uploaded Agents', 'agent-builder' ) }
					href={ buildUrl( 'agentic-agents' ) }
				/>
				<Metric
					value={ formatInt( agents.user_created ) }
					label={ __( 'User-Created Agents', 'agent-builder' ) }
					href={ buildUrl( 'agentic-agents' ) }
				/>
				<Metric
					value={ formatInt( agents.community ) }
					label={ __( 'Community Agents', 'agent-builder' ) }
					href="https://agentic-plugin.com/community-agents/"
				/>
			</div>
		</Fragment>
	);
}

document.addEventListener( 'DOMContentLoaded', () => {
	const mount = document.getElementById( 'agentic-dashboard-activity-root' );
	if ( mount ) {
		createRoot( mount ).render( <ActivityCard /> );
	}
} );
