<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

/**
 * Typography FormControl
 * Renders typography styling properties for form/page/row text elements
 * Includes font family, size, color, weight, letter spacing, and text transform
 */
class Typography extends \GriffinForms\Admin\Html\FormControls\FormTheme\Format
{
    protected $property_type;  // 'form_title', 'form_description', 'page_heading', etc.

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

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

    public function html()
    {
        echo '<div class="griffinforms-typography-control" style="display: grid; grid-template-columns: 1fr; gap: 15px;">';

        // Font Family
        $this->renderFontFamily();

        // Font Size
        $this->renderFontSize();

        // Font Color
        $this->renderFontColor();

        // Font Weight
        $this->renderFontWeight();

        // Letter Spacing
        $this->renderLetterSpacing();

        // Text Transform
        $this->renderTextTransform();

        // Text Alignment
        $this->renderTextAlignment();

        echo '</div>';
    }

    /**
     * Renders font family dropdown
     */
    protected function renderFontFamily()
    {
        $current_value = $this->getFontValue('font-family');
        $field_name = $this->getNestedFieldName($this->name, 'default', 'font-family');

        // Use FontRegistry as the single source of truth
        $font_registry = new FontRegistry();
        $fonts = $font_registry->getCombined();

        echo '<div>';
        echo '<label class="form-label">' . esc_html(__('Font Family', 'griffinforms-form-builder')) . '</label>';
        echo '<select class="form-select form-select-sm" name="' . esc_attr($field_name) . '">';

        foreach ($fonts as $value => $label) {
            $selected = ($current_value === $value) ? ' selected' : '';
            echo '<option value="' . esc_attr($value) . '"' . esc_attr($selected) . '>';
            echo esc_html($label);
            echo '</option>';
        }

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

    /**
     * Renders font size dimension input with unit dropdown
     */
    protected function renderFontSize()
    {
        $dimension_control = new \GriffinForms\Admin\Html\FormControls\FormTheme\DimensionInput(
            $this->name,
            $this->getFontValue('font-size'),
            array(
                'label' => __('Font Size', 'griffinforms-form-builder'),
                'state' => 'default',
                'property' => 'font-size',
                'base_key' => $this->name
            )
        );
        $dimension_control->html();
    }

    /**
     * Renders font color picker
     */
    protected function renderFontColor()
    {
        $current_value = $this->getFontValue('color');
        $field_name = $this->getNestedFieldName($this->name, 'default', 'color');

        echo '<div>';
        echo '<label class="form-label">' . esc_html(__('Font Color', 'griffinforms-form-builder')) . '</label>';
        echo '<div style="display: grid; grid-template-columns: 1fr; gap: 8px;">';
        echo '<input type="text" class="griffinforms-color-picker" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'value="' . esc_attr($current_value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'placeholder="#000000" ';
        echo 'title="' . esc_attr(__('Click to select font color', 'griffinforms-form-builder')) . '" ';
        echo 'style="width: 100%; cursor: pointer;" />';
        echo '</div>';
        echo '</div>';
    }

    /**
     * Renders font weight select
     */
    protected function renderFontWeight()
    {
        $current_value = $this->getFontValue('font-weight');
        $field_name = $this->getNestedFieldName($this->name, 'default', 'font-weight');

        $weights = array(
            '300' => __('300 – Light', 'griffinforms-form-builder'),
            '400' => __('400 – Regular', 'griffinforms-form-builder'),
            '500' => __('500 – Medium', 'griffinforms-form-builder'),
            '600' => __('600 – Semi Bold', 'griffinforms-form-builder'),
            '700' => __('700 – Bold', 'griffinforms-form-builder'),
        );

        echo '<div>';
        echo '<label class="form-label">' . esc_html(__('Font Weight', 'griffinforms-form-builder')) . '</label>';
        echo '<select class="form-select form-select-sm" name="' . esc_attr($field_name) . '">';

        foreach ($weights as $value => $label) {
            $selected = ($current_value === $value) ? ' selected' : '';
            echo '<option value="' . esc_attr($value) . '"' . esc_attr($selected) . '>';
            echo esc_html($label);
            echo '</option>';
        }

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

    /**
     * Renders letter spacing with px unit only
     */
    protected function renderLetterSpacing()
    {
        $current_value = $this->getFontValue('letter-spacing');
        $field_name = $this->getNestedFieldName($this->name, 'default', 'letter-spacing');

        // Extract numeric value from current value (e.g., "0px" -> "0")
        $numeric_value = preg_replace('/[^0-9.-]/', '', $current_value);

        echo '<div>';
        echo '<label class="form-label">' . esc_html(__('Letter Spacing', 'griffinforms-form-builder')) . '</label>';
        echo '<div style="display: grid; grid-template-columns: 1fr 100px; gap: 6px; align-items: center;">';

        // Numeric input
        echo '<input type="text" class="griffinforms-letter-spacing-input" ';
        echo 'name="' . esc_attr($field_name) . '[value]" ';
        echo 'placeholder="0" ';
        echo 'value="' . esc_attr($numeric_value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'style="width: 100%;">';
        echo '</input>';

        // Unit select dropdown with only px
        echo '<select class="griffinforms-dimension-unit" ';
        echo 'name="' . esc_attr($field_name) . '[unit]" ';
        echo 'data-field-name="' . esc_attr($field_name) . '" ';
        echo 'style="width: 100%;">';
        echo '<option value="px" selected>px</option>';
        echo '</select>';

        // Hidden input to store the full value with unit
        echo '<input type="hidden" class="griffinforms-dimension-value" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'value="' . esc_attr($current_value) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '">';
        echo '</input>';

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

    /**
     * Renders text transform select
     */
    protected function renderTextTransform()
    {
        $current_value = $this->getFontValue('text-transform');
        $field_name = $this->getNestedFieldName($this->name, 'default', 'text-transform');

        $transforms = array(
            'none' => __('None', 'griffinforms-form-builder'),
            'uppercase' => __('Uppercase', 'griffinforms-form-builder'),
            'lowercase' => __('Lowercase', 'griffinforms-form-builder'),
            'capitalize' => __('Capitalize', 'griffinforms-form-builder'),
        );

        echo '<div>';
        echo '<label class="form-label">' . esc_html(__('Text Transform', 'griffinforms-form-builder')) . '</label>';
        echo '<select class="form-select form-select-sm" name="' . esc_attr($field_name) . '">';

        foreach ($transforms as $value => $label) {
            $selected = ($current_value === $value) ? ' selected' : '';
            echo '<option value="' . esc_attr($value) . '"' . esc_attr($selected) . '>';
            echo esc_html($label);
            echo '</option>';
        }

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

    /**
     * Renders text alignment select
     */
    protected function renderTextAlignment()
    {
        $current_value = $this->getFontValue('text-align');
        $field_name = $this->getNestedFieldName($this->name, 'default', 'text-align');

        $alignments = array(
            'left' => __('Left', 'griffinforms-form-builder'),
            'center' => __('Center', 'griffinforms-form-builder'),
            'right' => __('Right', 'griffinforms-form-builder'),
            'justify' => __('Justify', 'griffinforms-form-builder'),
        );

        echo '<div>';
        echo '<label class="form-label">' . esc_html(__('Text Alignment', 'griffinforms-form-builder')) . '</label>';
        echo '<select class="form-select form-select-sm" name="' . esc_attr($field_name) . '">';

        foreach ($alignments as $value => $label) {
            $selected = ($current_value === $value) ? ' selected' : '';
            echo '<option value="' . esc_attr($value) . '"' . esc_attr($selected) . '>';
            echo esc_html($label);
            echo '</option>';
        }

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

    /**
     * Gets a typography property value from nested array
     * Returns default values if database value is null/empty
     */
    protected function getFontValue($property)
    {
        // If value is not an array (null, empty string, etc.), use defaults
        if (!is_array($this->value)) {
            return $this->getDefaultFontValue($property);
        }

        if (isset($this->value['default'][$property])) {
            return $this->value['default'][$property];
        }

        // If property not found in database value, use default
        return $this->getDefaultFontValue($property);
    }

    /**
     * Gets default font values for typography properties
     */
    protected function getDefaultFontValue($property)
    {
        $defaults = array(
            'font-family' => 'inherit',
            'font-size' => '14px',
            'font-weight' => '400',
            'color' => '#000000',
            'letter-spacing' => '0px',
            'text-transform' => 'none',
            'text-align' => 'left'
        );

        return isset($defaults[$property]) ? $defaults[$property] : '';
    }

    /**
     * Normalizes color values to hex format for the color input
     */
    protected function normalizeColorToHex($color)
    {
        if (is_array($color)) {
            return '#000000';
        }

        $color = trim($color);

        // Already hex
        if (preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
            return $color;
        }

        // Hex with alpha - return without alpha for input type="color"
        if (preg_match('/^#[0-9a-fA-F]{8}$/', $color)) {
            return substr($color, 0, 7);
        }

        // RGB to hex
        if (preg_match('/^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i', $color, $matches)) {
            return '#' . str_pad(dechex($matches[1]), 2, '0', STR_PAD_LEFT) .
                   str_pad(dechex($matches[2]), 2, '0', STR_PAD_LEFT) .
                   str_pad(dechex($matches[3]), 2, '0', STR_PAD_LEFT);
        }

        // Default
        return '#000000';
    }

}
