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

add_action( 'init', 'elementsell_register_thank_you_shortcode' );
add_action( 'init', 'elementsell_ensure_thank_you_page', 12 );
add_action( 'admin_init', 'elementsell_maybe_repair_thank_you_page_access_roles', 25 );
add_filter( 'theme_page_templates', 'elementsell_register_thank_you_page_template' );
add_filter( 'template_include', 'elementsell_load_thank_you_page_template', 99 );
add_action( 'template_redirect', 'elementsell_route_order_return_page', 1 );
add_action( 'template_redirect', 'elementsell_prepare_thank_you_page_for_payment_return', 0 );
add_action( 'template_redirect', 'elementsell_handle_thank_you_password_post', 5 );
add_action( 'template_redirect', 'elementsell_gate_thank_you_page_public_access', 6 );
add_action( 'template_redirect', 'elementsell_maybe_redirect_thank_you_logged_in', 8 );
add_filter( 'the_content', 'elementsell_inject_thank_you_shortcode_content', 1 );
add_action( 'wp_head', 'elementsell_print_thank_you_noindex', 1 );
add_action( 'wp_head', 'elementsell_print_thank_you_minimal_styles_in_head', 99 );
add_action( 'wp_head', 'elementsell_print_thank_you_slot_frontend_hide_styles', 100 );
add_action( 'pre_get_posts', 'elementsell_exclude_thank_you_page_from_search' );
add_filter( 'wp_sitemaps_posts_query_args', 'elementsell_exclude_thank_you_page_from_sitemap', 10, 2 );

/**
 * @return int
 */
function elementsell_get_thank_you_page_id() {
    return (int) get_option( 'elementsell_thank_you_page_id', 0 );
}

/**
 * @return string[]
 */
function elementsell_get_thank_you_page_slugs() {
    return [
        'diky',
        'elementsell-dekujeme',
    ];
}

/**
 * @param array $templates
 * @return array
 */
function elementsell_register_thank_you_page_template( $templates ) {
    $templates['elementsell-thank-you-blank.php'] = 'ElementSell – čistá stránka';

    return $templates;
}

/**
 * @param int $page_id
 * @return bool
 */
function elementsell_page_content_is_thank_you_shortcode_only( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return false;
    }

    $page = get_post( $page_id );

    if ( ! $page instanceof WP_Post ) {
        return false;
    }

    $content = trim( (string) $page->post_content );

    if ( $content === '' || ! has_shortcode( $content, 'elementsell_thank_you' ) ) {
        return false;
    }

    $without_shortcode = str_replace( '[elementsell_thank_you]', '', $content );
    $without_shortcode = preg_replace( '/<!--.*?-->/s', '', $without_shortcode );
    $without_shortcode = trim( wp_strip_all_tags( $without_shortcode ) );

    return $without_shortcode === '';
}

/**
 * @param int $page_id
 * @return bool
 */
function elementsell_page_should_use_plugin_thank_you_layout( $page_id = 0 ) {
    $page_id = $page_id > 0 ? (int) $page_id : ( is_page() ? (int) get_queried_object_id() : 0 );

    if ( $page_id <= 0 ) {
        return false;
    }

    if ( (string) get_post_meta( $page_id, '_elementor_data', true ) !== '' ) {
        return false;
    }

    if ( get_post_meta( $page_id, '_elementsell_thank_you_managed', true ) === '1' ) {
        return true;
    }

    if ( elementsell_page_content_is_thank_you_shortcode_only( $page_id ) ) {
        return true;
    }

    if ( get_post_meta( $page_id, '_elementsell_thank_you_legacy', true ) === '1' ) {
        return false;
    }

    if ( get_post_meta( $page_id, '_created_by_plugin', true ) ) {
        return false;
    }

    return false;
}

/**
 * Děkovací stránka nesmí být omezená rolí ani označená jako login destination.
 *
 * @param int $page_id
 * @return void
 */
function elementsell_clear_thank_you_page_access_restrictions( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return;
    }

    delete_post_meta( $page_id, '_access_roles' );
    delete_post_meta( $page_id, '_elementsell_access_roles_auto' );
    delete_post_meta( $page_id, '_elementsell_login_destination' );
}

/**
 * Jednorázově sundá role z /diky (a dalších gated thank-you stránek).
 *
 * @return void
 */
function elementsell_maybe_repair_thank_you_page_access_roles() {
    if ( get_option( 'elementsell_thank_you_access_repair_v1' ) ) {
        return;
    }

    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( ! function_exists( 'elementsell_get_gated_thank_you_page_ids' ) ) {
        return;
    }

    foreach ( elementsell_get_gated_thank_you_page_ids() as $page_id ) {
        elementsell_clear_thank_you_page_access_restrictions( (int) $page_id );
    }

    update_option( 'elementsell_thank_you_access_repair_v1', 1, false );
}

/**
 * @param int $page_id
 * @return void
 */
function elementsell_sync_thank_you_page_mode( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return;
    }

    elementsell_clear_thank_you_page_access_restrictions( $page_id );

    if ( elementsell_page_should_use_plugin_thank_you_layout( $page_id ) ) {
        elementsell_mark_thank_you_page_managed( $page_id );
        elementsell_assign_thank_you_page_template( $page_id );
        elementsell_ensure_page_has_thank_you_shortcode( $page_id );
        return;
    }

    if ( (string) get_post_meta( $page_id, '_elementor_data', true ) !== '' ) {
        elementsell_mark_thank_you_page_legacy( $page_id );
    }
}

/**
 * @param int $page_id
 * @return int
 */
function elementsell_get_thank_you_page_id_for_request( $page_id = 0 ) {
    if ( $page_id > 0 ) {
        return (int) $page_id;
    }

    if ( is_page() ) {
        return (int) get_queried_object_id();
    }

    return (int) get_option( 'elementsell_thank_you_page_id', 0 );
}

/**
 * @return bool
 */
function elementsell_is_thank_you_page() {
    $page_id = elementsell_get_thank_you_page_id_for_request();

    if ( $page_id <= 0 || ! is_page( $page_id ) ) {
        return false;
    }

    if ( (int) get_option( 'elementsell_thank_you_page_id', 0 ) === $page_id ) {
        return true;
    }

    return elementsell_page_should_use_plugin_thank_you_layout( $page_id );
}

/**
 * Děkovací stránka pluginu — veřejně jen přes platbu / e-mail (payment_uid).
 * V adminu a mezi stránkami WP zůstává normálně editovatelná.
 *
 * Pokrývá i Elementor „legacy“ /diky (nejen managed shortcode stránku).
 *
 * @param int $page_id
 * @return bool
 */
function elementsell_is_gated_thank_you_page( $page_id = 0 ) {
    $page_id = $page_id > 0 ? (int) $page_id : ( is_singular( 'page' ) ? (int) get_queried_object_id() : 0 );

    if ( $page_id <= 0 || get_post_type( $page_id ) !== 'page' ) {
        return false;
    }

    if ( (int) get_option( 'elementsell_thank_you_page_id', 0 ) === $page_id ) {
        return true;
    }

    if ( get_post_meta( $page_id, '_elementsell_thank_you_managed', true ) === '1' ) {
        return true;
    }

    // Elementor děkovací stránka (po sync / navratova_url).
    if ( get_post_meta( $page_id, '_elementsell_thank_you_legacy', true ) === '1' ) {
        return true;
    }

    $page = get_post( $page_id );

    if ( ! is_object( $page ) || ! isset( $page->post_name ) ) {
        return false;
    }

    // Výchozí slugy pluginu — typicky /diky na produkci.
    if ( in_array( (string) $page->post_name, elementsell_get_thank_you_page_slugs(), true ) ) {
        return true;
    }

    if ( has_shortcode( (string) $page->post_content, 'elementsell_thank_you' ) ) {
        return true;
    }

    $elementor_data = (string) get_post_meta( $page_id, '_elementor_data', true );

    if ( $elementor_data !== '' && false !== strpos( $elementor_data, 'elementsell_thank_you' ) ) {
        return true;
    }

    return false;
}

