<?php
namespace Softech_Addons_for_Elementor\Widgets;

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

if ( ! class_exists( '\\Softech_Addons_for_Elementor\\Includes\\SITS_Single_Post_Widget_Base' ) ) {
    require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-single-post-widget-base.php';
}

use Elementor\Controls_Manager;
use Elementor\Icons_Manager;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use Elementor\Repeater;
use Softech_Addons_for_Elementor\Includes\SITS_Single_Post_Widget_Base;

class sitsel_post_meta extends SITS_Single_Post_Widget_Base {

    protected function get_style_handle(): string { return 'sitsel-post-meta-css'; }
    protected function get_style_file(): string { return 'assets/css/sitsel-post-meta.css'; }
    protected function get_script_handle(): string { return 'sitsel-post-meta-js'; }
    protected function get_script_file(): string { return 'assets/js/sitsel-post-meta.js'; }

    public function get_name() { return 'sitsel_post_meta'; }
    public function get_title() { return __( 'SITS Post Meta', 'softech-addons-for-elementor' ); }
    public function get_icon() { return 'eicon-info-circle'; }
    public function get_keywords() { return [ 'post', 'meta', 'date', 'author', 'category', 'tag' ]; }

    protected function _register_controls() {
        $repeater = new Repeater();
        $repeater->add_control( 'item_type', [
            'label'   => esc_html__( 'Meta Item', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SELECT,
            'default' => 'date',
            'options' => [
                'date'          => esc_html__( 'Date', 'softech-addons-for-elementor' ),
                'modified_date'  => esc_html__( 'Modified Date', 'softech-addons-for-elementor' ),
                'author'         => esc_html__( 'Author', 'softech-addons-for-elementor' ),
                'categories'     => esc_html__( 'Categories', 'softech-addons-for-elementor' ),
                'tags'           => esc_html__( 'Tags', 'softech-addons-for-elementor' ),
                'comments'       => esc_html__( 'Comments Count', 'softech-addons-for-elementor' ),
                'reading_time'    => esc_html__( 'Reading Time', 'softech-addons-for-elementor' ),
            ],
        ] );
        $repeater->add_control( 'show_icon', [
            'label'   => esc_html__( 'Show Icon', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SWITCHER,
            'default' => 'yes',
        ] );
        $repeater->add_control( 'icon', [
            'label' => esc_html__( 'Icon', 'softech-addons-for-elementor' ),
            'type'  => Controls_Manager::ICONS,
            'condition' => [ 'show_icon' => 'yes' ],
        ] );
        $repeater->add_control( 'prefix', [
            'label'   => esc_html__( 'Prefix Text', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::TEXT,
            'default' => '',
        ] );
        $repeater->add_control( 'suffix', [
            'label'   => esc_html__( 'Suffix Text', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::TEXT,
            'default' => '',
        ] );
        $repeater->add_control( 'apply_link', [
            'label'        => esc_html__( 'Apply Link', 'softech-addons-for-elementor' ),
            'type'         => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default'      => '',
            'description'  => esc_html__( 'Enable links only for items that support them, such as author, categories, and tags.', 'softech-addons-for-elementor' ),
            'condition'    => [ 'item_type' => [ 'author', 'categories', 'tags' ] ],
        ] );

        $this->start_controls_section( 'section_content', [ 'label' => esc_html__( 'Content', 'softech-addons-for-elementor' ) ] );

        $this->add_control( 'meta_items', [
            'label'       => esc_html__( 'Meta Items', 'softech-addons-for-elementor' ),
            'type'        => Controls_Manager::REPEATER,
            'fields'      => $repeater->get_controls(),
            'title_field' => '{{{ item_type }}}',
            'default'     => [
                [ 'item_type' => 'date', 'show_icon' => 'yes', 'icon' => $this->get_default_meta_icon( 'date' ) ],
                [ 'item_type' => 'author', 'show_icon' => 'yes', 'icon' => $this->get_default_meta_icon( 'author' ) ],
                [ 'item_type' => 'categories', 'show_icon' => '', 'icon' => $this->get_default_meta_icon( 'categories' ) ],
            ],
        ] );

        $this->add_control( 'layout', [
            'label'   => esc_html__( 'Layout', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SELECT,
            'default' => 'inline',
            'options' => [
                'inline'  => esc_html__( 'Inline', 'softech-addons-for-elementor' ),
                'stacked' => esc_html__( 'Stacked', 'softech-addons-for-elementor' ),
                'grid'    => esc_html__( 'Grid', 'softech-addons-for-elementor' ),
            ],
        ] );

        $this->add_control( 'alignment', [
            'label'        => esc_html__( 'Alignment', 'softech-addons-for-elementor' ),
            'type'         => Controls_Manager::CHOOSE,
            'default'      => 'left',
            'options'      => [
                'left'   => [ 'title' => esc_html__( 'Left', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-left' ],
                'center' => [ 'title' => esc_html__( 'Center', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-center' ],
                'right'  => [ 'title' => esc_html__( 'Right', 'softech-addons-for-elementor' ), 'icon' => 'eicon-text-align-right' ],
            ],
            'prefix_class' => 'sitsel-post-meta-align-',
        ] );

        $this->add_control( 'separator', [
            'label'   => esc_html__( 'Separator', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::TEXT,
            'default' => '|',
        ] );

        $this->add_control( 'date_format', [
            'label'   => esc_html__( 'Date Format', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SELECT,
            'default' => 'F j, Y',
            'options' => [
                'F j, Y' => esc_html__( 'January 1, 2024', 'softech-addons-for-elementor' ),
                'm/d/Y'  => esc_html__( '01/01/2024', 'softech-addons-for-elementor' ),
                'd/m/Y'  => esc_html__( '01/01/2024', 'softech-addons-for-elementor' ),
                'Y-m-d'  => esc_html__( '2024-01-01', 'softech-addons-for-elementor' ),
                'custom' => esc_html__( 'Custom', 'softech-addons-for-elementor' ),
            ],
        ] );

        $this->add_control( 'date_format_custom', [
            'label'     => esc_html__( 'Custom Date Format', 'softech-addons-for-elementor' ),
            'type'      => Controls_Manager::TEXT,
            'default'   => 'F j, Y',
            'condition' => [ 'date_format' => 'custom' ],
        ] );

        $this->add_control( 'author_display', [
            'label'   => esc_html__( 'Author Display', 'softech-addons-for-elementor' ),
            'type'    => Controls_Manager::SELECT,
            'default' => 'name',
            'options' => [
                'name'     => esc_html__( 'Name Only', 'softech-addons-for-elementor' ),
                'avatar'   => esc_html__( 'With Avatar', 'softech-addons-for-elementor' ),
                'bio-link' => esc_html__( 'With Bio Link', 'softech-addons-for-elementor' ),
            ],
        ] );

        $this->add_responsive_control( 'avatar_size', [
            'label'       => esc_html__( 'Avatar Size', 'softech-addons-for-elementor' ),
            'type'        => Controls_Manager::SLIDER,
            'size_units'  => [ 'px' ],
            'range'       => [ 'px' => [ 'min' => 24, 'max' => 128 ] ],
            'default'     => [ 'size' => 36, 'unit' => 'px' ],
            'condition'   => [ 'author_display' => 'avatar' ],
        ] );

        $this->end_controls_section();

        $this->start_controls_section( 'section_style', [ 'label' => esc_html__( 'Style', 'softech-addons-for-elementor' ), 'tab' => Controls_Manager::TAB_STYLE ] );
        $this->add_control( 'text_color', [ 'label' => esc_html__( 'Text Color', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::COLOR, 'default' => '#4b5563', 'selectors' => [ '{{WRAPPER}} .sitsel-post-meta-item, {{WRAPPER}} .sitsel-post-meta-separator' => 'color: {{VALUE}};' ] ] );
        $this->add_control( 'link_color', [ 'label' => esc_html__( 'Link Color', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sitsel-post-meta-item a' => 'color: {{VALUE}};' ] ] );
        $this->add_control( 'icon_color', [
            'label' => esc_html__( 'Icon Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-icon' => 'color: {{VALUE}};',
                '{{WRAPPER}} .sitsel-post-meta-icon .elementor-icon' => 'color: {{VALUE}};',
                '{{WRAPPER}} .sitsel-post-meta-icon i' => 'color: {{VALUE}};',
                '{{WRAPPER}} .sitsel-post-meta-icon svg' => 'fill: {{VALUE}}; stroke: {{VALUE}}; color: {{VALUE}};',
                '{{WRAPPER}} .sitsel-post-meta-icon svg *' => 'fill: {{VALUE}}; stroke: {{VALUE}};',
            ],
        ] );
        $this->add_responsive_control( 'icon_size', [ 'label' => esc_html__( 'Icon Size', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::SLIDER, 'size_units' => [ 'px' ], 'range' => [ 'px' => [ 'min' => 10, 'max' => 32 ] ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-meta-icon' => '--sitsel-post-meta-icon-size: {{SIZE}}{{UNIT}}; font-size: {{SIZE}}{{UNIT}};', '{{WRAPPER}} .sitsel-post-meta-icon .elementor-icon' => 'font-size: {{SIZE}}{{UNIT}};' ] ] );
        $this->add_responsive_control( 'icon_width', [ 'label' => esc_html__( 'Icon Width', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::SLIDER, 'size_units' => [ 'px', 'em' ], 'range' => [ 'px' => [ 'min' => 10, 'max' => 80 ], 'em' => [ 'min' => 0.5, 'max' => 5 ] ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-meta-icon' => 'width: {{SIZE}}{{UNIT}}; min-width: {{SIZE}}{{UNIT}};', '{{WRAPPER}} .sitsel-post-meta-icon .elementor-icon' => 'width: {{SIZE}}{{UNIT}}; min-width: {{SIZE}}{{UNIT}};' ] ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'meta_typography', 'label' => esc_html__( 'Meta Typography', 'softech-addons-for-elementor' ), 'selector' => '{{WRAPPER}} .sitsel-post-meta-item' ] );
        $this->add_control( 'has_author_item', [
            'type'    => Controls_Manager::HIDDEN,
            'default' => 'yes',
        ] );
        $this->add_control( 'has_category_item', [
            'type'    => Controls_Manager::HIDDEN,
            'default' => 'yes',
        ] );
        $this->add_group_control( Group_Control_Background::get_type(), [ 'name' => 'meta_background', 'types' => [ 'classic', 'gradient' ], 'selector' => '{{WRAPPER}} .sitsel-post-meta-box' ] );
        $this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'meta_border', 'selector' => '{{WRAPPER}} .sitsel-post-meta-box' ] );
        $this->add_group_control( Group_Control_Box_Shadow::get_type(), [ 'name' => 'meta_shadow', 'selector' => '{{WRAPPER}} .sitsel-post-meta-box' ] );
        $this->add_responsive_control( 'meta_padding', [ 'label' => esc_html__( 'Padding', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', 'em', 'rem' ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-meta-box' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ] ] );
        $this->add_responsive_control( 'meta_spacing', [ 'label' => esc_html__( 'Item Spacing', 'softech-addons-for-elementor' ), 'type' => Controls_Manager::SLIDER, 'size_units' => [ 'px' ], 'range' => [ 'px' => [ 'min' => 0, 'max' => 40 ] ], 'selectors' => [ '{{WRAPPER}} .sitsel-post-meta' => 'gap: {{SIZE}}{{UNIT}};' ] ] );
        $this->end_controls_section();

        $this->start_controls_section( 'section_author_style', [
            'label'     => esc_html__( 'Author Item', 'softech-addons-for-elementor' ),
            'tab'       => Controls_Manager::TAB_STYLE,
            'condition' => [ 'has_author_item' => 'yes' ],
        ] );
        $this->add_control( 'author_text_color', [
            'label' => esc_html__( 'Author Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'default' => '',
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-author' => 'color: {{VALUE}};',
                '{{WRAPPER}} .sitsel-post-meta-author a' => 'color: {{VALUE}} !important;',
                '{{WRAPPER}} .sitsel-post-meta-author a *' => 'color: {{VALUE}} !important; fill: {{VALUE}} !important; stroke: {{VALUE}} !important;',
            ],
        ] );
        $this->add_control( 'author_hover_color', [
            'label' => esc_html__( 'Author Hover Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-author a:hover' => 'color: {{VALUE}} !important;',
                '{{WRAPPER}} .sitsel-post-meta-author a:focus-visible' => 'color: {{VALUE}} !important;',
                '{{WRAPPER}} .sitsel-post-meta-author a:hover *, {{WRAPPER}} .sitsel-post-meta-author a:focus-visible *' => 'color: {{VALUE}} !important; fill: {{VALUE}} !important; stroke: {{VALUE}} !important;',
            ],
        ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [
            'name' => 'author_typography',
            'selector' => '{{WRAPPER}} .sitsel-post-meta-author, {{WRAPPER}} .sitsel-post-meta-author a',
        ] );
        $this->add_responsive_control( 'author_padding', [
            'label' => esc_html__( 'Padding', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', 'em', 'rem', '%' ],
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-author' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                '{{WRAPPER}} .sitsel-post-meta-author a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            ],
        ] );
        $this->add_group_control( Group_Control_Border::get_type(), [
            'name' => 'author_border',
            'selector' => '{{WRAPPER}} .sitsel-post-meta-author, {{WRAPPER}} .sitsel-post-meta-author a',
        ] );
        $this->add_responsive_control( 'author_border_radius', [
            'label' => esc_html__( 'Border Radius', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', 'em', 'rem', '%' ],
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-author' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                '{{WRAPPER}} .sitsel-post-meta-author a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            ],
        ] );
        $this->end_controls_section();

        $this->start_controls_section( 'section_category_style', [
            'label'     => esc_html__( 'Category Item', 'softech-addons-for-elementor' ),
            'tab'       => Controls_Manager::TAB_STYLE,
            'condition' => [ 'has_category_item' => 'yes' ],
        ] );
        $this->add_control( 'category_text_color', [
            'label' => esc_html__( 'Category Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'default' => '',
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-categories' => 'color: {{VALUE}};',
                '{{WRAPPER}} .sitsel-post-meta-categories a' => 'color: {{VALUE}} !important;',
                '{{WRAPPER}} .sitsel-post-meta-categories a *' => 'color: {{VALUE}} !important; fill: {{VALUE}} !important; stroke: {{VALUE}} !important;',
            ],
        ] );
        $this->add_control( 'category_hover_color', [
            'label' => esc_html__( 'Category Hover Color', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::COLOR,
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-categories a:hover' => 'color: {{VALUE}} !important;',
                '{{WRAPPER}} .sitsel-post-meta-categories a:focus-visible' => 'color: {{VALUE}} !important;',
                '{{WRAPPER}} .sitsel-post-meta-categories a:hover *, {{WRAPPER}} .sitsel-post-meta-categories a:focus-visible *' => 'color: {{VALUE}} !important; fill: {{VALUE}} !important; stroke: {{VALUE}} !important;',
            ],
        ] );
        $this->add_group_control( Group_Control_Typography::get_type(), [
            'name' => 'category_typography',
            'selector' => '{{WRAPPER}} .sitsel-post-meta-categories, {{WRAPPER}} .sitsel-post-meta-categories a',
        ] );
        $this->add_responsive_control( 'category_padding', [
            'label' => esc_html__( 'Padding', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', 'em', 'rem', '%' ],
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-categories' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                '{{WRAPPER}} .sitsel-post-meta-categories a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            ],
        ] );
        $this->add_group_control( Group_Control_Border::get_type(), [
            'name' => 'category_border',
            'selector' => '{{WRAPPER}} .sitsel-post-meta-categories, {{WRAPPER}} .sitsel-post-meta-categories a',
        ] );
        $this->add_responsive_control( 'category_border_radius', [
            'label' => esc_html__( 'Border Radius', 'softech-addons-for-elementor' ),
            'type' => Controls_Manager::DIMENSIONS,
            'size_units' => [ 'px', 'em', 'rem', '%' ],
            'selectors' => [
                '{{WRAPPER}} .sitsel-post-meta-categories' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                '{{WRAPPER}} .sitsel-post-meta-categories a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            ],
        ] );
        $this->end_controls_section();
    }

    protected function render() {
        $settings      = $this->get_settings_for_display();
        $post_id       = $this->get_render_post_id();
        $rows          = is_array( $settings['meta_items'] ?? [] ) ? $settings['meta_items'] : [];
        $layout        = $settings['layout'] ?? 'inline';
        $separator     = (string) ( $settings['separator'] ?? '|' );
        $date_format   = 'custom' === ( $settings['date_format'] ?? '' ) ? ( $settings['date_format_custom'] ?? 'F j, Y' ) : ( $settings['date_format'] ?? 'F j, Y' );
        $is_editor     = $this->is_editor_mode();
        $author_id     = $post_id ? (int) get_post_field( 'post_author', $post_id ) : ( $is_editor ? get_current_user_id() : 0 );
        $author        = $author_id ? get_userdata( $author_id ) : null;
        $author_url    = $author_id ? get_author_posts_url( $author_id ) : '';
        $avatar_size   = absint( $settings['avatar_size']['size'] ?? 36 );
        $visible_count = 0;

        $this->add_render_attribute( 'wrapper', [ 'class' => [ 'sitsel-post-meta-wrapper', 'layout-' . $layout ] ] );
        $this->add_render_attribute( 'box', [ 'class' => 'sitsel-post-meta-box' ] );
        $this->add_render_attribute( 'list', [ 'class' => 'sitsel-post-meta' ] );

        echo '<div ' . $this->get_render_attribute_string( 'wrapper' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.
        echo '<div ' . $this->get_render_attribute_string( 'box' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.
        echo '<div ' . $this->get_render_attribute_string( 'list' ) . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Render attribute strings are generated by Elementor.

        foreach ( $rows as $row ) {
            $type = sanitize_key( $row['item_type'] ?? '' );
            if ( '' === $type ) {
                continue;
            }

            $apply_link = 'yes' === ( $row['apply_link'] ?? '' );
            // Only allow apply_link for author, categories, and tags
            if ( ! in_array( $type, [ 'author', 'categories', 'tags' ], true ) ) {
                $apply_link = false;
            }
            $value = $this->get_meta_item_value( $type, $post_id, $author, $author_url, $date_format, (string) ( $settings['author_display'] ?? 'name' ), $avatar_size, $is_editor, $apply_link );
            if ( '' === trim( wp_strip_all_tags( (string) $value ) ) ) {
                continue;
            }

            if ( $visible_count > 0 && '' !== trim( $separator ) ) {
                echo '<span class="sitsel-post-meta-separator" aria-hidden="true">' . esc_html( $separator ) . '</span>';
            }

            $prefix = sanitize_text_field( $row['prefix'] ?? '' );
            $suffix = sanitize_text_field( $row['suffix'] ?? '' );
            $icon   = $this->get_meta_icon( $row, $type );

            echo '<span class="sitsel-post-meta-item sitsel-post-meta-' . esc_attr( $type ) . '">';

            if ( ! empty( $row['show_icon'] ) && ! empty( $icon['value'] ) ) {
                echo '<span class="sitsel-post-meta-icon" aria-hidden="true">';
                $this->enqueue_meta_icon_assets( $icon );
                Icons_Manager::render_icon( $icon, [ 'aria-hidden' => 'true' ] );
                echo '</span>';
            }

            if ( '' !== $prefix ) {
                echo '<span class="sitsel-post-meta-prefix">' . esc_html( $prefix ) . '</span>';
            }

            echo wp_kses_post( $value );

            if ( '' !== $suffix ) {
                echo '<span class="sitsel-post-meta-suffix">' . esc_html( $suffix ) . '</span>';
            }

            echo '</span>';
            $visible_count++;
        }

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

    private function get_meta_icon( array $row, string $type ): array {
        $icon = is_array( $row['icon'] ?? null ) ? $row['icon'] : [];
        $default_icon = $this->get_default_meta_icon( $type );

        if ( empty( $icon['value'] ) ) {
            return $default_icon;
        }

        $icon_value   = sanitize_text_field( (string) $icon['value'] );
        $icon_library = sanitize_key( (string) ( $icon['library'] ?? '' ) );

        if ( '' === $icon_library ) {
            if ( 0 === strpos( $icon_value, 'eicon-' ) ) {
                $icon['library'] = 'eicon';
                $icon_library    = 'eicon';
            } elseif ( 0 === strpos( $icon_value, 'fas ' ) || 0 === strpos( $icon_value, 'fa-solid' ) ) {
                $icon['library'] = 'fa-solid';
                $icon_library    = 'fa-solid';
            } elseif ( 0 === strpos( $icon_value, 'far ' ) || 0 === strpos( $icon_value, 'fa-regular' ) ) {
                $icon['library'] = 'fa-regular';
                $icon_library    = 'fa-regular';
            } elseif ( 0 === strpos( $icon_value, 'fab ' ) || 0 === strpos( $icon_value, 'fa-brands' ) ) {
                $icon['library'] = 'fa-brands';
                $icon_library    = 'fa-brands';
            }
        }

        if ( 0 === strpos( $icon_value, 'eicon-' ) && in_array( $icon_library, [ '', 'elementor-icons' ], true ) ) {
            $icon['library'] = 'eicon';
            $icon_library    = 'eicon';
        }

        if ( $this->is_placeholder_meta_icon( $icon_value, $type ) && in_array( $icon_library, [ '', 'eicon', 'elementor-icons' ], true ) ) {
            return $default_icon;
        }

        return $icon;
    }

    private function get_default_meta_icon( string $type ): array {
        $icons = [
            'date'          => [ 'value' => 'eicon-calendar', 'library' => 'eicon' ],
            'modified_date' => [ 'value' => 'eicon-edit', 'library' => 'eicon' ],
            'author'        => [ 'value' => 'eicon-person', 'library' => 'eicon' ],
            'categories'    => [ 'value' => 'eicon-folder', 'library' => 'eicon' ],
            'category'      => [ 'value' => 'eicon-folder', 'library' => 'eicon' ],
            'tags'          => [ 'value' => 'eicon-tags', 'library' => 'eicon' ],
            'tag'           => [ 'value' => 'eicon-tags', 'library' => 'eicon' ],
            'comments'      => [ 'value' => 'eicon-comments', 'library' => 'eicon' ],
            'reading_time'  => [ 'value' => 'eicon-clock', 'library' => 'eicon' ],
        ];

        return $icons[ $type ] ?? [ 'value' => 'eicon-info-circle', 'library' => 'eicon' ];
    }

    private function is_placeholder_meta_icon( string $icon_value, string $type ): bool {
        $type = sanitize_key( $type );

        if ( '' === $icon_value ) {
            return true;
        }

        $placeholder_icons = [
            'author'       => [ 'eicon-calendar', 'eicon-user' ],
            'categories'   => [ 'eicon-calendar', 'eicon-user', 'eicon-tag' ],
            'category'     => [ 'eicon-calendar', 'eicon-user', 'eicon-tag' ],
            'tags'         => [ 'eicon-calendar', 'eicon-user', 'eicon-tag' ],
            'tag'          => [ 'eicon-calendar', 'eicon-user', 'eicon-tag' ],
            'modified_date' => [ 'eicon-calendar' ],
            'comments'     => [ 'eicon-calendar' ],
            'reading_time' => [ 'eicon-calendar' ],
        ];

        return in_array( $icon_value, $placeholder_icons[ $type ] ?? [ 'eicon-calendar' ], true );
    }

    private function enqueue_meta_icon_assets( array $icon ): void {
        $library = sanitize_key( (string) ( $icon['library'] ?? '' ) );

        if ( '' === $library || 'eicon' === $library || 'elementor-icons' === $library ) {
            if ( wp_style_is( 'elementor-icons', 'registered' ) ) {
                wp_enqueue_style( 'elementor-icons' );
            }

            return;
        }

        $handle = 'elementor-icons-' . $library;
        if ( wp_style_is( $handle, 'registered' ) ) {
            wp_enqueue_style( $handle );
        }
    }

    private function get_meta_item_value( string $type, int $post_id, ?\WP_User $author, string $author_url, string $date_format, string $author_display, int $avatar_size, bool $is_editor, bool $apply_link ): string {
        switch ( $type ) {
            case 'date':
                return esc_html( get_the_date( $date_format, $post_id ) );

            case 'modified_date':
                return esc_html( get_the_modified_date( $date_format, $post_id ) );

            case 'author':
                return $this->get_author_value_markup( $author, $author_url, $author_display, $avatar_size, $is_editor, $apply_link );

            case 'categories':
                $categories = $this->get_term_list( 'category', ', ', $apply_link );
                if ( '' !== trim( wp_strip_all_tags( (string) $categories ) ) ) {
                    return wp_kses_post( $categories );
                }
                if ( $is_editor ) {
                    return esc_html__( 'Category Name', 'softech-addons-for-elementor' );
                }
                return '';

            case 'tags':
                $tags = $this->get_term_list( 'post_tag', ', ', $apply_link );
                if ( '' !== trim( wp_strip_all_tags( (string) $tags ) ) ) {
                    return wp_kses_post( $tags );
                }
                if ( $is_editor ) {
                    return esc_html__( 'Tag Name', 'softech-addons-for-elementor' );
                }
                return '';

            case 'comments':
                $count = (int) get_comments_number( $post_id );
                if ( 1 === $count ) {
                    return esc_html__( '1 Comment', 'softech-addons-for-elementor' );
                }
                return esc_html( number_format_i18n( $count ) . ' ' . esc_html__( 'Comments', 'softech-addons-for-elementor' ) );

            case 'reading_time':
                return esc_html( $this->get_reading_time( $post_id ) );
        }

        return '';
    }

    private function get_author_value_markup( ?\WP_User $author, string $author_url, string $author_display, int $avatar_size, bool $is_editor, bool $apply_link ): string {
        $author_name = $author ? (string) $author->display_name : '';

        if ( '' === trim( $author_name ) && $is_editor ) {
            $current_user = wp_get_current_user();
            if ( $current_user && $current_user->exists() && '' !== trim( (string) $current_user->display_name ) ) {
                $author      = $current_user;
                $author_name = (string) $current_user->display_name;
                $author_url  = get_author_posts_url( (int) $current_user->ID );
            }
        }

        if ( '' === trim( $author_name ) ) {
            $author_name = $this->get_author_data()['name'];
        }

        $author_link_open  = ( $apply_link && '' !== $author_url ) ? '<a href="' . esc_url( $author_url ) . '">' : '';
        $author_link_close = ( $apply_link && '' !== $author_url ) ? '</a>' : '';

        if ( 'avatar' === $author_display && $author && $author->ID ) {
            $avatar = get_avatar( (int) $author->ID, $avatar_size );
            $html   = '<span class="sitsel-post-meta-avatar">' . wp_kses_post( $avatar ) . '</span> <span class="sitsel-post-meta-author-name">' . esc_html( $author_name ) . '</span>';

            return $author_link_open . $html . $author_link_close;
        }

        if ( 'bio-link' === $author_display && $apply_link && '' !== $author_url ) {
            return '<a href="' . esc_url( $author_url ) . '">' . esc_html( $author_name ) . '</a>';
        }

        return $author_link_open . esc_html( $author_name ) . $author_link_close;
    }

    protected function get_term_list( string $taxonomy, string $separator = ', ', bool $apply_link = true ): string {
        $post_id = $this->get_render_post_id();
        if ( ! $post_id ) {
            return '';
        }

        $terms = get_the_terms( $post_id, $taxonomy );
        if ( empty( $terms ) || is_wp_error( $terms ) ) {
            return '';
        }

        $parts = [];
        foreach ( $terms as $term ) {
            if ( ! $term instanceof \WP_Term ) {
                continue;
            }

            if ( $apply_link ) {
                $term_link = get_term_link( $term );
                if ( ! is_wp_error( $term_link ) ) {
                    $parts[] = '<a href="' . esc_url( $term_link ) . '">' . esc_html( $term->name ) . '</a>';
                    continue;
                }
            }

            $parts[] = esc_html( $term->name );
        }

        return implode( $separator, $parts );
    }

    private function is_editor_mode(): bool {
        return class_exists( '\\Elementor\\Plugin' ) && isset( \Elementor\Plugin::$instance ) && \Elementor\Plugin::$instance->editor && \Elementor\Plugin::$instance->editor->is_edit_mode();
    }
}
