<?php

namespace GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls;

class SelectField extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls\Format
{
    public function getHtml()
    {
        $this->renderFieldStyles(array('select_input'));

        $control_id  = $this->getFieldControlId('select');
        $attributes  = $this->getFieldStyleAttributes('select_input');
        $placeholder = $this->getFieldPlaceholder();

        $option_groups = $this->parseFieldOptions();
        $has_named     = $this->hasNamedGroups($option_groups);

        echo '<div class="gf-dropdown-field-wrap" data-gf-field-id="' . esc_attr($this->item_id) . '">';

        // ── Native select (preview only; pointer-events disabled by CSS) ──────
        echo '<select id="' . esc_attr($control_id) . '" class="form-select gf-dropdown-select-preview"' . $attributes . '>';
        if ($placeholder !== '') {
            echo '<option value="">' . esc_html($placeholder) . '</option>';
        }
        $this->echoSelectOptions($option_groups);
        echo '</select>';

        // ── Transparent overlay that intercepts all clicks ────────────────────
        echo '<div class="gf-dropdown-trigger-overlay" aria-hidden="true"></div>';

        // ── Editable options panel (hidden until overlay clicked) ─────────────
        echo '<div class="gf-dropdown-options-panel" hidden data-gf-grouped="' . ($has_named ? 'true' : 'false') . '"' . $this->getFieldStyleAttributes('select_input') . '>';

        // Placeholder static row
        if ($placeholder !== '') {
            echo '<div class="gf-dropdown-placeholder-row">';
            echo esc_html($placeholder);
            echo '</div>';
        }

        if (!empty($option_groups) && is_array($option_groups)) {
            $total_options = 0;
            foreach ($option_groups as $opts) {
                $total_options += is_array($opts) ? count($opts) : 0;
            }

            foreach ($option_groups as $group_key => $options) {
                $is_ungrouped = ($group_key === '');

                echo '<div class="gf-dropdown-option-group" data-gf-group-key="' . esc_attr($group_key) . '">';

                if ($is_ungrouped) {
                    // Static "Ungrouped" header — shown only in grouped mode via CSS
                    echo '<div class="gf-dropdown-group-header gf-dropdown-group-header--ungrouped" aria-hidden="true">';
                    esc_html_e('Ungrouped', 'griffinforms-form-builder');
                    echo '</div>';
                } else {
                    // Editable named group header
                    echo '<div class="gf-dropdown-group-header">';
                    echo '<span class="gf-dropdown-group-name" contenteditable="true" spellcheck="false"';
                    echo ' data-gf-prev-value="' . esc_attr($group_key) . '">';
                    echo esc_html($group_key);
                    echo '</span>';
                    echo '<div class="gf-sub-toolbar gf-dropdown-group-toolbar" role="group" aria-label="' . esc_attr__('Group actions', 'griffinforms-form-builder') . '">';
                    echo '<button type="button" class="gf-sub-toolbar-btn gf-dropdown-group-delete" aria-label="' . esc_attr__('Delete group', 'griffinforms-form-builder') . '">';
                    $this->echoToolbarSvg('delete-forever.svg');
                    echo '</button>';
                    echo '</div>';
                    echo '</div>';
                }

                if (is_array($options)) {
                    $count = 0;
                    foreach ($options as $option_name => $option_value) {
                        $count++;
                        $is_only  = ($total_options === 1);
                        $is_first = ($count === 1 && $is_ungrouped);
                        $is_last  = ($count === count($options) && !$has_named);
                        $this->renderOptionRow($option_name, $option_value, $is_only, $is_first, $is_last);
                    }
                }

                // Add option button scoped to this group
                echo '<div class="gf-choice-field-add-option-wrap">';
                echo '<div class="gf-choice-field-add-option-bar"></div>';
                echo '<button type="button" class="gf-choice-field-add-option-btn"';
                echo ' aria-label="' . esc_attr__('Add option', 'griffinforms-form-builder') . '"';
                echo ' data-gf-group-key="' . esc_attr($group_key) . '">';
                echo '<span class="gf-choice-add-option-icon" aria-hidden="true">+</span>';
                echo '</button>';
                echo '</div>';

                echo '</div>'; // .gf-dropdown-option-group
            }
        } else {
            // Empty state
            echo '<div class="gf-dropdown-empty-state">';
            esc_html_e('No options.', 'griffinforms-form-builder');
            echo '</div>';
        }

        echo '<div class="gf-dropdown-add-group-wrap">';
        echo '<button type="button" class="gf-btn gf-btn-sm gf-dropdown-add-group-btn">';
        esc_html_e('+ Add group', 'griffinforms-form-builder');
        echo '</button>';
        echo '</div>';

        echo '</div>'; // .gf-dropdown-options-panel

        echo '</div>'; // .gf-dropdown-field-wrap
    }

