<?php

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

class InputlikertSettings extends \GriffinForms\Admin\Html\FormControls\Field\FieldSettings\Format
{
    private static function uid(string $prefix): string
    {
        return $prefix . '_' . bin2hex(random_bytes(3));
    }

    private static function defaultRows(): array
    {
        return [
            ['id' => self::uid('row'), 'label' => 'Row 1'],
            ['id' => self::uid('row'), 'label' => 'Row 2'],
            ['id' => self::uid('row'), 'label' => 'Row 3'],
        ];
    }

    private static function defaultColumns(): array
    {
        return [
            ['id' => self::uid('col'), 'label' => 'Strongly Disagree'],
            ['id' => self::uid('col'), 'label' => 'Disagree'],
            ['id' => self::uid('col'), 'label' => 'Neutral'],
            ['id' => self::uid('col'), 'label' => 'Agree'],
            ['id' => self::uid('col'), 'label' => 'Strongly Agree'],
        ];
    }

    public function html()
    {
        $s = is_array($this->value) ? $this->value : [];

        $rows          = $this->normalizeItems($s['rows']   ?? null, self::defaultRows());
        $columns       = $this->normalizeItems($s['columns'] ?? null, self::defaultColumns());
        $allow_na      = !empty($s['allow_na']);
        $required_mode = in_array($s['required_mode'] ?? '', ['all', 'none'], true) ? $s['required_mode'] : 'all';
        $column_width  = in_array($s['column_width']  ?? '', ['auto', 'equal'], true) ? $s['column_width'] : 'auto';

        $data_json = esc_attr(wp_json_encode([
            'rows'          => $rows,
            'columns'       => $columns,
            'allow_na'      => $allow_na,
            'required_mode' => $required_mode,
            'column_width'  => $column_width,
        ]));
        ?>
        <div class="inputlikert-settings" id="gf-likert-settings-wrap">

            <?php /* Hidden JSON carrier — written by JS before save */ ?>
            <input type="hidden"
                id="gf-likert-data"
                class="griffinforms-field griffinforms-formcontrol"
                data-gf-field-settings="1"
                value="<?php echo $data_json; ?>">

            <?php /* ── Grid editor ── */ ?>
            <div class="mb-3">
                <label class="form-label mb-2 fw-semibold"><?php echo esc_html($this->lang->getText('likert_grid', 'label')); ?></label>
                <div style="max-height:320px;overflow-y:auto;overflow-x:auto;">
                    <table class="table table-bordered table-sm gf-likert-editor-table" id="gf-likert-editor-table" style="table-layout:auto;width:max-content;min-width:100%;">
                        <thead>
                            <tr id="gf-likert-col-header-row">
                                <?php /* Row-label column header (empty) */ ?>
                                <th class="gf-likert-corner" style="min-width:120px;"></th>
                                <?php foreach ($columns as $col) : ?>
                                <th class="gf-likert-col-header text-center" data-col-id="<?php echo esc_attr($col['id']); ?>" style="min-width:110px;">
                                    <div class="d-flex align-items-center gap-1">
                                        <input type="text"
                                            class="form-control form-control-sm gf-likert-col-label"
                                            value="<?php echo esc_attr($col['label']); ?>"
                                            placeholder="<?php esc_attr_e('Column label', 'griffinforms-form-builder'); ?>"
                                            aria-label="<?php esc_attr_e('Column label', 'griffinforms-form-builder'); ?>">
                                        <button type="button" class="btn btn-sm text-danger p-0 text-decoration-none gf-likert-delete-col" aria-label="<?php esc_attr_e('Remove column', 'griffinforms-form-builder'); ?>">×</button>
                                    </div>
                                </th>
                                <?php endforeach; ?>
                                <?php if ($allow_na) : ?>
                                <th class="gf-likert-na-col text-center" id="gf-likert-na-header" style="min-width:70px;">
                                    <span class="text-muted small"><?php esc_html_e('N/A', 'griffinforms-form-builder'); ?></span>
                                </th>
                                <?php endif; ?>
                                <th class="gf-likert-add-col-cell border-0 bg-transparent" style="width:36px;">
                                    <button type="button" id="gf-likert-add-col" class="btn btn-sm btn-outline-secondary" title="<?php esc_attr_e('Add column', 'griffinforms-form-builder'); ?>">+</button>
                                </th>
                            </tr>
                        </thead>
                        <tbody id="gf-likert-tbody">
                            <?php foreach ($rows as $row) : ?>
                            <tr class="gf-likert-row" data-row-id="<?php echo esc_attr($row['id']); ?>">
                                <td class="gf-likert-row-label-cell">
                                    <div class="d-flex align-items-center gap-1">
                                        <span class="gf-likert-drag-handle text-muted" style="cursor:grab;" title="<?php esc_attr_e('Drag to reorder', 'griffinforms-form-builder'); ?>">⠿</span>
                                        <input type="text"
                                            class="form-control form-control-sm gf-likert-row-label"
                                            value="<?php echo esc_attr($row['label']); ?>"
                                            placeholder="<?php esc_attr_e('Row label', 'griffinforms-form-builder'); ?>"
                                            aria-label="<?php esc_attr_e('Row label', 'griffinforms-form-builder'); ?>">
                                        <button type="button" class="btn btn-sm text-danger p-0 text-decoration-none gf-likert-delete-row" aria-label="<?php esc_attr_e('Remove row', 'griffinforms-form-builder'); ?>">×</button>
                                    </div>
                                </td>
                                <?php foreach ($columns as $col) : ?>
                                <td class="text-center align-middle gf-likert-cell" data-col-id="<?php echo esc_attr($col['id']); ?>">
                                    <input type="radio" disabled>
                                </td>
                                <?php endforeach; ?>
                                <?php if ($allow_na) : ?>
                                <td class="text-center align-middle gf-likert-na-col gf-likert-cell">
                                    <input type="radio" disabled>
                                </td>
                                <?php endif; ?>
                                <td class="border-0 bg-transparent"></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <button type="button" id="gf-likert-add-row" class="btn btn-sm btn-outline-secondary mt-2">
                    <?php esc_html_e('+ Add row', 'griffinforms-form-builder'); ?>
                </button>
            </div>

            <?php /* ── Options ── */ ?>
            <div class="row g-3 mt-1">

                <div class="col-12">
                    <div class="d-flex align-items-center gap-2">
                        <input class="griffinforms-field griffinforms-formcontrol"
                            type="checkbox"
                            id="gf-likert-allow-na"
                            value="1"
                            <?php checked($allow_na); ?>>
                        <label for="gf-likert-allow-na">
                            <?php echo esc_html($this->lang->getText('likert_allow_na', 'label')); ?>
                        </label>
                    </div>
                    <div class="form-text text-muted"><?php echo esc_html($this->lang->getText('likert_allow_na', 'description')); ?></div>
                </div>

                <div class="col-md-6">
                    <label class="form-label"><?php echo esc_html($this->lang->getText('likert_required_mode', 'label')); ?></label>
                    <div class="d-flex flex-column gap-1">
                        <div class="d-flex align-items-center gap-2">
                            <input type="radio" name="gf-likert-required-mode" id="gf-likert-req-all" value="all" <?php checked($required_mode, 'all'); ?>>
                            <label for="gf-likert-req-all"><?php esc_html_e('All rows must be answered', 'griffinforms-form-builder'); ?></label>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <input type="radio" name="gf-likert-required-mode" id="gf-likert-req-none" value="none" <?php checked($required_mode, 'none'); ?>>
                            <label for="gf-likert-req-none"><?php esc_html_e('At least one row', 'griffinforms-form-builder'); ?></label>
                        </div>
                    </div>
                    <div class="form-text text-muted"><?php echo esc_html($this->lang->getText('likert_required_mode', 'description')); ?></div>
                </div>

                <div class="col-md-6">
                    <label class="form-label" for="gf-likert-column-width"><?php echo esc_html($this->lang->getText('likert_column_width', 'label')); ?></label>
                    <select class="form-select form-select-sm griffinforms-field griffinforms-formcontrol" id="gf-likert-column-width">
                        <option value="auto"  <?php selected($column_width, 'auto');  ?>><?php esc_html_e('Auto', 'griffinforms-form-builder'); ?></option>
                        <option value="equal" <?php selected($column_width, 'equal'); ?>><?php esc_html_e('Equal width', 'griffinforms-form-builder'); ?></option>
                    </select>
                    <div class="form-text text-muted"><?php echo esc_html($this->lang->getText('likert_column_width', 'description')); ?></div>
                </div>

            </div>
        </div>

        <script>
        (function($) {
            var wrap    = document.getElementById('gf-likert-settings-wrap');
            var dataIn  = document.getElementById('gf-likert-data');
            var table   = document.getElementById('gf-likert-editor-table');
            var tbody   = document.getElementById('gf-likert-tbody');
            var headRow = document.getElementById('gf-likert-col-header-row');

            if (!wrap || !dataIn || !table || !tbody || !headRow) return;

            var state = JSON.parse(dataIn.value || '{}');
            state.rows         = state.rows         || [];
            state.columns      = state.columns      || [];
            state.allow_na     = !!state.allow_na;
            state.required_mode = state.required_mode || 'all';
            state.column_width  = state.column_width  || 'auto';

            function uid(prefix) {
                return prefix + '_' + Math.random().toString(36).slice(2, 7);
            }

            /* ── write JSON to hidden input ── */
            function flush() {
                state.allow_na      = $('#gf-likert-allow-na').is(':checked');
                state.required_mode = $('input[name="gf-likert-required-mode"]:checked').val() || 'all';
                state.column_width  = $('#gf-likert-column-width').val() || 'auto';

                /* collect rows from DOM */
                state.rows = [];
                $('#gf-likert-tbody .gf-likert-row').each(function() {
                    state.rows.push({
                        id:    $(this).data('row-id'),
                        label: $(this).find('.gf-likert-row-label').val()
                    });
                });

                /* collect columns from DOM */
                state.columns = [];
                $('#gf-likert-col-header-row .gf-likert-col-header').each(function() {
                    state.columns.push({
                        id:    $(this).data('col-id'),
                        label: $(this).find('.gf-likert-col-label').val()
                    });
                });

                dataIn.value = JSON.stringify(state);
            }

            /* ── build a column <th> ── */
            function makeColHeader(col) {
                return $('<th class="gf-likert-col-header text-center" style="min-width:110px;">')
                    .attr('data-col-id', col.id)
                    .append(
                        $('<div class="d-flex align-items-center gap-1">')
                            .append($('<input type="text" class="form-control form-control-sm gf-likert-col-label">').val(col.label).attr('placeholder', '<?php echo esc_js(__('Column label', 'griffinforms-form-builder')); ?>'))
                            .append($('<button type="button" class="btn btn-sm text-danger p-0 text-decoration-none gf-likert-delete-col">×</button>').attr('aria-label', '<?php echo esc_js(__('Remove column', 'griffinforms-form-builder')); ?>'))
                    );
            }

            /* ── build a body cell <td> for a column ── */
            function makeBodyCell(colId) {
                return $('<td class="text-center align-middle gf-likert-cell">').attr('data-col-id', colId).append('<input type="radio" disabled>');
            }

            /* ── build a row <tr> ── */
            function makeRow(row) {
                var tr = $('<tr class="gf-likert-row">').attr('data-row-id', row.id);
                var labelCell = $('<td class="gf-likert-row-label-cell">')
                    .append(
                        $('<div class="d-flex align-items-center gap-1">')
                            .append('<span class="gf-likert-drag-handle text-muted" style="cursor:grab;" title="<?php echo esc_js(__('Drag to reorder', 'griffinforms-form-builder')); ?>">⠿</span>')
                            .append($('<input type="text" class="form-control form-control-sm gf-likert-row-label">').val(row.label).attr('placeholder', '<?php echo esc_js(__('Row label', 'griffinforms-form-builder')); ?>'))
                            .append($('<button type="button" class="btn btn-sm text-danger p-0 text-decoration-none gf-likert-delete-row">×</button>').attr('aria-label', '<?php echo esc_js(__('Remove row', 'griffinforms-form-builder')); ?>'))
                    );
                tr.append(labelCell);

                /* one cell per column */
                $('#gf-likert-col-header-row .gf-likert-col-header').each(function() {
                    tr.append(makeBodyCell($(this).data('col-id')));
                });

                /* N/A cell if enabled */
                if ($('#gf-likert-allow-na').is(':checked')) {
                    tr.append('<td class="text-center align-middle gf-likert-na-col gf-likert-cell"><input type="radio" disabled></td>');
                }

                tr.append('<td class="border-0 bg-transparent"></td>');
                return tr;
            }

            /* ── add column ── */
            $('#gf-likert-add-col').on('click', function() {
                var col = { id: uid('col'), label: '<?php echo esc_js(__('Column', 'griffinforms-form-builder')); ?>' };

                var addBtn = $('#gf-likert-col-header-row .gf-likert-add-col-cell');
                var naHeader = $('#gf-likert-na-header').closest('th');
                if (naHeader.length) {
                    makeColHeader(col).insertBefore(naHeader);
                } else {
                    makeColHeader(col).insertBefore(addBtn);
                }

                /* append cell to each body row */
                tbody.querySelectorAll('.gf-likert-row').forEach(function(tr) {
                    var addCell = tr.lastElementChild;
                    $(makeBodyCell(col.id)).insertBefore($(addCell));
                });

                flush();
            });

            /* ── add row ── */
            $('#gf-likert-add-row').on('click', function() {
                var row = { id: uid('row'), label: '<?php echo esc_js(__('Row', 'griffinforms-form-builder')); ?>' };
                $(tbody).append(makeRow(row));
                initSortable();
                flush();
            });

            /* ── delete column (delegated) ── */
            $(headRow).on('click', '.gf-likert-delete-col', function() {
                if ($('#gf-likert-col-header-row .gf-likert-col-header').length <= 2) {
                    return; /* enforce min 2 columns */
                }
                var th  = $(this).closest('th');
                var cid = th.data('col-id');
                th.remove();
                tbody.querySelectorAll('[data-col-id="' + cid + '"]').forEach(function(td) { td.remove(); });
                flush();
            });

            /* ── delete row (delegated) ── */
            $(tbody).on('click', '.gf-likert-delete-row', function() {
                if ($(tbody).find('.gf-likert-row').length <= 1) {
                    return; /* enforce min 1 row */
                }
                $(this).closest('tr').remove();
                flush();
            });

            /* ── allow N/A toggle ── */
            $('#gf-likert-allow-na').on('change', function() {
                var checked = $(this).is(':checked');
                var addBtn  = $('#gf-likert-col-header-row .gf-likert-add-col-cell');

                if (checked) {
                    $('<th class="gf-likert-na-col text-center" id="gf-likert-na-header" style="min-width:70px;"><span class="text-muted small">N/A</span></th>')
                        .insertBefore(addBtn);
                    tbody.querySelectorAll('.gf-likert-row').forEach(function(tr) {
                        var addCell = tr.lastElementChild;
                        $('<td class="text-center align-middle gf-likert-na-col gf-likert-cell"><input type="radio" disabled></td>')
                            .insertBefore($(addCell));
                    });
                } else {
                    $('#gf-likert-na-header').closest('th').remove();
                    tbody.querySelectorAll('.gf-likert-na-col').forEach(function(td) { td.remove(); });
                }
                flush();
            });

            /* ── flush on any input/select change ── */
            $(wrap).on('input change', 'input[type="text"], input[type="radio"], select', flush);

            /* ── jQuery UI Sortable on rows ── */
            function initSortable() {
                if (typeof $.fn.sortable === 'undefined') return;
                $(tbody).sortable({
                    handle:      '.gf-likert-drag-handle',
                    axis:        'y',
                    placeholder: 'gf-likert-sort-placeholder',
                    stop:        flush,
                    helper: function(e, tr) {
                        var label = tr.find('.gf-likert-row-label').val() || '';
                        return $('<div>')
                            .css({
                                background:   '#fff',
                                border:       '1px solid #ccc',
                                borderRadius: '4px',
                                padding:      '4px 10px',
                                fontSize:     '13px',
                                boxShadow:    '0 2px 6px rgba(0,0,0,0.15)',
                                whiteSpace:   'nowrap',
                                display:      'inline-block',
                                cursor:       'grabbing',
                            })
                            .text(label || '<?php echo esc_js(__('Row', 'griffinforms-form-builder')); ?>');
                    }
                });
            }
            initSortable();

        })(jQuery);
        </script>
        <?php
    }

    private function normalizeItems(?array $raw, array $defaults): array
    {
        if (!is_array($raw) || empty($raw)) {
            return $defaults;
        }
        $out = [];
        foreach ($raw as $item) {
            if (!isset($item['id'], $item['label'])) continue;
            $out[] = [
                'id'    => sanitize_key((string) $item['id']),
                'label' => sanitize_text_field((string) $item['label']),
            ];
        }
        return empty($out) ? $defaults : $out;
    }
}
