/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps, RichText } from '@wordpress/block-editor';

/**
 * The save function defines the way in which the different attributes should
 * be combined into the final markup, which is then serialized by the block
 * editor into `post_content`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#save
 *
 * @param {Object} props Block properties
 * @return {Element} Element to render.
 */
export default function save( { attributes } ) {
	const { entries } = attributes;
	
	const sortedEntries = [ ...entries ].sort( ( a, b ) => 
		parseInt( a.year ) - parseInt( b.year )
	);

	const years = [ ...new Set( sortedEntries.map( entry => entry.year ) ) ];

	return (
		<div { ...useBlockProps.save() }>
			<div className="wp-block-telex-company-timeline">
				<div className="timeline-sidebar">
					<div className="timeline-years">
						<h3>Timeline</h3>
						{ years.map( ( year ) => (
							<a 
								key={ year }
								href={ `#year-${ year }` }
								className="year-link"
								data-year={ year }
							>
								{ year }
							</a>
						) ) }
					</div>
				</div>

				<div className="timeline-content">
					{ sortedEntries.map( ( entry, index ) => (
						<div 
							key={ index } 
							className="timeline-entry"
							id={ `year-${ entry.year }` }
							data-year={ entry.year }
						>
							<div className="timeline-year-marker">
								<h2>{ entry.year }</h2>
							</div>
							
							<div className="timeline-entry-content">
								{ entry.title && (
									<RichText.Content
										tagName="h3"
										value={ entry.title }
										className="timeline-title"
									/>
								) }
								
								{ entry.description && (
									<RichText.Content
										tagName="p"
										value={ entry.description }
										className="timeline-description"
									/>
								) }
								
								{ entry.imageUrl && (
									<div className="timeline-media">
										<img src={ entry.imageUrl } alt={ entry.title || '' } />
									</div>
								) }
							</div>
						</div>
					) ) }
				</div>
			</div>
		</div>
	);
}
