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

export const TABLE_BLOCK = 'axcelersblocks/table';
export const TABLE_SECTION_BLOCK = 'axcelersblocks/table-section';
export const TABLE_ROW_BLOCK = 'axcelersblocks/table-row';
export const TABLE_CELL_BLOCK = 'axcelersblocks/table-cell';
export const BODYCOPY_BLOCK = 'axcelersblocks/bodycopy';

// Tags are now chosen manually per block (no head/body/foot auto-sync). These
// helpers only provide the default starter content for a freshly created cell.
export const getCellContent = ( tag ) => ( tag === 'th' ? 'Head' : 'Data' );

export const createBodycopyBlock = ( content = '' ) =>
	createBlock( BODYCOPY_BLOCK, {
		content,
		tagName: 'p',
	} );

// New cells carry a bodycopy seeded with "Head" (th) or "Data" (td) so a freshly
// added cell is never empty. The tag is fully manual — callers pass it in.
export const createTableCellBlock = ( { tag = 'td' } = {} ) =>
	createBlock(
		TABLE_CELL_BLOCK,
		{
			tagName: tag,
		},
		[ createBodycopyBlock( getCellContent( tag ) ) ]
	);

export const createTableRowBlock = ( { columns = 1, tag = 'td' } = {} ) =>
	createBlock(
		TABLE_ROW_BLOCK,
		{},
		Array.from( { length: Math.max( 1, columns ) }, () =>
			createTableCellBlock( { tag } )
		)
	);

export const createTableSectionBlock = ( {
	tagName = 'tbody',
	rows = 1,
	columns = 1,
	tag = 'td',
} = {} ) =>
	createBlock(
		TABLE_SECTION_BLOCK,
		{
			tagName,
		},
		Array.from( { length: Math.max( 1, rows ) }, () =>
			createTableRowBlock( { columns, tag } )
		)
	);

// Initial structure from the grid picker: a single tbody section with
// rows × columns td cells. Everything after is manual (tags, sections, colgroup).
export const createTableFromGrid = ( { rows = 2, columns = 3 } = {} ) => [
	createTableSectionBlock( {
		tagName: 'tbody',
		rows: Math.max( 1, rows ),
		columns: Math.max( 1, columns ),
		tag: 'td',
	} ),
];
