<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

class CustomCss extends \GriffinForms\Admin\Html\FormControls\FormTheme\Format
{
    protected $state;
    protected $property;

    public function __construct($name = '', $value = '', $data = '')
    {
        parent::__construct($name, $value, $data);

        if (isset($data['state'])) {
            $this->state = $data['state'];
        }

        if (isset($data['property'])) {
            $this->property = $data['property'];
        }

    }

    public function html()
    {
        $current_value = $this->getCustomCssValue();

        // Build field name for custom_css property
        $field_name = $this->buildSimpleStyleName($this->state, 'custom_css');

        // Textarea for custom CSS
        echo '<div class="griffinforms-custom-css-wrapper">';
        echo '<label class="form-label">' . esc_html(__('Custom CSS', 'griffinforms-form-builder')) . '</label>';
        echo '<textarea class="griffinforms-custom-css-textarea form-control" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'placeholder="' . esc_attr($this->getPlaceholderText()) . '" ';
        echo 'style="font-family: \'Monaco\', \'Courier New\', monospace; font-size: 12px; height: 120px; resize: vertical;">';
        echo esc_textarea($current_value);
        echo '</textarea>';

        // Help text
        echo '<small class="form-text text-muted d-block mt-2">';
        echo esc_html(__('Enter CSS properties to override UI settings. Format: property: value; (one per line). Example: font-weight: 800; This CSS will be applied after all UI-generated styles.', 'griffinforms-form-builder'));
        echo '</small>';
        echo '</div>';
    }

    /**
     * Gets the custom CSS value from nested array structure
     */
    protected function getCustomCssValue()
    {
        // If value is a scalar string, return it directly
        if (!is_array($this->value)) {
            return $this->value ?: '';
        }

        $value = $this->value;

        // Handle direct structure (e.g., form_style[default][custom_css])
        if ($this->state && isset($value[$this->state]['custom_css'])) {
            return $value[$this->state]['custom_css'];
        }

        return '';
    }

    /**
     * Returns placeholder text with CSS examples
     */
    protected function getPlaceholderText()
    {
        return "font-weight: 800;\ntext-decoration: none;\nline-height: 1.5;";
    }
}
