<?php

namespace GriffinForms\Editors\Gutenberg;

/**
 * Renders a lightweight HTML preview from REST payloads for the block editor.
 * No front-end assets or scripts are enqueued; output is sanitized plain markup.
 */
class PreviewRenderer
{
    private $payload_page_style_css = '';
    private $payload_row_style_css = '';
    private $payload_signature_canvas_style = '';
    private $payload_richtext_editor_style = '';
    private $payload_likert_table_style = ['wrapper' => '', 'border_color' => ''];

    /**
     * Render preview HTML from a structure payload.
     *
     * @param array $payload Structure data from RestStructureBuilder.
     * @return string
     */
    public function render(array $payload): string
    {
        $this->payload_page_style_css = $payload['page_style_css'] ?? '';
        $this->payload_row_style_css = $payload['row_style_css'] ?? '';
        $this->payload_signature_canvas_style = $payload['signature_canvas_style'] ?? '';
        $this->payload_richtext_editor_style = $payload['richtext_editor_style'] ?? '';
        $lts = $payload['likert_table_style'] ?? [];
        $this->payload_likert_table_style = is_array($lts) ? $lts : ['wrapper' => '', 'border_color' => ''];
        if (empty($payload) || !is_array($payload)) {
            return '';
        }

        $form_style = '';
        if (!empty($payload['form_style_css'])) {
            $form_style = ' style="' . esc_attr($payload['form_style_css']) . '"';
        }

        $html = '<div class="griffinforms-block-preview"' . $form_style . '>';
        if (!empty($payload['theme_css'])) {
            $html .= '<style class="gf-bp-theme">' . $payload['theme_css'] . '</style>';
        }

        if (!empty($payload['heading'])) {
            $html .= '<div class="gf-block-preview-heading" style="font-size:18px;font-weight:600;margin-bottom:4px;">' . esc_html($payload['heading']) . '</div>';
        }

        if (!empty($payload['description'])) {
            $html .= '<div class="gf-block-preview-desc" style="color:#555;font-size:13px;margin-bottom:12px;">' . esc_html($payload['description']) . '</div>';
        }

        if (!empty($payload['pages']) && is_array($payload['pages'])) {
            foreach ($payload['pages'] as $page_index => $page) {
                $html .= $this->renderPage($page_index, $page);
            }
        }

        if (!empty($payload['submit_label'])) {
            $html .= '<div class="gf-block-preview-submit" style="margin-top:12px;">';
            $html .= '<button type="button" style="padding:8px 14px;border-radius:4px;border:1px solid #ccc;background:#f5f5f5;font-weight:600;">' . esc_html($payload['submit_label']) . '</button>';
            $html .= '</div>';
        }

        if (!empty($payload['truncated']) && !empty($payload['truncated_notice'])) {
            $html .= '<div class="gf-block-preview-truncated" style="margin-top:12px;padding:8px;border:1px dashed #d9534f;color:#a94442;background:#fff5f5;font-size:12px;border-radius:4px;">' . esc_html($payload['truncated_notice']) . '</div>';
        }

        $html .= '</div>';
        return $html;
    }

