/**
 * Upgrade saved placement attrs when library field shapes change.
 * Mirrors PlacementAttrMigrator (PHP).
 */

const CARD_SLUGS = new Set( [ 'cards', 'blog-cards', 'simple-cards' ] );

/**
 * @param {object} link
 * @return {{ title: string, url: string, opensInNewTab: boolean }}
 */
function normalizeLinkShape( link = {} ) {
	return {
		title: link?.title != null ? String( link.title ) : '',
		url: link?.url != null ? String( link.url ) : '',
		opensInNewTab: Boolean( link?.opensInNewTab ),
	};
}

/**
 * Default CTA button styles for feature cards.
 *
 * @param {object} link
 * @return {object}
 */
function defaultCardButton( link = {} ) {
	return {
		link: normalizeLinkShape( link ),
		bg: '#3525cd',
		color: '#ffffff',
		bgHover: '#2a1ea4',
		colorHover: '#ffffff',
		size: 'medium',
		padY: '0.625rem',
		padX: '1.25rem',
		borderRadius: '8px',
		icon: '',
		iconPosition: 'right',
	};
}

/**
 * Promote legacy single `link` → `buttons[]` (and keep existing buttons).
 *
 * @param {object} attrs
 * @return {{ attrs: object, changed: boolean }}
 */
export function upgradeCardsLinkToButtons( attrs = {} ) {
	const cards = attrs?.cards;
	if ( ! Array.isArray( cards ) || ! cards.length ) {
		return { attrs, changed: false };
	}

	let changed = false;
	const nextCards = cards.map( ( card ) => {
		if ( ! card || typeof card !== 'object' ) {
			return card;
		}
		const buttons = card.buttons;
		const hasButtons = Array.isArray( buttons ) && buttons.length > 0;
		const hasLink =
			card.link && typeof card.link === 'object' && ! Array.isArray( card.link );

		if ( hasButtons ) {
			if ( hasLink || Object.prototype.hasOwnProperty.call( card, 'link' ) ) {
				const { link: _removed, ...rest } = card;
				changed = true;
				return rest;
			}
			return card;
		}

		if ( ! hasLink ) {
			return card;
		}

		const { link, ...rest } = card;
		changed = true;
		return {
			...rest,
			buttons: [ defaultCardButton( link ) ],
		};
	} );

	if ( ! changed ) {
		return { attrs, changed: false };
	}
	return { attrs: { ...attrs, cards: nextCards }, changed: true };
}

/** @deprecated Use upgradeCardsLinkToButtons */
export function upgradeCardsButtonsToLink( attrs = {} ) {
	return upgradeCardsLinkToButtons( attrs );
}

/**
 * @param {string} blockName
 * @param {object} attrs
 * @param {object} [meta]
 * @return {{ attrs: object, changed: boolean }}
 */
export function upgradePlacementAttrs( blockName = '', attrs = {}, meta = {} ) {
	const slug =
		meta.systemSlug ||
		( String( blockName ).startsWith( 'joc-blockora-morph/' )
			? String( blockName ).slice( 'joc-blockora-morph/'.length )
			: '' );

	if ( CARD_SLUGS.has( slug ) ) {
		return upgradeCardsLinkToButtons( attrs );
	}

	return { attrs, changed: false };
}