/**
 * @return string
 */
function elementsell_get_thank_you_request_payment_uid() {
    if ( isset( $_GET['payment_uid'] ) ) {
        return sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) );
    }

    if ( isset( $_POST['payment_uid'] ) ) {
        return sanitize_text_field( wp_unslash( $_POST['payment_uid'] ) );
    }

    return '';
}

/**
 * Přístup po zaplacení nebo z e-mailu = existující objednávka podle payment_uid.
 *
 * @return bool
 */
function elementsell_thank_you_request_has_order_access() {
    $payment_uid = elementsell_get_thank_you_request_payment_uid();

    if ( $payment_uid === '' || ! function_exists( 'elementsell_get_order_by_payment_uid' ) ) {
        return false;
    }

    return (bool) elementsell_get_order_by_payment_uid( $payment_uid );
}

/**
 * @param int $page_id
 * @return bool
 */
function elementsell_user_can_preview_thank_you_page( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return false;
    }

    if ( function_exists( 'elementsell_is_elementor_context' ) && elementsell_is_elementor_context() ) {
        return true;
    }

    return is_user_logged_in() && current_user_can( 'edit_post', $page_id );
}

/**
 * Bez platného payment_uid (nebo práva editovat) vrátí 404 — stránka není veřejný landing.
 *
 * @return void
 */
function elementsell_gate_thank_you_page_public_access() {
    if ( is_admin() || wp_doing_ajax() || ! is_singular( 'page' ) ) {
        return;
    }

    $page_id = (int) get_queried_object_id();

    if ( $page_id <= 0 || ! elementsell_is_gated_thank_you_page( $page_id ) ) {
        return;
    }

    if ( elementsell_user_can_preview_thank_you_page( $page_id ) ) {
        return;
    }

    if ( elementsell_thank_you_request_has_order_access() ) {
        return;
    }

    elementsell_render_thank_you_page_not_found();
}

/**
 * @return void
 */
function elementsell_render_thank_you_page_not_found() {
    global $wp_query;

    if ( $wp_query instanceof WP_Query ) {
        $wp_query->set_404();
    }

    status_header( 404 );
    nocache_headers();

    $template = get_query_template( '404' );

    if ( is_string( $template ) && $template !== '' && file_exists( $template ) ) {
        include $template;
        exit;
    }

    wp_die(
        esc_html__( 'Stránka nebyla nalezena.', 'platebni-formular' ),
        esc_html__( 'Stránka nenalezena', 'platebni-formular' ),
        [ 'response' => 404 ]
    );
}

/**
 * @return void
 */
function elementsell_print_thank_you_noindex() {
    if ( is_admin() || ! is_singular( 'page' ) ) {
        return;
    }

    if ( ! elementsell_is_gated_thank_you_page() ) {
        return;
    }

    echo '<meta name="robots" content="noindex,nofollow">' . "\n";
}

/**
 * @param WP_Query $query
 * @return void
 */
function elementsell_exclude_thank_you_page_from_search( $query ) {
    if ( is_admin() || ! $query instanceof WP_Query || ! $query->is_main_query() || ! $query->is_search() ) {
        return;
    }

    $page_ids = elementsell_get_gated_thank_you_page_ids();

    if ( empty( $page_ids ) ) {
        return;
    }

    $excluded = array_map( 'intval', (array) $query->get( 'post__not_in' ) );
    $query->set( 'post__not_in', array_values( array_unique( array_merge( $excluded, $page_ids ) ) ) );
}

/**
 * @param array  $args
 * @param string $post_type
 * @return array
 */
function elementsell_exclude_thank_you_page_from_sitemap( $args, $post_type ) {
    if ( $post_type !== 'page' || ! is_array( $args ) ) {
        return $args;
    }

    $page_ids = elementsell_get_gated_thank_you_page_ids();

    if ( empty( $page_ids ) ) {
        return $args;
    }

    $excluded         = isset( $args['post__not_in'] ) ? array_map( 'intval', (array) $args['post__not_in'] ) : [];
    $args['post__not_in'] = array_values( array_unique( array_merge( $excluded, $page_ids ) ) );

    return $args;
}

/**
 * @return int[]
 */
function elementsell_get_gated_thank_you_page_ids() {
    $ids = [];

    $main_id = (int) get_option( 'elementsell_thank_you_page_id', 0 );

    if ( $main_id > 0 ) {
        $ids[] = $main_id;
    }

    if ( function_exists( 'get_page_by_path' ) ) {
        foreach ( elementsell_get_thank_you_page_slugs() as $slug ) {
            $page = get_page_by_path( $slug );

            if ( $page instanceof WP_Post ) {
                $ids[] = (int) $page->ID;
            }
        }
    }

    return array_values( array_unique( array_filter( array_map( 'intval', $ids ) ) ) );
}

/**
 * @param string $template
 * @return string
 */
function elementsell_load_thank_you_page_template( $template ) {
    if ( ! is_page() ) {
        return $template;
    }

    $page_id = (int) get_queried_object_id();

    if ( $page_id <= 0 || ! elementsell_is_gated_thank_you_page( $page_id ) ) {
        return $template;
    }

    // Elementor /diky bez managed shortcode: po platbě vždy plugin layout,
    // jinak krátký kód vůbec neproběhne a stránka zůstane bílá.
    $use_plugin_layout = elementsell_page_should_use_plugin_thank_you_layout( $page_id )
        || elementsell_get_thank_you_request_payment_uid() !== '';

    if ( ! $use_plugin_layout ) {
        return $template;
    }

    $plugin_template = dirname( __DIR__, 2 ) . '/templates/thank-you-blank.php';

    if ( file_exists( $plugin_template ) ) {
        return $plugin_template;
    }

    return $template;
}

/**
 * @param int $page_id
 * @return bool
 */
function elementsell_thank_you_page_is_managed( $page_id = 0 ) {
    if ( $page_id <= 0 ) {
        $page_id = elementsell_get_thank_you_page_id();

        if ( $page_id <= 0 && is_page() ) {
            $page_id = (int) get_queried_object_id();
        }
    }

    return elementsell_page_should_use_plugin_thank_you_layout( $page_id );
}

/**
 * @param int $page_id
 * @return void
 */
function elementsell_mark_thank_you_page_legacy( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return;
    }

    update_post_meta( $page_id, '_elementsell_thank_you_legacy', '1' );
    delete_post_meta( $page_id, '_elementsell_thank_you_managed' );
    elementsell_repair_legacy_thank_you_page( $page_id );
}

/**
 * @param int $page_id
 * @return void
 */
function elementsell_mark_thank_you_page_managed( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return;
    }

    update_post_meta( $page_id, '_elementsell_thank_you_managed', '1' );
    delete_post_meta( $page_id, '_elementsell_thank_you_legacy' );
}

