<?php

namespace GriffinForms\Admin\Html\FormControls\Field\FieldSettings;

class InputRatingSettings extends \GriffinForms\Admin\Html\FormControls\Field\FieldSettings\Format
{
    public function html()
    {
        $s = is_array($this->value) ? $this->value : [];
        $scale = max(2, min(10, absint($s['scale'] ?? 5)));
        $icon_group = sanitize_key((string) ($s['icon_group'] ?? 'star'));
        $icon_size = max(16, min(64, absint($s['icon_size'] ?? 32)));
        $icon_spacing = max(0, min(24, absint($s['icon_spacing'] ?? 4)));
        $color_filled = !empty($s['color_filled']) ? $s['color_filled'] : '#f5a623';
        $color_empty = !empty($s['color_empty']) ? $s['color_empty'] : '#d1d5db';
        $custom_image_id = absint($s['custom_image_id'] ?? 0);
        $step_image_ids = array_values(is_array($s['step_image_ids'] ?? null) ? $s['step_image_ids'] : []);
        $step_labels = array_values(is_array($s['step_labels'] ?? null) ? $s['step_labels'] : []);
        $has_step_labels = false;
        foreach ($step_labels as $step_label) {
            if (trim((string) $step_label) !== '') {
                $has_step_labels = true;
                break;
            }
        }
        $allow_clear = !empty($s['allow_clear']);

        $scale_field = new \GriffinForms\Admin\Html\FormControls\InputNumber('scale', $scale);
        $scale_field->setAttr('min', 2);
        $scale_field->setAttr('max', 10);
        $icon_size_field = new \GriffinForms\Admin\Html\FormControls\InputNumber('icon_size', $icon_size);
        $icon_size_field->setAttr('min', 16);
        $icon_size_field->setAttr('max', 64);
        $icon_spacing_field = new \GriffinForms\Admin\Html\FormControls\InputNumber('icon_spacing', $icon_spacing);
        $icon_spacing_field->setAttr('min', 0);
        $icon_spacing_field->setAttr('max', 24);
        $groups = ['star' => 'Star', 'heart' => 'Heart', 'thumb' => 'Thumb', 'face' => 'Face', 'circle' => 'Circle', 'flag' => 'Flag', 'bolt' => 'Bolt', 'diamond' => 'Diamond', 'custom' => 'Custom'];
        wp_enqueue_media();
        $labels_json = wp_json_encode($step_labels);
        $images_json = wp_json_encode($step_image_ids);
        $custom_image_thumb = $custom_image_id ? wp_get_attachment_image($custom_image_id, 'thumbnail', false, ['class' => 'img-thumbnail', 'style' => 'width:48px;height:48px;object-fit:cover;']) : '';
        $icon_asset_base = trailingslashit(WP_PLUGIN_DIR) . 'griffinforms-form-builder-pro/admin/images/rating-icons/';
        $icon_asset_url_base = trailingslashit(WP_PLUGIN_URL) . 'griffinforms-form-builder-pro/admin/images/rating-icons/';
        $icon_preview_map = [
            'star' => 'star-filled.svg',
            'heart' => 'heart-filled.svg',
            'thumb' => 'thumb-filled.svg',
            'face' => 'face-filled.svg',
            'circle' => 'circle-filled.svg',
            'flag' => 'flag-filled.svg',
            'bolt' => 'bolt-filled.svg',
            'diamond' => 'diamond-filled.svg',
        ];
        $icon_picker_color = '#6b7280';
        ?>
        <div class="inputrating-settings">
            <div class="row g-3 align-items-start">
                <div class="col-md-4"><label class="form-label me-2"><?php echo esc_html($this->lang->getText('rating_scale_label')); ?></label><?php $scale_field->html(); ?></div>
                <div class="col-md-4"><label class="form-label me-2"><?php echo esc_html($this->lang->getText('rating_icon_size_label')); ?></label><?php $icon_size_field->html(); ?></div>
                <div class="col-md-4"><label class="form-label me-2"><?php echo esc_html($this->lang->getText('rating_icon_spacing_label')); ?></label><?php $icon_spacing_field->html(); ?></div>
                <div class="col-md-4"><label class="form-label me-2"><?php echo esc_html($this->lang->getText('rating_color_filled_label')); ?></label><input type="color" id="griffinforms-rating-colorfilled-inputcolor" value="<?php echo esc_attr($color_filled); ?>"></div>
                <div class="col-md-4"><label class="form-label me-2"><?php echo esc_html($this->lang->getText('rating_color_empty_label')); ?></label><input type="color" id="griffinforms-rating-colorempty-inputcolor" value="<?php echo esc_attr($color_empty); ?>"></div>
                <div class="col-md-4"></div>
                <div class="col-12 pt-1">
                    <label class="form-label"><?php echo esc_html($this->lang->getText('rating_icon_group_label')); ?></label>
                    <div class="d-flex flex-wrap gap-2">
                        <?php foreach ($groups as $key => $label) : ?>
                            <label class="border rounded px-3 py-2 griffinforms-rating-group-option d-inline-flex align-items-center gap-2 <?php echo $icon_group === $key ? 'border-primary bg-light' : ''; ?>" data-icon-group="<?php echo esc_attr($key); ?>">
                                <input type="radio" name="icon_group" value="<?php echo esc_attr($key); ?>" <?php checked($icon_group, $key); ?>>
                                <span class="griffinforms-rating-group-icon d-inline-flex align-items-center justify-content-center" aria-hidden="true" style="width:18px;height:18px;line-height:1;">
                                    <?php if (!empty($icon_preview_map[$key]) && is_readable($icon_asset_base . $icon_preview_map[$key])) : ?>
                                        <?php echo $this->maskIconSpan($icon_asset_url_base . $icon_preview_map[$key], 18, $icon_picker_color); ?>
                                    <?php else : ?>
                                        <span class="small">◌</span>
                                    <?php endif; ?>
                                </span>
                                <span class="small fw-semibold lh-1"><?php echo esc_html($label); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="col-md-6" id="griffinforms-rating-customimage-wrap">
                    <label class="form-label me-2"><?php echo esc_html($this->lang->getText('rating_custom_image_label')); ?></label>
                    <div class="d-flex gap-2 align-items-center flex-wrap">
                        <span id="griffinforms-rating-customimage-thumb" class="d-inline-flex align-items-center justify-content-center"><?php echo wp_kses_post($custom_image_thumb); ?></span>
                        <button type="button" class="button button-secondary" id="griffinforms-rating-customimage-select"><?php esc_html_e('Select image', 'griffinforms-form-builder'); ?></button>
                        <button type="button" class="button" id="griffinforms-rating-customimage-clear"><?php esc_html_e('Clear', 'griffinforms-form-builder'); ?></button>
                        <input type="hidden" id="griffinforms-rating-customimage-id" value="<?php echo esc_attr($custom_image_id); ?>">
                    </div>
                    <div class="form-text text-muted mt-2">
                        <?php esc_html_e('Used for all ratings unless a step-specific image is set.', 'griffinforms-form-builder'); ?>
                    </div>
                </div>
                <div class="col-12" id="griffinforms-rating-steps-wrap">
                    <label class="form-label me-2"><?php echo esc_html__('Per-step images and labels', 'griffinforms-form-builder'); ?></label>
                    <div id="griffinforms-rating-steps" data-scale="<?php echo esc_attr($scale); ?>"></div>
                    <div class="form-text text-muted mt-2">
                        <?php esc_html_e('Per-step labels are always shown. Per-step images override the current icon group and any custom image for that step.', 'griffinforms-form-builder'); ?>
                    </div>
                </div>
                <div class="col-12">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-4">
                            <label class="d-flex align-items-center gap-2 mb-0">
                                <input type="checkbox" id="griffinforms-rating-clear-togglecheckbox" <?php checked($allow_clear); ?>>
                                <span><?php echo esc_html($this->lang->getText('rating_allow_clear_label')); ?></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script>
        jQuery(function($){
            const stepLabels = <?php echo $labels_json ?: '[]'; ?>;
            const stepImages = <?php echo $images_json ?: '[]'; ?>;
            const defaultScale = <?php echo (int) $scale; ?>;
            let mediaFrame = null;
            const setVisibility = function() {
                const isCustom = $('input[name="icon_group"]:checked').val() === 'custom';

                $('#griffinforms-rating-customimage-wrap').toggle(isCustom);
            };

            function renderRows() {
                const scale = parseInt($('#griffinforms-scale-inputnumber').val(), 10) || defaultScale;
                const liveLabels = [];
                const liveImages = [];
                $('#griffinforms-rating-steps .rating-step-label').each(function() { liveLabels.push($(this).val()); });
                $('#griffinforms-rating-steps .rating-step-image-id').each(function() { liveImages.push(parseInt($(this).val(), 10) || 0); });
                const currentLabels = (liveLabels.length ? liveLabels : stepLabels).slice(0, scale);
                const currentImages = (liveImages.length ? liveImages : stepImages).slice(0, scale);
                const steps = $('#griffinforms-rating-steps').empty();

                for (let i = 1; i <= scale; i++) {
                    const labelValue = currentLabels[i - 1] || '';
                    const imageValue = currentImages[i - 1] || 0;
                    steps.append(
                        '<div class="d-flex flex-wrap gap-3 align-items-center mb-2 rating-step-row" data-step="' + i + '">' +
                        '<span class="small text-muted" style="width:24px">' + i + '</span>' +
                        '<div class="rating-step-image-controls d-flex gap-2 align-items-center flex-wrap">' +
                        '<span class="rating-step-image-thumb d-inline-flex align-items-center justify-content-center" style="width:48px;height:48px;"></span>' +
                        '<button type="button" class="button button-secondary rating-step-image-select">Select image</button>' +
                        '<button type="button" class="button rating-step-image-clear">Clear</button>' +
                        '<input type="hidden" class="rating-step-image-id" value="' + imageValue + '">' +
                        '</div>' +
                        '<div class="flex-grow-1" style="min-width:220px;max-width:320px;margin-left:8px">' +
                        '<input type="text" class="form-control rating-step-label" value="' + $('<div>').text(labelValue).html() + '" placeholder="Label">' +
                        '</div>' +
                        '</div>'
                    );
                }
            }

            function renderStepThumbs() {
                $('#griffinforms-rating-steps .rating-step-row').each(function() {
                    const row = $(this);
                    const thumb = row.find('.rating-step-image-thumb');
                    const id = parseInt(row.find('.rating-step-image-id').val(), 10) || 0;

                    thumb.empty();
                    if (!id || typeof wp === 'undefined' || !wp.media || !wp.media.attachment) {
                        return;
                    }

                    const attachment = wp.media.attachment(id);
                    attachment.fetch().then(function() {
                        const data = attachment.toJSON();
                        const thumbUrl = data.sizes && data.sizes.thumbnail ? data.sizes.thumbnail.url : data.url;
                        if (thumbUrl) {
                            thumb.html('<img src="' + thumbUrl + '" class="img-thumbnail" style="width:48px;height:48px;object-fit:cover;" alt="">');
                        }
                    });
                });
            }

            function openMedia(targetInput) {
                if (typeof wp === 'undefined' || !wp.media) {
                    return;
                }
                mediaFrame = wp.media({
                    title: '<?php echo esc_js(__('Select rating image', 'griffinforms-form-builder')); ?>',
                    button: { text: '<?php echo esc_js(__('Use this image', 'griffinforms-form-builder')); ?>' },
                    multiple: false
                });
                mediaFrame.off('select');
                mediaFrame.on('select', function() {
                    const attachment = mediaFrame.state().get('selection').first().toJSON();
                    targetInput.val(attachment.id || 0).trigger('change');
                    const thumbUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
                    const thumbHtml = thumbUrl ? '<img src="' + thumbUrl + '" class="img-thumbnail" style="width:48px;height:48px;object-fit:cover;" alt="">' : '';
                    if (targetInput.attr('id') === 'griffinforms-rating-customimage-id') {
                        $('#griffinforms-rating-customimage-thumb').html(thumbHtml);
                    } else {
                        targetInput.closest('.rating-step-row').find('.rating-step-image-thumb').html(thumbHtml);
                    }
                    renderStepThumbs();
                });
                mediaFrame.open();
            }

            $('#griffinforms-rating-steps').on('click', '.rating-step-image-select', function() {
                openMedia($(this).siblings('.rating-step-image-id'));
            });
            $('#griffinforms-rating-steps').on('click', '.rating-step-image-clear', function() {
                const row = $(this).closest('.rating-step-row');
                row.find('.rating-step-image-id').val(0).trigger('change');
                row.find('.rating-step-image-thumb').empty();
            });
            $('#griffinforms-rating-customimage-select').on('click', function() {
                openMedia($('#griffinforms-rating-customimage-id'));
            });
            $('#griffinforms-rating-customimage-clear').on('click', function() {
                $('#griffinforms-rating-customimage-id').val(0).trigger('change');
                $('#griffinforms-rating-customimage-thumb').empty();
            });
            $(document).on('change input', '#griffinforms-scale-inputnumber', renderRows);
            $(document).on('change', '#griffinforms-rating-steps .rating-step-image-id', renderStepThumbs);
            $(document).on('input', '#griffinforms-rating-steps .rating-step-label', function() {
                $(this).data('value', $(this).val());
            });
            $(document).on('change', 'input[name="icon_group"]', setVisibility);
            renderRows();
            renderStepThumbs();
            setVisibility();
        });
        </script>
        <?php
    }

    private function maskIconSpan(string $icon_url, int $size, string $color): string
    {
        $safe_url = esc_url($icon_url);
        $safe_size = max(1, $size);
        $safe_color = sanitize_hex_color($color) ?: '#6b7280';
        $style = sprintf(
            'width:%1$dpx;height:%1$dpx;background-color:%2$s;-webkit-mask-image:url(%3$s);mask-image:url(%3$s);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;-webkit-mask-size:contain;mask-size:contain;',
            $safe_size,
            esc_attr($safe_color),
            $safe_url
        );

        return '<span style="' . esc_attr($style) . '"></span>';
    }
}
