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

/**
 * @param string $hex
 * @param string $default
 * @return string
 */
function elementsell_payment_normalize_hex_color( $hex, $default = '#22c55e' ) {
    $hex = trim( (string) $hex );

    if ( preg_match( '/^#([a-f0-9]{3})$/i', $hex, $matches ) ) {
        $short = $matches[1];

        return strtolower(
            sprintf(
                '#%s%s%s',
                $short[0] . $short[0],
                $short[1] . $short[1],
                $short[2] . $short[2]
            )
        );
    }

    if ( preg_match( '/^#([a-f0-9]{6})$/i', $hex ) ) {
        return strtolower( $hex );
    }

    return strtolower( $default );
}

/**
 * @param string $hex
 * @param float  $white_ratio
 * @return string
 */
function elementsell_payment_mix_hex_with_white( $hex, $white_ratio = 0.86 ) {
    $hex         = ltrim( elementsell_payment_normalize_hex_color( $hex ), '#' );
    $white_ratio = max( 0.0, min( 1.0, (float) $white_ratio ) );
    $color_ratio = 1 - $white_ratio;
    $r           = (int) round( hexdec( substr( $hex, 0, 2 ) ) * $color_ratio + 255 * $white_ratio );
    $g           = (int) round( hexdec( substr( $hex, 2, 2 ) ) * $color_ratio + 255 * $white_ratio );
    $b           = (int) round( hexdec( substr( $hex, 4, 2 ) ) * $color_ratio + 255 * $white_ratio );

    return sprintf( '#%02x%02x%02x', $r, $g, $b );
}

/**
 * @param string $hex
 * @return array{0: float, 1: float, 2: float}
 */
function elementsell_payment_hex_to_hsl( $hex ) {
    $hex = ltrim( elementsell_payment_normalize_hex_color( $hex ), '#' );
    $r   = hexdec( substr( $hex, 0, 2 ) ) / 255;
    $g   = hexdec( substr( $hex, 2, 2 ) ) / 255;
    $b   = hexdec( substr( $hex, 4, 2 ) ) / 255;
    $max = max( $r, $g, $b );
    $min = min( $r, $g, $b );
    $l   = ( $max + $min ) / 2;

    if ( $max === $min ) {
        return [ 0.0, 0.0, $l ];
    }

    $d = $max - $min;
    $s = $l > 0.5 ? $d / ( 2 - $max - $min ) : $d / ( $max + $min );

    if ( $max === $r ) {
        $h = ( $g - $b ) / $d + ( $g < $b ? 6 : 0 );
    } elseif ( $max === $g ) {
        $h = ( $b - $r ) / $d + 2;
    } else {
        $h = ( $r - $g ) / $d + 4;
    }

    return [ $h / 6, $s, $l ];
}

/**
 * @param float $h 0–1
 * @param float $s 0–1
 * @param float $l 0–1
 * @return string
 */
function elementsell_payment_hsl_to_hex( $h, $s, $l ) {
    $h = fmod( (float) $h, 1.0 );
    if ( $h < 0 ) {
        $h += 1.0;
    }

    $s = max( 0.0, min( 1.0, (float) $s ) );
    $l = max( 0.0, min( 1.0, (float) $l ) );

    if ( $s === 0.0 ) {
        $channel = (int) round( $l * 255 );

        return sprintf( '#%02x%02x%02x', $channel, $channel, $channel );
    }

    $q = $l < 0.5 ? $l * ( 1 + $s ) : $l + $s - ( $l * $s );
    $p = ( 2 * $l ) - $q;

    $r = elementsell_payment_hue_to_rgb_channel( $p, $q, $h + ( 1 / 3 ) );
    $g = elementsell_payment_hue_to_rgb_channel( $p, $q, $h );
    $b = elementsell_payment_hue_to_rgb_channel( $p, $q, $h - ( 1 / 3 ) );

    return sprintf( '#%02x%02x%02x', (int) round( $r * 255 ), (int) round( $g * 255 ), (int) round( $b * 255 ) );
}

/**
 * @param float $p
 * @param float $q
 * @param float $t
 * @return float
 */
function elementsell_payment_hue_to_rgb_channel( $p, $q, $t ) {
    if ( $t < 0 ) {
        $t += 1;
    }

    if ( $t > 1 ) {
        $t -= 1;
    }

    if ( $t < ( 1 / 6 ) ) {
        return $p + ( ( $q - $p ) * 6 * $t );
    }

    if ( $t < 0.5 ) {
        return $q;
    }

    if ( $t < ( 2 / 3 ) ) {
        return $p + ( ( $q - $p ) * ( ( 2 / 3 ) - $t ) * 6 );
    }

    return $p;
}

/**
 * @param string $hex
 * @return float
 */
function elementsell_payment_relative_luminance( $hex ) {
    $hex = ltrim( elementsell_payment_normalize_hex_color( $hex ), '#' );
    $channels = [];

    foreach ( [ 0, 2, 4 ] as $offset ) {
        $value = hexdec( substr( $hex, $offset, 2 ) ) / 255;
        $channels[] = $value <= 0.03928 ? $value / 12.92 : pow( ( $value + 0.055 ) / 1.055, 2.4 );
    }

    return ( 0.2126 * $channels[0] ) + ( 0.7152 * $channels[1] ) + ( 0.0722 * $channels[2] );
}

