import apiFetch from '@wordpress/api-fetch';

let apiConfigured = false;

function configureApi() {
	if ( apiConfigured ) {
		return;
	}
	const boot = window.newsroomSettingsBoot || {};
	if ( boot.nonce ) {
		apiFetch.use( apiFetch.createNonceMiddleware( boot.nonce ) );
	}
	apiConfigured = true;
}

function restErrorMessage( error ) {
	if ( ! error ) {
		return '';
	}
	if ( error.message ) {
		return String( error.message );
	}
	if ( error.data && error.data.message ) {
		return String( error.data.message );
	}
	if ( error.code ) {
		return String( error.code );
	}
	return '';
}

async function fetchViaAjax( action, body = {} ) {
	const boot = window.newsroomSettingsBoot || {};
	if ( ! boot.ajaxUrl || ! boot.ajaxNonce ) {
		throw new Error( 'ajax_unavailable' );
	}
	const form = new FormData();
	form.append( 'action', action );
	form.append( 'nonce', boot.ajaxNonce );
	Object.keys( body ).forEach( ( key ) => {
		const val = body[ key ];
		form.append(
			key,
			typeof val === 'object' ? JSON.stringify( val ) : String( val )
		);
	} );
	const res = await fetch( boot.ajaxUrl, {
		method: 'POST',
		credentials: 'same-origin',
		body: form,
	} );
	const raw = await res.text();
	let json;
	try {
		json = JSON.parse( raw );
	} catch ( parseError ) {
		const snippet = raw.replace( /\s+/g, ' ' ).trim().slice( 0, 160 );
		throw new Error( snippet || 'invalid_json_response' );
	}
	if ( ! json || ! json.success ) {
		const msg = json && json.data && json.data.message ? json.data.message : 'ajax_error';
		throw new Error( msg );
	}
	return json.data;
}

function settingsUrl() {
	const boot = window.newsroomSettingsBoot || {};
	return boot.settingsUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/settings` : '' );
}

function actionUrl() {
	const boot = window.newsroomSettingsBoot || {};
	return boot.actionUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/settings/action` : '' );
}

export async function loadSettingsPayload() {
	configureApi();
	const url = settingsUrl();
	try {
		if ( url ) {
			return await apiFetch( { url, method: 'GET' } );
		}
		return await apiFetch( { path: '/newsroom-os/v1/settings', method: 'GET' } );
	} catch ( restError ) {
		try {
			return await fetchViaAjax( 'newsai_settings_registry_get' );
		} catch ( ajaxError ) {
			const combined = [ restErrorMessage( restError ), restErrorMessage( ajaxError ) ].filter( Boolean ).join( ' · ' );
			throw new Error( combined || 'load_failed' );
		}
	}
}

export async function saveSettingsSection( sectionId, data ) {
	configureApi();
	const url = settingsUrl();
	try {
		if ( url ) {
			return await apiFetch( {
				url,
				method: 'PATCH',
				data: { section: sectionId, data },
			} );
		}
		return await apiFetch( {
			path: '/newsroom-os/v1/settings',
			method: 'PATCH',
			data: { section: sectionId, data },
		} );
	} catch ( restError ) {
		return fetchViaAjax( 'newsai_settings_registry_patch', {
			section: sectionId,
			data,
		} );
	}
}

export async function runSettingsAction( action, params = {} ) {
	configureApi();
	const url = actionUrl();
	try {
		if ( url ) {
			return await apiFetch( {
				url,
				method: 'POST',
				data: { action, params },
			} );
		}
		return await apiFetch( {
			path: '/newsroom-os/v1/settings/action',
			method: 'POST',
			data: { action, params },
		} );
	} catch ( restError ) {
		return fetchViaAjax( 'newsai_settings_registry_action', {
			settings_action: action,
			params,
		} );
	}
}

export async function refreshSettingsMeta() {
	configureApi();
	const boot = window.newsroomSettingsBoot || {};
	const metaUrl = boot.metaUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/settings/meta` : '' );
	try {
		if ( metaUrl ) {
			return await apiFetch( { url: metaUrl, method: 'GET' } );
		}
		return await apiFetch( { path: '/newsroom-os/v1/settings/meta', method: 'GET' } );
	} catch ( e ) {
		return fetchViaAjax( 'newsai_settings_registry_meta' );
	}
}

export async function runLegacyAjax( action, fields = {} ) {
	const boot = window.newsroomSettingsBoot || {};
	if ( ! boot.ajaxUrl || ! boot.ajaxNonce ) {
		throw new Error( 'ajax_unavailable' );
	}
	const form = new FormData();
	form.append( 'action', action );
	form.append( 'nonce', boot.ajaxNonce );
	Object.keys( fields ).forEach( ( key ) => {
		form.append( key, fields[ key ] );
	} );
	const res = await fetch( boot.ajaxUrl, {
		method: 'POST',
		credentials: 'same-origin',
		body: form,
	} );
	const json = await res.json();
	if ( ! json || ! json.success ) {
		const msg = json && json.data && json.data.message ? json.data.message : 'ajax_error';
		throw new Error( msg );
	}
	return json.data;
}

export async function loadDashboardPayload() {
	configureApi();
	const boot = window.newsroomSettingsBoot || {};
	const dashUrl = boot.dashboardUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/dashboard` : '' );
	try {
		if ( dashUrl ) {
			return await apiFetch( { url: dashUrl, method: 'GET' } );
		}
		return await apiFetch( { path: '/newsroom-os/v1/dashboard', method: 'GET' } );
	} catch ( restError ) {
		try {
			return await fetchViaAjax( 'newsai_dashboard_registry_get' );
		} catch ( ajaxError ) {
			const combined = [ restErrorMessage( restError ), restErrorMessage( ajaxError ) ].filter( Boolean ).join( ' · ' );
			throw new Error( combined || 'load_failed' );
		}
	}
}

