<?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;

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

<section class="container mx-auto mt-[22px]" id="<?php echo esc_attr($unique_id); ?>">
    <div class="text-[24px] font-[700] mb-[20px] text-[#374151]">
        <?php echo esc_html($form_title); ?>
    </div>

    <div class="form-block-wrapper bg-white p-[30px] rounded-[12px] max-w-[300px]"
         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); ?>">
        <?php echo do_shortcode('[fluentform id="' . esc_attr($form_id) . '"]'); ?>
    </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>