<?php

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

class AIEO_SSO_Surfaces {

    public static function register() {
        
        
        add_action('woocommerce_login_form_end',     array(__CLASS__, 'render_login'),    20);
        add_action('woocommerce_register_form_end',  array(__CLASS__, 'render_register'), 20);

        
        
        
        

        
        
        add_action('woocommerce_checkout_before_customer_details', array(__CLASS__, 'render_classic_checkout'), 20);

        
        
        
        
        
        
        add_action('woocommerce_blocks_loaded', array(__CLASS__, 'register_block_checkout_integration'));
        AIEO_SSO_Block::register();

        
        
        
        add_action('roosterx_newsletter_banner_after_form', array(__CLASS__, 'render_newsletter'), 10);

        
        if (class_exists('AIEO_Magic_Link')) {
            AIEO_Magic_Link::register();
        }

        
        
        
        
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_magic_link_assets'), 25);
    }

    
    public static function enqueue_magic_link_assets() {
        if (is_admin()) { return; }

        $rel = 'assets/js/aieo-magic-link-modal.js';
        $abs = defined('AIEO_DIR') ? AIEO_DIR . $rel : '';
        if ($abs === '' || !file_exists($abs)) { return; }

        wp_enqueue_script(
            'aieo-magic-link-modal',
            plugins_url($rel, AIEO_DIR . 'ai-eshop-optimizer.php'),
            array(),
            (string) filemtime($abs),
            true
        );

        
        
        
        
        $redirect_to = home_url('/');
        if (function_exists('is_checkout') && is_checkout())                       { $redirect_to = wc_get_checkout_url(); }
        elseif (function_exists('is_account_page') && is_account_page())           { $redirect_to = wc_get_page_permalink('myaccount'); }
        elseif (isset($_SERVER['REQUEST_URI']))                                    { $redirect_to = home_url(esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']))); }

        wp_localize_script('aieo-magic-link-modal', 'aieoMagicLinkCfg', array(
            'endpoint'   => rest_url('aieo/v1/social-login/magic-link/request'),
            'intent'     => function_exists('is_checkout') && is_checkout() ? 'checkout' : 'login',
            'redirectTo' => $redirect_to,
            'i18n'       => array(
                'title'        => __('Σύνδεση με email', 'ai-eshop-optimizer'),
                'intro'        => __('Δώσε το email σου και θα σου στείλουμε σύνδεσμο σύνδεσης. Δεν χρειάζεται κωδικός.', 'ai-eshop-optimizer'),
                'emailLabel'   => __('Email', 'ai-eshop-optimizer'),
                'emailPh'      => __('name@example.com', 'ai-eshop-optimizer'),
                'submit'       => __('Στείλε μου σύνδεσμο', 'ai-eshop-optimizer'),
                'sending'      => __('Αποστολή...', 'ai-eshop-optimizer'),
                'sent'         => __('Σου στείλαμε σύνδεσμο σύνδεσης. Έλεγξε το email σου.', 'ai-eshop-optimizer'),
                'failed'       => __('Κάτι πήγε στραβά. Δοκίμασε ξανά.', 'ai-eshop-optimizer'),
                'invalidEmail' => __('Παρακαλώ δώσε έγκυρο email.', 'ai-eshop-optimizer'),
                'rateLimited'  => __('Πολλές προσπάθειες. Δοκίμασε ξανά σε λίγο.', 'ai-eshop-optimizer'),
                'close'        => __('Κλείσιμο', 'ai-eshop-optimizer'),
            ),
        ));
    }

    public static function render_login() {
        echo AIEO_SSO_Buttons::render('login', array('layout' => 'inline'));
    }

    public static function render_register() {
        echo AIEO_SSO_Buttons::render('register', array('layout' => 'inline'));
    }

    public static function render_my_account_login() {
        
        
        $html = AIEO_SSO_Buttons::render('login', array('layout' => 'inline'));
        if ($html === '') { return; }
        echo '<div class="aieo-sso-account-page-wrapper" style="margin-top:18px;text-align:center;">';
        echo '<p style="margin:0 0 12px;color:#4b5563;font-size:13px;line-height:1.5;">'
            . esc_html__('Χρησιμοποιείστε τον λογαριασμό σας Facebook ή Google για γρήγορη και ασφαλή είσοδο στο Femme Fatale. Δεν θα χρειαστεί να γράψετε το mail σας ή να δημιουργήσετε ξεχωριστό κωδικό πρόσβασης.', 'ai-eshop-optimizer')
            . '</p>';
        echo '<div style="max-width:640px;margin:0 auto;">' . $html . '</div>';
        echo '</div>';
    }

    public static function render_classic_checkout() {
        if (is_user_logged_in()) { return; }
        echo AIEO_SSO_Buttons::render('checkout', array('layout' => 'inline'));
    }

    public static function render_newsletter() {
        
        
        
        $html = AIEO_SSO_Buttons::render('subscribe', array(
            'layout' => 'inline',
            'compact' => true,
            'intro' => __('ή εγγραφείτε με:', 'ai-eshop-optimizer'),
        ));
        if ($html === '') { return; }
        echo '<div class="aieo-sso-newsletter-slot" style="margin-top:14px;">' . $html . '</div>';
    }

    
    public static function register_block_checkout_integration() {
        if (!class_exists('Automattic\\WooCommerce\\StoreApi\\StoreApi')) { return; }
        if (!class_exists('Automattic\\WooCommerce\\StoreApi\\Schemas\\ExtendSchema')) { return; }

        try {
            $extend = Automattic\WooCommerce\StoreApi\StoreApi::container()->get(
                Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema::class
            );
        } catch (\Throwable $e) {
            return;
        }

        
        
        
        
        
        
        $extend->register_endpoint_data(array(
            'endpoint'        => Automattic\WooCommerce\StoreApi\Schemas\V1\CartSchema::IDENTIFIER,
            'namespace'       => 'aieo_social_login',
            'data_callback'   => array(__CLASS__, 'block_checkout_data'),
            'schema_callback' => array(__CLASS__, 'block_checkout_schema'),
        ));

        
        
        
        
        
        
    }

    public static function block_checkout_data() {
        
        if (is_user_logged_in()) { return array('html' => ''); }
        $html = AIEO_SSO_Buttons::render('checkout', array('layout' => 'inline'));
        return array('html' => $html);
    }

    public static function block_checkout_schema() {
        return array(
            'html' => array(
                'description' => __('Pre-rendered HTML of SSO buttons.', 'ai-eshop-optimizer'),
                'type'        => 'string',
                'context'     => array('view', 'edit'),
                'readonly'    => true,
            ),
        );
    }

    public static function enqueue_block_checkout_script() {
        if (!function_exists('has_block') || !function_exists('is_checkout')) { return; }
        if (!is_checkout()) { return; }

        wp_register_script('aieo-sso-block-checkout-shim', '', array(), '1.0', true);
        wp_enqueue_script('aieo-sso-block-checkout-shim');
        wp_add_inline_script('aieo-sso-block-checkout-shim', self::block_checkout_inline_js());
    }

    public static function noop_filter($x) { return $x; }

    
    private static function block_checkout_inline_js() {
        return <<<'JS'
(function(){
  function inject(html) {
    if (window.__aieoSsoInjected) return;
    var contact = document.querySelector('[data-block-name="woocommerce/checkout-contact-information-block"]');
    if (!contact || !html) return;
    var holder = document.createElement('div');
    holder.className = 'aieo-sso-block-checkout-slot';
    holder.style.margin = '0 0 18px';
    holder.innerHTML = html;
    contact.parentNode.insertBefore(holder, contact);
    window.__aieoSsoInjected = true;
  }
  function tryFromStore() {
    if (window.__aieoSsoInjected) return true;
    if (typeof wp === 'undefined' || !wp.data) return false;
    try {
      var sel = wp.data.select('wc/store/cart');
      if (!sel || typeof sel.getCartData !== 'function') return false;
      var cart = sel.getCartData();
      if (!cart || !cart.extensions || !cart.extensions.aieo_social_login) return false;
      inject(cart.extensions.aieo_social_login.html || '');
      return !!window.__aieoSsoInjected;
    } catch(e) { return false; }
  }
  function tryFromFetch() {
    fetch('/wp-json/wc/store/v1/cart', { credentials:'same-origin', headers:{ 'Accept':'application/json' } })
      .then(function(r){ return r.ok ? r.json() : null; })
      .then(function(j){
        if (!j || !j.extensions || !j.extensions.aieo_social_login) return;
        inject(j.extensions.aieo_social_login.html || '');
      })
      .catch(function(){});
  }
  // Poll the redux store first (zero network); fall back to a single
  // fetch on the cart endpoint if the store isn't populated yet.
  var tries = 0;
  var t = setInterval(function(){
    if (tryFromStore()) { clearInterval(t); return; }
    if (++tries > 8) { clearInterval(t); tryFromFetch(); }
  }, 300);
})();
JS;
    }
}
