/**
 * Formatting helpers shared across screens.
 *
 * Log timestamps are stored as UTC MySQL datetimes. They are printed with the
 * date and time formats from Settings > General, in the site's timezone, so a
 * date here reads exactly like every other date in wp-admin. AdminAssets falls
 * back to a hyphenated day when either option has been saved empty.
 */

import { dateI18n } from '@wordpress/date';
import { __, sprintf } from '@wordpress/i18n';

import { getBootstrap } from '../../common';

const { dates } = getBootstrap();

const DATE_FORMAT = dates?.date || 'd-m-Y';
const TIME_FORMAT = dates?.time || 'H:i';

export function parseUtc( value ) {
	if ( ! value ) {
		return null;
	}

	const parsed = new Date( `${ value.replace( ' ', 'T' ) }Z` );

	return Number.isNaN( parsed.getTime() ) ? null : parsed;
}

/**
 * A date on its own, in the site's configured format.
 *
 * @param {string} value UTC MySQL datetime.
 * @return {string} Formatted date, or "Never" when there is nothing to show.
 */
export function formatDate( value ) {
	const date = parseUtc( value );

	if ( ! date ) {
		return __( 'Never', 'rewind-form-bridge-for-brevo' );
	}

	return dateI18n( DATE_FORMAT, date );
}

/**
 * A date and a clock time, in the site's configured formats.
 *
 * @param {string} value UTC MySQL datetime.
 * @return {string} Formatted timestamp, or "Never" when there is nothing to
 *                  show.
 */
export function formatDateTime( value ) {
	const date = parseUtc( value );

	if ( ! date ) {
		return __( 'Never', 'rewind-form-bridge-for-brevo' );
	}

	return dateI18n( `${ DATE_FORMAT } ${ TIME_FORMAT }`, date );
}

export function formatRelative( value ) {
	const date = parseUtc( value );

	if ( ! date ) {
		return __( 'Never', 'rewind-form-bridge-for-brevo' );
	}

	const seconds = Math.round( ( Date.now() - date.getTime() ) / 1000 );

	if ( seconds < 60 ) {
		return __( 'Just now', 'rewind-form-bridge-for-brevo' );
	}

	const minutes = Math.round( seconds / 60 );

	if ( minutes < 60 ) {
		return sprintf(
			/* translators: %d: number of minutes. */
			__( '%d min ago', 'rewind-form-bridge-for-brevo' ),
			minutes
		);
	}

	const hours = Math.round( minutes / 60 );

	if ( hours < 24 ) {
		return sprintf(
			/* translators: %d: number of hours. */
			__( '%d h ago', 'rewind-form-bridge-for-brevo' ),
			hours
		);
	}

	const days = Math.round( hours / 24 );

	/* translators: %d: number of days. */
	return sprintf( __( '%d d ago', 'rewind-form-bridge-for-brevo' ), days );
}

/**
 * Pretty-print a JSON string for the payload viewer, leaving non-JSON bodies
 * (Brevo answers 204 with an empty body) exactly as they arrived.
 *
 * @param {string} raw Stored request or response body.
 * @return {string} Formatted text.
 */
export function prettyJson( raw ) {
	if ( ! raw ) {
		return __( '(empty)', 'rewind-form-bridge-for-brevo' );
	}

	try {
		return JSON.stringify( JSON.parse( raw ), null, 2 );
	} catch ( error ) {
		return raw;
	}
}

/**
 * Hand the browser a generated file. Used for the CSV and settings exports,
 * both of which arrive as strings inside an authenticated REST response.
 *
 * @param {string} filename Suggested file name.
 * @param {string} contents File body.
 * @param {string} mime     MIME type.
 */
export function downloadFile( filename, contents, mime ) {
	const blob = new Blob( [ contents ], { type: mime } );
	const url = URL.createObjectURL( blob );
	const link = document.createElement( 'a' );

	link.href = url;
	link.download = filename;
	document.body.appendChild( link );
	link.click();
	document.body.removeChild( link );
	URL.revokeObjectURL( url );
}
