<?php
/**
 * Reusable Gutenberg page and section patterns.
 *
 * @package HaPantheon
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Resolve an imported demo post URL, with an editable fallback path.
 *
 * @param string $slug Post slug.
 * @return string
 */
function hapantheon_pattern_post_url( $slug ) {
	$post = get_page_by_path( sanitize_title( $slug ), OBJECT, 'post' );
	return $post ? get_permalink( $post ) : home_url( '/' . trim( $slug, '/' ) . '/' );
}

/**
 * Resolve a category URL, with a normal category-path fallback.
 *
 * @param string $slug Category slug.
 * @return string
 */
function hapantheon_pattern_category_url( $slug ) {
	$term = get_category_by_slug( sanitize_title( $slug ) );
	if ( $term ) {
		$url = get_category_link( $term->term_id );
		if ( ! is_wp_error( $url ) ) {
			return $url;
		}
	}
	return home_url( '/category/' . trim( $slug, '/' ) . '/' );
}

/**
 * Read and normalize a bundled block pattern.
 *
 * @param string $filename Content filename.
 * @return string
 */
function hapantheon_pattern_content( $filename ) {
	$path = HAPANTHEON_DIR . '/demo/content/' . basename( $filename );
	if ( ! is_readable( $path ) ) {
		return '';
	}

	$content = file_get_contents( $path );
	if ( false === $content ) {
		return '';
	}

	$oracle = get_category_by_slug( 'oracle' );
	$content = str_replace(
		array(
			'{{theme_uri}}',
			'{{oracle_category_id}}',
			'archive.html?cat=recipes',
			'archive.html?cat=stories',
			'archive.html?cat=travel',
			'archive.html?cat=diy',
			'archive.html?cat=oracle',
			'archive.html',
			'about.html',
			'oracle.html',
			'faq.html',
			'contact.html',
			'article-sidebar.html',
			'article-hero.html',
			'article.html',
			'recipe.html',
		),
		array(
			HAPANTHEON_URI,
			$oracle ? (string) $oracle->term_id : '0',
			hapantheon_pattern_category_url( 'recipes' ),
			hapantheon_pattern_category_url( 'stories' ),
			hapantheon_pattern_category_url( 'travel' ),
			hapantheon_pattern_category_url( 'diy' ),
			hapantheon_pattern_category_url( 'oracle' ),
			hapantheon_get_archive_url(),
			hapantheon_get_page_url_by_slug( 'about' ),
			hapantheon_get_page_url_by_slug( 'oracle' ),
			hapantheon_get_page_url_by_slug( 'faq' ),
			hapantheon_get_page_url_by_slug( 'contact' ),
			hapantheon_pattern_post_url( 'the-letter-inside-a-used-book' ),
			hapantheon_pattern_post_url( 'cappadocia-without-a-map' ),
			hapantheon_pattern_post_url( 'the-night-the-fuel-ran-out' ),
			hapantheon_pattern_post_url( 'golden-ratio-cold-espresso' ),
		),
		$content
	);

	return $content;
}

/**
 * Register the pattern library.
 */