    private function renderPage(int $page_index, array $page): string
    {
        $base_page_style = 'display:block;width:100%;';
        $page_style = '';
        if (!empty($page['page_style_css'])) {
            $page_style = ' style="' . esc_attr($page['page_style_css'] . ';' . $base_page_style) . '"';
        } elseif (!empty($this->payload_page_style_css)) {
            $page_style = ' style="' . esc_attr($this->payload_page_style_css . ';' . $base_page_style) . '"';
        } else {
            $page_style = ' style="' . esc_attr($base_page_style) . '"';
        }

        $row_style = !empty($this->payload_row_style_css) ? $this->payload_row_style_css : '';

        $html = '<div class="gf-block-preview-page" style="margin-bottom:12px;"' . $page_style . '>';

        if (!empty($page['heading'])) {
            $html .= '<div class="gf-block-preview-page-title" style="font-weight:600;font-size:14px;margin-bottom:6px;">' . esc_html($page['heading']) . '</div>';
        }

        if (!empty($page['description'])) {
            $html .= '<div class="gf-block-preview-page-desc" style="color:#666;font-size:12px;margin-bottom:6px;">' . esc_html($page['description']) . '</div>';
        }

        $html .= '<div class="gf-block-preview-page-body" style="display:block;width:100%;">';

        if (!empty($page['rows']) && is_array($page['rows'])) {
            foreach ($page['rows'] as $row) {
                $html .= $this->renderRow($row);
            }
        }

        $html .= '</div>';

        // Navigation (inside page)
        // Placeholder nav inside page for structure; real nav logic handled client-side
        $html .= '<div class="gf-block-preview-pagenav" style="display:flex;justify-content:space-between;gap:8px;margin-top:10px;grid-column:1/-1;">';
        $html .= '<button type="button" class="gf-bp-submit-btn gf-bp-nav-btn gf-bp-nav-prev" style="padding:8px 14px;border-radius:4px;border:1px solid #ccc;background:#f5f5f5;font-weight:600;">' . esc_html__('Previous', 'griffinforms-form-builder') . '</button>';
        $html .= '<button type="button" class="gf-bp-submit-btn gf-bp-nav-btn gf-bp-nav-next" style="padding:8px 14px;border-radius:4px;border:1px solid #ccc;background:#f5f5f5;font-weight:600;">' . esc_html__('Next', 'griffinforms-form-builder') . '</button>';
        $html .= '<button type="button" class="gf-bp-submit-btn gf-bp-nav-btn gf-bp-nav-submit" style="padding:8px 14px;border-radius:4px;border:1px solid #ccc;background:#f5f5f5;font-weight:600;">' . esc_html__('Submit', 'griffinforms-form-builder') . '</button>';
        $html .= '</div>';

        $html .= '</div>';
        return $html;
    }

    private function renderRow(array $row): string
    {
        $row_style = '';
        if (!empty($this->payload_row_style_css)) {
            $row_style .= $this->payload_row_style_css . ' ';
        }
        $row_style .= 'margin-bottom:8px;display:grid !important;grid-template-columns:repeat(12,minmax(0,1fr)) !important;gap:8px !important;width:100% !important;';
        $html = '<div class="gf-block-preview-row" style="' . esc_attr($row_style) . '">';

        if (!empty($row['heading'])) {
            $html .= '<div class="gf-block-preview-row-heading" style="font-weight:600;font-size:13px;margin-bottom:4px;flex:0 0 100%;">' . esc_html($row['heading']) . '</div>';
        }

        if (!empty($row['columns']) && is_array($row['columns'])) {
            foreach ($row['columns'] as $column) {
                $html .= $this->renderColumn($column, $row_style);
            }
        }

        if (!empty($row['description'])) {
            $html .= '<div class="gf-block-preview-row-desc" style="color:#777;font-size:12px;margin-bottom:4px;flex:0 0 100%;">' . esc_html($row['description']) . '</div>';
        }

        $html .= '</div>';
        return $html;
    }

    private function renderColumn(array $column, string $row_style = ''): string
    {
        $width = isset($column['width']) && $column['width'] > 0 ? (int) $column['width'] : 12;
        $span = max(1, min(12, $width));
        $inline = 'margin-bottom:6px;box-sizing:border-box;grid-column:span ' . esc_attr($span) . ';min-width:0;';
        if ($row_style !== '') {
            $inline .= ' ' . $row_style;
        }
        $html = '<div class="gf-block-preview-column" style="' . esc_attr($inline) . '">';

        if (!empty($column['fields']) && is_array($column['fields'])) {
            foreach ($column['fields'] as $field) {
                $html .= $this->renderField($field);
            }
        }

        $html .= '</div>';
        return $html;
    }

