<?php
/**
 * Plugin Name: OFDM Demo — catalog by browser language
 * Description: Show demo-en or demo-es products from Accept-Language (default EN). Demo-only helper.
 * Author: Reborn Labs
 */

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

/**
 * @return 'en'|'es'
 */
function ofdm_demo_browser_lang() {
	static $cached = null;
	if ( null !== $cached ) {
		return $cached;
	}

	$header = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ? (string) $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
	$cached = 'en';
	if ( $header === '' ) {
		return $cached;
	}

	$parts = array_map( 'trim', explode( ',', $header ) );
	foreach ( $parts as $part ) {
		$code = strtolower( trim( explode( ';', $part )[0] ) );
		if ( $code === '' ) {
			continue;
		}
		if ( $code === 'es' || str_starts_with( $code, 'es-' ) ) {
			$cached = 'es';
			break;
		}
		if ( $code === 'en' || str_starts_with( $code, 'en-' ) ) {
			$cached = 'en';
			break;
		}
	}

	return $cached;
}

function ofdm_demo_catalog_cat_slug() {
	return ofdm_demo_browser_lang() === 'es' ? 'demo-es' : 'demo-en';
}

/**
 * Front-page / sticky-bar copy by Accept-Language.
 *
 * @return array<string,string>
 */
function ofdm_demo_ui_copy() {
	static $copy = null;
	if ( null !== $copy ) {
		return $copy;
	}

	if ( ofdm_demo_browser_lang() === 'es' ) {
		$copy = array(
			'eyebrow'       => 'Demo de Order From DM',
			'headline'      => 'Convierte DMs en pedidos reales de WooCommerce',
			'lead'          => 'Envía un link de checkout personalizado desde Instagram o WhatsApp — tu cliente termina en estilo chat, tú recibes el pedido. Prueba el plugin gratis.',
			'download'      => 'Descargar gratis',
			'see_checkout'  => 'Ver checkout del cliente',
			'lunch'         => 'Desde $9/mes · o $79/año.',
			'sheet_label'   => 'Vista previa del checkout',
			'sheet_close'   => 'Cerrar',
			'featured'      => 'Productos destacados',
			'featured_lead' => 'Todos los productos de muestra de esta tienda demo.',
		);
	} else {
		$copy = array(
			'eyebrow'       => 'Order From DM Demo',
			'headline'      => 'Turn DMs into real WooCommerce orders',
			'lead'          => 'Send a personalized checkout link from Instagram or WhatsApp — your customer finishes in chat style, you get the order. Try the free plugin.',
			'download'      => 'Download Free',
			'see_checkout'  => 'See customer checkout',
			'lunch'         => 'From $9/mo · or $79/yr.',
			'sheet_label'   => 'Customer checkout preview',
			'sheet_close'   => 'Close',
			'featured'      => 'Featured products',
			'featured_lead' => 'All sample products in this demo store.',
		);
	}

	return $copy;
}

/**
 * Swap stored English front-page strings when browser language is Spanish.
 */
add_filter(
	'the_content',
	static function ( $content ) {
		if ( ! is_front_page() || ofdm_demo_browser_lang() !== 'es' || ! is_string( $content ) || $content === '' ) {
			return $content;
		}

		$c = ofdm_demo_ui_copy();
		$map = array(
			'Order From DM Demo' => $c['eyebrow'],
			'Turn DMs into real WooCommerce orders' => $c['headline'],
			'Send a personalized checkout link from Instagram or WhatsApp — your customer finishes in chat style, you get the order. Try the free plugin.' => $c['lead'],
			'Download Free' => $c['download'],
			'See customer checkout' => $c['see_checkout'],
			'Featured products' => $c['featured'],
			'All sample products in this demo store.' => $c['featured_lead'],
		);

		return strtr( $content, $map );
	},
	20
);

