<?php

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

use GriffinForms\Items\FormTheme;

class InputRichText extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls\Format
{
    private const 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',
    ];

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

        $toolbar = is_array($s['toolbar'] ?? null)
            ? $s['toolbar']
            : ['bold', 'italic', 'underline', 'strike', 'bulletlist', 'orderedlist', 'blockquote', 'link', 'clearformatting'];

        $placeholder = isset($s['placeholder']) && $s['placeholder'] !== ''
            ? $s['placeholder']
            : __('Write something…', 'griffinforms-form-builder');

        $min_height = isset($s['min_height']) ? max(50, (int) $s['min_height']) : 160;

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

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

        // Outer wrapper carries the border/radius; overflow:hidden clips children to the radius.
        echo '<div class="overflow-hidden' . $fallback_wrap . '"' . $style_attrs . '>';

        // Toolbar strip — no outer border, only an internal bottom divider via renderToolbarStyle().
        echo '<div class="gf-richtext-preview-toolbar d-flex flex-wrap gap-1 p-1" ' . $toolbar_group . '>';
        foreach ($toolbar as $item) {
            $label = self::TOOLBAR_LABELS[$item] ?? $item;
            echo '<span class="gf-rt-toolbar-icon d-inline-flex align-items-center justify-content-center" style="min-width:24px;height:24px;font-size:11px;font-weight:600;padding:0 3px;cursor:default;" title="' . esc_attr($item) . '">' . esc_html($label) . '</span>';
        }
        echo '</div>';

        // Editor area — no border of its own; the outer wrapper owns it.
        echo '<div class="d-flex align-items-center justify-content-center" style="min-height:' . esc_attr($min_height) . 'px;">';
        echo '<span style="font-size:13px;opacity:0.5;">' . esc_html($placeholder) . '</span>';
        echo '</div>';

        echo '</div>';
    }

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

        if ($this->isThemeSet()) {
            $resolved     = $this->form_theme->getFieldStyleResolved('text_input', 'default');
            $bg_color     = !empty($resolved['background-color']) ? $resolved['background-color'] : '#f8f9fa';
            $border_color = !empty($resolved['border']['color']) ? $resolved['border']['color'] : '#dee2e6';
            $icon_color   = $this->form_theme->getLabelColor() ?: '#6c757d';
        } else {
            $bg_color     = '#f8f9fa';
            $border_color = '#dee2e6';
            $icon_color   = '#6c757d';
        }

        // Suppress theme padding on the outer wrapper (border/radius come from theme; padding would break layout).
        $css = $wrapper_selector . ' { padding: 0 !important; }'
            . ' ' . $toolbar_selector . ' { background-color: ' . esc_attr($bg_color) . ' !important; border-bottom: 1px solid ' . esc_attr($border_color) . ' !important; }'
            . ' ' . $toolbar_selector . ' .gf-rt-toolbar-icon { color: ' . esc_attr($icon_color) . ' !important; }';

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