    private function renderOptionRow($option_name, $option_value, $is_only = false, $is_first = false, $is_last = false)
    {
        echo '<div class="gf-choice-option-row text-start w-100 pb-2"';
        echo ' data-gf-option-label="' . esc_attr($option_name) . '"';
        echo ' data-gf-option-value="' . esc_attr($option_value) . '">';

        $this->renderOptionToolbar($option_value, $is_only, $is_first, $is_last);

        echo '<span class="gf-choice-option-label align-baseline" contenteditable="true" spellcheck="false"';
        echo ' data-gf-prev-value="' . esc_attr($option_name) . '">';
        echo esc_html($option_name);
        echo '</span>';

        echo '</div>';
    }

    private function renderOptionToolbar($option_value, $is_only = false, $is_first = false, $is_last = false)
    {
        $delete_attr  = $is_only  ? ' disabled' : '';
        $move_up_attr = $is_first ? ' disabled' : '';
        $move_dn_attr = $is_last  ? ' disabled' : '';

        echo '<div class="gf-sub-toolbar gf-choice-option-toolbar" role="group" aria-label="' . esc_attr__('Option actions', 'griffinforms-form-builder') . '">';
        echo '<button type="button" class="gf-sub-toolbar-btn gf-choice-option-drag-handle" aria-label="' . esc_attr__('Drag to reorder', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('drag.svg');
        echo '</button>';
        echo '<div class="gf-sub-toolbar-composite">';
        echo '<button type="button" class="gf-sub-toolbar-btn gf-choice-option-move-up"' . $move_up_attr . ' aria-label="' . esc_attr__('Move option up', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('up.svg');
        echo '</button>';
        echo '<button type="button" class="gf-sub-toolbar-btn gf-choice-option-move-down"' . $move_dn_attr . ' aria-label="' . esc_attr__('Move option down', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('down.svg');
        echo '</button>';
        echo '</div>';
        echo '<button type="button" class="gf-sub-toolbar-btn gf-choice-option-value-btn" aria-label="' . esc_attr__('Edit option value', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('option-value.svg');
        echo '</button>';
        echo '<button type="button" class="gf-sub-toolbar-btn gf-choice-option-delete"' . $delete_attr . ' aria-label="' . esc_attr__('Delete option', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('delete-forever.svg');
        echo '</button>';
        echo '</div>';

        echo '<div class="gf-choice-option-value-popover" hidden>';
        echo '<input type="text" class="gf-choice-option-value-input form-control form-control-sm" value="' . esc_attr($option_value) . '" aria-label="' . esc_attr__('Option value', 'griffinforms-form-builder') . '">';
        echo '<div class="gf-choice-option-value-error" hidden></div>';
        echo '</div>';
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    private function parseFieldOptions()
    {
        $option_groups = $this->item->getProp('field_options');

        if (is_string($option_groups)) {
            $decoded = maybe_unserialize($option_groups);
            if (is_string($decoded)) {
                $json = json_decode($decoded, true);
                $option_groups = json_last_error() === JSON_ERROR_NONE && is_array($json) ? $json : $decoded;
            } else {
                $option_groups = $decoded;
            }
        }

        return is_array($option_groups) ? $option_groups : array();
    }

    private function hasNamedGroups(array $option_groups): bool
    {
        foreach ($option_groups as $key => $opts) {
            if ($key !== '') {
                return true;
            }
        }
        return false;
    }

    private function echoSelectOptions(array $option_groups)
    {
        foreach ($option_groups as $option_group => $options) {
            if ($option_group !== '') {
                echo '<optgroup label="' . esc_attr($option_group) . '">';
            }
            if (!is_array($options)) {
                if ($option_group !== '') {
                    echo '</optgroup>';
                }
                continue;
            }
            foreach ($options as $option_name => $option_value) {
                echo '<option value="' . esc_attr($option_value) . '">' . esc_html($option_name) . '</option>';
            }
            if ($option_group !== '') {
                echo '</optgroup>';
            }
        }
    }

    protected function echoToolbarSvg($filename)
    {
        $path = \GriffinForms\Config::getInstance()->getRootPath() . 'admin/images/toolbar-icons/builder/' . $filename;
        if (!file_exists($path)) {
            return;
        }
        $svg = file_get_contents($path);
        if ($svg === false || trim($svg) === '') {
            return;
        }
        $svg = preg_replace('/<svg\b([^>]*)>/i', '<svg$1 class="gf-fe-action-svg" aria-hidden="true" focusable="false">', $svg, 1);
        $svg = preg_replace('/\sfill="(?!none)([^"]*)"/i', ' fill="currentColor"', $svg);
        $svg = preg_replace('/\sstroke="(?!none)([^"]*)"/i', ' stroke="currentColor"', $svg);
        echo $svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }
}