function ofdm_demo_should_filter_product_query( $query ) {
	if ( is_admin() && ! wp_doing_ajax() ) {
		return false;
	}
	if ( ! $query instanceof WP_Query ) {
		return false;
	}
	if ( $query->get( 'ofdm_skip_lang_filter' ) ) {
		return false;
	}

	$post_type  = $query->get( 'post_type' );
	$is_product = ( 'product' === $post_type )
		|| ( is_array( $post_type ) && in_array( 'product', $post_type, true ) )
		|| ( empty( $post_type ) && $query->is_post_type_archive( 'product' ) );

	if ( ! $is_product ) {
		return false;
	}

	if ( $query->is_singular( 'product' ) ) {
		return false;
	}

	return true;
}

function ofdm_demo_append_cat_tax_query( $tax_query ) {
	if ( ! is_array( $tax_query ) ) {
		$tax_query = array();
	}

	$slug = ofdm_demo_catalog_cat_slug();
	foreach ( $tax_query as $clause ) {
		if ( ! is_array( $clause ) ) {
			continue;
		}
		if ( ( $clause['taxonomy'] ?? '' ) === 'product_cat' ) {
			$terms = $clause['terms'] ?? array();
			if ( ! is_array( $terms ) ) {
				$terms = array( $terms );
			}
			if ( in_array( $slug, $terms, true ) || in_array( (int) $slug, array_map( 'intval', $terms ), true ) ) {
				return $tax_query;
			}
		}
	}

	$tax_query[] = array(
		'taxonomy' => 'product_cat',
		'field'    => 'slug',
		'terms'    => array( $slug ),
		'operator' => 'IN',
	);

	if ( count( $tax_query ) > 1 && empty( $tax_query['relation'] ) ) {
		$tax_query['relation'] = 'AND';
	}

	return $tax_query;
}

add_action(
	'pre_get_posts',
	static function ( $query ) {
		if ( ! ofdm_demo_should_filter_product_query( $query ) ) {
			return;
		}
		$query->set( 'tax_query', ofdm_demo_append_cat_tax_query( $query->get( 'tax_query' ) ) );
	},
	30
);

add_filter(
	'woocommerce_product_data_store_cpt_get_products_query',
	static function ( $wp_query_args, $query_vars ) {
		if ( is_admin() && ! wp_doing_ajax() ) {
			return $wp_query_args;
		}
		if ( ! empty( $query_vars['ofdm_skip_lang_filter'] ) ) {
			return $wp_query_args;
		}
		$wp_query_args['tax_query'] = ofdm_demo_append_cat_tax_query( $wp_query_args['tax_query'] ?? array() );
		return $wp_query_args;
	},
	20,
	2
);

add_filter(
	'woocommerce_related_products',
	static function ( $related_ids ) {
		if ( ! is_array( $related_ids ) || ! $related_ids ) {
			return $related_ids;
		}
		$slug = ofdm_demo_catalog_cat_slug();
		$out  = array();
		foreach ( $related_ids as $id ) {
			if ( has_term( $slug, 'product_cat', $id ) ) {
				$out[] = $id;
			}
		}
		return $out;
	},
	20
);

/**
 * Front page: hide only the page H1 "Home" — keep product titles.
 */
add_filter(
	'render_block',
	static function ( $block_content, $block ) {
		if ( ! is_front_page() ) {
			return $block_content;
		}
		if ( ( $block['blockName'] ?? '' ) !== 'core/post-title' ) {
			return $block_content;
		}
		$attrs = is_array( $block['attrs'] ?? null ) ? $block['attrs'] : array();
		if ( ! empty( $attrs['__woocommerceNamespace'] ) ) {
			return $block_content;
		}
		$level = isset( $attrs['level'] ) ? (int) $attrs['level'] : 1;
		if ( 1 === $level ) {
			return '';
		}
		return $block_content;
	},
	10,
	2
);