function hapantheon_register_patterns() {
	if ( ! function_exists( 'register_block_pattern' ) ) {
		return;
	}

	register_block_pattern_category(
		'hapantheon-pages',
		array( 'label' => __( 'HaPantheon — Complete Pages', 'hapantheon' ) )
	);
	register_block_pattern_category(
		'hapantheon-sections',
		array( 'label' => __( 'HaPantheon — Sections', 'hapantheon' ) )
	);

	$pages = array(
		'homepage' => array(
			'title'       => __( 'HaPantheon Homepage', 'hapantheon' ),
			'description' => __( 'Complete editable homepage composed from source-preserving section blocks.', 'hapantheon' ),
			'file'        => 'index.blocks.html',
			'post_types'  => array( 'page' ),
		),
		'about' => array(
			'title'       => __( 'HaPantheon About Page', 'hapantheon' ),
			'description' => __( 'Manifesto, statistics, principles, timeline, editorial process and newsletter.', 'hapantheon' ),
			'file'        => 'about.blocks.html',
			'post_types'  => array( 'page' ),
		),
		'oracle' => array(
			'title'       => __( 'HaPantheon Oracle Page', 'hapantheon' ),
			'description' => __( 'Oracle introduction, principles, filtered query loop and question call to action.', 'hapantheon' ),
			'file'        => 'oracle.blocks.html',
			'post_types'  => array( 'page' ),
		),
		'faq' => array(
			'title'       => __( 'HaPantheon FAQ Page', 'hapantheon' ),
			'description' => __( 'A complete editable FAQ whose dynamic block emits the original details hierarchy.', 'hapantheon' ),
			'file'        => 'faq.blocks.html',
			'post_types'  => array( 'page' ),
		),
		'contact' => array(
			'title'       => __( 'HaPantheon Contact Page', 'hapantheon' ),
			'description' => __( 'Contact channels and the native HaPantheon contact form block.', 'hapantheon' ),
			'file'        => 'contact.blocks.html',
			'post_types'  => array( 'page' ),
		),
		'article-body' => array(
			'title'       => __( 'HaPantheon Editorial Article', 'hapantheon' ),
			'description' => __( 'Long-form editorial body with headings, image, list and pull quote.', 'hapantheon' ),
			'file'        => 'article-body.blocks.html',
			'post_types'  => array( 'post' ),
		),
		'recipe-body' => array(
			'title'       => __( 'HaPantheon Recipe Article', 'hapantheon' ),
			'description' => __( 'Recipe ingredients, equipment, method, video and editable gallery.', 'hapantheon' ),
			'file'        => 'recipe-body.blocks.html',
			'post_types'  => array( 'post' ),
		),
	);

	foreach ( $pages as $slug => $pattern ) {
		$content = hapantheon_pattern_content( $pattern['file'] );
		if ( ! $content ) {
			continue;
		}
		register_block_pattern(
			'hapantheon/' . $slug,
			array(
				'title'       => $pattern['title'],
				'description' => $pattern['description'],
				'categories'  => array( 'hapantheon-pages' ),
				'keywords'    => array( 'hapantheon', 'editorial', 'rtl' ),
				'postTypes'   => $pattern['post_types'],
				'viewportWidth'=> 1440,
				'content'     => $content,
			)
		);
	}

	register_block_pattern(
		'hapantheon/newsletter-section',
		array(
			'title'       => __( 'HaPantheon Newsletter Section', 'hapantheon' ),
			'description' => __( 'Editable newsletter heading, copy and native signup form.', 'hapantheon' ),
			'categories'  => array( 'hapantheon-sections' ),
			'viewportWidth'=> 1200,
			'content'     => '<!-- wp:hapantheon/newsletter-section {"eyebrow":"THE SCROLL","title":"המגילה הבאה, ישירות אליכם","lede":"עדכון אחד כשיש משהו שבאמת ראוי לשלוח. בלי רעש ובלי לוח זמנים מלאכותי.","placeholder":"הדוא״ל שלכם","buttonLabel":"הרשמה","source":"pattern"} /-->',
		)
	);

	register_block_pattern(
		'hapantheon/contact-form-section',
		array(
			'title'       => __( 'HaPantheon Contact Form Section', 'hapantheon' ),
			'description' => __( 'A framed native contact form ready for visual editing.', 'hapantheon' ),
			'categories'  => array( 'hapantheon-sections' ),
			'viewportWidth'=> 1000,
			'content'     => '<!-- wp:hapantheon/contact-layout {"eyebrow":"כתבו אלינו","title":"כתבו לנו","lede":"בחרו נושא, מלאו את הפרטים ושלחו את ההודעה.","channels":[],"stats":[],"quote":""} /-->',
		)
	);
}
add_action( 'init', 'hapantheon_register_patterns', 20 );