/**
 * Vrátí šablonu a obsah stránky, pokud je plugin dříve přepsal.
 *
 * @param int $page_id
 * @return void
 */
function elementsell_repair_legacy_thank_you_page( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 ) {
        return;
    }

    $template = (string) get_post_meta( $page_id, '_wp_page_template', true );

    if ( $template === 'elementsell-thank-you-blank.php' ) {
        update_post_meta( $page_id, '_wp_page_template', 'default' );
    }

    $page = get_post( $page_id );

    if ( ! $page instanceof WP_Post ) {
        return;
    }

    $content = (string) $page->post_content;

    if ( $content === '' || ! has_shortcode( $content, 'elementsell_thank_you' ) ) {
        return;
    }

    if ( (string) get_post_meta( $page_id, '_elementor_data', true ) !== '' ) {
        $clean_content = trim( preg_replace( '/\s*\[elementsell_thank_you\]\s*/', '', $content ) );

        if ( $clean_content !== trim( $content ) ) {
            wp_update_post(
                [
                    'ID'           => $page_id,
                    'post_content' => $clean_content,
                ]
            );
        }
    }
}

/**
 * @param int $page_id
 * @return void
 */
function elementsell_assign_thank_you_page_template( $page_id ) {
    if ( ! elementsell_thank_you_page_is_managed( $page_id ) ) {
        return;
    }

    update_post_meta( (int) $page_id, '_wp_page_template', 'elementsell-thank-you-blank.php' );
}

/**
 * @param string $path
 * @return string
 */
function elementsell_get_thank_you_title_from_path( $path ) {
    $path = trim( (string) $path, '/' );

    if ( $path === '' ) {
        return elementsell_get_default_thank_you_page_slug();
    }

    $segments = array_values(
        array_filter(
            explode( '/', $path )
        )
    );

    return $segments ? (string) end( $segments ) : elementsell_get_default_thank_you_page_slug();
}

/**
 * @param int    $page_id
 * @param string $path
 * @return void
 */
function elementsell_maybe_fix_thank_you_page_title( $page_id, $path ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 || ! elementsell_thank_you_page_is_managed( $page_id ) ) {
        return;
    }

    $page = get_post( $page_id );

    if ( ! $page instanceof WP_Post ) {
        return;
    }

    $expected_title = elementsell_get_thank_you_title_from_path( $path );
    $generic_titles = [
        'Děkujeme',
        'Po zaplacení',
        'Dekujeme',
    ];

    if ( in_array( (string) $page->post_title, $generic_titles, true ) ) {
        wp_update_post(
            [
                'ID'         => $page_id,
                'post_title' => $expected_title,
            ]
        );
    }
}

/**
 * @return string
 */
function elementsell_get_default_thank_you_page_slug() {
    return 'diky';
}

/**
 * @param int $page_id
 * @return void
 */
function elementsell_ensure_page_has_thank_you_shortcode( $page_id ) {
    $page_id = (int) $page_id;

    if ( $page_id <= 0 || ! elementsell_thank_you_page_is_managed( $page_id ) ) {
        return;
    }

    $page = get_post( $page_id );

    if ( ! $page instanceof WP_Post || $page->post_type !== 'page' ) {
        return;
    }

    if ( has_shortcode( $page->post_content, 'elementsell_thank_you' ) ) {
        return;
    }

    wp_update_post(
        [
            'ID'           => $page_id,
            'post_content' => trim( $page->post_content . "\n\n[elementsell_thank_you]" ),
        ]
    );
}

/**
 * @param object $order
 * @return string
 */
function elementsell_get_effective_return_page_url_for_order( $order ) {
    $preferred        = elementsell_get_return_url_for_order( $order );
    $custom_navratova = trim( (string) elementsell_get_order_field( $order->id, 'navratova_url' ) );

    if ( $custom_navratova !== '' ) {
        if ( ! function_exists( 'elementsell_ensure_page_from_widget_url' ) ) {
            require_once PF_PLUGIN_DIR . 'includes/pages/widget-page-ensure.php';
        }

        elementsell_ensure_page_from_widget_url( $custom_navratova, 'thank_you' );
    }

    $page_id = function_exists( 'elementsell_resolve_internal_page_id_from_url' )
        ? elementsell_resolve_internal_page_id_from_url( $preferred )
        : (int) url_to_postid( $preferred );

    if ( $page_id > 0 && get_post_status( $page_id ) === 'publish' ) {
        if ( elementsell_page_has_access_restrictions( $page_id ) ) {
            return elementsell_get_thank_you_page_url();
        }

        if ( elementsell_thank_you_page_is_managed( $page_id ) ) {
            elementsell_sync_thank_you_page_mode( $page_id );
            elementsell_ensure_page_has_thank_you_shortcode( $page_id );
        }

        $permalink = get_permalink( $page_id );

        if ( $permalink ) {
            return $permalink;
        }
    }

    return elementsell_get_thank_you_page_url();
}

/**
 * @return int
 */
function elementsell_ensure_thank_you_page() {
    if ( elementsell_is_elementor_context() ) {
        return (int) get_option( 'elementsell_thank_you_page_id', 0 );
    }

    $page_id = (int) get_option( 'elementsell_thank_you_page_id', 0 );

    if ( $page_id > 0 && get_post_status( $page_id ) ) {
        elementsell_sync_thank_you_page_mode( $page_id );

        if ( elementsell_page_should_use_plugin_thank_you_layout( $page_id ) ) {
            return $page_id;
        }

        // Elementor / vlastní děkovací stránka — necháme ji jako oficiální return page
        // (dřív se option mazala a gate ji pak nepoznal).
        if ( get_post_meta( $page_id, '_elementsell_thank_you_legacy', true ) === '1' ) {
            return $page_id;
        }

        delete_option( 'elementsell_thank_you_page_id' );
    }

    foreach ( elementsell_get_thank_you_page_slugs() as $slug ) {
        $existing = get_page_by_path( $slug );

        if ( ! $existing instanceof WP_Post ) {
            continue;
        }

        $existing_id = (int) $existing->ID;

        update_option( 'elementsell_thank_you_page_id', $existing_id );
        elementsell_sync_thank_you_page_mode( $existing_id );

        return $existing_id;
    }

    $slug = elementsell_get_default_thank_you_page_slug();

    $page_id = wp_insert_post(
        [
            'post_title'   => $slug,
            'post_name'    => $slug,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_content' => '[elementsell_thank_you]',
        ],
        true
    );

    if ( is_wp_error( $page_id ) ) {
        error_log( 'ElementSell: nepodařilo se vytvořit výchozí stránku po zaplacení: ' . $page_id->get_error_message() );
        return 0;
    }

    update_option( 'elementsell_thank_you_page_id', (int) $page_id );
    elementsell_mark_thank_you_page_managed( (int) $page_id );
    elementsell_assign_thank_you_page_template( (int) $page_id );

    return (int) $page_id;
}

/**
 * @return string
 */
function elementsell_get_thank_you_page_url() {
    elementsell_ensure_thank_you_page();

    $page_id = (int) get_option( 'elementsell_thank_you_page_id', 0 );

    if ( $page_id > 0 ) {
        $permalink = get_permalink( $page_id );

        if ( $permalink ) {
            return $permalink;
        }
    }

    return home_url( '/' . elementsell_get_default_thank_you_page_slug() . '/' );
}

/**
 * @param string $url
 * @return string
 */