    private function renderField(array $field): string
    {
        $label = !empty($field['label']) ? esc_html($field['label']) : __('Untitled field', 'griffinforms-form-builder');
        $description = !empty($field['description']) ? esc_html($field['description']) : '';
        $required = !empty($field['required']);

        $html = '<div class="gf-block-preview-field" style="margin-bottom:8px;">';
        $html .= '<label class="gf-bp-label" style="display:block;font-weight:600;font-size:13px;margin-bottom:2px;">' . $label;
        if ($required) {
            $settings = \GriffinForms\Settings::getInstance();
            $mode     = (string) $settings->getOption('required_indicator_mode', 'asterisk');
            $text     = $mode === 'asterisk' ? '*' : (string) $settings->getOption('required_indicator_custom_text', '');
            if ($text === 'none') { $text = ''; }
            if ($text !== '') {
                $html .= ' <span class="gf-required-indicator" aria-hidden="true" style="color:#d9534f;">' . esc_html($text) . '</span>';
            }
        }
        $html .= '</label>';

        $html .= '<div style="margin-bottom:4px;">' . $this->placeholderControl($field) . '</div>';

        if ($description !== '') {
            $html .= '<div style="color:#666;font-size:12px;margin-bottom:2px;">' . $description . '</div>';
        }

        $html .= '</div>';
        return $html;
    }