/**
 * @param string $foreground
 * @param string $background
 * @return float
 */
function elementsell_payment_contrast_ratio( $foreground, $background ) {
    $l1 = elementsell_payment_relative_luminance( $foreground );
    $l2 = elementsell_payment_relative_luminance( $background );
    $lighter = max( $l1, $l2 );
    $darker  = min( $l1, $l2 );

    return ( $lighter + 0.05 ) / ( $darker + 0.05 );
}

/**
 * Komplementární barva textu čitelná na pozadí v barvě tlačítka.
 *
 * @param string $background_hex
 * @return string
 */
function elementsell_payment_get_complementary_text_color( $background_hex ) {
    [ $h, $s ] = elementsell_payment_hex_to_hsl( $background_hex );
    $h          = fmod( $h + 0.5, 1.0 );
    $candidates = [
        elementsell_payment_hsl_to_hex( $h, min( 1.0, $s + 0.15 ), 0.96 ),
        elementsell_payment_hsl_to_hex( $h, min( 1.0, $s + 0.1 ), 0.12 ),
        '#ffffff',
        '#111827',
    ];

    $best_color  = '#ffffff';
    $best_ratio  = 0.0;

    foreach ( $candidates as $candidate ) {
        $ratio = elementsell_payment_contrast_ratio( $candidate, $background_hex );

        if ( $ratio > $best_ratio ) {
            $best_ratio = $ratio;
            $best_color = $candidate;
        }
    }

    return strtolower( $best_color );
}

trait ElementSell_Widget_Render {

    protected function render_form() {
        $this->render_form_content();
    }