function elementsell_get_url_path( $url ) {
    $path = wp_parse_url( $url, PHP_URL_PATH );

    return untrailingslashit( (string) $path );
}

/**
 * @return string
 */
function elementsell_get_current_request_path() {
    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
    $path        = wp_parse_url( $request_uri, PHP_URL_PATH );

    return untrailingslashit( (string) $path );
}

/**
 * Vrátí návratovou URL pro objednávku: vlastní z widgetu, nebo výchozí stránku pluginu.
 *
 * @param object $order
 * @return string
 */
function elementsell_get_return_url_for_order( $order ) {
    $custom = trim( (string) elementsell_get_order_field( $order->id, 'navratova_url' ) );

    if ( $custom !== '' ) {
        return elementsell_normalize_page_url( $custom );
    }

    return elementsell_get_thank_you_page_url();
}

/**
 * Před vykreslením stránky po platbě přepne shortcode-only stránku do managed režimu.
 *
 * @return void
 */
function elementsell_prepare_thank_you_page_for_payment_return() {
    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' || ! is_page() ) {
        return;
    }

    $page_id = (int) get_queried_object_id();

    if ( $page_id <= 0 || ! elementsell_page_content_is_thank_you_shortcode_only( $page_id ) ) {
        return;
    }

    elementsell_sync_thank_you_page_mode( $page_id );
}

/**
 * @param object $order
 * @return bool
 */
function elementsell_is_order_return_page_request( $order ) {
    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' || $payment_uid !== (string) $order->payment_uid ) {
        return false;
    }

    $current_path = elementsell_get_current_request_path();
    $paths        = [
        elementsell_get_url_path( elementsell_get_return_url_for_order( $order ) ),
        elementsell_get_url_path( elementsell_get_effective_return_page_url_for_order( $order ) ),
        elementsell_get_url_path( elementsell_get_thank_you_page_url() ),
    ];

    if ( in_array( $current_path, array_filter( $paths ), true ) ) {
        return true;
    }

    if ( is_page() ) {
        $page_id = (int) get_queried_object_id();

        if ( $page_id > 0 && elementsell_is_gated_thank_you_page( $page_id ) ) {
            return true;
        }

        if ( $page_id > 0 && has_shortcode( (string) get_post_field( 'post_content', $page_id ), 'elementsell_thank_you' ) ) {
            return true;
        }
    }

    return false;
}

/**
 * @param object $order
 * @return string
 */
function elementsell_get_thank_you_url_for_order( $order ) {
    return add_query_arg(
        'payment_uid',
        rawurlencode( (string) $order->payment_uid ),
        elementsell_get_effective_return_page_url_for_order( $order )
    );
}

/**
 * Doručí zákazníka na stránku objednávky podle payment_uid (všechny stavy platby).
 *
 * @return void
 */
function elementsell_route_order_return_page() {
    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        return;
    }

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order ) {
        return;
    }

    if ( (string) $order->payment_method === 'thepay' ) {
        $order = elementsell_refresh_thepay_order_payment_status( $order );
    } elseif ( (string) $order->payment_method === 'fio' ) {
        $order = elementsell_refresh_fio_order_payment_status( $order );
    }

    if ( elementsell_is_order_payment_paid( $order ) ) {
        elementsell_complete_paid_order_side_effects( (int) $order->id, true );
        $order = elementsell_get_order( (int) $order->id );

        if ( ! $order ) {
            return;
        }
    }

    $target_url = elementsell_get_thank_you_url_for_order( $order );

    if ( elementsell_get_url_path( $target_url ) !== elementsell_get_current_request_path() ) {
        wp_safe_redirect( $target_url );
        exit;
    }
}

/**
 * @param string $content
 * @return string
 */
function elementsell_inject_thank_you_shortcode_content( $content ) {
    if ( is_admin() || ! is_main_query() || ! in_the_loop() ) {
        return $content;
    }

    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        return $content;
    }

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order || ! elementsell_is_order_return_page_request( $order ) ) {
        return $content;
    }

    if ( has_shortcode( $content, 'elementsell_thank_you' ) ) {
        return $content;
    }

    $dynamic = elementsell_render_thank_you_shortcode();

    if ( $dynamic === '' ) {
        return $content;
    }

    // Elementor legacy /diky: doplň dynamický blok (dřív se inject přeskočil → bílá stránka).
    if ( elementsell_is_thank_you_page() && ! elementsell_thank_you_page_is_managed() ) {
        return $content . $dynamic;
    }

    return $dynamic;
}

/**
 * @return void
 */
function elementsell_register_thank_you_shortcode() {
    add_shortcode( 'elementsell_thank_you', 'elementsell_render_thank_you_shortcode' );
}

/**
 * @param object $order
 * @return array{subject: string, body: string}
 */
function elementsell_get_paid_message_for_order( $order ) {
    $subject = (string) elementsell_get_order_field( $order->id, 'email_subject' );
    $body    = (string) elementsell_get_order_field( $order->id, 'email_body' );

    if ( $subject === '' ) {
        $subject = 'Platba proběhla v pořádku';
    }

    if ( $body === '' ) {
        $body = 'Děkujeme za platbu.';
    }

    $subject = elementsell_replace_email_variables( $subject, $order );
    $body    = elementsell_replace_email_variables( $body, $order );

    return [
        'subject' => $subject,
        'body'    => $body,
    ];
}

/**
 * @return bool
 */
function elementsell_is_thank_you_editor_preview() {
    return function_exists( 'elementsell_is_elementor_editor_render' ) && elementsell_is_elementor_editor_render();
}

/**
 * Placeholder jen v Elementor editoru na stránce po zaplacení — ne na /vstup apod.
 *
 * @return bool
 */
function elementsell_should_show_thank_you_editor_placeholder() {
    if ( ! elementsell_is_thank_you_editor_preview() || ! elementsell_is_thank_you_page() ) {
        return false;
    }

    if ( function_exists( 'elementsell_page_is_login_destination' ) && elementsell_page_is_login_destination() ) {
        return false;
    }

    return true;
}

/**
 * @return string
 */
function elementsell_render_thank_you_editor_placeholder() {
    static $styles_rendered = false;

    $html = '';

    if ( ! $styles_rendered ) {
        $styles_rendered = true;
        $html .= '<style>
            .elementsell-thank-you-slot--editor {
                margin: 0 auto;
                max-width: 520px;
                padding: 18px 20px;
                border: 1px dashed #9ca3af;
                border-radius: 8px;
                background: #f9fafb;
                color: #4b5563;
                font-size: 15px;
                line-height: 1.5;
                text-align: center;
            }
        </style>';
    }

    $html .= '<div class="elementsell-thank-you-slot elementsell-thank-you-slot--editor">'
        . esc_html__( 'Obsah po zaplacení (ElementSell)', 'platebni-formular' )
        . '</div>';

    return $html;
}

/**
 * @param array $atts
 * @return string
 */
