<?php

namespace Calio\Widgets;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use Elementor\Repeater;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Renders a simpler feature list closer to classic icon-plus-copy layouts with an optional side panel.
 */
class FeatureListSimpleWidget extends BaseWidget
{
    public function get_name(): string
    {
        return 'calio-feature-list-simple';
    }

    public function get_title(): string
    {
        return esc_html__('Feature List Simple', 'calio-addon');
    }

    public function get_icon(): string
    {
        return 'eicon-editor-list-ul';
    }

    public function get_style_depends(): array
    {
        return $this->resolve_widget_style_depends('calio-widget-feature-list-simple');
    }

    protected function register_controls(): void
    {
        $this->start_controls_section('layout_section', ['label' => esc_html__('Layout', 'calio-addon')]);
        $this->add_control('icon_shape', [
            'label' => esc_html__('Icon Shape', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'circle',
            'options' => [
                'circle' => esc_html__('Circle', 'calio-addon'),
                'square' => esc_html__('Square', 'calio-addon'),
                'rhombus' => esc_html__('Rhombus', 'calio-addon'),
            ],
        ]);
        $this->add_control('shape_view', [
            'label' => esc_html__('Shape View', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'stacked',
            'options' => [
                'stacked' => esc_html__('Stacked', 'calio-addon'),
                'framed' => esc_html__('Framed', 'calio-addon'),
            ],
        ]);
        $this->add_control('hover_skin', [
            'label' => esc_html__('Hover Skin', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'soft',
            'options' => [
                'none' => esc_html__('None', 'calio-addon'),
                'soft' => esc_html__('Soft', 'calio-addon'),
                'lift' => esc_html__('Lift', 'calio-addon'),
            ],
        ]);
        $this->add_control('content_alignment', [
            'label' => esc_html__('Content Alignment', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'start',
            'options' => [
                'start' => esc_html__('Top', 'calio-addon'),
                'center' => esc_html__('Center', 'calio-addon'),
            ],
        ]);
        $this->add_control('media_position', [
            'label' => esc_html__('Icon Alignment', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'left',
            'options' => [
                'left' => esc_html__('Left', 'calio-addon'),
                'right' => esc_html__('Right', 'calio-addon'),
                'top' => esc_html__('Top', 'calio-addon'),
            ],
        ]);
        $this->add_control('show_connector', [
            'label' => esc_html__('Show Connector', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('show_side_panel', [
            'label' => esc_html__('Show Side Panel', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('show_panel_accent', [
            'label' => esc_html__('Show Panel Accent', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
            'condition' => ['show_side_panel' => 'yes'],
        ]);
        $this->add_control('panel_position', [
            'label' => esc_html__('Side Panel Position', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'right',
            'options' => [
                'right' => esc_html__('Right', 'calio-addon'),
                'left' => esc_html__('Left', 'calio-addon'),
            ],
            'condition' => ['show_side_panel' => 'yes'],
        ]);
        $this->end_controls_section();

        $this->start_controls_section('items_section', ['label' => esc_html__('Feature Items', 'calio-addon')]);
        $repeater = new Repeater();
        $repeater->add_control('media_type', [
            'label' => esc_html__('Media Type', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'icon',
            'options' => [
                'icon' => esc_html__('Icon', 'calio-addon'),
                'image' => esc_html__('Image', 'calio-addon'),
            ],
        ]);
        $repeater->add_control('icon', [
            'label' => esc_html__('Icon', 'calio-addon'),
            'type' => Controls_Manager::ICONS,
            'default' => [
                'value' => 'fas fa-check',
                'library' => 'fa-solid',
            ],
            'condition' => ['media_type' => 'icon'],
        ]);
        $repeater->add_control('image', [
            'label' => esc_html__('Image', 'calio-addon'),
            'type' => Controls_Manager::MEDIA,
            'condition' => ['media_type' => 'image'],
        ]);
        $repeater->add_control('title', [
            'label' => esc_html__('Title', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Amazing Design', 'calio-addon'),
            'label_block' => true,
        ]);
        $repeater->add_control('description', [
            'label' => esc_html__('Description', 'calio-addon'),
            'type' => Controls_Manager::TEXTAREA,
            'default' => esc_html__('Use a simpler icon-and-copy row to explain one product benefit in a cleaner way.', 'calio-addon'),
        ]);
        $repeater->add_control('link', [
            'label' => esc_html__('Item Link', 'calio-addon'),
            'type' => Controls_Manager::URL,
            'default' => ['url' => ''],
        ]);

        $this->add_control('items', [
            'label' => esc_html__('Items', 'calio-addon'),
            'type' => Controls_Manager::REPEATER,
            'fields' => $repeater->get_controls(),
            'title_field' => '{{{ title }}}',
            'default' => [
                [
                    'title' => 'Amazing Design',
                    'description' => 'Use its simple icon-and-copy structure to highlight one sharp product value.',
                ],
                [
                    'title' => 'Feature Items',
                    'description' => 'Add as many rows as you need while keeping the layout easier to scan.',
                ],
                [
                    'title' => 'Ease of Styling',
                    'description' => 'Keep spacing, connector and icon styling under cleaner grouped controls.',
                ],
            ],
        ]);
        $this->end_controls_section();

        $this->start_controls_section('panel_section', ['label' => esc_html__('Side Panel', 'calio-addon'), 'condition' => ['show_side_panel' => 'yes']]);
        $this->add_control('panel_preset', [
            'label' => esc_html__('Panel Preset', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'soft',
            'options' => [
                'soft' => esc_html__('Soft', 'calio-addon'),
                'outline' => esc_html__('Outline', 'calio-addon'),
                'contrast' => esc_html__('Contrast', 'calio-addon'),
            ],
        ]);
        $this->add_control('panel_eyebrow', [
            'label' => esc_html__('Eyebrow', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Why It Works', 'calio-addon'),
        ]);
        $this->add_control('panel_title', [
            'label' => esc_html__('Title', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('A simpler side panel keeps the section balanced.', 'calio-addon'),
            'label_block' => true,
        ]);
        $this->add_control('panel_description', [
            'label' => esc_html__('Description', 'calio-addon'),
            'type' => Controls_Manager::TEXTAREA,
            'default' => esc_html__('Use the static panel for a short summary, a supporting visual or one CTA while the left side handles the repeatable feature rows.', 'calio-addon'),
        ]);
        $this->add_control('panel_button_text', [
            'label' => esc_html__('Button Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Learn More', 'calio-addon'),
        ]);
        $this->add_control('panel_button_url', [
            'label' => esc_html__('Button Link', 'calio-addon'),
            'type' => Controls_Manager::URL,
            'default' => ['url' => ''],
        ]);
        $this->add_control('panel_image', [
            'label' => esc_html__('Panel Image', 'calio-addon'),
            'type' => Controls_Manager::MEDIA,
        ]);
        $this->end_controls_section();

        $this->start_controls_section('style_list', ['label' => esc_html__('List', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_control('feature_list_simple_gap', [
            'label' => esc_html__('Item Spacing', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 0, 'max' => 48]],
            'default' => ['size' => 18],
            'selectors' => ['{{WRAPPER}} .calio-feature-list-simple-list' => '--calio-feature-list-simple-gap: {{SIZE}}{{UNIT}}; gap: var(--calio-feature-list-simple-gap);'],
        ]);
        $this->add_control('feature_list_simple_connector_width', [
            'label' => esc_html__('Connector Width', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 1, 'max' => 6]],
            'default' => ['size' => 1],
            'condition' => ['show_connector' => 'yes'],
            'selectors' => ['{{WRAPPER}} .calio-feature-list-simple.has-connector .calio-feature-list-simple-item:not(:last-child)::after' => 'width: {{SIZE}}{{UNIT}};'],
        ]);
        $this->add_control('feature_list_simple_connector_offset', [
            'label' => esc_html__('Connector Offset', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 0, 'max' => 80]],
            'default' => ['size' => 28],
            'condition' => ['show_connector' => 'yes'],
            'selectors' => ['{{WRAPPER}} .calio-feature-list-simple.has-connector .calio-feature-list-simple-item:not(:last-child)::after' => 'left: {{SIZE}}{{UNIT}};'],
        ]);
        $this->add_background_paint_controls('feature_list_simple_connector_color', esc_html__('Connector Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-item::after', ['condition' => ['show_connector' => 'yes']]);
        $this->end_controls_section();

        $this->start_controls_section('style_icon', ['label' => esc_html__('Icon', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_text_paint_controls('feature_list_simple_icon_text', esc_html__('Primary Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-media');
        $this->add_background_type_control('feature_list_simple_icon_bg', '{{WRAPPER}} .calio-feature-list-simple-media');
        $this->add_control('feature_list_simple_icon_size', [
            'label' => esc_html__('Icon Size', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 12, 'max' => 72]],
            'default' => ['size' => 20],
            'selectors' => [
                '{{WRAPPER}} .calio-feature-list-simple-media i' => 'font-size: {{SIZE}}{{UNIT}};',
                '{{WRAPPER}} .calio-feature-list-simple-media svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_control('feature_list_simple_media_width', [
            'label' => esc_html__('Media Width', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 32, 'max' => 140]],
            'default' => ['size' => 56],
            'selectors' => [
                '{{WRAPPER}} .calio-feature-list-simple-media' => '--feature-list-simple-media-width: {{SIZE}}{{UNIT}}; width: var(--feature-list-simple-media-width); height: var(--feature-list-simple-media-width);',
            ],
        ]);
        $this->add_dimensions_control('feature_list_simple_icon_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-media', 'padding');
        $this->add_dimensions_control('feature_list_simple_icon_radius', esc_html__('Border Radius', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-media, {{WRAPPER}} .calio-feature-list-simple-media img', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'feature_list_simple_icon_border', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-media']);
        $this->end_controls_section();

        $this->start_controls_section('style_content', ['label' => esc_html__('Content', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'feature_list_simple_title_typography', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-title']);
        $this->add_text_paint_controls('feature_list_simple_title_text', esc_html__('Title Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-title');
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'feature_list_simple_description_typography', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-description']);
        $this->add_text_paint_controls('feature_list_simple_description_text', esc_html__('Description Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-description');
        $this->add_control('feature_list_simple_title_spacing', [
            'label' => esc_html__('Title Spacing', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 0, 'max' => 32]],
            'default' => ['size' => 6],
            'selectors' => ['{{WRAPPER}} .calio-feature-list-simple-title' => 'margin-bottom: {{SIZE}}{{UNIT}};'],
        ]);
        $this->add_text_paint_controls('feature_list_simple_link_arrow_text', esc_html__('Link Arrow Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-title-link::after');
        $this->end_controls_section();

        $this->start_controls_section('style_panel', ['label' => esc_html__('Side Panel', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['show_side_panel' => 'yes']]);
        $this->add_background_type_control('feature_list_simple_panel_bg', '{{WRAPPER}} .calio-feature-list-simple-panel');
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'feature_list_simple_panel_border', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'feature_list_simple_panel_shadow', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel']);
        $this->add_dimensions_control('feature_list_simple_panel_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_dimensions_control('feature_list_simple_panel_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel', 'padding');
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'feature_list_simple_panel_eyebrow_typography', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel-eyebrow']);
        $this->add_text_paint_controls('feature_list_simple_panel_eyebrow_text', esc_html__('Eyebrow Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel-eyebrow');
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'feature_list_simple_panel_title_typography', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel-title']);
        $this->add_text_paint_controls('feature_list_simple_panel_title_text', esc_html__('Title Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel-title');
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'feature_list_simple_panel_description_typography', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel-description']);
        $this->add_text_paint_controls('feature_list_simple_panel_description_text', esc_html__('Description Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel-description');
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'feature_list_simple_panel_button_typography', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel-button']);
        $this->add_text_paint_controls('feature_list_simple_panel_button_text', esc_html__('Button Text Color', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel-button');
        $this->add_background_type_control('feature_list_simple_panel_button_bg', '{{WRAPPER}} .calio-feature-list-simple-panel-button');
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'feature_list_simple_panel_button_border', 'selector' => '{{WRAPPER}} .calio-feature-list-simple-panel-button']);
        $this->add_dimensions_control('feature_list_simple_panel_button_radius', esc_html__('Button Radius', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel-button', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_dimensions_control('feature_list_simple_panel_button_padding', esc_html__('Button Padding', 'calio-addon'), '{{WRAPPER}} .calio-feature-list-simple-panel-button', 'padding');
        $this->end_controls_section();
    }

    protected function render(): void
    {
        $settings = $this->get_settings_for_display();
        $items = isset($settings['items']) && is_array($settings['items']) ? $settings['items'] : [];

        if ($items === []) {
            return;
        }

        $classes = [
            'calio-feature-list-simple',
            'shape-' . sanitize_html_class((string) ($settings['icon_shape'] ?? 'circle')),
            'view-' . sanitize_html_class((string) ($settings['shape_view'] ?? 'stacked')),
            'hover-' . sanitize_html_class((string) ($settings['hover_skin'] ?? 'soft')),
            'align-' . sanitize_html_class((string) ($settings['content_alignment'] ?? 'start')),
            'media-' . sanitize_html_class((string) ($settings['media_position'] ?? 'left')),
        ];

        if (($settings['show_connector'] ?? 'yes') === 'yes') {
            $classes[] = 'has-connector';
        }

        if (($settings['show_side_panel'] ?? 'yes') === 'yes') {
            $classes[] = 'has-panel';
            $classes[] = 'panel-' . sanitize_html_class((string) ($settings['panel_position'] ?? 'right'));
            if (($settings['show_panel_accent'] ?? 'yes') === 'yes') {
                $classes[] = 'show-panel-accent';
            }
        }

        echo '<div class="' . esc_attr(implode(' ', $classes)) . '">';
        echo '<div class="calio-feature-list-simple-list">';

        foreach ($items as $item) {
            echo '<div class="calio-feature-list-simple-item">';
            echo '<div class="calio-feature-list-simple-media">';
            echo wp_kses_post($this->render_media((string) ($item['media_type'] ?? 'icon'), $item));
            echo '</div>';
            echo '<div class="calio-feature-list-simple-copy">';

            $title_markup = '<span class="calio-feature-list-simple-title-text">' . esc_html((string) ($item['title'] ?? '')) . '</span>';
            if (!empty($item['link']['url'])) {
                $title_markup = $this->wrap_link($title_markup, $item['link'], 'calio-feature-list-simple-title-link');
            }

            echo '<h3 class="calio-feature-list-simple-title">' . wp_kses_post($title_markup) . '</h3>';

            if (!empty($item['description'])) {
                echo '<div class="calio-feature-list-simple-description">' . esc_html((string) $item['description']) . '</div>';
            }

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

        echo '</div>';

        if (($settings['show_side_panel'] ?? 'yes') === 'yes') {
            echo '<aside class="calio-feature-list-simple-panel preset-' . esc_attr(sanitize_html_class((string) ($settings['panel_preset'] ?? 'soft'))) . '">';
            if (!empty($settings['panel_eyebrow'])) {
                echo '<div class="calio-feature-list-simple-panel-eyebrow">' . esc_html((string) $settings['panel_eyebrow']) . '</div>';
            }
            if (!empty($settings['panel_title'])) {
                echo '<h3 class="calio-feature-list-simple-panel-title">' . esc_html((string) $settings['panel_title']) . '</h3>';
            }
            if (!empty($settings['panel_description'])) {
                echo '<div class="calio-feature-list-simple-panel-description">' . esc_html((string) $settings['panel_description']) . '</div>';
            }
            if (!empty($settings['panel_button_text']) && !empty($settings['panel_button_url']['url'])) {
                echo wp_kses_post($this->build_button_markup((string) $settings['panel_button_text'], $settings['panel_button_url'], 'calio-feature-list-simple-panel-button'));
            }
            if (!empty($settings['panel_image']['url'])) {
                $panel_url = (string) $settings['panel_image']['url'];
                $panel_alt = get_post_meta((int) ($settings['panel_image']['id'] ?? 0), '_wp_attachment_image_alt', true);
                echo '<div class="calio-feature-list-simple-panel-media"><img src="' . esc_url($panel_url) . '" alt="' . esc_attr($panel_alt ?: wp_basename($panel_url)) . '"></div>';
            }
            echo '</aside>';
        }

        echo '</div>';
    }

    /**
     * Renders either an icon or an image for one simple feature row.
     *
     * @param array<string, mixed> $item
     */
    private function render_media(string $media_type, array $item): string
    {
        if ($media_type === 'image' && !empty($item['image']['url'])) {
            $url = (string) $item['image']['url'];
            $alt = get_post_meta((int) ($item['image']['id'] ?? 0), '_wp_attachment_image_alt', true);

            return '<img src="' . esc_url($url) . '" alt="' . esc_attr($alt ?: wp_basename($url)) . '">';
        }

        return $this->get_icon_markup($item['icon'] ?? []);
    }

    /**
     * Wraps simple title content with a secure anchor.
     *
     * @param array<string, mixed> $link
     */
    private function wrap_link(string $content, array $link, string $class_name): string
    {
        $href = isset($link['url']) ? (string) $link['url'] : '';
        if ($href === '') {
            return $content;
        }

        $rel = [];

        if (!empty($link['nofollow'])) {
            $rel[] = 'nofollow';
        }

        if (!empty($link['is_external'])) {
            $rel[] = 'noopener';
            $rel[] = 'noreferrer';
        }

        $output = '<a class="' . esc_attr($class_name) . '" href="' . esc_url($href) . '"';
        if (!empty($link['is_external'])) {
            $output .= ' target="' . esc_attr('_blank') . '"';
        }
        if (!empty($rel)) {
            $output .= ' rel="' . esc_attr(implode(' ', array_unique($rel))) . '"';
        }

        return $output . '>' . $content . '</a>';
    }

    /**
     * Builds the side-panel button only when text and URL are available.
     *
     * @param array<string, mixed> $link
     */
    private function build_button_markup(string $text, array $link, string $class_name): string
    {
        $text = trim($text);
        $href = isset($link['url']) ? (string) $link['url'] : '';

        if ($text === '' || $href === '') {
            return '';
        }

        $rel = [];

        if (!empty($link['nofollow'])) {
            $rel[] = 'nofollow';
        }

        if (!empty($link['is_external'])) {
            $rel[] = 'noopener';
            $rel[] = 'noreferrer';
        }

        $output = '<a class="' . esc_attr($class_name) . '" href="' . esc_url($href) . '"';
        if (!empty($link['is_external'])) {
            $output .= ' target="' . esc_attr('_blank') . '"';
        }
        if (!empty($rel)) {
            $output .= ' rel="' . esc_attr(implode(' ', array_unique($rel))) . '"';
        }

        return $output . '>' . esc_html($text) . '</a>';
    }
}