add_action(
	'wp_head',
	static function () {
		if ( is_front_page() ) {
			echo '<style id="ofdm-demo-front-flush">'
				. '.wp-site-blocks > main.wp-block-group{margin-top:0!important;padding-top:0!important}'
				. 'body.home .wp-block-cover.alignfull{margin-top:0!important}'
				. '</style>';
			echo '<style id="ofdm-demo-hero-stage">'
				. 'body.home .wp-block-cover.alignfull{'
				. 'min-height:min(86svh,920px)!important;'
				. 'padding-top:clamp(3.25rem,9vh,6rem)!important;'
				. 'padding-bottom:clamp(3.25rem,9vh,6rem)!important;'
				. 'display:flex;align-items:center'
				. '}'
				. 'body.home .wp-block-cover.alignfull .wp-block-cover__image-background{'
				. 'object-fit:cover;object-position:center center'
				. '}'
				/* Soft vignette — keep purple stage + icons visible */
				. 'body.home .wp-block-cover.alignfull .wp-block-cover__background{'
				. 'opacity:1!important;'
				. 'background:linear-gradient(180deg,rgba(24,10,48,.28) 0%,rgba(24,10,48,.08) 42%,rgba(24,10,48,.42) 100%)!important'
				. '}'
				. 'body.home .wp-block-cover.alignfull .wp-block-cover__inner-container{'
				. 'color:#fff;text-shadow:0 1px 20px rgba(16,6,36,.45)'
				. '}'
				. 'body.home .wp-block-cover.alignfull .wp-block-button.is-style-outline .wp-block-button__link{'
				. 'border-color:rgba(255,255,255,.72)!important;color:#fff!important;'
				. 'background:rgba(255,255,255,.08)!important;backdrop-filter:blur(6px)'
				. '}'
				. 'body.home .wp-block-cover.alignfull .wp-block-button.is-style-outline .wp-block-button__link:hover{'
				. 'background:rgba(255,255,255,.16)!important;border-color:#fff!important'
				. '}'
				. '@supports not (height:1svh){body.home .wp-block-cover.alignfull{min-height:min(86vh,920px)!important}}'
				. '</style>';
			echo '<style id="ofdm-demo-hero-cta">'
				. 'body.home .wp-block-cover .wp-block-buttons{gap:14px}'
				. 'body.home .wp-block-cover .ofdm-open-chat-preview{'
				. 'position:relative;overflow:hidden;isolation:isolate;'
				. 'background:linear-gradient(135deg,#6366f1 0%,#a855f7 48%,#ec4899 100%)!important;'
				. 'color:#fff!important;border:0!important;'
				. 'font-weight:650;letter-spacing:.01em;'
				. 'box-shadow:0 14px 34px rgba(109,40,217,.42),0 0 0 1px rgba(255,255,255,.18) inset;'
				. 'transform:translateZ(0);'
				. 'animation:ofdm-demo-cta-pulse 2.6s ease-in-out infinite'
				. '}'
				. 'body.home .wp-block-cover .ofdm-open-chat-preview::before{'
				. 'content:"";position:absolute;inset:-40% -60%;'
				. 'background:linear-gradient(105deg,transparent 35%,rgba(255,255,255,.34) 50%,transparent 65%);'
				. 'transform:translateX(-30%) rotate(8deg);'
				. 'animation:ofdm-demo-cta-shine 3.4s ease-in-out infinite;pointer-events:none;z-index:-1'
				. '}'
				. 'body.home .wp-block-cover .ofdm-open-chat-preview:hover{'
				. 'filter:brightness(1.05);transform:translateY(-2px);'
				. 'box-shadow:0 18px 40px rgba(109,40,217,.5),0 0 0 1px rgba(255,255,255,.22) inset'
				. '}'
				. 'body.home .wp-block-cover .ofdm-open-chat-preview:focus-visible{outline:2px solid #fff;outline-offset:3px}'
				. '@keyframes ofdm-demo-cta-pulse{'
				. '0%,100%{box-shadow:0 14px 34px rgba(109,40,217,.4),0 0 0 0 rgba(168,85,247,.45)}'
				. '55%{box-shadow:0 18px 42px rgba(109,40,217,.55),0 0 0 12px rgba(168,85,247,0)}'
				. '}'
				. '@keyframes ofdm-demo-cta-shine{'
				. '0%,55%{transform:translateX(-40%) rotate(8deg);opacity:0}'
				. '70%{opacity:1}'
				. '100%{transform:translateX(40%) rotate(8deg);opacity:0}'
				. '}'
				. '@media (prefers-reduced-motion:reduce){'
				. 'body.home .wp-block-cover .ofdm-open-chat-preview,'
				. 'body.home .wp-block-cover .ofdm-open-chat-preview::before{animation:none}'
				. '}'
				. '</style>';
		}
		echo '<style id="ofdm-demo-footer-cols">footer .ofdm-footer-links{list-style:none;margin:0;padding:0}footer .ofdm-footer-links li{margin:0 0 .55rem}footer .ofdm-footer-links a{text-decoration:none}footer .wp-block-columns.is-not-stacked-on-mobile{display:flex!important;flex-wrap:nowrap!important;gap:2rem;align-items:flex-start}footer .wp-block-columns.is-not-stacked-on-mobile>.wp-block-column{flex-basis:50%!important;width:50%!important;max-width:50%!important}</style>';
	},
	100
);

