<?php
/**
 * Real theme header/footer HTML + front styles for editor parity.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Theme;

final class ThemeChrome {

	private string $layout_css = '';

	/**
	 * @return array{
	 *   header:string,
	 *   footer:string,
	 *   hasHeader:bool,
	 *   hasFooter:bool,
	 *   styles:array{links:list<string>,inline:string},
	 *   contentStyles:array{links:list<string>,inline:string},
	 *   homeUrl:string
	 * }
	 */
	public function parts(): array {
		// Reset layout CSS collected during render.
		$this->layout_css = '';

		// Prefer Aura Theme Builder header/footer when enabled (matches Theme Builder editor).
		// Otherwise fall back to FSE theme template parts, then static fallback.
		$header = $this->builder_part_html( 'header' );
		$footer = $this->builder_part_html( 'footer' );

		if ( $header === '' ) {
			$header = $this->render_part( 'header' );
		}
		if ( $footer === '' ) {
			$footer = $this->render_part( 'footer' );
		}

		if ( $header === '' ) {
			$header = $this->fallback_header();
		}
		if ( $footer === '' ) {
			$footer = $this->fallback_footer();
		}

		// Collect layout/block-support CSS generated while rendering.
		if ( function_exists( 'wp_style_engine_get_stylesheet_from_context' ) ) {
			$supports = wp_style_engine_get_stylesheet_from_context( 'block-supports' );
			if ( is_string( $supports ) && $supports !== '' ) {
				$this->layout_css .= $supports . "\n";
			}
		}

		$theme_styles  = ( new ThemeStyles() )->for_editor();
		$chrome_styles = $this->front_styles();

		// StyleEngine CSS for header/footer docs (grid spans, colors, backgrounds).
		// Without this, menu column collapses to 1/12 and footer loses blue background in editor chrome.
		$chrome_styles['inline'] = ( $theme_styles['inline'] ?? '' )
			. "\n" . ( $chrome_styles['inline'] ?? '' )
			. "\n" . $this->builder_part_css( 'header' )
			. "\n" . $this->builder_part_css( 'footer' );

		// Force https on stylesheet links (mixed-content breaks menu CSS in editor).
		$merged_links = array_merge( $theme_styles['links'] ?? array(), $chrome_styles['links'] ?? array() );
		$chrome_styles['links'] = array_values(
			array_unique(
				array_filter(
					array_map(
						static function ( $u ) {
							$u = (string) $u;
							if ( $u === '' ) {
								return '';
							}
							if ( class_exists( \AuraBuilder\Support\Assets::class ) ) {
								return \AuraBuilder\Support\Assets::force_https_url( $u );
							}
							return $u;
						},
						$merged_links
					)
				)
			)
		);

		return array(
			'header'        => $header,
			'footer'        => $footer,
			'hasHeader'     => $header !== '',
			'hasFooter'     => $footer !== '',
			'styles'        => $chrome_styles,
			// Full theme styles for the editable canvas (page body).
			'contentStyles' => $theme_styles,
			'homeUrl'       => home_url( '/' ),
		);
	}

	/**
	 * Compiled StyleEngine CSS for a Theme Builder part (header/footer).
	 */
	private function builder_part_css( string $type ): string {
		$type = $type === 'footer' ? 'footer' : 'header';
		$part = ThemeBuilder::get_part( $type );
		if ( empty( $part['enabled'] ) || empty( $part['document'] ) || ! is_array( $part['document'] ) ) {
			return '';
		}
		try {
			$doc = \AuraBuilder\Document\DocumentSanitizer::sanitize( $part['document'] );
			$out = ( new \AuraBuilder\Renderer\DocumentRenderer() )->render(
				$doc,
				array( 'editor' => true )
			);
			$css = (string) ( $out['css'] ?? '' );
			// Strip broken HTML entities from any accidental esc_url in CSS.
			$css = str_replace( array( '&#038;', '&amp;' ), '&', $css );
			return $css;
		} catch ( \Throwable $e ) {
			return '';
		}
	}

	/**
	 * HTML from Aura Theme Builder (nav_menu + logo widgets), for editor chrome parity.
	 */
	private function builder_part_html( string $type ): string {
		$type = $type === 'footer' ? 'footer' : 'header';
		$part = ThemeBuilder::get_part( $type );
		if ( empty( $part['enabled'] ) || ( $part['source'] ?? '' ) !== 'builder' ) {
			return '';
		}
		if ( empty( $part['document'] ) || ! is_array( $part['document'] ) ) {
			return '';
		}
		// Display conditions: in editor always show if enabled (preview).
		$part['_type'] = $type;
		$html          = ThemeBuilder::render_part_html( $part, true );
		return is_string( $html ) ? trim( $html ) : '';
	}

	/**
	 * Render a template part and expand patterns / navigation fully.
	 */
	private function render_part( string $slug ): string {
		$content = $this->template_part_content( $slug );
		if ( $content === '' ) {
			return '';
		}

		// Ensure block types are registered (REST can be sparse).
		if ( function_exists( 'do_blocks' ) ) {
			$html = (string) do_blocks( $content );
		} else {
			$html = $content;
		}

		return trim( $html );
	}

	private function template_part_content( string $slug ): string {
		if ( ! function_exists( 'get_block_templates' ) ) {
			return '';
		}

		// Prefer customized (DB) template parts over theme defaults.
		$templates = get_block_templates(
			array(
				'slug__in' => array( $slug ),
			),
			'wp_template_part'
		);

		$best = null;
		foreach ( $templates as $tpl ) {
			if ( ! $tpl || empty( $tpl->content ) ) {
				continue;
			}
			// custom source beats theme.
			if ( isset( $tpl->source ) && $tpl->source === 'custom' ) {
				$best = $tpl;
				break;
			}
			if ( null === $best ) {
				$best = $tpl;
			}
		}

		if ( $best && ! empty( $best->content ) ) {
			return (string) $best->content;
		}

		$theme = get_stylesheet();
		$tpl   = get_block_template( $theme . '//' . $slug, 'wp_template_part' );
		if ( $tpl && ! empty( $tpl->content ) ) {
			return (string) $tpl->content;
		}

		return '';
	}

	/**
	 * @return array{links:list<string>,inline:string}
	 */
	public function front_styles(): array {
		$links  = array();
		$inline = '';

		// Block library + navigation (critical for menu).
		$links[] = includes_url( 'css/dist/block-library/style.min.css' );
		$links[] = includes_url( 'css/dist/block-library/theme.min.css' );
		// WP 6.3+ may serve navigation from /blocks/navigation/.
		$nav_css = ABSPATH . WPINC . '/blocks/navigation/style.min.css';
		if ( is_file( $nav_css ) ) {
			$links[] = includes_url( 'blocks/navigation/style.min.css' );
		}
		$nav_view = ABSPATH . WPINC . '/blocks/navigation/style.css';
		if ( is_file( $nav_view ) && ! is_file( $nav_css ) ) {
			$links[] = includes_url( 'blocks/navigation/style.css' );
		}

		// Aura front widgets CSS (nav_menu, etc.) for Theme Builder chrome.
		if ( class_exists( \AuraBuilder\Support\Assets::class ) ) {
			$links[] = \AuraBuilder\Support\Assets::url( 'frontend/css/front.css' );
		} elseif ( defined( 'AURA_BUILDER_URL' ) ) {
			$links[] = AURA_BUILDER_URL . 'frontend/css/front.css';
		}

		// Theme style.
		$theme_style = get_stylesheet_uri();
		if ( is_string( $theme_style ) && $theme_style !== '' ) {
			$links[] = $theme_style;
		}
		// Minified theme style if present.
		$min = get_stylesheet_directory() . '/style.min.css';
		if ( is_file( $min ) ) {
			$links[] = get_stylesheet_directory_uri() . '/style.min.css';
		}
		if ( get_template_directory() !== get_stylesheet_directory() ) {
			$links[] = get_template_directory_uri() . '/style.css';
		}

		// Global styles (theme.json) — colors, spacing, typography, fonts.
		if ( function_exists( 'wp_get_global_stylesheet' ) ) {
			$variables = wp_get_global_stylesheet( array( 'variables' ) );
			$presets   = wp_get_global_stylesheet( array( 'presets' ) );
			$styles    = wp_get_global_stylesheet( array( 'styles' ) );
			foreach ( array( $variables, $presets, $styles ) as $chunk ) {
				if ( is_string( $chunk ) && $chunk !== '' ) {
					$inline .= $chunk . "\n";
				}
			}
		}

		// Layout classes generated for this render (justify-content etc.).
		if ( $this->layout_css !== '' ) {
			$inline .= $this->layout_css . "\n";
		}

		// Local fonts (@font-face) for Source Serif etc.
		if ( function_exists( 'wp_print_font_faces' ) ) {
			ob_start();
			wp_print_font_faces();
			$fonts = (string) ob_get_clean();
			// wp_print_font_faces prints <style> tags — extract CSS.
			if ( preg_match_all( '/<style[^>]*>(.*?)<\/style>/is', $fonts, $m ) ) {
				foreach ( $m[1] as $css ) {
					$inline .= $css . "\n";
				}
			} else {
				$inline .= $fonts;
			}
		}

		$inline .= $this->editor_chrome_css();

		$links = array_values( array_unique( array_filter( $links ) ) );

		return array(
			'links'  => $links,
			'inline' => $inline,
		);
	}

	/**
	 * CSS only for the editor chrome iframe: force desktop header/footer look.
	 */
	private function editor_chrome_css(): string {
		return <<<'CSS'
html, body {
  margin: 0 !important;
  padding: 0 !important;
  overflow-x: hidden;
}
body.ab-chrome-frame {
  min-height: 0;
  /* Slightly compact for editor chrome without destroying layout */
  --wp--custom--spacing--large: 2rem;
  --wp--custom--spacing--small: 1rem;
}

/* Aura Builder layout (header grid + menu + footer columns) */
.ab-document { width: 100%; box-sizing: border-box; display: flow-root; }
.ab-node { position: relative; box-sizing: border-box; float: none !important; max-width: 100%; min-width: 0; }
.ab-type-section.ab-section--grid {
  display: grid !important;
  grid-template-columns: repeat(12, minmax(0, 1fr)) !important;
  align-items: center !important;
  width: 100% !important;
}
.ab-type-section.ab-section--grid > .ab-type-container {
  clear: none !important;
  float: none !important;
  min-width: 0;
  max-width: 100%;
}
/* Common 2-col header: logo | menu */
.ab-theme-builder-header .ab-type-section.ab-section--grid > .ab-type-container:first-child:nth-last-child(2) {
  grid-column: span 3;
}
.ab-theme-builder-header .ab-type-section.ab-section--grid > .ab-type-container:last-child:nth-child(2) {
  grid-column: span 9;
}
/* Common 3-col footer */
.ab-theme-builder-footer .ab-type-section.ab-section--grid > .ab-type-container:nth-child(1):nth-last-child(3),
.ab-theme-builder-footer .ab-type-section.ab-section--grid > .ab-type-container:nth-child(2):nth-last-child(2),
.ab-theme-builder-footer .ab-type-section.ab-section--grid > .ab-type-container:nth-child(3):nth-last-child(1) {
  grid-column: span 4;
}
.ab-nav-menu { width: 100%; max-width: 100%; position: relative; z-index: 40; overflow: visible !important; }
.ab-nav-menu--horizontal .ab-nav-menu__list {
  display: flex !important;
  flex-direction: row !important;
  flex-wrap: wrap !important;
  align-items: center !important;
  list-style: none !important;
  margin: 0 !important;
  padding: 0 !important;
  gap: 8px !important;
}
.ab-nav-menu--horizontal .ab-nav-menu__item {
  width: auto !important;
  flex: 0 0 auto !important;
  display: block !important;
  position: relative !important;
  list-style: none !important;
}
.ab-nav-menu--horizontal .ab-nav-menu__link {
  display: inline-flex !important;
  width: auto !important;
  white-space: nowrap;
}
/* Never use mobile drawer in chrome preview */
.ab-nav-menu__toggle { display: none !important; }
.ab-nav-menu--mobile-drawer .ab-nav-menu__list {
  display: flex !important;
  flex-direction: row !important;
  position: static !important;
  width: auto !important;
  background: transparent !important;
  border: 0 !important;
  box-shadow: none !important;
  padding: 0 !important;
}
/* Dropdown: overlay panel (never in-flow nested list with bullets) */
.ab-nav-menu__sub,
.ab-nav-menu--mobile-drawer .ab-nav-menu__sub {
  list-style: none !important;
  margin: 0 !important;
  padding: 6px 0 !important;
  position: absolute !important;
  top: calc(100% + 6px) !important;
  left: 0 !important;
  min-width: 220px !important;
  background: #fff !important;
  border: 1px solid #e8edf3 !important;
  border-radius: 10px !important;
  box-shadow: 0 12px 32px rgba(15, 23, 42, 0.14) !important;
  opacity: 0 !important;
  visibility: hidden !important;
  pointer-events: none !important;
  z-index: 300 !important;
  transform: translateY(6px);
}
.ab-nav-menu__item.has-children:hover > .ab-nav-menu__sub,
.ab-nav-menu__item.has-children.is-open > .ab-nav-menu__sub {
  opacity: 1 !important;
  visibility: visible !important;
  pointer-events: auto !important;
  transform: translateY(0) !important;
}
.ab-nav-menu__sub-item,
.ab-nav-menu__sub > li {
  list-style: none !important;
  margin: 0 !important;
  padding: 0 !important;
  display: block !important;
}
.ab-nav-menu__sub-item::marker,
.ab-nav-menu__sub > li::marker { content: none !important; }
.ab-nav-menu__sub-link {
  display: block !important;
  padding: 11px 16px !important;
  color: #1e293b !important;
  text-decoration: none !important;
  white-space: nowrap;
  font: 500 14px/1.35 system-ui, sans-serif !important;
}
.ab-nav-menu__sub-link:hover { background: #f8fafc !important; }
.ab-theme-builder-header,
.ab-theme-builder-header .ab-type-section,
.ab-theme-builder-header .ab-type-container,
.ab-theme-builder-header .ab-type-nav_menu {
  overflow: visible !important;
}

/* ---- Navigation: always show desktop menu (overlay type) ---- */
.wp-block-navigation__responsive-container-open,
.wp-block-navigation__responsive-container-close {
  display: none !important;
}
.wp-block-navigation__responsive-container,
.wp-block-navigation__responsive-container:not(.is-menu-open),
.wp-block-navigation__responsive-container.hidden-by-default {
  display: block !important;
  position: static !important;
  width: auto !important;
  height: auto !important;
  max-width: none !important;
  max-height: none !important;
  min-width: 0 !important;
  background: transparent !important;
  overflow: visible !important;
  opacity: 1 !important;
  visibility: visible !important;
  pointer-events: auto !important;
  transform: none !important;
  animation: none !important;
  inset: auto !important;
  z-index: auto !important;
  padding: 0 !important;
}
.wp-block-navigation__responsive-close,
.wp-block-navigation__responsive-dialog {
  display: block !important;
  position: static !important;
  width: auto !important;
  max-width: none !important;
  margin: 0 !important;
  padding: 0 !important;
  background: transparent !important;
  box-shadow: none !important;
  overflow: visible !important;
}
/* Content of open/always-visible nav: keep HORIZONTAL (not mobile drawer stack). */
.wp-block-navigation__responsive-container-content,
.wp-block-navigation__responsive-container-content[aria-hidden="true"],
.wp-block-navigation__responsive-container.is-menu-open .wp-block-navigation__responsive-container-content {
  display: flex !important;
  flex-direction: row !important;
  flex-wrap: wrap !important;
  align-items: center !important;
  justify-content: flex-end !important;
  visibility: visible !important;
  padding: 0 !important;
  opacity: 1 !important;
  width: auto !important;
  height: auto !important;
}
ul.wp-block-navigation__container,
.wp-block-navigation__container,
.wp-block-navigation__responsive-container.is-menu-open .wp-block-navigation__container,
.wp-block-navigation .wp-block-page-list {
  display: flex !important;
  flex-direction: row !important;
  flex-wrap: wrap !important;
  align-items: center !important;
  justify-content: flex-end !important;
  gap: 0.35rem 1.1rem !important;
  list-style: none !important;
  margin: 0 !important;
  padding: 0 !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto !important;
}
.wp-block-navigation .wp-block-navigation-item,
.wp-block-navigation .wp-block-pages-list-item {
  display: inline-flex !important;
  flex-direction: row !important;
  visibility: visible !important;
  width: auto !important;
  float: none !important;
}
.wp-block-navigation .wp-block-navigation-item a,
.wp-block-navigation .wp-block-pages-list-item a {
  text-decoration: none;
  color: inherit;
  white-space: nowrap;
  display: inline-block;
}
/* Kill modal/drawer stacking from is-menu-open mobile styles */
.wp-block-navigation__responsive-container.is-menu-open {
  display: block !important;
  position: static !important;
  width: auto !important;
  height: auto !important;
  overflow: visible !important;
  background: transparent !important;
}
.wp-block-navigation__responsive-container.is-menu-open .wp-block-navigation__responsive-dialog {
  max-width: none !important;
  margin: 0 !important;
}

/* Header row layout */
.wp-block-group.is-layout-flex,
.is-layout-flex {
  display: flex !important;
  flex-wrap: nowrap !important;
  align-items: center !important;
  gap: 1rem;
  width: 100% !important;
}
.wp-block-group.is-layout-flex > * {
  flex-shrink: 0;
}
.wp-block-group.is-layout-flex > .wp-block-navigation {
  flex: 1 1 auto;
  min-width: 0;
  justify-content: flex-end !important;
}
.is-content-justification-space-between {
  justify-content: space-between !important;
}
.is-content-justification-left {
  justify-content: flex-start !important;
}
.is-content-justification-right,
.wp-block-navigation.is-content-justification-right {
  justify-content: flex-end !important;
}
.wp-block-site-logo {
  line-height: 0;
}
.wp-block-site-logo img {
  height: auto;
  max-width: 64px;
}
.wp-block-site-title {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
}
.wp-block-site-title a {
  text-decoration: none;
  color: inherit;
}

/* Footer */
.is-content-justification-space-between.wp-block-group {
  width: 100%;
}
.has-text-align-right {
  text-align: right;
}

/* Fallback */
.ab-theme-fallback-header,
.ab-theme-fallback-footer {
  padding: 1.25rem 2rem;
}
.ab-theme-fallback-inner {
  max-width: 1200px;
  margin: 0 auto;
}
.ab-theme-brand {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}
.ab-theme-brand img { max-height: 64px; width: auto; }
.ab-theme-site-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: inherit;
  text-decoration: none;
}
.ab-theme-nav ul {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem 1.5rem;
  list-style: none;
  margin: 0;
  padding: 0;
  justify-content: flex-end;
}
.ab-theme-nav a { text-decoration: none; color: inherit; }
CSS;
	}

	private function fallback_header(): string {
		$logo = '';
		if ( function_exists( 'has_custom_logo' ) && has_custom_logo() ) {
			$logo = get_custom_logo();
		}
		$name = get_bloginfo( 'name' );
		$menu = $this->first_menu_html();

		return '<header class="ab-theme-fallback-header">'
			. '<div class="ab-theme-fallback-inner">'
			. '<div class="ab-theme-brand">'
			. ( $logo ?: '' )
			. '<a class="ab-theme-site-title" href="' . esc_url( home_url( '/' ) ) . '">' . esc_html( $name ) . '</a>'
			. '</div>'
			. ( is_string( $menu ) ? $menu : '' )
			. '</div></header>';
	}

	private function fallback_footer(): string {
		$name = get_bloginfo( 'name' );
		return '<footer class="ab-theme-fallback-footer">'
			. '<div class="ab-theme-fallback-inner" style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:1rem">'
			. '<p class="wp-block-site-title" style="margin:0">' . esc_html( $name ) . '</p>'
			. '<p style="margin:0">Orgulhosamente feito com <a href="https://br.wordpress.org/" rel="nofollow">WordPress</a></p>'
			. '</div></footer>';
	}

	private function first_menu_html(): string {
		// Prefer "Topo" / primary menus used by the school site.
		$menus = wp_get_nav_menus();
		foreach ( $menus as $menu ) {
			if ( in_array( strtolower( $menu->name ), array( 'topo', 'principal', 'primary', 'main' ), true )
				|| in_array( $menu->slug, array( 'topo', 'principal', 'primary' ), true ) ) {
				$html = wp_nav_menu(
					array(
						'menu'            => (int) $menu->term_id,
						'container'       => 'nav',
						'container_class' => 'ab-theme-nav',
						'echo'            => false,
						'fallback_cb'     => false,
					)
				);
				if ( is_string( $html ) && $html !== '' ) {
					return $html;
				}
			}
		}
		if ( has_nav_menu( 'primary' ) ) {
			$html = wp_nav_menu(
				array(
					'theme_location'  => 'primary',
					'container'       => 'nav',
					'container_class' => 'ab-theme-nav',
					'echo'            => false,
					'fallback_cb'     => false,
				)
			);
			return is_string( $html ) ? $html : '';
		}
		if ( ! empty( $menus[0] ) ) {
			$html = wp_nav_menu(
				array(
					'menu'            => (int) $menus[0]->term_id,
					'container'       => 'nav',
					'container_class' => 'ab-theme-nav',
					'echo'            => false,
					'fallback_cb'     => false,
				)
			);
			return is_string( $html ) ? $html : '';
		}
		return '';
	}
}
