<?php

/**
 * GT BOGO Engine — Countdown Timer Superpower
 * Real-time countdown tied to active rule end_date.
 * Falls back to session-based daily deal timer if no end date.
 * Multiple placement hooks. Inherits theme styles. Off by default.
 *
 * Intelligence: Signal Bus (urgency copy) | Profile Tracker (returning copy)
 *               LTV/RFM (VIP label) | Margin Intelligence (suppress if thin)
 *               Theme Intelligence (visual config)
 *
 * @package GT_BOGO_Engine
 * @since   3.17.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class GT_BOGO_Countdown_Timer {
 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound

	private $id           = 'countdown_timer';
	private ?array $_cfg  = null;
	private ?array $_anim = null;

	public function __construct() {
		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
			return;
		}
		if ( ! $this->enabled() ) {
			return;
		}
		if ( class_exists( 'GT_BOGO_Attribution_Engine' ) ) {
			GT_BOGO_Attribution_Engine::record_impression( $this->id );
		}
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
		if ( class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( $this->id );
			if ( $cfg['animate'] && class_exists( 'GT_BOGO_Animation_Engine' ) ) {
				add_action( 'wp_footer', array( 'GT_BOGO_Animation_Engine', 'enqueue' ), 5 );
			}
		}
	}


	/**
	 * Get AI-generated copy for a field, with fallback to default.
	 * Reads from gtbogo_sp_{id}_ai_copy option set by GT_BOGO_AI_Copywriter.
	 *
	 * @param string $field   Copy field name (headline, message, cta, badge_text, etc.)
	 * @param string $default Default text if AI copy not available
	 * @return string
	 * @since 5.0.0
	 */
	private function ai_copy( string $field, string $default = '' ): string {
		$copy = get_option( 'gtbogo_sp_' . $this->id . '_ai_copy', array() );
		return ! empty( $copy[ $field ] ) ? wp_kses_post( $copy[ $field ] ) : $default;
	}


	private function enabled(): bool {

		// ── Orchestrator: autonomous enable/intensity decision ─────────────
		if ( class_exists( 'GT_BOGO_Superpower_Orchestrator' ) ) {
			$orch = GT_BOGO_Superpower_Orchestrator::decision( $this->id );
			if ( isset( $orch['enabled'] ) && ! $orch['enabled'] ) {
				return false;
			}
		}
		return (bool) get_option( 'gtbogo_sp_' . $this->id . '_enabled', 0 )
			&& get_option( 'gtbogo_sp_' . $this->id . '_intensity', 'subtle' ) !== 'off';
	}

	private function intensity(): string {
		if ( class_exists( 'GT_BOGO_Superpower_Orchestrator' ) ) {
			$d = GT_BOGO_Superpower_Orchestrator::decision( $this->id );
			if ( ! empty( $d['intensity'] ) ) {
				return $d['intensity'];
			}
		}
		return get_option( 'gtbogo_sp_' . $this->id . '_intensity', 'subtle' );
	}

	private function cfg(): array {
		if ( $this->_cfg === null && class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$this->_cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( $this->id );
		}
		return $this->_cfg ?? array();
	}

	private function anim(): array {
		if ( $this->_anim === null && class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$this->_anim = GT_BOGO_Superpower_Theme_Intelligence::animation_profile( $this->cfg() );
		}
		return $this->_anim ?? array(
			'use_gamification' => false,
			'use_entrance'     => false,
			'use_micro'        => true,
			'gamif_intensity'  => 'subtle',
			'speed_token'      => 'var(--gtbogo-sp-duration-subtle,350ms)',
			'ease_token'       => 'var(--gtbogo-sp-ease-subtle,ease)',
			'family'           => 'universal',
		);
	}


	private function styles(): array {
		// ── Theme Intelligence: single source of visual truth ─────────────
		if ( class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( $this->id );
			$m   = $cfg['multipliers'] ?? array();
			return array(
				'font_size' => $m['font_size'],
				'padding'   => $m['padding_v'] . 'px ' . $m['padding_h'] . 'px',
				'opacity'   => (string) $m['opacity'],
				'animate'   => $cfg['animate'],
				'intensity' => $cfg['intensity'],
			);
		}
		// Token-based fallback — Theme Intelligence always loaded in production
		return array(
			'font_size' => 'var(--gtbogo-sp-fs-base,0.87em)',
			'padding'   => 'var(--gtbogo-sp-pad-v,12px) var(--gtbogo-sp-pad-h,18px)',
			'opacity'   => 'var(--gtbogo-sp-opacity-secondary,0.65)',
		);
	}

	private function get_end_time(): array {
		if ( function_exists( 'gt_bogo_has_pro' ) && gt_bogo_has_pro() ) {
			global $wpdb;
			$rule = $wpdb->get_row(
				$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
					"SELECT end_date, name FROM {$wpdb->prefix}gtbogo_rules WHERE status = %s AND end_date IS NOT NULL AND end_date != '' ORDER BY priority ASC LIMIT 1",
					'active'
				),
				ARRAY_A
			);
			if ( $rule && strtotime( $rule['end_date'] ) > time() ) {
				return array(
					'ts'    => strtotime( $rule['end_date'] ),
					'label' => $rule['name'] ?? '',
				);
			}
		}
		return array(
			'ts'    => strtotime( 'tomorrow midnight' ),
			'label' => '',
		);
	}

	public function enqueue(): void {
		if ( ! function_exists( 'is_cart' ) ) {
			return;
		}
		if ( ! is_cart() && ! is_checkout() ) {
			return;
		}
		$timer = $this->get_end_time();
		wp_add_inline_style(
			'woocommerce-general',
			'
        .gtbogo-countdown{width:100%;box-sizing:border-box;font-family:inherit;color:inherit;border-top:2px solid var(--gtbogo-sp-accent,currentColor);border-bottom:2px solid var(--gtbogo-sp-accent,currentColor);text-align:center;margin-bottom:16px;background:var(--gtbogo-sp-accent-tint,transparent)}
        .gtbogo-cd-inner{display:inline-flex;align-items:center;gap:20px;flex-wrap:wrap;justify-content:center}
        .gtbogo-cd-label{font-weight:var(--gtbogo-sp-fw-ui,600);text-transform:var(--gtbogo-sp-text-transform,uppercase);letter-spacing:var(--gtbogo-sp-tracking,0.08em);font-size:var(--gtbogo-sp-fs-sm,0.78em);opacity:0.7;color:var(--gtbogo-sp-accent,inherit)}
        .gtbogo-cd-units{display:flex;gap:6px;align-items:center}
        .gtbogo-cd-unit{display:flex;flex-direction:column;align-items:center;min-width:2.8em}
        .gtbogo-cd-num{font-size:var(--gtbogo-sp-fs-xl,1.5em);font-weight:var(--gtbogo-sp-fw-ui,700);line-height:1;font-variant-numeric:tabular-nums;color:var(--gtbogo-sp-accent,inherit)}
        .gtbogo-cd-sub{font-size:var(--gtbogo-sp-fs-xs,0.52em);opacity:var(--gtbogo-sp-opacity-secondary,0.55);text-transform:var(--gtbogo-sp-text-transform,uppercase);letter-spacing:var(--gtbogo-sp-tracking,0.1em);margin-top:1px}
        .gtbogo-cd-sep{font-size:var(--gtbogo-sp-fs-lg,1.2em);opacity:0.35;font-weight:var(--gtbogo-sp-fw-light,300);padding-bottom:6px;color:var(--gtbogo-sp-accent,inherit)}
        .gtbogo-cd-vip{font-size:var(--gtbogo-sp-fs-xs,0.7em);opacity:var(--gtbogo-sp-opacity-secondary,0.6);margin-left:8px;font-style:italic}
        @media(prefers-reduced-motion:no-preference){
            .gtbogo-cd-num{transition:color var(--gtbogo-sp-duration-subtle,0.3s) ease}
        }
        
        @media(max-width:480px){
            .gtbogo-countdown-timer-wrap,.gtbogo-countdown-timer{
                font-size:var(--gtbogo-sp-fs-base,0.82em);
                padding:var(--gtbogo-sp-pad-v,10px) var(--gtbogo-sp-pad-h,14px)
            }
            .gtbogo-countdown-timer-cta,.gtbogo-countdown-timer-btn{
                min-height:var(--gtbogo-sp-touch-target,44px)
            }
        }
        @media(prefers-reduced-motion:reduce){
            .gtbogo-countdown-timer-wrap,.gtbogo-countdown-timer{transition:none!important;animation:none!important}
        }
        '
		);
		wp_add_inline_script(
			'wc-add-to-cart',
			'
        (function(){
            var end = ' . (int) $timer['ts'] . ' * 1000;
            function tick(){
                var d = end - Date.now();
                if(d <= 0){ document.querySelectorAll(".gtbogo-countdown").forEach(function(el){ el.style.display="none"; }); return; }
                var h = Math.floor(d/3600000), m = Math.floor((d%3600000)/60000), s = Math.floor((d%60000)/1000);
                document.querySelectorAll("#gtbogo-cd-h").forEach(function(el){ el.textContent=("0"+h).slice(-2); });
                document.querySelectorAll("#gtbogo-cd-m").forEach(function(el){ el.textContent=("0"+m).slice(-2); });
                document.querySelectorAll("#gtbogo-cd-s").forEach(function(el){ el.textContent=("0"+s).slice(-2); });
            }
            tick(); setInterval(tick,1000);
        })();
        ',
			'after'
		);
	}

	public function render(): void {
		$timer = $this->get_end_time();
		$s     = $this->styles();

		// ── Margin Intelligence: suppress if cart too heavily discounted ───
		if ( class_exists( 'GT_BOGO_Cart_Value_Intelligence' ) ) {
			$ratio = GT_BOGO_Cart_Value_Intelligence::get_cart_margin_ratio();
			if ( $ratio !== null && $ratio < 0.30 ) {
				return;
			}
		}

		// ── Signal Bus: escalate urgency copy ─────────────────────────────
		$base_msg = $timer['label'] ?: get_option( 'gtbogo_sp_countdown_timer_message', GT_BOGO_Copy::get( 'countdown_label', $this->intensity() ) );
		if ( class_exists( 'GT_BOGO_Signal_Bus' ) ) {
			$score = GT_BOGO_Signal_Bus::composite_score();
			if ( $score >= 1.3 ) {
				$msg = __( 'Deal ending — claim it now!', 'gt-bogo-engine' );
			} elseif ( $score >= 1.1 ) {
				$msg = $this->ai_copy( 'headline', __( 'Deal expiring soon', 'gt-bogo-engine' ) );
			} else {
				$msg = $base_msg;
			}
		} else {
			$msg = $base_msg;
		}

		// ── Profile Tracker: returning customer personalisation ────────────
		$welcome_back = '';
		if ( is_user_logged_in() && class_exists( 'GT_BOGO_Customer_Profile_Tracker' ) ) {
			$profile = GT_BOGO_Customer_Profile_Tracker::get_profile( get_current_user_id() );
			if ( $profile && (int) ( $profile->total_orders ?? 0 ) >= 2 ) {
				$welcome_back = __( 'Welcome back —', 'gt-bogo-engine' ) . ' ';
				$msg          = $welcome_back . lcfirst( $msg );
			}
		}

		// ── LTV/RFM: VIP tier label ───────────────────────────────────────
		$vip_label = '';
		if ( is_user_logged_in() ) {
			$ltv = class_exists( 'GT_BOGO_LTV_Scoring' )
				? GT_BOGO_LTV_Scoring::get_score( get_current_user_id() ) : 0.0;
			$rfm = class_exists( 'GT_BOGO_Repeat_Prediction' )
				? GT_BOGO_Repeat_Prediction::get_score( get_current_user_id() ) : 0.0;
			if ( $ltv >= 2500 || $rfm >= 4.0 ) {
				$vip_label = __( 'Platinum deal', 'gt-bogo-engine' );
			} elseif ( $ltv >= 1000 || $rfm >= 3.5 ) {
				$vip_label = __( 'Member deal', 'gt-bogo-engine' );
			}
		}
		?>
		<div class="gtbogo-countdown" style="<?php echo esc_attr( GT_BOGO_Superpower_Theme_Intelligence::style_attr( $this->cfg() ) ); ?>">
			<div class="gtbogo-cd-inner">
				<?php if ( $msg ) : ?>
				<span class="gtbogo-cd-label">
					<?php echo esc_html( $msg ); ?>
					<?php if ( $vip_label ) : ?>
					<span class="gtbogo-cd-vip"><?php echo esc_html( $vip_label ); ?></span>
					<?php endif; ?>
				</span>
				<?php endif; ?>
				<div class="gtbogo-cd-units">
					<div class="gtbogo-cd-unit"><span class="gtbogo-cd-num" id="gtbogo-cd-h">00</span><span class="gtbogo-cd-sub"><?php esc_html_e( 'hrs', 'gt-bogo-engine' ); ?></span></div>
					<span class="gtbogo-cd-sep">:</span>
					<div class="gtbogo-cd-unit"><span class="gtbogo-cd-num" id="gtbogo-cd-m">00</span><span class="gtbogo-cd-sub"><?php esc_html_e( 'min', 'gt-bogo-engine' ); ?></span></div>
					<span class="gtbogo-cd-sep">:</span>
					<div class="gtbogo-cd-unit"><span class="gtbogo-cd-num" id="gtbogo-cd-s">00</span><span class="gtbogo-cd-sub"><?php esc_html_e( 'sec', 'gt-bogo-engine' ); ?></span></div>
				</div>
			</div>
		</div>
		<?php
	}
}