function elementsell_render_thank_you_shortcode( $atts = [] ) {
    if ( elementsell_should_show_thank_you_editor_placeholder() ) {
        return elementsell_render_thank_you_editor_placeholder();
    }

    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        return '';
    }

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order ) {
        return elementsell_render_thank_you_minimal_output(
            '<p>Tuto platbu se nepodařilo dohledat.</p>',
            ''
        );
    }

    if ( (string) $order->payment_method === 'thepay' && ! elementsell_is_order_payment_paid( $order ) ) {
        $order = elementsell_refresh_thepay_order_payment_status( $order );
    } elseif ( (string) $order->payment_method === 'fio' && ! elementsell_is_order_payment_paid( $order ) ) {
        $order = elementsell_refresh_fio_order_payment_status( $order );
    }

    if ( elementsell_is_order_payment_paid( $order ) ) {
        elementsell_complete_paid_order_side_effects( (int) $order->id, true );
        $refreshed = elementsell_get_order( (int) $order->id );

        if ( $refreshed ) {
            $order = $refreshed;
        }
    }

    $view   = elementsell_get_thank_you_view_for_order( $order );
    $body   = (string) $view['body'] . (string) $view['actions'] . elementsell_render_thank_you_auto_refresh_script( $view['auto_refresh'] );
    $access = (string) ( $view['access'] ?? '' );

    if ( elementsell_is_thank_you_admin_preview( $order ) ) {
        $notice = elementsell_render_thank_you_admin_preview_notice();

        if (
            strpos( $access, 'elementsell-thank-you-admin-notice' ) === false
            && strpos( $body, 'elementsell-thank-you-admin-notice' ) === false
        ) {
            if ( elementsell_thank_you_uses_elementor_slot() ) {
                $access = $notice . $access;
            } else {
                $body = $notice . $body;
            }
        }
    }

    if ( elementsell_thank_you_uses_elementor_slot() ) {
        if ( trim( $access ) !== '' ) {
            return elementsell_render_thank_you_minimal_output( '', $access );
        }

        // Elementor slot dřív zahodil body → u čekání na platbu / bez hesla stránka vypadala prázdná.
        if ( trim( $body ) !== '' ) {
            return elementsell_render_thank_you_minimal_output( $body, '' );
        }

        return '';
    }

    return elementsell_render_thank_you_minimal_output( $body, $access );
}

/**
 * Stránka po zaplacení je v Elementoru — dynamický slot bez vlastních nadpisů.
 *
 * @return bool
 */
function elementsell_thank_you_uses_elementor_slot() {
    return elementsell_is_thank_you_page() && ! elementsell_thank_you_page_is_managed();
}

/**
 * Přihlášený správce webu (testuje děkovací stránku).
 *
 * @return bool
 */
function elementsell_thank_you_viewer_is_site_admin() {
    return is_user_logged_in() && current_user_can( 'manage_options' );
}

/**
 * Náhled pro admina: objednávka na admin e-mail, nebo je právě přihlášený správce.
 *
 * @param object|null $order
 * @return bool
 */
function elementsell_is_thank_you_admin_preview( $order = null ) {
    if ( elementsell_thank_you_viewer_is_site_admin() ) {
        return true;
    }

    return $order && function_exists( 'elementsell_email_belongs_to_site_admin' )
        && elementsell_email_belongs_to_site_admin( $order->email );
}

/**
 * @return string
 */
function elementsell_render_thank_you_admin_preview_notice() {
    return '<div class="elementsell-thank-you-admin-notice" role="status">'
        . '<strong>Pozor:</strong> jste přihlášeni jako administrátor. '
        . 'Níže je náhled stejný jako u zákazníka — pro reálný test se odhlaste a otestujte to jako zákazník (jiný e-mail).'
        . '</div>';
}

/**
 * Formulář hesla po zaplacení (u admin náhledu jen vizuálně, bez odeslání).
 *
 * @param object $order
 * @param string $email_html
 * @param bool   $preview
 * @return string
 */
function elementsell_render_thank_you_password_form( $order, $email_html = '', $preview = false ) {
    $error = isset( $_GET['elementsell_error'] ) ? sanitize_text_field( wp_unslash( $_GET['elementsell_error'] ) ) : '';

    ob_start();
    ?>
    <div class="elementsell-thank-you-access elementsell-thank-you-access--primary<?php echo $preview ? ' elementsell-thank-you-access--admin-preview' : ''; ?>">
        <?php if ( $email_html !== '' ) : ?>
            <?php echo $email_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
        <?php endif; ?>
        <?php if ( $error && ! $preview ) : ?>
            <p class="elementsell-thank-you-error"><?php echo esc_html( $error ); ?></p>
        <?php endif; ?>
        <form
            method="post"
            action="<?php echo esc_url( elementsell_get_thank_you_url_for_order( $order ) ); ?>"
            class="elementsell-thank-you-access-form"
            <?php echo $preview ? ' onsubmit="return false;" aria-disabled="true"' : ''; ?>
        >
            <?php if ( ! $preview ) : ?>
                <?php wp_nonce_field( 'elementsell_thank_you_' . $order->payment_uid, 'elementsell_thank_you_nonce' ); ?>
                <input type="hidden" name="elementsell_thank_you_setup" value="1">
                <input type="hidden" name="payment_uid" value="<?php echo esc_attr( $order->payment_uid ); ?>">
            <?php endif; ?>
            <div class="elementsell-thank-you-password-wrap">
                <input
                    type="password"
                    id="elementsell_thank_you_password"
                    name="elementsell_password"
                    <?php echo $preview ? '' : 'required minlength="8"'; ?>
                    autocomplete="new-password"
                    placeholder="Nastav si heslo"
                    <?php disabled( $preview ); ?>
                >
                <button type="button" class="elementsell-thank-you-password-toggle" data-target="elementsell_thank_you_password" aria-label="Zobrazit heslo" aria-pressed="false"<?php echo $preview ? ' disabled' : ''; ?>>
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
                        <path class="elementsell-eye-on" fill="currentColor" d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                        <path class="elementsell-eye-off" fill="currentColor" d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>
                    </svg>
                </button>
            </div>
            <button type="<?php echo $preview ? 'button' : 'submit'; ?>" class="elementsell-thank-you-button elementsell-thank-you-button--primary"<?php echo $preview ? ' disabled' : ''; ?>>Pokračovat</button>
        </form>
        <?php if ( ! $preview ) : ?>
        <script>
            document.querySelectorAll('.elementsell-thank-you-password-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    var input = document.getElementById(button.getAttribute('data-target'));
                    if (!input) return;
                    var show = input.type === 'password';
                    input.type = show ? 'text' : 'password';
                    button.classList.toggle('is-revealed', show);
                    button.setAttribute('aria-label', show ? 'Skrýt heslo' : 'Zobrazit heslo');
                    button.setAttribute('aria-pressed', show ? 'true' : 'false');
                });
            });
        </script>
        <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * @param object $order
 * @param string $email_body
 * @return string
 */