/**
 * Home: customer checkout preview bottom sheet (EN/ES by browser language)
 * + sticky CTA bar (hero buttons) after scrolling past the hero.
 */
add_action(
	'wp_footer',
	static function () {
		if ( ! is_front_page() ) {
			return;
		}
		$en           = esc_url( home_url( '/c/demo-en-personalized-order/' ) );
		$es           = esc_url( home_url( '/c/demo-es-pedido-personalizado/' ) );
		$download_url = esc_url( 'https://orderfromdm.rebornlabs.me/#download' );
		$copy         = ofdm_demo_ui_copy();
		?>
		<style id="ofdm-chat-sheet-css">
			.ofdm-chat-sheet{position:fixed;inset:0;z-index:100000;display:none}
			.ofdm-chat-sheet.is-open{display:block}
			.ofdm-chat-sheet__backdrop{position:absolute;inset:0;background:rgba(0,0,0,.42);opacity:0;transition:opacity .22s ease}
			.ofdm-chat-sheet.is-open .ofdm-chat-sheet__backdrop{opacity:1}
			.ofdm-chat-sheet__panel{
				--ofdm-sheet-top-gap: max(20px, env(safe-area-inset-top, 0px));
				--ofdm-sheet-bottom-gap: max(12px, env(safe-area-inset-bottom, 0px));
				position:absolute;
				left:50%;
				bottom: var(--ofdm-sheet-bottom-gap);
				transform:translate(-50%, calc(100% + 24px));
				width:min(430px, calc(100% - 24px));
				height: calc(100dvh - var(--ofdm-sheet-top-gap) - var(--ofdm-sheet-bottom-gap));
				max-height: calc(100dvh - var(--ofdm-sheet-top-gap) - var(--ofdm-sheet-bottom-gap));
				background:#000;
				border-radius:18px;
				overflow:hidden;
				box-shadow:0 -8px 32px rgba(0,0,0,.28);
				transition:transform .28s cubic-bezier(.22,.9,.28,1);
				display:flex;flex-direction:column;
			}
			.ofdm-chat-sheet.is-open .ofdm-chat-sheet__panel{transform:translate(-50%,0)}
			.ofdm-chat-sheet__close{
				position:absolute;top:12px;right:12px;z-index:3;
				width:36px;height:36px;border:0;border-radius:9999px;
				background:#fff;color:#111;cursor:pointer;
				display:inline-flex;align-items:center;justify-content:center;
				box-shadow:0 2px 10px rgba(0,0,0,.18);
				font-size:22px;line-height:1;padding:0;
			}
			.ofdm-chat-sheet__close:hover{background:#f4f4f4}
			.ofdm-chat-sheet__close:focus-visible{outline:2px solid #3797f0;outline-offset:2px}
			.ofdm-chat-sheet__frame{border:0;width:100%;height:100%;background:#000;display:block}
			body.ofdm-chat-sheet-lock{overflow:hidden}
			@supports not (height: 100dvh) {
				.ofdm-chat-sheet__panel{
					height: calc(100vh - var(--ofdm-sheet-top-gap) - var(--ofdm-sheet-bottom-gap));
					max-height: calc(100vh - var(--ofdm-sheet-top-gap) - var(--ofdm-sheet-bottom-gap));
				}
			}

			.ofdm-demo-bottom-bar{
				position:fixed;
				left:16px;right:16px;
				bottom:max(16px, env(safe-area-inset-bottom, 0px));
				z-index:99990;
				max-width:560px;
				margin-inline:auto;
				padding:10px 12px;
				border-radius:22px;
				border:1px solid rgba(255,255,255,.95);
				background:rgba(255,255,255,.68);
				backdrop-filter:blur(20px);
				-webkit-backdrop-filter:blur(20px);
				box-shadow:0 10px 40px rgba(88,56,130,.14),0 2px 8px rgba(88,56,130,.08);
				transform:translateY(calc(100% + 36px));
				opacity:0;
				pointer-events:none;
				transition:transform .28s ease, opacity .28s ease;
			}
			.ofdm-demo-bottom-bar.is-visible{
				transform:translateY(0);
				opacity:1;
				pointer-events:auto;
			}
			body.ofdm-chat-sheet-lock .ofdm-demo-bottom-bar{opacity:0;pointer-events:none;transform:translateY(calc(100% + 36px))}
			.ofdm-demo-bottom-bar__actions{
				display:flex;align-items:center;justify-content:space-between;gap:8px;width:100%;
			}
			.ofdm-demo-bottom-bar__btn{
				flex:1 1 0;min-width:0;
				display:inline-flex;align-items:center;justify-content:center;
				padding:11px 10px;border-radius:999px;
				font-size:.82rem;font-weight:650;line-height:1.2;
				text-align:center;text-decoration:none;white-space:nowrap;
				transition:transform .15s ease, box-shadow .15s ease, filter .15s ease;
			}
			.ofdm-demo-bottom-bar__btn:hover{transform:translateY(-1px)}
			.ofdm-demo-bottom-bar__btn--ghost{
				border:1px solid rgba(26,20,40,.1);
				background:rgba(255,255,255,.92);
				color:#1a1428;
				box-shadow:0 8px 22px rgba(88,56,130,.08);
			}
			.ofdm-demo-bottom-bar__btn--primary{
				border:0;
				background:linear-gradient(135deg,#6366f1 0%,#a855f7 48%,#ec4899 100%);
				color:#fff;
				box-shadow:0 12px 28px rgba(109,40,217,.32);
			}
			.ofdm-demo-bottom-bar__btn--primary:hover{filter:brightness(1.04)}
			.ofdm-demo-bottom-bar__note{
				margin:7px 0 0;
				text-align:center;
				width:100%;
				font-size:.65rem;
				font-style:italic;
				font-weight:500;
				line-height:1.35;
				color:#1a1428;
				opacity:.82;
			}
			body.home.ofdm-demo-bar-pad{padding-bottom:108px}
			@media (max-width:380px){
				.ofdm-demo-bottom-bar__btn{font-size:.74rem;padding:10px 8px}
			}
		</style>
		<div class="ofdm-demo-bottom-bar" id="ofdm-demo-bottom-bar" aria-hidden="true">
			<div class="ofdm-demo-bottom-bar__actions">
				<a class="ofdm-demo-bottom-bar__btn ofdm-demo-bottom-bar__btn--ghost" href="<?php echo $download_url; ?>"><?php echo esc_html( $copy['download'] ); ?></a>
				<a class="ofdm-demo-bottom-bar__btn ofdm-demo-bottom-bar__btn--primary ofdm-open-chat-preview" href="#preview-checkout" role="button"><?php echo esc_html( $copy['see_checkout'] ); ?></a>
			</div>
			<p class="ofdm-demo-bottom-bar__note"><?php echo esc_html( $copy['lunch'] ); ?></p>
		</div>
		<div class="ofdm-chat-sheet" id="ofdm-chat-sheet" hidden>
			<div class="ofdm-chat-sheet__backdrop" data-ofdm-sheet-close aria-hidden="true"></div>
			<div class="ofdm-chat-sheet__panel" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr( $copy['sheet_label'] ); ?>">
				<button type="button" class="ofdm-chat-sheet__close" data-ofdm-sheet-close aria-label="<?php echo esc_attr( $copy['sheet_close'] ); ?>">×</button>
				<iframe class="ofdm-chat-sheet__frame" id="ofdm-chat-sheet-frame" title="Order From DM checkout" src="about:blank" loading="lazy"></iframe>
			</div>
		</div>
		<script id="ofdm-chat-sheet-js">
		(function () {
			var urls = { en: <?php echo wp_json_encode( $en ); ?>, es: <?php echo wp_json_encode( $es ); ?> };
			var serverLang = <?php echo wp_json_encode( ofdm_demo_browser_lang() ); ?>;
			var sheet = document.getElementById('ofdm-chat-sheet');
			var frame = document.getElementById('ofdm-chat-sheet-frame');
			var bar = document.getElementById('ofdm-demo-bottom-bar');
			var hero = document.querySelector('body.home .wp-block-cover.alignfull');
			if (!sheet || !frame) return;

			function pickUrl() {
				return serverLang === 'es' ? urls.es : urls.en;
			}

			function setBarVisible(show) {
				if (!bar) return;
				bar.classList.toggle('is-visible', show);
				bar.setAttribute('aria-hidden', show ? 'false' : 'true');
				document.body.classList.toggle('ofdm-demo-bar-pad', show);
			}

			function openSheet(e) {
				if (e) e.preventDefault();
				frame.src = pickUrl();
				sheet.hidden = false;
				requestAnimationFrame(function () {
					sheet.classList.add('is-open');
				});
				document.body.classList.add('ofdm-chat-sheet-lock');
			}

			function closeSheet() {
				sheet.classList.remove('is-open');
				document.body.classList.remove('ofdm-chat-sheet-lock');
				setTimeout(function () {
					if (!sheet.classList.contains('is-open')) {
						sheet.hidden = true;
						frame.src = 'about:blank';
					}
				}, 280);
			}

			document.addEventListener('click', function (e) {
				var openBtn = e.target.closest('.ofdm-open-chat-preview');
				if (openBtn) {
					openSheet(e);
					return;
				}
				if (e.target.closest('[data-ofdm-sheet-close]')) {
					closeSheet();
				}
			});
			document.addEventListener('keydown', function (e) {
				if (e.key === 'Escape' && sheet.classList.contains('is-open')) closeSheet();
			});

			if (bar && hero && 'IntersectionObserver' in window) {
				var observer = new IntersectionObserver(
					function (entries) {
						var entry = entries[0];
						// Appear early — once ~half the hero has scrolled away.
						var show = !entry.isIntersecting || entry.intersectionRatio < 0.72;
						setBarVisible(show);
					},
					{ threshold: [0, 0.2, 0.4, 0.55, 0.72, 0.9, 1], rootMargin: '-12% 0px 0px 0px' }
				);
				observer.observe(hero);
			} else if (bar && hero) {
				function onScroll() {
					var rect = hero.getBoundingClientRect();
					setBarVisible(rect.bottom < window.innerHeight * 0.88);
				}
				window.addEventListener('scroll', onScroll, { passive: true });
				onScroll();
			}
		})();
		</script>
		<?php
	},
	40
);