    private function placeholderControl(array $field): string
    {
        $type = isset($field['field_type']) ? sanitize_key($field['field_type']) : 'inputtext';
        $placeholder = !empty($field['placeholder']) ? esc_attr($field['placeholder']) : '';
        $options = isset($field['options']) && is_array($field['options']) ? $field['options'] : array();

        switch ($type) {
            case 'textarea':
                return '<textarea style="width:100%;min-height:60px;box-sizing:border-box;border:1px solid #ccc;border-radius:4px;padding:8px;background:#fcfcfc;" placeholder="' . $placeholder . '"></textarea>';
            case 'selectfield':
                $html = '<select style="width:100%;max-width:100%;box-sizing:border-box;min-height:38px;border:1px solid #ccc;border-radius:4px;padding:8px;background:#fcfcfc;">';
                if (!empty($options)) {
                    foreach ($options as $group) {
                        $group_label = isset($group['group']) ? $group['group'] : '';
                        $group_options = isset($group['options']) && is_array($group['options']) ? $group['options'] : array();
                        if ($group_label !== '') {
                            $html .= '<optgroup label="' . esc_attr($group_label) . '">';
                        }
                        foreach ($group_options as $opt) {
                            $label = isset($opt['label']) ? $opt['label'] : '';
                            $html .= '<option>' . esc_html($label) . '</option>';
                        }
                        if ($group_label !== '') {
                            $html .= '</optgroup>';
                        }
                    }
                } else {
                    $html .= '<option>' . ($placeholder !== '' ? $placeholder : esc_html__('Select an option', 'griffinforms-form-builder')) . '</option>';
                }
                $html .= '</select>';
                return $html;
            case 'inputradio':
                $radio_cols = '';
                foreach ($options as $group) {
                    $group_options = isset($group['options']) && is_array($group['options']) ? $group['options'] : array();
                    if (empty($group_options)) {
                        continue;
                    }
                    $radio_cols .= '<div style="display:flex;flex-direction:column;gap:6px;margin-right:12px;">';
                    foreach ($group_options as $opt) {
                        $label = isset($opt['label']) ? $opt['label'] : __('Option', 'griffinforms-form-builder');
                        $radio_cols .= '<div style="display:flex;gap:6px;align-items:center;color:#555;"><span style="width:12px;height:12px;border:1px solid #999;border-radius:50%;display:inline-block;"></span><span>' . esc_html($label) . '</span></div>';
                    }
                    $radio_cols .= '</div>';
                }
                if ($radio_cols === '') {
                    $radio_cols = '<div style="display:flex;gap:8px;color:#555;"><span style="display:inline-flex;align-items:center;gap:4px;"><span style="width:12px;height:12px;border:1px solid #999;border-radius:50%;display:inline-block;"></span>' . __('Option', 'griffinforms-form-builder') . '</span></div>';
                } else {
                    $radio_cols = '<div style="display:flex;flex-wrap:wrap;">' . $radio_cols . '</div>';
                }
                return $radio_cols;
            case 'inputcheckbox':
                $check_cols = '';
                foreach ($options as $group) {
                    $group_options = isset($group['options']) && is_array($group['options']) ? $group['options'] : array();
                    if (empty($group_options)) {
                        continue;
                    }
                    $check_cols .= '<div style="display:flex;flex-direction:column;gap:6px;margin-right:12px;">';
                    foreach ($group_options as $opt) {
                        $label = isset($opt['label']) ? $opt['label'] : __('Option', 'griffinforms-form-builder');
                        $check_cols .= '<div style="display:flex;gap:6px;align-items:center;color:#555;"><span style="width:12px;height:12px;border:1px solid #999;display:inline-block;"></span><span>' . esc_html($label) . '</span></div>';
                    }
                    $check_cols .= '</div>';
                }
                if ($check_cols === '') {
                    $check_cols = '<div style="display:flex;gap:8px;color:#555;"><span style="display:inline-flex;align-items:center;gap:4px;"><span style="width:12px;height:12px;border:1px solid #999;display:inline-block;"></span>' . __('Option', 'griffinforms-form-builder') . '</span></div>';
                } else {
                    $check_cols = '<div style="display:flex;flex-wrap:wrap;">' . $check_cols . '</div>';
                }
                return $check_cols;
            case 'inputlikert':
                $lk_rows      = is_array($field['likert_rows'] ?? null)    ? $field['likert_rows']    : [['id' => 'row_1', 'label' => 'Row 1'], ['id' => 'row_2', 'label' => 'Row 2']];
                $lk_cols      = is_array($field['likert_columns'] ?? null) ? $field['likert_columns'] : [['id' => 'col_1', 'label' => 'Disagree'], ['id' => 'col_2', 'label' => 'Neutral'], ['id' => 'col_3', 'label' => 'Agree']];
                $lk_allow_na  = !empty($field['likert_allow_na']);
                $lk_col_width = ($field['likert_column_width'] ?? 'auto') === 'equal' ? 'fixed' : 'auto';
                $lk_style       = $this->payload_likert_table_style;
                $lk_wrapper     = !empty($lk_style['wrapper']) ? $lk_style['wrapper'] : 'border:1px solid #dee2e6;border-radius:4px;';
                $lk_bc          = !empty($lk_style['border_color']) ? $lk_style['border_color'] : '#dee2e6';
                $lk_label_color = !empty($lk_style['label_color']) ? $lk_style['label_color'] : '';
                $lk_label_css   = $lk_label_color !== '' ? 'color:' . esc_attr($lk_label_color) . ';' : '';
                $lk_bg_color    = !empty($lk_style['bg_color']) ? $lk_style['bg_color'] : '';
                $lk_bg_css      = $lk_bg_color !== '' ? 'background-color:' . esc_attr($lk_bg_color) . ';' : '';
                $lk_vb          = 'border-left:1px solid ' . esc_attr($lk_bc) . ';';
                $lk_html        = '<div style="overflow:hidden;' . esc_attr($lk_wrapper) . '">';
                $lk_html       .= '<div style="overflow-x:auto;">';
                $lk_html       .= '<table style="width:100%;border-collapse:collapse;table-layout:' . esc_attr($lk_col_width) . ';font-size:12px;' . $lk_bg_css . '">';
                $lk_html       .= '<thead><tr>';
                $lk_html       .= '<th style="text-align:left;padding:5px 8px;border-bottom:1px solid ' . esc_attr($lk_bc) . ';min-width:90px;"></th>';
                foreach ($lk_cols as $col) {
                    $lk_html .= '<th style="text-align:center;padding:5px 8px;border-bottom:1px solid ' . esc_attr($lk_bc) . ';' . $lk_vb . $lk_label_css . 'min-width:80px;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;">' . esc_html($col['label'] ?? '') . '</th>';
                }
                if ($lk_allow_na) {
                    $lk_html .= '<th style="text-align:center;padding:5px 8px;border-bottom:1px solid ' . esc_attr($lk_bc) . ';' . $lk_vb . 'min-width:44px;color:#aaa;">N/A</th>';
                }
                $lk_html .= '</tr></thead><tbody>';
                $lk_row_count = count($lk_rows);
                foreach ($lk_rows as $lk_ri => $row) {
                    $is_last_row = ($lk_ri === $lk_row_count - 1);
                    $cell_border = $is_last_row ? 'none' : '1px solid ' . esc_attr($lk_bc);
                    $lk_html    .= '<tr>';
                    $lk_html    .= '<td style="text-align:left;padding:5px 8px;border-bottom:' . $cell_border . ';white-space:nowrap;' . $lk_label_css . '">' . esc_html($row['label'] ?? '') . '</td>';
                    foreach ($lk_cols as $_col) {
                        $lk_html .= '<td style="text-align:center;padding:5px 8px;border-bottom:' . $cell_border . ';' . $lk_vb . '"><input type="radio" disabled style="opacity:0.6;"></td>';
                    }
                    if ($lk_allow_na) {
                        $lk_html .= '<td style="text-align:center;padding:5px 8px;border-bottom:' . $cell_border . ';' . $lk_vb . '"><input type="radio" disabled style="opacity:0.35;"></td>';
                    }
                    $lk_html .= '</tr>';
                }
                $lk_html .= '</tbody></table></div></div>';
                return $lk_html;
            case 'imageselection':
                $imagesel_options = is_array($field['imagesel_options'] ?? null) ? $field['imagesel_options'] : array();
                $imagesel_columns = isset($field['imagesel_columns_desktop']) ? max(1, min(4, absint($field['imagesel_columns_desktop']))) : 3;
                $imagesel_show_title = !empty($field['imagesel_show_title']);
                $imagesel_show_description = !empty($field['imagesel_show_description']);
                $imagesel_display = !empty($imagesel_options) ? array_slice($imagesel_options, 0, 4) : array(
                    array('image_url' => '', 'title' => __('Image Option', 'griffinforms-form-builder'), 'description' => ''),
                    array('image_url' => '', 'title' => __('Image Option', 'griffinforms-form-builder'), 'description' => ''),
                    array('image_url' => '', 'title' => __('Image Option', 'griffinforms-form-builder'), 'description' => ''),
                );
                $imagesel_html = '<div style="display:grid;grid-template-columns:repeat(' . esc_attr((string) $imagesel_columns) . ',minmax(0,1fr));gap:8px;">';
                foreach ($imagesel_display as $index => $option) {
                    $title = !empty($option['title']) ? sanitize_text_field((string) $option['title']) : __('Image Option', 'griffinforms-form-builder');
                    $description = !empty($option['description']) ? sanitize_textarea_field((string) $option['description']) : '';
                    $image_url = !empty($option['image_url']) ? esc_url((string) $option['image_url']) : '';
                    $selected_style = $index === 0 ? 'border-color:var(--wp-admin-theme-color, #3858e9);position:relative;z-index:1;box-shadow:none;' : '';
                    $imagesel_html .= '<div style="border:1px solid #d0d7de;border-radius:8px;overflow:hidden;background:#fff;display:flex;flex-direction:column;height:100%;' . $selected_style . '">';
                    if ($image_url !== '') {
                        $imagesel_html .= '<div style="aspect-ratio:1/1;background:#f6f7f7 url(' . $image_url . ') center/cover no-repeat;"></div>';
                    } else {
                        $imagesel_html .= '<div style="aspect-ratio:1/1;background:linear-gradient(135deg,#f6f7f7,#e9ecef);display:flex;align-items:center;justify-content:center;color:#8c8f94;font-size:11px;">' . esc_html__('Image', 'griffinforms-form-builder') . '</div>';
                    }
                    if (($imagesel_show_title && $title !== '') || ($imagesel_show_description && $description !== '')) {
                        $imagesel_html .= '<div style="padding:6px 8px;border-top:1px solid #e2e8f0;background:#fff;flex:1 1 auto;">';
                        if ($imagesel_show_title && $title !== '') {
                            $imagesel_html .= '<div style="font-size:11px;font-weight:600;line-height:1.3;color:#1d2327;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' . esc_html($title) . '</div>';
                        }
                        if ($imagesel_show_description && $description !== '') {
                            $imagesel_html .= '<div style="margin-top:4px;font-size:10px;line-height:1.4;color:#646970;">' . esc_html($description) . '</div>';
                        }
                        $imagesel_html .= '</div>';
                    }
                    $imagesel_html .= '</div>';
                }
                $imagesel_html .= '</div>';
                return $imagesel_html;
            case 'inputrichtext':
                $rt_height = isset($field['richtext_min_height']) && $field['richtext_min_height'] > 0 ? (int) $field['richtext_min_height'] : 120;
                $rt_placeholder = !empty($field['richtext_placeholder']) ? esc_html($field['richtext_placeholder']) : esc_html__('Write something…', 'griffinforms-form-builder');
                $rt_toolbar = !empty($field['richtext_toolbar']) && is_array($field['richtext_toolbar']) ? $field['richtext_toolbar'] : ['bold', 'italic', 'underline', 'bulletlist', 'link'];
                $toolbar_labels = ['bold' => 'B', 'italic' => 'I', 'underline' => 'U', 'strike' => 'S̶', 'heading1' => 'H1', 'heading2' => 'H2', 'heading3' => 'H3', 'bulletlist' => '≡', 'orderedlist' => '1.', 'blockquote' => '❝', 'code' => '</>', 'link' => '🔗', 'horizontalrule' => '—', 'clearformatting' => 'Tx'];
                $editor_style = 'width:100%;box-sizing:border-box;height:' . $rt_height . 'px;display:flex;align-items:center;justify-content:center;border-top:0;border-radius:0 0 4px 4px;';
                $editor_style .= $this->payload_richtext_editor_style !== '' ? $this->payload_richtext_editor_style : 'border:1px solid #ccc;border-radius:4px;';
                $toolbar_html = '';
                foreach ($rt_toolbar as $item) {
                    $lbl = isset($toolbar_labels[$item]) ? $toolbar_labels[$item] : $item;
                    $toolbar_html .= '<span style="font-size:12px;font-weight:600;color:#6c757d;min-width:24px;height:26px;display:inline-flex;align-items:center;justify-content:center;padding:0 3px;">' . esc_html($lbl) . '</span>';
                }
                return '<div style="border:1px solid #ccc;border-radius:4px;overflow:hidden;' . ($this->payload_richtext_editor_style !== '' ? str_replace('border-radius:0 0 4px 4px;', '', $this->payload_richtext_editor_style) : '') . '">'
                    . '<div style="border-bottom:1px solid #dee2e6;padding:6px 8px;display:flex;gap:4px;flex-wrap:wrap;align-items:center;">' . $toolbar_html . '</div>'
                    . '<div style="' . esc_attr($editor_style) . '">'
                    . '<span style="font-size:12px;color:#aaa;opacity:0.8;">' . $rt_placeholder . '</span>'
                    . '</div>'
                    . '</div>';
            case 'signature':
                $sig_height = isset($field['pad_height']) && $field['pad_height'] > 0 ? (int) $field['pad_height'] : 120;
                $sig_placeholder = !empty($field['signature_placeholder']) ? esc_html($field['signature_placeholder']) : esc_html__('Sign here', 'griffinforms-form-builder');
                $sig_bg = !empty($field['signature_bg_color']) ? $field['signature_bg_color'] : '#ffffff';
                $sig_pen = !empty($field['signature_pen_color']) ? $field['signature_pen_color'] : '#000000';
                $canvas_style = 'width:100%;box-sizing:border-box;height:' . $sig_height . 'px;display:flex;align-items:center;justify-content:center;background-color:' . esc_attr($sig_bg) . ';';
                if ($this->payload_signature_canvas_style !== '') {
                    $canvas_style .= $this->payload_signature_canvas_style;
                } else {
                    $canvas_style .= 'border:1px solid #ccc;border-radius:4px;';
                }
                return '<div style="' . esc_attr($canvas_style) . '">'
                    . '<span style="color:' . esc_attr($sig_pen) . ';font-size:12px;opacity:0.4;">' . $sig_placeholder . '</span>'
                    . '</div>'
                    . '<div style="text-align:right;margin-top:4px;">'
                    . ($this->payload_signature_canvas_style !== ''
                        ? '<button type="button" disabled data-gf-button-type="previous">' . esc_html__('Clear', 'griffinforms-form-builder') . '</button>'
                        : '<button type="button" disabled style="font-size:11px;padding:2px 8px;cursor:default;border:1px solid #ccc;border-radius:4px;background:#f5f5f5;">' . esc_html__('Clear', 'griffinforms-form-builder') . '</button>')
                    . '</div>';
            case 'fileupload':
                return '<input type="file" style="width:100%;box-sizing:border-box;min-height:38px;border:1px solid #ccc;border-radius:4px;padding:6px;background:#fcfcfc;">';
            case 'inputphone':
                $options_html = '<option>' . ($placeholder !== '' ? $placeholder : esc_html__('Select a country', 'griffinforms-form-builder')) . '</option>';
                if (class_exists('\\GriffinForms\\Includes\\Helpers\\PhoneCountries')) {
                    $countries = \GriffinForms\Includes\Helpers\PhoneCountries::getCountries();
                    $sample = array_slice($countries, 0, 5);
                    foreach ($sample as $country) {
                        $label = trim(($country['flag'] ?? '') . ' ' . ($country['dial_code'] ?? ''));
                        if ($label === '') {
                            $label = $country['name'] ?? __('Country', 'griffinforms-form-builder');
                        }
                        $options_html .= '<option>' . esc_html($label) . '</option>';
                    }
                }
                return '<div style="display:flex;width:100%;gap:0;">'
                    . '<span style="display:none;">gf-phone-preview-v2</span>'
                    . '<select style="width:30%;min-width:120px;box-sizing:border-box;min-height:38px;border:1px solid #ccc;border-right:0;border-radius:4px 0 0 4px;padding:8px;background:#fcfcfc;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'
                    . $options_html
                    . '</select>'
                    . '<input type="text" style="flex:1;min-width:0;box-sizing:border-box;min-height:38px;border:1px solid #ccc;border-left:0;border-radius:0 4px 4px 0;padding:8px;background:#fcfcfc;" placeholder="' . $placeholder . '">'
                    . '</div>';
            case 'payment':
                $pay_products = isset($field['payment_products']) && is_array($field['payment_products']) ? $field['payment_products'] : array();
                $pay_layout   = isset($field['payment_layout']) ? $field['payment_layout'] : 'cards';
                if (empty($pay_products)) {
                    return '<div style="padding:10px;border:1px dashed #ccc;border-radius:4px;color:#888;font-size:12px;">' . esc_html__('No products configured.', 'griffinforms-form-builder') . '</div>';
                }
                $pay_symbol  = '';
                if (class_exists('\\GriffinForms\\Includes\\Helpers\\Currency') && class_exists('\\GriffinForms\\Settings')) {
                    $pay_settings = \GriffinForms\Settings::getInstance();
                    $pay_currency = (string) $pay_settings->getOption('payment_currency', 'USD');
                    $pay_symbol   = \GriffinForms\Includes\Helpers\Currency::getInstance()->getCurrencySymbol($pay_currency);
                }
                $pay_is_list  = $pay_layout === 'list';
                $pay_grid_css = $pay_is_list
                    ? 'display:grid;gap:10px;'
                    : 'display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px;';
                $pay_html = '<div style="' . $pay_grid_css . '">';
                foreach ($pay_products as $pay_prod) {
                    $pay_name  = esc_html($pay_prod['name'] ?? __('Product', 'griffinforms-form-builder'));
                    $pay_price = number_format((float) ($pay_prod['price'] ?? 0), 2, '.', '');
                    $pay_desc  = esc_html($pay_prod['description'] ?? '');
                    $pay_img   = esc_url($pay_prod['image'] ?? '');
                    if ($pay_is_list) {
                        $pay_html .= '<div style="border:1px solid #e5e7eb;border-radius:8px;padding:10px;display:flex;gap:12px;align-items:flex-start;">';
                        if ($pay_img !== '') {
                            $pay_html .= '<img src="' . $pay_img . '" alt="' . $pay_name . '" style="width:80px;height:80px;object-fit:cover;border-radius:6px;flex-shrink:0;">';
                        }
                        $pay_html .= '<div style="flex:1 1 0;min-width:0;">';
                        $pay_html .= '<div style="display:flex;justify-content:space-between;gap:8px;margin-bottom:4px;"><span style="font-weight:600;font-size:13px;">' . $pay_name . '</span><span style="font-weight:600;font-size:13px;white-space:nowrap;">' . esc_html($pay_symbol) . $pay_price . '</span></div>';
                        if ($pay_desc !== '') {
                            $pay_html .= '<div style="font-size:11px;color:#666;margin-bottom:6px;">' . $pay_desc . '</div>';
                        }
                        $pay_html .= '<div style="display:flex;align-items:center;gap:6px;font-size:12px;"><input type="checkbox" disabled style="margin:0;"> <span style="font-weight:600;">' . esc_html__('Include this item', 'griffinforms-form-builder') . '</span></div>';
                        $pay_html .= '</div></div>';
                    } else {
                        $pay_html .= '<div style="border:1px solid #e5e7eb;border-radius:10px;padding:12px;background:#fff;">';
                        if ($pay_img !== '') {
                            $pay_html .= '<img src="' . $pay_img . '" alt="' . $pay_name . '" style="width:100%;height:120px;object-fit:cover;border-radius:8px;margin-bottom:8px;">';
                        }
                        $pay_html .= '<div style="display:flex;justify-content:space-between;gap:8px;margin-bottom:4px;"><span style="font-weight:600;font-size:13px;">' . $pay_name . '</span><span style="font-weight:600;font-size:13px;white-space:nowrap;">' . esc_html($pay_symbol) . $pay_price . '</span></div>';
                        if ($pay_desc !== '') {
                            $pay_html .= '<div style="font-size:11px;color:#666;margin-bottom:6px;">' . $pay_desc . '</div>';
                        }
                        $pay_html .= '<div style="display:flex;align-items:center;gap:6px;font-size:12px;"><input type="checkbox" disabled style="margin:0;"> <span style="font-weight:600;">' . esc_html__('Include this item', 'griffinforms-form-builder') . '</span></div>';
                        $pay_html .= '</div>';
                    }
                }
                $pay_html .= '</div>';
                return $pay_html;
            default:
                return '<input type="text" style="width:100%;box-sizing:border-box;min-height:38px;border:1px solid #ccc;border-radius:4px;padding:8px;background:#fcfcfc;" placeholder="' . $placeholder . '">';
        }
    }
}
