<?php

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

use GriffinForms\Items\FormTheme;

class InputLikert extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls\Format
{
    private function normalizeLikertItems($items): array
    {
        if (!is_array($items) || empty($items)) {
            return [];
        }

        $normalized = [];

        foreach ($items as $index => $item) {
            if (is_array($item)) {
                $label = isset($item['label']) ? trim((string) $item['label']) : '';
                $id = isset($item['id']) ? trim((string) $item['id']) : '';

                if ($label === '' && $id === '') {
                    continue;
                }

                $normalized[] = [
                    'id' => $id !== '' ? $id : 'item_' . $index,
                    'label' => $label !== '' ? $label : $id,
                ];
                continue;
            }

            $label = trim((string) $item);
            if ($label === '') {
                continue;
            }

            $normalized[] = [
                'id' => 'item_' . $index,
                'label' => $label,
            ];
        }

        return $normalized;
    }

    public function getHtml()
    {
        $field_settings = $this->item->getProp('field_settings');
        $s = is_array($field_settings) ? $field_settings : [];

        $rows = $this->normalizeLikertItems($s['rows'] ?? []);

        $columns = $this->normalizeLikertItems($s['columns'] ?? []);

        $allow_na     = !empty($s['allow_na']);
        $column_width = ($s['column_width'] ?? 'auto') === 'equal' ? 'fixed' : 'auto';

        $this->renderFieldStyles(['text_input']);
        $this->renderLikertTableStyle();

        $style_attrs   = $this->getFieldStyleAttributes('text_input');
        $group_id      = esc_attr($this->getFieldStyleGroupId());
        $table_group   = 'data-gf-style-group="' . $group_id . '" data-gf-style-type="gf_likert_table"';
        $fallback_wrap = $this->isThemeSet() ? '' : ' border rounded';

        echo '<div class="overflow-hidden' . $fallback_wrap . '" style="padding:0 !important;"' . $style_attrs . '>';
        echo '<div style="overflow-x:auto;overflow-y:auto;max-height:260px;">';

        if (empty($rows) || empty($columns)) {
            echo '<div class="text-muted small p-3">' . esc_html__('Likert field options are not configured.', 'griffinforms-form-builder') . '</div>';
            echo '</div>';
            echo '</div>';
            return;
        }

        echo '<table ' . $table_group . ' style="width:100%;border-collapse:collapse;table-layout:' . esc_attr($column_width) . ';font-size:12px;">';

        // Header row — no inline border-bottom; owned by scoped CSS
        echo '<thead><tr>';
        echo '<th style="text-align:left;padding:6px 8px;font-weight:600;min-width:100px;white-space:nowrap;"></th>';
        foreach ($columns as $col) {
            echo '<th style="text-align:center;padding:6px 8px;font-weight:600;min-width:90px;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' . esc_html($col['label']) . '</th>';
        }
        if ($allow_na) {
            echo '<th style="text-align:center;padding:6px 8px;font-weight:600;min-width:50px;color:#aaa;">N/A</th>';
        }
        echo '</tr></thead>';

        // Body rows — no inline border-bottom; owned by scoped CSS
        echo '<tbody>';
        foreach ($rows as $row) {
            echo '<tr>';
            echo '<td style="text-align:left;padding:6px 8px;white-space:nowrap;">' . esc_html($row['label']) . '</td>';
            foreach ($columns as $col) {
                echo '<td style="text-align:center;padding:6px 8px;"><input type="radio" class="gf-likert-preview-radio gf-checkbox-radio-input"></td>';
            }
            if ($allow_na) {
                echo '<td style="text-align:center;padding:6px 8px;"><input type="radio" class="gf-likert-preview-radio gf-checkbox-radio-input" style="opacity:0.5;"></td>';
            }
            echo '</tr>';
        }
        echo '</tbody>';

        echo '</table>';
        echo '</div>';
        echo '</div>';
    }

    private function renderLikertTableStyle(): void
    {
        $group_id         = esc_attr($this->getFieldStyleGroupId());
        $wrapper_selector = '[data-gf-style-group="' . $group_id . '"][data-gf-style-type="text_input"]';
        $table_selector   = '[data-gf-style-group="' . $group_id . '"][data-gf-style-type="gf_likert_table"]';

        if ($this->isThemeSet()) {
            $resolved     = $this->form_theme->getFieldStyleResolved('text_input', 'default');
            $border_color = !empty($resolved['border']['color']) ? $resolved['border']['color'] : '#dee2e6';
            $accent_color = $this->form_theme->getSubmitButtonBackgroundColor() ?: '#0d6efd';
        } else {
            $border_color = '#dee2e6';
            $accent_color = '#0d6efd';
        }

        $row_border = $this->isThemeSet() ? $border_color : '#f0f0f0';

        $css = $wrapper_selector . ' { padding: 0 !important; }'
            . ' ' . $table_selector . ' thead th { border-bottom: 1px solid ' . esc_attr($border_color) . ' !important; }'
            . ' ' . $table_selector . ' thead th:not(:first-child) { border-left: 1px solid ' . esc_attr($border_color) . ' !important; }'
            . ' ' . $table_selector . ' tbody td { border-bottom: 1px solid ' . esc_attr($row_border) . ' !important; }'
            . ' ' . $table_selector . ' tbody td:not(:first-child) { border-left: 1px solid ' . esc_attr($border_color) . ' !important; }'
            . ' ' . $table_selector . ' tbody tr:last-child td { border-bottom: none !important; }'
            . ' ' . $table_selector . ' .gf-likert-preview-radio { accent-color: ' . esc_attr($accent_color) . '; cursor: pointer; }';

        $css = FormTheme::prepareStyleTagContent($css);
        if ($css !== '') {
            echo '<style>' . $css . '</style>';
        }
    }
}