function elementsell_render_thank_you_access_section( $order, $email_body = '' ) {
    $email_body = trim( (string) $email_body );
    $email_html = '';

    if ( $email_body !== '' && ! elementsell_thank_you_uses_elementor_slot() ) {
        $email_html = '<div class="elementsell-thank-you-access-email">'
            . wpautop( wp_kses_post( $email_body ) )
            . '</div>';
    }

    $admin_preview = elementsell_is_thank_you_admin_preview( $order );
    $admin_notice  = $admin_preview ? elementsell_render_thank_you_admin_preview_notice() : '';

    // Admin e-mail: nezasahovat do účtu správce — ukázat stejný náhled jako u zákazníka.
    if ( elementsell_email_belongs_to_site_admin( $order->email ) ) {
        if ( ! elementsell_should_send_login_credentials( (int) $order->id ) ) {
            return $admin_notice
                . ( $email_html !== ''
                    ? '<div class="elementsell-thank-you-access elementsell-thank-you-access--admin">' . $email_html . '</div>'
                    : '' );
        }

        return $admin_notice . elementsell_render_thank_you_password_form( $order, $email_html, true );
    }

    elementsell_setup_customer_account_for_order( $order );
    elementsell_complete_returning_customer_access( $order );

    if ( elementsell_is_order_access_completed( (int) $order->id ) ) {
        $destination = elementsell_get_post_login_destination_for_order( $order );

        if ( elementsell_order_matches_current_user( $order ) ) {
            return $admin_notice
                . '<div class="elementsell-thank-you-access elementsell-thank-you-access--done">'
                . $email_html
                . '<p class="elementsell-thank-you-access-action"><a class="elementsell-thank-you-button elementsell-thank-you-button--primary" href="' . esc_url( $destination ) . '">Přejít na obsah</a></p>'
                . '</div>';
        }

        return $admin_notice
            . '<div class="elementsell-thank-you-access elementsell-thank-you-access--done">'
            . $email_html
            . '<p class="elementsell-thank-you-access-action"><a class="elementsell-thank-you-button elementsell-thank-you-button--primary elementsell-thank-you-button--login" href="' . esc_url( wp_login_url( $destination ) ) . '">'
            . elementsell_render_thank_you_login_icon()
            . '<span>Přihlásit se</span></a></p>'
            . '</div>';
    }

    return $admin_notice . elementsell_render_thank_you_password_form( $order, $email_html, false );
}

/**
 * @return string
 */
function elementsell_render_thank_you_login_icon() {
    return '<svg class="elementsell-thank-you-button__icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">'
        . '<path fill="currentColor" d="M11 7 9.6 8.4 12.2 11H2v2h10.2l-2.6 2.6L11 17l6-6-6-6zm8 12h-8v-2h8V5h-8V3h8c1.1 0 2 .9 2 2v14c0 1.1-.9 2-2 2z"/>'
        . '</svg>';
}

/**
 * @return void
 */
function elementsell_maybe_redirect_thank_you_logged_in() {
    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        return;
    }

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order || ! elementsell_should_send_login_credentials( (int) $order->id ) ) {
        return;
    }

    if ( elementsell_email_belongs_to_site_admin( $order->email ) ) {
        return;
    }

    if ( ! elementsell_is_order_return_page_request( $order ) ) {
        return;
    }

    if ( ! elementsell_is_order_access_completed( (int) $order->id ) ) {
        return;
    }

    $destination = elementsell_get_post_login_destination_for_order( $order );

    if ( elementsell_order_matches_current_user( $order ) ) {
        wp_safe_redirect( $destination );
        exit;
    }
}

/**
 * @return void
 */
function elementsell_handle_thank_you_password_post() {
    if ( empty( $_POST['elementsell_thank_you_setup'] ) ) {
        return;
    }

    $payment_uid = isset( $_POST['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_POST['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        return;
    }

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order ) {
        return;
    }

    if (
        empty( $_POST['elementsell_thank_you_nonce'] )
        || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elementsell_thank_you_nonce'] ) ), 'elementsell_thank_you_' . $order->payment_uid )
    ) {
        elementsell_redirect_thank_you_with_error( $order, 'Neplatný požadavek. Zkuste to prosím znovu.' );
    }

    $password = isset( $_POST['elementsell_password'] ) ? (string) wp_unslash( $_POST['elementsell_password'] ) : '';

    $redirect = elementsell_complete_order_access( $order, $password );

    if ( is_wp_error( $redirect ) ) {
        elementsell_redirect_thank_you_with_error( $order, $redirect->get_error_message() );
    }

    wp_safe_redirect( $redirect );
    exit;
}

/**
 * @param object $order
 * @param string $message
 * @return void
 */
function elementsell_redirect_thank_you_with_error( $order, $message ) {
    wp_safe_redirect(
        add_query_arg(
            'elementsell_error',
            rawurlencode( $message ),
            elementsell_get_thank_you_url_for_order( $order )
        )
    );
    exit;
}

/**
 * @param string $body_content
 * @param string $access_content
 * @return string
 */
function elementsell_render_thank_you_minimal_output( $body_content, $access_content = '' ) {
    $body_content   = trim( (string) $body_content );
    $access_content = trim( (string) $access_content );

    if ( $body_content === '' && $access_content === '' ) {
        return '';
    }

    elementsell_ensure_thank_you_minimal_styles_printed();

    $html = '<div class="elementsell-thank-you-minimal" data-es-thank-you="2026-07-14.10">';

    if ( $body_content !== '' ) {
        $html .= '<div class="elementsell-thank-you-minimal__main">' . $body_content . '</div>';
    }

    if ( $access_content !== '' ) {
        $html .= '<div class="elementsell-thank-you-minimal__access">' . $access_content . '</div>';
    }

    $html .= '</div>';

    return $html;
}

/**
 * @return bool
 */
function elementsell_should_print_thank_you_minimal_styles() {
    if ( is_admin() ) {
        return false;
    }

    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        return false;
    }

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

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( $order && elementsell_is_order_return_page_request( $order ) ) {
        return true;
    }

    $page_id = (int) get_queried_object_id();

    return $page_id > 0
        && has_shortcode( (string) get_post_field( 'post_content', $page_id ), 'elementsell_thank_you' );
}

/**
 * @return void
 */
function elementsell_print_thank_you_minimal_styles_in_head() {
    if ( ! elementsell_should_print_thank_you_minimal_styles() ) {
        return;
    }

    elementsell_ensure_thank_you_minimal_styles_printed();
}

/**
 * Skryje editor placeholder dynamického bloku na živém webu.
 *
 * @return void
 */
function elementsell_print_thank_you_slot_frontend_hide_styles() {
    if ( is_admin() ) {
        return;
    }

    echo '<style id="elementsell-thank-you-slot-hide">body:not(.elementor-editor-active) .elementsell-thank-you-slot--editor{display:none!important}</style>';
}

/**
 * @param bool $force
 * @return void
 */