    private function render_form_content() {
        $settings   = $this->get_settings_for_display();
        $amount     = isset( $settings['amount'] ) ? (float) $settings['amount'] : 100.0;
        $is_editor  = elementsell_is_elementor_editor_render();
        $widget_id  = $this->get_id();

        $payment_context = apply_filters(
            'elementsell_payment_form_context',
            [
                'amount'      => $amount,
                'settings'    => $settings,
                'widget_id'   => $widget_id,
                'is_editor'   => $is_editor,
                'offer_token' => '',
            ],
            $settings
        );

        if ( is_array( $payment_context ) ) {
            if ( ! empty( $payment_context['amount_override'] ) ) {
                $amount = (float) $payment_context['amount_override'];
            }

            if ( ! empty( $payment_context['settings_overrides'] ) && is_array( $payment_context['settings_overrides'] ) ) {
                $settings = array_merge( $settings, $payment_context['settings_overrides'] );
            }
        }

        $promo_text   = is_array( $payment_context ) ? (string) ( $payment_context['promo_text'] ?? '' ) : '';
        $offer_token  = is_array( $payment_context ) ? sanitize_text_field( (string) ( $payment_context['offer_token'] ?? '' ) ) : '';
        $prefill_email = is_array( $payment_context ) ? sanitize_email( (string) ( $payment_context['prefill_email'] ?? '' ) ) : '';
        $offer_error  = is_array( $payment_context ) ? (string) ( $payment_context['offer_error'] ?? '' ) : '';
        $is_action_offer = is_array( $payment_context ) && ! empty( $payment_context['is_action_offer'] );
        $flash_countdown_end = is_array( $payment_context ) ? (int) ( $payment_context['flash_countdown_end'] ?? 0 ) : 0;
        $flash_countdown_start = is_array( $payment_context ) ? (int) ( $payment_context['flash_countdown_start'] ?? 0 ) : 0;
        $action_discount_reason = is_array( $payment_context ) ? trim( (string) ( $payment_context['action_discount_reason'] ?? '' ) ) : '';
        $action_discount_percent = is_array( $payment_context ) ? max( 0, (int) ( $payment_context['action_discount_percent'] ?? 0 ) ) : 0;

        if ( is_array( $payment_context ) && ! empty( $payment_context['crossed_amount_override'] ) ) {
            $settings['crossed_amount'] = (float) $payment_context['crossed_amount_override'];
        }

        if ( $action_discount_percent <= 0 && ! empty( $settings['crossed_amount'] ) && (float) $settings['crossed_amount'] > $amount ) {
            $action_discount_percent = (int) round( ( 1 - ( $amount / (float) $settings['crossed_amount'] ) ) * 100 );
        }

        $show_action_price_in_banner = $is_action_offer
            && $flash_countdown_end > time()
            && $action_discount_reason !== ''
            && ! empty( $settings['crossed_amount'] )
            && (float) $settings['crossed_amount'] > $amount;

        $action_accent_color    = elementsell_payment_normalize_hex_color( $settings['button_color'] ?? '' );
        $accent_parts           = sscanf( ltrim( $action_accent_color, '#' ), '%02x%02x%02x' );
        $action_accent_shadow_rgb = is_array( $accent_parts ) && count( $accent_parts ) === 3
            ? implode( ', ', array_map( 'intval', $accent_parts ) )
            : '34, 197, 94';

        $lock_email   = $offer_token !== '' && $prefill_email !== '';
        $wrapper_id = 'elementsell-payment-' . $widget_id;
        $form_id    = 'payment-form-' . $widget_id;

        if ( ! $is_editor && ! get_option( 'custom_widget_used' ) ) {
            update_option( 'custom_widget_used', true );
        }

        $nonce             = $is_editor ? '' : wp_create_nonce( 'discount_nonce' );
        $billing_attention = ( $is_editor || elementsell_is_elementor_context() )
            ? false
            : elementsell_should_show_billing_form_hint();
        $required_attr    = $is_editor ? '' : ' required';
        $button_type      = $is_editor ? 'button' : 'submit';
        $form_action      = $is_editor ? '#' : esc_url( admin_url( 'admin-post.php' ) );
        $form_target      = $is_editor ? '' : ' target="_blank"';
        $form_onsubmit    = $is_editor ? ' onsubmit="return false;"' : '';
        $discount_id      = 'discount_code-' . $widget_id;
        $original_price_id = 'original-price-' . $widget_id;
        $final_amount_id  = 'final_amount-' . $widget_id;
        $source_page_id   = 'elementsell_source_page_url-' . $widget_id;
        $upsell_enabled   = elementsell_upsell_is_enabled( $settings );
        $upsell_price     = $upsell_enabled ? (int) elementsell_get_upsell_price( $settings ) : 0;

        if ( ! $is_editor ) {
            $navratova_url      = esc_attr( $settings['navratova_url'] );
            $create_profile     = isset( $settings['create_profile'] ) && $settings['create_profile'] === 'yes' ? 1 : 0;
            $login_url          = esc_attr( $settings['login_url'] );
            $source_post_id     = elementsell_get_payment_widget_document_post_id( $this );
            $source_page_url    = '';

            if ( $source_post_id > 0 ) {
                $source_page_url = (string) get_permalink( $source_post_id );
            } elseif ( is_singular() ) {
                $source_page_url = (string) get_permalink( (int) get_queried_object_id() );
            }
            $email_from_name = isset( $settings['email_from_name'] ) ? trim( (string) $settings['email_from_name'] ) : '';

            if (
                function_exists( 'elementsell_is_legacy_widget_sender_name' )
                && elementsell_is_legacy_widget_sender_name( $email_from_name )
            ) {
                $email_from_name = function_exists( 'elementsell_get_sender_name' )
                    ? elementsell_get_sender_name()
                    : ( function_exists( 'elementsell_get_widget_email_from_name_default' )
                        ? elementsell_get_widget_email_from_name_default()
                        : '' );
            }

            if ( ! empty( $settings['meta_pixel_code'] ) ) {
                echo $settings['meta_pixel_code'];
            }
        }

        ?>

        <div id="<?php echo esc_attr( $wrapper_id ); ?>" class="elementsell-payment-widget<?php echo $billing_attention ? ' elementsell-payment-widget--attention' : ''; ?>" style="text-align:center; position: relative; scroll-margin-top: 80px;">
            <?php if ( $billing_attention ) : ?>
                <?php elementsell_render_billing_form_attention_notice(); ?>
            <?php endif; ?>

            <?php if ( $promo_text !== '' && ! $is_action_offer ) : ?>
                <div class="elementsell-automation-promo" style="margin:0 0 14px;padding:12px 16px;border-radius:10px;background:#f0f9ff;color:#0c4a6e;font-size:15px;line-height:1.45;">
                    <?php echo wp_kses_post( wpautop( $promo_text ) ); ?>
                </div>
            <?php endif; ?>

            <?php if ( $offer_error !== '' ) : ?>
                <div class="elementsell-automation-offer-error" style="margin:0 0 14px;padding:12px 16px;border-radius:10px;background:#fef2f2;color:#991b1b;font-size:14px;">
                    <?php echo esc_html( $offer_error ); ?>
                </div>
            <?php endif; ?>

            <form id="<?php echo esc_attr( $form_id ); ?>" class="elementsell-payment-form" method="POST" action="<?php echo $form_action; ?>"<?php echo $form_target . $form_onsubmit; ?>>
                <?php if ( $is_action_offer && $flash_countdown_end > time() && $action_discount_reason !== '' ) : ?>
                    <div
                        class="elementsell-action-offer"
                        role="status"
                        aria-live="polite"
                        style="--es-action-accent: <?php echo esc_attr( $action_accent_color ); ?>; --es-action-shadow: <?php echo esc_attr( $action_accent_shadow_rgb ); ?>;"
                    >
                        <?php if ( $show_action_price_in_banner && $action_discount_percent > 0 ) : ?>
                            <span class="elementsell-action-offer__badge">−<?php echo (int) $action_discount_percent; ?> %</span>
                        <?php endif; ?>
                        <p class="elementsell-action-offer__title"><?php echo esc_html( $action_discount_reason ); ?></p>
                        <?php if ( $show_action_price_in_banner ) : ?>
                            <div class="elementsell-action-offer__divider" aria-hidden="true"></div>
                            <div class="elementsell-action-offer__price-row">
                                <span class="elementsell-action-offer__price-old">
                                    <?php echo esc_html( number_format( (float) $settings['crossed_amount'], 0, ',', ' ' ) ); ?> Kč
                                </span>
                                <span class="elementsell-action-offer__price-new" id="<?php echo esc_attr( $original_price_id ); ?>">
                                    <?php echo esc_html( number_format( (float) $amount, 0, ',', ' ' ) ); ?> Kč
                                </span>
                                <span class="elementsell-action-offer__spark" aria-hidden="true">
                                    <svg viewBox="0 0 24 24" width="18" height="18" focusable="false" aria-hidden="true">
                                        <path fill="currentColor" d="M12 2l1.2 4.2L17 7l-3.8 1.8L12 13l-1.2-4.2L7 7l3.8-1.8L12 2zm7 9l.8 2.8L22 14l-2.2 1.2L19 18l-.8-2.8L16 14l2.2-1.2L19 11zm-14 5l.7 2.3L8 19l-2.3 1.2L5 22l-.7-2.3L2 19l2.3-1.2L5 16z"></path>
                                    </svg>
                                </span>
                            </div>
                        <?php endif; ?>
                        <p class="elementsell-action-offer__timer-row">
                            <span class="elementsell-action-offer__timer-wrap">
                                <span id="elementsell-countdown-<?php echo esc_attr( $widget_id ); ?>" class="elementsell-action-offer__timer">--:--:--</span>
                            </span>
                        </p>
                    </div>
                <?php endif; ?>

                <?php if ( ! $is_editor ) : ?>
                    <input type="hidden" name="action" value="elementsell_payment">
                    <?php wp_nonce_field( 'platebni_formular_nonce' ); ?>
                    <div class="elementsell-hp" aria-hidden="true">
                        <label for="elementsell-hp-<?php echo esc_attr( $widget_id ); ?>">Nevyplňovat</label>
                        <input type="text" id="elementsell-hp-<?php echo esc_attr( $widget_id ); ?>" name="elementsell_hp" tabindex="-1" autocomplete="off">
                    </div>
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_name'] ) : ?>
                    <input type="text" name="first_name" placeholder="Jméno" class="elementsell-field"<?php echo $required_attr; ?>>
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_surname'] ) : ?>
                    <input type="text" name="surname" placeholder="Příjmení" class="elementsell-field"<?php echo $required_attr; ?>>
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_email'] ) : ?>
                    <input type="email" name="email" placeholder="Email" class="elementsell-field" value="<?php echo esc_attr( $prefill_email ); ?>"<?php echo $required_attr; ?><?php echo $lock_email ? ' readonly' : ''; ?>>
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_phone'] ) : ?>
                    <input type="tel" name="phone" placeholder="Telefonní číslo" class="elementsell-field"<?php echo $required_attr; ?>>
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_address'] ) : ?>
                    <input type="text" name="address" placeholder="Adresa" class="elementsell-field"<?php echo $required_attr; ?>>
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_company'] ) : ?>
                    <input type="text" name="company" placeholder="Firma" class="elementsell-field">
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_ico'] ) : ?>
                    <input type="text" name="ico" placeholder="IČO" class="elementsell-field">
                <?php endif; ?>

                <?php if ( 'yes' === $settings['show_dic'] ) : ?>
                    <input type="text" name="dic" placeholder="DIČ" class="elementsell-field">
                <?php endif; ?>

                <?php
                $custom_fields = elementsell_get_custom_fields_from_widget_settings( $settings );

                foreach ( $custom_fields as $custom_field_index => $custom_field ) :
                    elementsell_render_payment_custom_field(
                        $custom_field,
                        $custom_field_index,
                        $is_editor,
                        $required_attr
                    );
                endforeach;
                ?>

                <?php if ( 'yes' === $settings['show_discount_code'] ) : ?>
                    <input type="text" id="<?php echo esc_attr( $discount_id ); ?>" name="discount_code" placeholder="Slevový kód" class="elementsell-field">
                <?php endif; ?>

                <?php if ( ! $show_action_price_in_banner && ! empty( $settings['crossed_amount'] ) ) : ?>
                    <div class="elementsell-price-block">
                        <div id="crossed-price-<?php echo esc_attr( $widget_id ); ?>" class="elementsell-price-old">
                            <?php echo number_format( $settings['crossed_amount'], 0, ',', ' ' ); ?> Kč
                        </div>
                <?php endif; ?>

                <?php if ( ! $show_action_price_in_banner ) : ?>
                <div class="elementsell-price-main<?php echo ! empty( $settings['crossed_amount'] ) ? '' : ' elementsell-price-main--solo'; ?>" id="<?php echo esc_attr( $original_price_id ); ?>">
                    <?php echo number_format( (float) $amount, 0, ',', ' ' ); ?> Kč
                </div>
                <?php endif; ?>

                <?php if ( ! $show_action_price_in_banner && ! empty( $settings['crossed_amount'] ) ) : ?>
                    </div>
                <?php endif; ?>

                <?php if ( ! $is_editor ) : ?>
                    <input type="hidden" id="<?php echo esc_attr( $final_amount_id ); ?>" name="amount" value="<?php echo esc_attr( (string) $amount ); ?>">
                    <input type="hidden" name="elementsell_post_id" value="<?php echo esc_attr( (string) $source_post_id ); ?>">
                    <input type="hidden" name="elementsell_widget_id" value="<?php echo esc_attr( $widget_id ); ?>">
                    <input type="hidden" name="email_subject" value="<?php echo esc_attr( $settings['email_subject'] ); ?>">
                    <input type="hidden" name="email_body" value="<?php echo esc_attr( $settings['email_body'] ); ?>">
                    <input type="hidden" name="email_from_name" value="<?php echo esc_attr( $email_from_name ); ?>">
                    <input type="hidden" name="product_name" value="<?php echo esc_attr( $settings['product_name'] ); ?>">
                    <input type="hidden" name="navratova_url" value="<?php echo esc_attr( $navratova_url ); ?>">
                    <input type="hidden" name="vytvorit_profil" value="<?php echo $create_profile; ?>">
                    <input type="hidden" name="login_url" value="<?php echo esc_attr( $login_url ); ?>">
                    <input type="hidden" name="payment_method" value="<?php echo esc_attr( $settings['payment_method'] ); ?>">
                    <input type="hidden" id="<?php echo esc_attr( $source_page_id ); ?>" name="source_page_url" value="<?php echo esc_url( $source_page_url ); ?>">
                    <input type="hidden" name="upsell_accepted" id="upsell_accepted-<?php echo esc_attr( $widget_id ); ?>" value="0">
                    <input type="hidden" name="upsell_decided" id="upsell_decided-<?php echo esc_attr( $widget_id ); ?>" value="0">
                    <?php if ( $offer_token !== '' ) : ?>
                        <input type="hidden" name="es_offer_token" value="<?php echo esc_attr( $offer_token ); ?>">
                    <?php endif; ?>
                <?php endif; ?>

                <button type="<?php echo esc_attr( $button_type ); ?>" class="platebni-button">
                    <?php echo esc_html( $settings['button_text'] ); ?>
                </button>

                <?php elementsell_render_payment_consent_notice( $is_editor ); ?>
            </form>

            <?php elementsell_render_payment_form_byline(); ?>
            <?php elementsell_render_payment_upsell_modal( $settings, $wrapper_id, $widget_id, $is_editor ); ?>
        </div>

        <?php if ( ! $is_editor ) : ?>
            <script nonce="<?php echo esc_attr( $nonce ); ?>">
            document.addEventListener('DOMContentLoaded', function () {
                var form = document.getElementById(<?php echo wp_json_encode( $form_id ); ?>);
                var wrapper = document.getElementById(<?php echo wp_json_encode( $wrapper_id ); ?>);
                if (!form || !wrapper) return;

                <?php if ( $is_action_offer && $flash_countdown_end > time() ) : ?>
                (function () {
                    var countdownEl = document.getElementById(<?php echo wp_json_encode( 'elementsell-countdown-' . $widget_id ); ?>);
                    var endTs = <?php echo (int) $flash_countdown_end; ?> * 1000;

                    function pad(n) { return n < 10 ? '0' + n : String(n); }

                    function updateCountdown() {
                        if (!countdownEl) return;
                        var diff = endTs - Date.now();
                        if (diff <= 0) {
                            countdownEl.textContent = '00:00:00';
                            return;
                        }
                        var totalSec = Math.floor(diff / 1000);
                        var days = Math.floor(totalSec / 86400);
                        var hours = Math.floor((totalSec % 86400) / 3600);
                        var mins = Math.floor((totalSec % 3600) / 60);
                        var secs = totalSec % 60;
                        countdownEl.textContent = (days > 0 ? days + 'd ' : '') + pad(hours) + ':' + pad(mins) + ':' + pad(secs);
                    }

                    updateCountdown();
                    setInterval(updateCountdown, 1000);
                })();
                <?php endif; ?>

                var source = document.getElementById(<?php echo wp_json_encode( $source_page_id ); ?>);
                var originalPrice = <?php echo wp_json_encode( (float) $amount ); ?>;
                var upsellPrice = <?php echo wp_json_encode( (float) $upsell_price ); ?>;
                var upsellEnabled = <?php echo $upsell_enabled ? 'true' : 'false'; ?>;
                var originalPriceId = <?php echo wp_json_encode( $original_price_id ); ?>;
                var finalAmountId = <?php echo wp_json_encode( $final_amount_id ); ?>;
                var upsellAcceptedInput = document.getElementById(<?php echo wp_json_encode( 'upsell_accepted-' . $widget_id ); ?>);
                var upsellDecidedInput = document.getElementById(<?php echo wp_json_encode( 'upsell_decided-' . $widget_id ); ?>);
                var upsellModal = document.getElementById(<?php echo wp_json_encode( 'elementsell-upsell-' . $widget_id ); ?>);
                var discountField = document.getElementById(<?php echo wp_json_encode( $discount_id ); ?>);
                var discounts = {};
                var pendingSubmit = false;
                var prefillStorageKey = 'elementsell_form_prefill_' + <?php echo wp_json_encode( $widget_id ); ?>;
                var lockEmailField = <?php echo $lock_email ? 'true' : 'false'; ?>;
                var prefillFieldNames = [
                    'first_name',
                    'surname',
                    'email',
                    'phone',
                    'address',
                    'company',
                    'ico',
                    'dic',
                    'discount_code'
                ];
                <?php if ( ! empty( $settings['discount_codes'] ) && is_array( $settings['discount_codes'] ) ) : ?>
                    <?php foreach ( $settings['discount_codes'] as $code ) : ?>
                        discounts[<?php echo wp_json_encode( strtolower( (string) $code['code'] ) ); ?>] = <?php echo (float) $code['discount']; ?> / 100;
                    <?php endforeach; ?>
                <?php endif; ?>

                function collectFormPrefillData() {
                    var data = { fields: {}, custom: {} };

                    prefillFieldNames.forEach(function (name) {
                        var input = form.elements[name];

                        if ( ! input || input.type === 'password' ) {
                            return;
                        }

                        if ( name === 'email' && lockEmailField ) {
                            return;
                        }

                        if ( input.type === 'checkbox' ) {
                            data.fields[name] = input.checked ? '1' : '';
                        } else {
                            data.fields[name] = input.value;
                        }
                    } );

                    form.querySelectorAll(
                        'input[name^="elementsell_custom_fields["], select[name^="elementsell_custom_fields["]'
                    ).forEach(function (input) {
                        var match = input.name.match( /^elementsell_custom_fields\[(\d+)\]\[value\]$/ );

                        if ( ! match ) {
                            return;
                        }

                        if ( input.type === 'checkbox' ) {
                            data.custom[match[1]] = input.checked ? '1' : '';
                        } else {
                            data.custom[match[1]] = input.value;
                        }
                    } );

                    return data;
                }

                function restoreFormPrefillData( data ) {
                    if ( ! data || typeof data !== 'object' ) {
                        return;
                    }

                    if ( data.fields && typeof data.fields === 'object' ) {
                        prefillFieldNames.forEach(function (name) {
                            if ( ! Object.prototype.hasOwnProperty.call( data.fields, name ) ) {
                                return;
                            }

                            if ( name === 'email' && lockEmailField ) {
                                return;
                            }

                            var input = form.elements[name];

                            if ( ! input || input.readOnly ) {
                                return;
                            }

                            if ( input.type === 'checkbox' ) {
                                input.checked = data.fields[name] === '1';
                            } else {
                                input.value = data.fields[name];
                            }
                        } );
                    }

                    if ( data.custom && typeof data.custom === 'object' ) {
                        Object.keys( data.custom ).forEach(function (index) {
                            var input = form.querySelector(
                                '[name="elementsell_custom_fields[' + index + '][value]"]'
                            );

                            if ( ! input ) {
                                return;
                            }

                            if ( input.type === 'checkbox' ) {
                                input.checked = data.custom[index] === '1';
                            } else {
                                input.value = data.custom[index];
                            }
                        } );
                    }
                }

                function saveFormPrefillData() {
                    try {
                        localStorage.setItem(
                            prefillStorageKey,
                            JSON.stringify( collectFormPrefillData() )
                        );
                    } catch (err) {}
                }

                function loadFormPrefillData() {
                    try {
                        var raw = localStorage.getItem( prefillStorageKey );

                        if ( ! raw ) {
                            return;
                        }

                        restoreFormPrefillData( JSON.parse( raw ) );
                    } catch (err) {}
                }

                function getDiscountedBase() {
                    var finalPrice = originalPrice;

                    if (discountField) {
                        var discountCode = discountField.value.trim().toLowerCase();
                        if (discountCode !== '' && discounts.hasOwnProperty(discountCode)) {
                            finalPrice = originalPrice * (1 - discounts[discountCode]);
                        }
                    }

                    return Math.round(finalPrice);
                }

                function updateDisplayedAmount() {
                    var total = getDiscountedBase();

                    if (upsellAcceptedInput && upsellAcceptedInput.value === '1') {
                        total += upsellPrice;
                    }

                    var priceEl = document.getElementById(originalPriceId);
                    var amountEl = document.getElementById(finalAmountId);

                    if (priceEl) {
                        priceEl.innerHTML = total + ' Kč';
                    }
                    if (amountEl) {
                        amountEl.value = String(total);
                    }
                }

                function finalizeUpsellChoice(accepted) {
                    if (upsellAcceptedInput) {
                        upsellAcceptedInput.value = accepted ? '1' : '0';
                    }
                    if (upsellDecidedInput) {
                        upsellDecidedInput.value = '1';
                    }
                    if (upsellModal) {
                        upsellModal.setAttribute('hidden', 'hidden');
                    }
                    updateDisplayedAmount();
                    pendingSubmit = true;
                    form.submit();
                }

                if (discountField) {
                    discountField.addEventListener('input', updateDisplayedAmount);
                }

                loadFormPrefillData();
                updateDisplayedAmount();

                if (upsellModal) {
                    upsellModal.querySelectorAll('[data-upsell-accept]').forEach(function(button) {
                        button.addEventListener('click', function() {
                            finalizeUpsellChoice(button.getAttribute('data-upsell-accept') === '1');
                        });
                    });
                }

                form.addEventListener('submit', function(event) {
                    saveFormPrefillData();

                    if (source) {
                        var pageUrl = window.location.href.split('#')[0];

                        try {
                            var cleanUrl = new URL(pageUrl);
                            [ 'preview', 'preview_id', 'preview_nonce', 'elementor-preview' ].forEach(function (key) {
                                cleanUrl.searchParams.delete(key);
                            });
                            pageUrl = cleanUrl.toString();
                        } catch (e) {}

                        source.value = pageUrl + '#' + <?php echo wp_json_encode( $wrapper_id ); ?>;
                    }

                    if (pendingSubmit) {
                        return;
                    }

                    updateDisplayedAmount();

                    if (upsellEnabled && upsellDecidedInput && upsellDecidedInput.value !== '1') {
                        event.preventDefault();
                        if (upsellModal) {
                            upsellModal.removeAttribute('hidden');
                        }
                        return;
                    }

                    if (typeof fbq !== 'undefined') {
                        var amountEl = document.getElementById(finalAmountId);
                        fbq('track', 'InitiateCheckout', {
                            value: amountEl ? parseFloat(amountEl.value || '0') : originalPrice,
                            currency: 'CZK'
                        });
                    }
                });
            });
            </script>
        <?php endif; ?>

        <style>
        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-form {
            width: 100%;
            margin: 0 auto;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-hp {
            position: absolute;
            left: -10000px;
            width: 1px;
            height: 1px;
            overflow: hidden;
            opacity: 0;
            pointer-events: none;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer {
            width: 100%;
            margin: 0 0 14px;
            padding: 20px 18px 18px;
            border: 1px solid #e8edf2;
            border-radius: 16px;
            background: #ffffff;
            text-align: center;
            box-sizing: border-box;
            box-shadow: 0 10px 28px rgba(15, 23, 42, 0.08);
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__badge {
            display: inline-block;
            margin: 0 0 12px;
            padding: 6px 14px;
            border-radius: 999px;
            background: var(--es-action-accent);
            color: #ffffff;
            font-size: 14px;
            font-weight: 700;
            line-height: 1.2;
            letter-spacing: 0.02em;
            box-shadow: 0 6px 16px rgba(var(--es-action-shadow), 0.22);
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__title {
            margin: 0 0 14px;
            font-size: 18px;
            font-weight: 700;
            line-height: 1.35;
            color: #111827;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__divider {
            height: 1px;
            margin: 0 0 16px;
            background: #eef2f6;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__price-row {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-wrap: wrap;
            gap: 10px 12px;
            margin: 0 0 14px;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__price-old {
            color: #9ca3af;
            font-size: 18px;
            font-weight: 500;
            line-height: 1.2;
            text-decoration: line-through;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__price-new {
            color: var(--es-action-accent);
            font-size: 36px;
            font-weight: 800;
            line-height: 1;
            font-variant-numeric: tabular-nums;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__spark {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: var(--es-action-accent);
            opacity: 0.9;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__timer-row {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__timer-wrap {
            display: inline-flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 999px;
            background: color-mix(in srgb, var(--es-action-accent) 10%, #ffffff);
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-action-offer__timer {
            color: var(--es-action-accent);
            font-size: 14px;
            font-weight: 700;
            font-variant-numeric: tabular-nums;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field {
            display: block;
            width: 100%;
            margin: 0 0 12px;
            padding: 14px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            background: #f9fafb;
            font-size: 16px;
            line-height: 1.4;
            color: #111827;
            box-sizing: border-box;
            outline: none;
            transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
            -webkit-appearance: none;
            appearance: none;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field::placeholder {
            color: #9ca3af;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field:hover {
            border-color: #d1d5db;
            background: #ffffff;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field:focus {
            border-color: #9ca3af;
            background: #ffffff;
            box-shadow: 0 0 0 3px rgba(17, 24, 39, 0.08);
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field:-webkit-autofill,
        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field:-webkit-autofill:hover,
        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field:-webkit-autofill:focus {
            -webkit-box-shadow: 0 0 0 1000px #f9fafb inset !important;
            -webkit-text-fill-color: #111827 !important;
            transition: background-color 9999s ease-out 0s;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> input[type="date"].elementsell-field {
            min-height: 52px;
            color-scheme: light;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-custom-field--date {
            margin: 0 0 12px;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-custom-field--date .elementsell-field {
            margin-bottom: 0;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-field-label {
            display: block;
            margin: 0 0 6px;
            font-size: 14px;
            font-weight: 600;
            line-height: 1.4;
            color: #374151;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-date-value {
            padding: 14px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            background: #f9fafb;
            font-size: 16px;
            line-height: 1.4;
            color: #111827;
            box-sizing: border-box;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-price-block {
            margin: 4px 0 18px;
            text-align: center;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-price-old {
            text-decoration: line-through;
            line-height: 1.3;
            margin-bottom: 4px;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-price-main {
            line-height: 1.2;
            margin: 0 0 18px;
            text-align: center;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-price-main--solo {
            margin-top: 4px;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-billing-form-hint {
            display: block;
            margin: 0 auto 16px;
            max-width: 66%;
            padding: 11px 14px;
            border: 1px solid #e6c200;
            border-left: 4px solid #dba617;
            background: #fcf9e8;
            color: #6b5a1e;
            font-size: 13px;
            font-weight: 600;
            line-height: 1.4;
            text-align: center;
            text-decoration: none;
            border-radius: 4px;
            box-sizing: border-box;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-billing-form-hint:hover,
        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-billing-form-hint:focus {
            background: #faf5d8;
            color: #574a16;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-consent {
            margin: 10px auto 0;
            max-width: 66%;
            font-size: 9px;
            color: #b0b0b0;
            line-height: 1.45;
            text-align: center;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-consent a {
            color: #b0b0b0;
            text-decoration: underline;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-consent a:hover {
            color: #888888;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-byline {
            margin: 10px 0 0;
            font-size: 10px;
            color: #b0b0b0;
            text-align: center;
            letter-spacing: 0.02em;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-byline a {
            color: #b0b0b0;
            text-decoration: none;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-payment-byline a:hover {
            color: #888888;
            text-decoration: underline;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .platebni-button {
            border: none;
            padding: 14px 48px;
            min-width: 176px;
            cursor: pointer;
            text-align: center;
            white-space: nowrap;
            display: inline-block;
            width: auto;
            max-width: none;
            box-sizing: border-box;
            border-radius: 9999px;
            box-shadow: 0 4px 14px rgba(15, 23, 42, 0.12);
            transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .platebni-button:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 18px rgba(15, 23, 42, 0.16);
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-custom-switch {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            gap: 12px;
            width: 100%;
            margin: 0 0 12px;
            padding: 4px 2px;
            text-align: left;
            cursor: pointer;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-custom-switch input[type="checkbox"] {
            width: 18px;
            height: 18px;
            margin: 0;
            padding: 0;
            flex: 0 0 auto;
            border: none !important;
            border-radius: 4px;
        }

        #<?php echo esc_attr( $wrapper_id ); ?> .elementsell-custom-switch span {
            flex: 1 1 auto;
            font-size: 15px;
            line-height: 1.45;
            color: #374151;
        }
        </style>

        <?php
    }
}

/**
 * Jsou načtené závislosti pro plný náhled formuláře v editoru?
 *
 * @return bool
 */
function elementsell_payment_widget_can_render_full_editor_preview() {
    return function_exists( 'elementsell_upsell_is_enabled' )
        && function_exists( 'elementsell_render_payment_consent_notice' )
        && function_exists( 'elementsell_get_billing_admin_url' )
        && function_exists( 'elementsell_get_custom_fields_from_widget_settings' );
}

/**
 * Plný server-side náhled z panelového nebo plného widgetu (render()).
 *
 * @param \Elementor\Widget_Base $widget
 * @return bool True pokud se podařilo vykreslit plný náhled.
 */
function elementsell_payment_widget_render_editor_preview( $widget ) {
    if ( ! $widget instanceof \Elementor\Widget_Base ) {
        return false;
    }

    if ( ! elementsell_payment_widget_can_render_full_editor_preview() ) {
        return false;
    }

    if ( function_exists( 'elementsell_boot_debug_log' ) ) {
        elementsell_boot_debug_log( 'payment widget: full editor render preview' );
    }

    $renderer = new ElementSell_Payment_Widget_Render_Proxy( $widget );
    $renderer->output_editor_preview();

    return true;
}

/**
 * Plná content_template pro plátno editoru (vyžaduje načtené závislosti).
 *
 * @return void
 */
function elementsell_payment_widget_echo_content_template() {
    if ( ! elementsell_payment_widget_can_render_full_editor_preview() ) {
        return;
    }

    if ( ! trait_exists( 'ElementSell_Widget_Content_Template', false ) ) {
        require_once __DIR__ . '/widget-content-template.php';
    }

    if ( function_exists( 'elementsell_boot_debug_log' ) ) {
        elementsell_boot_debug_log( 'payment widget: full editor content_template' );
    }

    $template = new ElementSell_Payment_Widget_Content_Template_Proxy();
    $template->output_editor_preview();
}

if ( ! class_exists( 'ElementSell_Payment_Widget_Render_Proxy', false ) ) {
    /**
     * Deleguje render traitu na existující instanci widgetu v editoru.
     */
    class ElementSell_Payment_Widget_Render_Proxy extends \Elementor\Widget_Base {
        use ElementSell_Widget_Render;

        /** @var \Elementor\Widget_Base */
        private $source_widget;

        public function __construct( \Elementor\Widget_Base $source_widget ) {
            $this->source_widget = $source_widget;
        }

        public function get_settings_for_display( $setting_key = null ) {
            return $this->source_widget->get_settings_for_display( $setting_key );
        }

        public function get_id() {
            return $this->source_widget->get_id();
        }

        public function get_name() {
            return $this->source_widget->get_name();
        }

        public function get_post_id() {
            if ( method_exists( $this->source_widget, 'get_post_id' ) ) {
                return (int) $this->source_widget->get_post_id();
            }

            return 0;
        }

        /**
         * @return void
         */
        public function output_editor_preview() {
            $this->render_form();
        }
    }
}

if ( ! class_exists( 'ElementSell_Payment_Widget_Content_Template_Proxy', false ) ) {
    if ( ! trait_exists( 'ElementSell_Widget_Content_Template', false ) ) {
        require_once __DIR__ . '/widget-content-template.php';
    }

    /**
     * Vypíše content_template bez instance widgetu (statická šablona polí).
     */
    class ElementSell_Payment_Widget_Content_Template_Proxy extends \Elementor\Widget_Base {
        use ElementSell_Widget_Content_Template;

        /**
         * @return string
         */
        public function get_name() {
            return 'elementsell_payment_form';
        }

        /**
         * @return void
         */
        public function output_editor_preview() {
            $this->render_form_content_template();
        }
    }
}