export function markReactAdminReady() {
	document.body.classList.add( 'newsroom-admin-react-ready' );
	document.body.classList.add( 'newsroom-dashboard-react-ready' );
	document.body.classList.add( 'newsroom-settings-react-ready' );
}

export function markReactDashboardReady() {
	markReactAdminReady();
}

export function markReactSettingsReady() {
	markReactAdminReady();
}

export async function loadInsightsPayload( days = 30 ) {
	configureApi();
	const boot = window.newsroomSettingsBoot || {};
	const url = boot.insightsUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/insights?days=${ days }` : '' );
	try {
		if ( url ) {
			return await apiFetch( { url: url.includes( '?' ) ? url : `${ url }?days=${ days }`, method: 'GET' } );
		}
		return await apiFetch( { path: `/newsroom-os/v1/insights?days=${ days }`, method: 'GET' } );
	} catch ( restError ) {
		try {
			return await fetchViaAjax( 'newsai_insights_registry_get', { days } );
		} catch ( ajaxError ) {
			const combined = [ restErrorMessage( restError ), restErrorMessage( ajaxError ) ].filter( Boolean ).join( ' · ' );
			throw new Error( combined || 'load_failed' );
		}
	}
}

export async function loadAuthorPerfPayload( days = 30 ) {
	configureApi();
	const boot = window.newsroomSettingsBoot || {};
	const url = boot.authorPerfUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/author-performance?days=${ days }` : '' );
	try {
		if ( url ) {
			return await apiFetch( { url: url.includes( '?' ) ? url : `${ url }?days=${ days }`, method: 'GET' } );
		}
		return await apiFetch( { path: `/newsroom-os/v1/author-performance?days=${ days }`, method: 'GET' } );
	} catch ( restError ) {
		try {
			return await fetchViaAjax( 'newsai_author_perf_registry_get', { days } );
		} catch ( ajaxError ) {
			const combined = [ restErrorMessage( restError ), restErrorMessage( ajaxError ) ].filter( Boolean ).join( ' · ' );
			throw new Error( combined || 'load_failed' );
		}
	}
}

export async function loadAuthorExpanded( userId, days, perfNonce ) {
	const boot = window.newsroomSettingsBoot || {};
	if ( ! boot.ajaxUrl ) {
		throw new Error( 'ajax_unavailable' );
	}
	const form = new FormData();
	form.append( 'action', 'newsai_author_perf_registry_expanded' );
	form.append( 'nonce', perfNonce );
	form.append( 'user_id', String( userId ) );
	form.append( 'days', String( days ) );
	const res = await fetch( boot.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: form } );
	const json = await res.json();
	if ( ! json?.success ) {
		throw new Error( json?.data?.message || 'ajax_error' );
	}
	return json.data;
}

export async function loadProPayload() {
	configureApi();
	const boot = window.newsroomSettingsBoot || {};
	const url = boot.proUrl || ( boot.restRoot ? `${ boot.restRoot.replace( /\/$/, '' ) }/pro` : '' );
	try {
		if ( url ) {
			return await apiFetch( { url, method: 'GET' } );
		}
		return await apiFetch( { path: '/newsroom-os/v1/pro', method: 'GET' } );
	} catch ( restError ) {
		return fetchViaAjax( 'newsai_pro_registry_get' );
	}
}

export async function runProLicenseAction( action, fields, licenseNonce ) {
	const boot = window.newsroomSettingsBoot || {};
	if ( ! boot.ajaxUrl ) {
		throw new Error( 'ajax_unavailable' );
	}
	const form = new FormData();
	form.append( 'action', 'newsai_pro_license_action' );
	form.append( 'license_nonce', licenseNonce );
	form.append( 'license_action', action );
	if ( fields.key ) {
		form.append( 'key', fields.key );
	}
	if ( fields.email ) {
		form.append( 'email', fields.email );
	}
	const res = await fetch( boot.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: form } );
	const json = await res.json();
	if ( ! json?.success ) {
		throw new Error( json?.data?.message || 'ajax_error' );
	}
	return json.data;
}

export async function saveEditorialTask( fields, taskNonce ) {
	const boot = window.newsroomSettingsBoot || {};
	if ( ! boot.ajaxUrl ) {
		throw new Error( 'ajax_unavailable' );
	}
	const form = new FormData();
	form.append( 'action', 'newsai_save_editorial_task' );
	form.append( 'task_nonce', taskNonce );
	Object.keys( fields ).forEach( ( key ) => {
		form.append( key === 'task_id' ? 'task_id' : key, String( fields[ key ] ?? '' ) );
	} );
	const res = await fetch( boot.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: form } );
	const json = await res.json();
	if ( ! json?.success ) {
		throw new Error( json?.data?.message || 'ajax_error' );
	}
	return json.data;
}

export async function loadDeviceBreakdown( days, channel ) {
	const data = await runLegacyAjax( 'newsai_chief_device_donut', { days, channel } );
	return data?.breakdown || data?.devices || [];
}

export async function runChiefBrief( days, mode ) {
	const data = await runLegacyAjax( 'newsai_ai_chief_daily_brief', { brief_days: days, brief_mode: mode } );
	return data?.html || '';
}

export async function runAuthorDeskOverview( days ) {
	const data = await runLegacyAjax( 'newsai_ai_author_desk_overview', { days } );
	return data?.html || '';
}
