import { __ } from '@wordpress/i18n';
import { createBlock } from '@wordpress/blocks';

export const CHILD_NAME = 'axcelersblocks/column';
const DEVICES = [ 'desktop', 'tablet', 'mobile' ];

const getResponsiveValue = ( values = {}, device ) => {
	const index = DEVICES.indexOf( device );
	for ( let i = index; i >= 0; i-- ) {
		const value = values?.[ DEVICES[ i ] ];
		if ( value ) {
			return value;
		}
	}
	return '';
};

const isStackedDirection = ( flexDirection = {}, device ) => {
	const direction = getResponsiveValue( flexDirection, device );
	return direction === 'column' || direction === 'column-reverse';
};

/**
 * Preset column structures shown in the on-insert picker. `widths` are the
 * desktop percentages for each column (the flex layout + gap shrink them to fit).
 */
export const COLUMN_STRUCTURES = [
	{ key: 'one',      label: __( '1 Column',  'axcelersblocks' ), widths: [ 100 ] },
	{ key: 'two',      label: __( '2 Columns', 'axcelersblocks' ), widths: [ 50, 50 ] },
	{ key: 'three',    label: __( '3 Columns', 'axcelersblocks' ), widths: [ 33.33, 33.33, 33.34 ] },
	{ key: 'four',     label: __( '4 Columns', 'axcelersblocks' ), widths: [ 25, 25, 25, 25 ] },
	{ key: '25-75',    label: '25 / 75',                            widths: [ 25, 75 ] },
	{ key: '25-25-50', label: '25 / 25 / 50',                       widths: [ 25, 25, 50 ] },
	{ key: '50-25-25', label: '50 / 25 / 25',                       widths: [ 50, 25, 25 ] },
	{ key: '25-50-25', label: '25 / 50 / 25',                       widths: [ 25, 50, 25 ] },
	{ key: 'five',     label: __( '5 Columns', 'axcelersblocks' ), widths: [ 20, 20, 20, 20, 20 ] },
	{ key: 'six',      label: __( '6 Columns', 'axcelersblocks' ), widths: [ 16.66, 16.66, 16.66, 16.66, 16.66, 16.7 ] },
	{ key: '15-70-15', label: '15 / 70 / 15',                       widths: [ 15, 70, 15 ] },
];

/** Responsive width attribute for a column: row layouts use %, stacked layouts use 100%. */
export const makeColumnWidthAttrs = ( percent, flexDirection = {} ) => {
	const w = `${ percent }%`;
	return {
		width: {
			desktop: isStackedDirection( flexDirection, 'desktop' ) ? '100%' : w,
			tablet: isStackedDirection( flexDirection, 'tablet' ) ? '100%' : w,
			mobile: '100%',
		},
	};
};

/** Build column blocks for a set of width percentages. */
export const createColumnsFromWidths = ( widths, flexDirection = {} ) =>
	widths.map( ( w ) => createBlock( CHILD_NAME, makeColumnWidthAttrs( w, flexDirection ) ) );
