<?php

$form_id = get_field('form_id') ?: '3';
$form_title = get_field('form_title') ?: 'Форма обратной связи';
$submit_button_text = get_field('submit_button_text') ?: 'Отправить';

$unique_id = 'form-block-' . $block['id'];

$current_url = home_url($_SERVER['REQUEST_URI']);
$page_title = get_the_title() ?: 'Главная страница';
$form_name = $form_title;

$room = get_current_room();
if ($room === 'gym') {
    $section_classes = 'bg-cover bg-center bg-no-repeat';
    $bg_image = get_template_directory_uri() . '/assets/images/form-bg-dark.png.webp';
    $style_attr = 'style="background-image: url(' . esc_url($bg_image) . ')"';
} else {
    $section_classes = 'bg-cover bg-center bg-no-repeat';
    $bg_image = get_template_directory_uri() . '/assets/images/form-bg-light.png.webp';
    $style_attr = 'style="background-image: url(' . esc_url($bg_image) . ')"';
}

$hidden_value = "Форма: {$form_name} | Страница: {$page_title} | URL: {$current_url}";
?>

<section data-scroll-section="trial-training" class="bg-[100%_8px] bg-no-repeat max-[1050px]:!bg-none bg-[linear-gradient(180deg,_#f2f2f2_69.59%,_#ededed_100%)] bg-cover"
         id="<?php echo esc_attr($unique_id); ?> "
    <?php echo $style_attr; ?>
>

    <div class="mt-[-9px] max-[1050px]:py-[0] max-[1050px]:flex-col-reverse max-[1050px]:items-center max-[1050px]:justify-center max-[1050px]:gap-[20px] container mx-auto py-[48px] flex relative">
     
        <div class="max-[1050px]:w-[calc(100%+20px)] max-[768px]:w-[calc(100%+48px)] bg-[100%_8px] bg-no-repeat max-[1050px]:flex max-[1050px]:items-center max-[1050px]:justify-center bg-cover bg-no-repeat absolute right-0 bottom-0 max-[1050px]:static"
             data-bg-image="<?php echo esc_url($bg_image); ?>">


            <img class="max-[1050px]:max-h-[274px] pointer-events-none z-0"
                 src="<?php echo esc_url(get_template_directory_uri() . '/assets/images/form-image-trainer.png'); ?>"
                 alt="Изображение тренера">
        </div>

        <script>
            function setResponsiveBackground() {
                const elements = document.querySelectorAll('[data-bg-image]');
                elements.forEach(el => {
                    if (window.innerWidth <= 1050) {
                        el.style.backgroundImage = `url(${el.dataset.bgImage})`;
                    } else {
                        el.style.backgroundImage = 'none';
                    }
                });
            }

            window.addEventListener('resize', setResponsiveBackground);
            setResponsiveBackground();
        </script>

        <div class="max-[768px]:p-[20px] form-block-wrapper relative z-[1] border border-[2px] border-[#fff] p-[48px] bg-[#f8f8f8] rounded-[32px] w-full max-w-[590px]"
             data-form-id="<?php echo esc_attr($form_id); ?>"
             data-submit-text="<?php echo esc_attr($submit_button_text); ?>"
             data-hidden-value="<?php echo esc_attr($hidden_value); ?>">
            <h3 class="max-[1050px]:text-[30px] max-[768px]:text-[24px] font-[500] text-[40px] leading-[120%] text-[#222]">Пробная <strong class="font-[700]">персональная
                    тренировка</strong>
                <span class="max-[768px]:text-[20px] max-[768px]:mt-[10px] max-[768px]:h-[29px] bg-[linear-gradient(90deg,_#9d9994_39.42%,_#ccc9c4_92.9%)] rounded-[32px] h-[43px] inline-flex items-center pr-[16px] pl-[16px] font-[600] text-[32px] leading-[115%] text-[#fff]">за 0 ₽</span>
            </h3>
            <p class="max-[1050px]:text-[18px] max-[768px]:text-[16px] mt-[16px] mb-[24px] font-[500] text-[20px] leading-[140%] text-[#222]">Познакомимся, покажем зал и
                <strong class="font-[600]">подберём
                    оптимальные для вас тренировки!</strong></p>
            <?php echo do_shortcode('[fluentform id="' . esc_attr($form_id) . '"]'); ?>
        </div>
    </div>
</section>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const section = document.getElementById('<?php echo esc_js($unique_id); ?>');
        if (!section) return;

        const block = section.querySelector('.form-block-wrapper');
        if (!block) return;

        const submitText = block.dataset.submitText;
        const hiddenValue = block.dataset.hiddenValue;

        function updateForm() {
            const submitButton = block.querySelector('.ff-btn-submit');
            const hiddenInput = block.querySelector('input[name="hidden"]');

            let updated = false;

            if (submitButton && submitText) {
                submitButton.textContent = submitText;
                updated = true;
            }

            if (hiddenInput && hiddenValue && !hiddenInput.value) {
                hiddenInput.value = hiddenValue;
                updated = true;
            }

            return updated;
        }

        if (!updateForm()) {
            let attempts = 0;
            const maxAttempts = 3;

            const interval = setInterval(() => {
                attempts++;
                if (updateForm() || attempts >= maxAttempts) {
                    clearInterval(interval);
                }
            }, 150);
        }

        block.addEventListener('focusin', updateForm, {once: true});
    });
</script>