function elementsell_ensure_thank_you_minimal_styles_printed( $force = false ) {
    static $styles_rendered = false;

    if ( $styles_rendered && ! $force ) {
        return;
    }

    $styles_rendered = true;

    echo elementsell_get_thank_you_minimal_styles(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

/**
 * @return string
 */
function elementsell_get_thank_you_minimal_styles() {
    ob_start();
    ?>
    <style id="elementsell-thank-you-minimal-styles">
        html.elementsell-thank-you-html {
            -webkit-text-size-adjust: 100%;
            text-size-adjust: 100%;
        }
        .elementsell-thank-you-minimal {
            width: 100%;
            max-width: 420px;
            margin: 0 auto;
            padding: 8px 16px 32px;
            box-sizing: border-box;
            text-align: center;
        }
        .elementsell-thank-you-minimal__main,
        .elementsell-thank-you-minimal__access,
        .elementsell-thank-you-minimal .elementsell-thank-you-access,
        .elementsell-thank-you-minimal .elementsell-thank-you-access-form {
            width: 100%;
            max-width: 100%;
            margin-left: auto;
            margin-right: auto;
            box-sizing: border-box;
        }
        .elementsell-thank-you-minimal__main {
            margin: 0 0 28px;
        }
        .elementsell-thank-you-minimal__access {
            margin: 0;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin: 0 auto;
            padding: 0;
            background: transparent;
            border: 0;
            box-shadow: none;
            text-align: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm__icon {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            width: 52px;
            height: 52px;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm__icon svg,
        .elementsell-thank-you-minimal .elementsell-thank-you-mood__svg,
        .elementsell-thank-you-minimal .elementsell-thank-you-button__icon {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            max-width: none !important;
            flex-shrink: 0;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm__icon svg {
            width: 52px !important;
            height: 52px !important;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-mood {
            margin: 0 auto 20px;
            text-align: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-mood__bubble {
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-mood__svg {
            width: 72px !important;
            height: 72px !important;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm__text {
            text-align: center;
            width: 100%;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm__title {
            margin: 0 0 4px;
            font-size: 18px;
            line-height: 1.3;
            font-weight: 700;
            color: #111827;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-confirm__subtitle {
            margin: 0;
            font-size: 15px;
            line-height: 1.5;
            color: #4b5563;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-body,
        .elementsell-thank-you-minimal .elementsell-thank-you-lead,
        .elementsell-thank-you-minimal .elementsell-thank-you-access-email,
        .elementsell-thank-you-minimal .elementsell-thank-you-access-email p {
            margin: 0 0 20px;
            font-size: 16px;
            line-height: 1.65;
            color: #374151;
            text-align: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-body p:last-child,
        .elementsell-thank-you-minimal .elementsell-thank-you-access-email p:last-child {
            margin-bottom: 0;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-access,
        .elementsell-thank-you-minimal .elementsell-thank-you-access--primary,
        .elementsell-thank-you-minimal .elementsell-thank-you-access--done,
        .elementsell-thank-you-minimal .elementsell-thank-you-access--admin {
            margin: 0;
            padding: 0;
            background: transparent;
            border: 0;
            text-align: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-admin-notice,
        .elementsell-thank-you-admin-notice {
            margin: 0 0 20px;
            padding: 14px 16px;
            border: 1px solid #f59e0b;
            border-radius: 10px;
            background: #fffbeb;
            color: #92400e;
            font-size: 15px;
            line-height: 1.5;
            text-align: left;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-admin-notice strong,
        .elementsell-thank-you-admin-notice strong {
            font-weight: 700;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-access--admin-preview {
            opacity: 0.92;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-access-action {
            margin: 0;
            text-align: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-access-form {
            margin: 0;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-password-wrap {
            position: relative;
            margin: 0 0 16px;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-password-wrap input[type="password"],
        .elementsell-thank-you-minimal .elementsell-thank-you-password-wrap input[type="text"] {
            width: 100%;
            box-sizing: border-box;
            margin: 0;
            padding: 14px 46px 14px 16px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 17px;
            background: #fff;
            -webkit-appearance: none;
            appearance: none;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-button {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            position: relative;
            width: 100%;
            box-sizing: border-box;
            border: 0;
            border-radius: 9999px;
            padding: 16px 32px;
            background: #1b4332;
            color: #fff !important;
            font-size: 18px;
            font-weight: 700;
            text-decoration: none;
            text-align: center;
            cursor: pointer;
            -webkit-appearance: none;
            appearance: none;
            -webkit-tap-highlight-color: transparent;
            text-transform: none;
            letter-spacing: normal;
            max-width: 100%;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-button--login .elementsell-thank-you-button__icon {
            position: absolute;
            left: 24px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px !important;
            height: 20px !important;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-button--login {
            gap: 0;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-button:hover {
            background: #163728;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-error {
            margin: 0 0 16px;
            padding: 12px 14px;
            border-radius: 8px;
            background: #fef2f2;
            color: #b91c1c;
            font-size: 14px;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-password-toggle {
            position: absolute;
            top: 0;
            right: 0;
            width: 44px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 0;
            background: transparent;
            color: #6b7280;
            cursor: pointer;
            -webkit-appearance: none;
            appearance: none;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-password-toggle svg {
            width: 20px !important;
            height: 20px !important;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-actions {
            margin-top: 20px;
            text-align: center;
        }
        .elementsell-thank-you-minimal .elementsell-thank-you-link {
            color: #1b4332;
            text-decoration: underline;
            font-size: 15px;
        }
        .elementsell-thank-you-slot--editor {
            margin: 0 auto;
            max-width: 520px;
            padding: 18px 20px;
            border: 1px dashed #9ca3af;
            border-radius: 8px;
            background: #f9fafb;
            color: #4b5563;
            font-size: 15px;
            line-height: 1.5;
            text-align: center;
        }
    </style>
    <?php
    return (string) ob_get_clean();
}

/**
 * @param string $access_content
 * @return string
 */
function elementsell_render_thank_you_slot_output( $access_content ) {
    return elementsell_render_thank_you_minimal_output( '', $access_content );
}

/**
 * @return string
 */
function elementsell_get_thank_you_slot_styles() {
    return elementsell_get_thank_you_minimal_styles();
}

/**
 * @param string $title
 * @param string $content
 * @param string $tone
 * @param string $access_content
 * @return string
 */
function elementsell_render_thank_you_shell( $title, $content, $tone = 'neutral', $access_content = '' ) {
    static $styles_rendered = false;

    $tone = in_array( $tone, [ 'success', 'processing', 'pending', 'warning', 'error', 'neutral' ], true )
        ? $tone
        : 'neutral';

    $access_content = trim( (string) $access_content );
    $has_access     = $access_content !== '';

    $html = '';

    if ( ! $styles_rendered ) {
        $styles_rendered = true;
        $html .= '<style>
            .elementsell-thank-you-wrap {
                max-width: 640px;
                margin: 0 auto;
                padding: 40px 16px;
                min-height: 100vh;
                box-sizing: border-box;
            }
            .elementsell-thank-you-wrap--split {
                display: flex;
                flex-direction: column;
                gap: 20px;
            }
            .elementsell-thank-you-card {
                background: #fff;
                border-radius: 14px;
                padding: 32px 28px;
                box-shadow: 0 4px 24px rgba(15, 23, 42, 0.06);
                color: #1f2937;
                border: 1px solid #e5e7eb;
            }
            .elementsell-thank-you-card--confirm {
                max-width: 520px;
                margin: 0 auto;
                width: 100%;
                padding: 18px 22px;
                box-shadow: 0 2px 12px rgba(15, 23, 42, 0.05);
            }
            .elementsell-thank-you-card--access {
                padding: 40px 36px;
                box-shadow: 0 8px 32px rgba(15, 23, 42, 0.08);
                border-color: #e5e7eb;
                background: #fff;
            }
            .elementsell-thank-you-card--success,
            .elementsell-thank-you-card--processing {
                border-color: #e5e7eb;
                background: #fff;
                box-shadow: 0 4px 24px rgba(15, 23, 42, 0.06);
            }
            .elementsell-thank-you-card h1 {
                margin: 0 0 16px;
                font-size: 26px;
                line-height: 1.3;
                text-align: center;
                color: #111827;
                font-weight: 700;
            }
            .elementsell-thank-you-confirm {
                display: flex;
                align-items: center;
                gap: 14px;
                text-align: left;
            }
            .elementsell-thank-you-confirm__icon {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 44px;
                height: 44px;
                flex-shrink: 0;
            }
            .elementsell-thank-you-confirm__icon svg {
                display: block;
                width: 44px;
                height: 44px;
            }
            .elementsell-thank-you-confirm__text {
                min-width: 0;
            }
            .elementsell-thank-you-confirm__title {
                margin: 0 0 4px;
                font-size: 18px;
                line-height: 1.3;
                font-weight: 700;
                color: #111827;
            }
            .elementsell-thank-you-confirm__subtitle {
                margin: 0;
                font-size: 15px;
                line-height: 1.5;
                color: #4b5563;
            }
            .elementsell-thank-you-body {
                font-size: 16px;
                line-height: 1.7;
                text-align: center;
                color: #374151;
            }
            .elementsell-thank-you-body--secondary {
                font-size: 14px;
                line-height: 1.65;
                color: #6b7280;
                margin-top: 16px;
                margin-bottom: 0;
            }
            .elementsell-thank-you-body--secondary p:last-child {
                margin-bottom: 0;
            }
            .elementsell-thank-you-lead {
                margin: 0;
                font-size: 17px;
                line-height: 1.75;
                color: #374151;
                text-align: center;
            }
            .elementsell-thank-you-mood {
                margin: 0 0 20px;
                text-align: center;
            }
            .elementsell-thank-you-access {
                margin-top: 0;
                padding-top: 0;
                border-top: 0;
            }
            .elementsell-thank-you-access--primary,
            .elementsell-thank-you-access--done,
            .elementsell-thank-you-access--admin {
                background: transparent;
                border: 0;
                border-radius: 0;
                padding: 0;
                text-align: center;
            }
            .elementsell-thank-you-admin-notice {
                margin: 0 0 20px;
                padding: 14px 16px;
                border: 1px solid #f59e0b;
                border-radius: 10px;
                background: #fffbeb;
                color: #92400e;
                font-size: 15px;
                line-height: 1.5;
                text-align: left;
            }
            .elementsell-thank-you-access-heading {
                margin: 0 0 12px;
                font-size: 28px;
                line-height: 1.3;
                color: #111827;
                font-weight: 700;
                text-align: center;
            }
            .elementsell-thank-you-access-lead {
                margin: 0 0 16px;
                font-size: 16px;
                line-height: 1.6;
                color: #4b5563;
                text-align: center;
            }
            .elementsell-thank-you-access-email {
                margin: 0 0 24px;
                font-size: 15px;
                line-height: 1.65;
                color: #374151;
                text-align: center;
            }
            .elementsell-thank-you-access-email p:last-child {
                margin-bottom: 0;
            }
            .elementsell-thank-you-access-note {
                margin: 0 0 24px;
                font-size: 14px;
                line-height: 1.6;
                color: #6b7280;
                text-align: center;
            }
            .elementsell-thank-you-access-action {
                margin: 0;
                text-align: center;
            }
            .elementsell-thank-you-label {
                display: block;
                margin: 0 0 8px;
                font-size: 14px;
                font-weight: 600;
                color: #374151;
                text-align: left;
            }
            .elementsell-thank-you-email {
                margin: 0 0 18px;
                font-size: 16px;
            }
            .elementsell-thank-you-password-wrap {
                position: relative;
                margin: 0 0 20px;
            }
            .elementsell-thank-you-password-wrap input[type="password"],
            .elementsell-thank-you-password-wrap input[type="text"] {
                width: 100%;
                box-sizing: border-box;
                margin: 0;
                padding: 14px 46px 14px 16px;
                border: 1px solid #d1d5db;
                border-radius: 8px;
                font-size: 17px;
                background: #fff;
            }
            .elementsell-thank-you-password-wrap input:focus {
                outline: none;
                border-color: #2d6a4f;
                box-shadow: 0 0 0 3px rgba(45, 106, 79, 0.12);
            }
            .elementsell-thank-you-password-toggle {
                position: absolute;
                top: 0;
                right: 0;
                width: 44px;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                border: 0;
                border-radius: 0 8px 8px 0;
                padding: 0;
                background: transparent;
                color: #6b7280;
                cursor: pointer;
            }
            .elementsell-thank-you-password-toggle:hover {
                color: #111827;
            }
            .elementsell-thank-you-password-toggle:focus {
                outline: none;
            }
            .elementsell-thank-you-password-toggle:focus-visible {
                color: #111827;
            }
            .elementsell-thank-you-password-toggle .elementsell-eye-off {
                display: none;
            }
            .elementsell-thank-you-password-toggle.is-revealed .elementsell-eye-on {
                display: none;
            }
            .elementsell-thank-you-password-toggle.is-revealed .elementsell-eye-off {
                display: block;
            }
            .elementsell-thank-you-button {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                gap: 10px;
                width: 100%;
                max-width: 100%;
                box-sizing: border-box;
                border: 0;
                border-radius: 9999px;
                padding: 15px 28px;
                background: #1b4332;
                color: #fff !important;
                font-size: 17px;
                font-weight: 700;
                text-decoration: none;
                text-align: center;
                cursor: pointer;
                transition: background-color 0.2s ease;
            }
            .elementsell-thank-you-button:hover {
                background: #163728;
            }
            .elementsell-thank-you-button--primary {
                margin-top: 0;
                padding: 16px 32px;
                font-size: 18px;
                box-shadow: 0 4px 14px rgba(27, 67, 50, 0.22);
            }
            .elementsell-thank-you-button__icon {
                display: block;
                flex-shrink: 0;
            }
            .elementsell-thank-you-upsell {
                margin: 0 0 24px;
                padding: 18px 16px;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                background: #f9fafb;
                text-align: center;
            }
            .elementsell-thank-you-upsell__title {
                margin: 0 0 10px;
                font-size: 16px;
                color: #111827;
            }
            .elementsell-thank-you-upsell__note {
                margin: 0;
                font-size: 15px;
                color: #374151;
            }
            .elementsell-thank-you-button--upsell {
                margin-top: 4px;
            }
            .elementsell-thank-you-actions {
                margin-top: 24px;
                padding-top: 20px;
                border-top: 1px solid #e5e5e5;
                text-align: center;
            }
            .elementsell-thank-you-link {
                color: #1b4332;
                text-decoration: underline;
                font-size: 15px;
            }
            .elementsell-thank-you-error {
                margin: 0 0 16px;
                padding: 12px 14px;
                border-radius: 8px;
                background: #fef2f2;
                color: #b91c1c;
                font-size: 14px;
            }
            @media (min-width: 520px) {
                .elementsell-thank-you-wrap--split {
                    gap: 24px;
                }
                .elementsell-thank-you-card--access {
                    padding: 44px 40px;
                }
                .elementsell-thank-you-card--confirm {
                    padding: 20px 24px;
                }
            }
        </style>';
    }

    $card_class = 'elementsell-thank-you-card';

    if ( $tone !== 'neutral' ) {
        $card_class .= ' elementsell-thank-you-card--' . $tone;
    }

    $wrap_class = 'elementsell-thank-you-wrap';

    if ( $has_access ) {
        $wrap_class .= ' elementsell-thank-you-wrap--split';
    }

    $html .= '<div class="' . esc_attr( $wrap_class ) . '">';

    if ( $has_access ) {
        $html .= '<div class="' . esc_attr( $card_class . ' elementsell-thank-you-card--confirm' ) . '">';
        $html .= $content;
        $html .= '</div>';
        $html .= '<div class="elementsell-thank-you-card elementsell-thank-you-card--access">';
        $html .= $access_content;
        $html .= '</div>';
    } else {
        $html .= '<div class="' . esc_attr( $card_class ) . '">';
        if ( $title !== '' ) {
            $html .= '<h1>' . esc_html( $title ) . '</h1>';
        }
        $html .= $content;
        $html .= '</div>';
    }

    $html .= '</div>';

    return $html;
}
