<?php
if ( ! defined( 'ABSPATH' ) ) exit;

$uniqClass   = 'woolentorblock-' . $settings['blockUniqId'];
$areaClasses = [ $uniqClass, 'woolentor_block_checkout_express' ];
! empty( $settings['align'] )     && $areaClasses[] = 'align' . $settings['align'];
! empty( $settings['className'] ) && $areaClasses[] = esc_attr( $settings['className'] );

echo '<div class="' . implode( ' ', $areaClasses ) . '">';

if ( $block['is_editor'] ) {

    // ── Editor preview ────────────────────────────────────────────────────────
    $sep_text = ! empty( $settings['separatorText'] ) ? $settings['separatorText'] : 'OR';
    $buttons  = [
        [ 'Apple Pay',       '#000000', '#ffffff' ],
        [ 'G Pay',           '#000000', '#ffffff' ],
        [ '❯ link', '#33CC66', '#ffffff' ],
    ];

    echo '<div class="wl-express-checkout-wrap wl-express-checkout-preview">';
    foreach ( $buttons as [ $label, $bg, $color ] ) {
        printf(
            '<div class="wl-express-btn-placeholder" style="background-color:%s;color:%s;">%s</div>',
            esc_attr( $bg ),
            esc_attr( $color ),
            esc_html( $label )
        );
    }

    if ( ! empty( $settings['showSeparator'] ) ) {
        echo '<p class="wl-express-checkout-separator"><span>' . esc_html( $sep_text ) . '</span></p>';
    }

} else {

    // ── Frontend ──────────────────────────────────────────────────────────────

    if ( ! class_exists( '\WC_Stripe_Express_Checkout_Element' ) ) {
        echo '<p class="wl-express-checkout-notice">' . esc_html__( 'Express Checkout requires the WooCommerce Stripe Gateway plugin.', 'woolentor' ) . '</p>';
        echo '</div>';
        return;
    }

    $stripe_ece = \WC_Stripe_Express_Checkout_Element::instance();
    if ( ! $stripe_ece ) {
        echo '<p class="wl-express-checkout-notice">' . esc_html__( 'Express Checkout is not initialized. Ensure Stripe Express Checkout is enabled in Stripe settings.', 'woolentor' ) . '</p>';
        echo '</div>';
        return;
    }

    // ── Enqueue Stripe assets ─────────────────────────────────────────────────
    if ( ! wp_script_is( 'stripe', 'registered' ) ) {
        wp_register_script( 'stripe', 'https://js.stripe.com/clover/stripe.js', [], null, true );
    }

    $asset_path = defined( 'WC_STRIPE_PLUGIN_PATH' ) ? WC_STRIPE_PLUGIN_PATH . '/build/express-checkout.asset.php' : '';
    $asset      = ( $asset_path && file_exists( $asset_path ) ) ? require $asset_path : [];
    $version    = $asset['version']      ?? ( defined( 'WC_STRIPE_VERSION' ) ? WC_STRIPE_VERSION : null );
    $deps       = $asset['dependencies'] ?? [];

    if ( ! wp_script_is( 'wc_stripe_express_checkout', 'registered' ) ) {
        $plugin_url = defined( 'WC_STRIPE_PLUGIN_URL' ) ? WC_STRIPE_PLUGIN_URL : '';
        wp_register_script(
            'wc_stripe_express_checkout',
            $plugin_url . '/build/express-checkout.js',
            array_merge( [ 'jquery', 'stripe' ], $deps ),
            $version,
            true
        );
    }

    if ( method_exists( $stripe_ece, 'javascript_params' ) ) {
        $params = apply_filters( 'wc_stripe_express_checkout_params', $stripe_ece->javascript_params() );
        $params['has_block']        = false;
        $params['is_cart_page']     = is_cart();
        $params['is_checkout_page'] = is_checkout();
        $params = apply_filters( 'woolentor/express_checkout/params', $params );
        wp_localize_script( 'wc_stripe_express_checkout', 'wc_stripe_express_checkout_params', $params );
    }

    if ( ! wp_style_is( 'wc_stripe_express_checkout_style', 'enqueued' ) ) {
        $plugin_url = defined( 'WC_STRIPE_PLUGIN_URL' ) ? WC_STRIPE_PLUGIN_URL : '';
        wp_enqueue_style( 'wc_stripe_express_checkout_style', $plugin_url . '/build/express-checkout.css', [], $version );
    }

    wp_enqueue_script( 'wc_stripe_express_checkout' );

    // Remove Stripe's default display hooks — we control placement via the block.
    remove_action( 'woocommerce_checkout_before_customer_details', [ $stripe_ece, 'display_express_checkout_button_html' ], 1 );
    remove_action( 'woocommerce_proceed_to_checkout',              [ $stripe_ece, 'display_express_checkout_button_html' ], 20 );
    remove_action( 'woocommerce_after_add_to_cart_form',           [ $stripe_ece, 'display_express_checkout_button_html' ], 1 );

    $sep_text = ! empty( $settings['separatorText'] ) ? $settings['separatorText'] : __( 'OR', 'woolentor' );

    echo '<div class="wl-express-checkout-wrap">';

    // Skeleton loader — visible until Stripe mounts its buttons.
    echo '<div class="wl-express-checkout-skeleton" aria-hidden="true">';
    echo '<div class="wl-ece-skeleton-btn"></div>';
    echo '<div class="wl-ece-skeleton-btn"></div>';
    echo '</div>';

    // Stripe button HTML — strip its internal separator to avoid duplicate IDs.
    ob_start();
    $stripe_ece->display_express_checkout_button_html();
    $stripe_html = ob_get_clean();
    $stripe_html = preg_replace(
        '/<p[^>]*\bid=["\']wc-stripe-express-checkout-button-separator["\'][^>]*>.*?<\/p>/s',
        '',
        $stripe_html
    );
    echo $stripe_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

    // Our separator
    if ( true === $settings['showSeparator'] ) {
        // ID must match what Stripe's ready event calls .show() on:
        //   getButtonSeparator: () => jQuery('#wc-stripe-express-checkout-button-separator')
        // Inner <span> lets CSS ::before/::after draw the horizontal lines.
        echo '<p class="wl-express-checkout-separator" id="wc-stripe-express-checkout-button-separator" style="display:none;">';
        echo '<span>' . esc_html( $sep_text ) . '</span>';
        echo '</p>';
    }

    // MutationObserver — hide skeleton when Stripe mounts buttons.
    echo '<script>(function(){'
       . 'var w=document.currentScript.parentElement;'
       . 'var sk=w&&w.querySelector(".wl-express-checkout-skeleton");'
       . 'var el=w&&w.querySelector("#wc-stripe-express-checkout-element");'
       . 'if(!sk||!el)return;'
       . 'function hide(){sk.style.display="none";}'
       . 'var t=setTimeout(hide,5000);'
       . 'var ob=new MutationObserver(function(){'
       . '  if(el.style.display!=="none"){ob.disconnect();clearTimeout(t);hide();}'
       . '});'
       . 'ob.observe(el,{attributes:true,attributeFilter:["style"]});'
       . '})();</script>';

    echo '</div>';
}

echo '</div>';
