<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class IDSC_IDVE_Blocks {

    public function __construct() {
        add_action( 'idve_register_blocks', array( $this, 'register_blocks' ) );
        add_action( 'idve_editor_scripts', array( $this, 'enqueue_editor_scripts' ) );
    }

    public function register_blocks( $blocks ) {

        // Alert / Notice
        $blocks->register( 'idsc_alert', array(
            'label'    => 'Alert',
            'icon'     => 'warning',
            'category' => 'shortcodes',
            'fields'   => array(
                'type'        => array( 'type' => 'select', 'label' => 'Type', 'options' => array( 'info', 'success', 'warning', 'error' ), 'default' => 'info' ),
                'title'       => array( 'type' => 'text', 'label' => 'Title', 'default' => '' ),
                'message'     => array( 'type' => 'textarea', 'label' => 'Message', 'default' => '' ),
                'dismissible' => array( 'type' => 'select', 'label' => 'Dismissible', 'options' => array( 'no', 'yes' ), 'default' => 'no' ),
                'show_icon'   => array( 'type' => 'select', 'label' => 'Show Icon', 'options' => array( 'yes', 'no' ), 'default' => 'yes' ),
            ),
            'render' => array( $this, 'render_alert' ),
        ) );

        // Testimonial
        $blocks->register( 'idsc_testimonial', array(
            'label'    => 'Testimonial',
            'icon'     => 'format-quote',
            'category' => 'shortcodes',
            'fields'   => array(
                'content' => array( 'type' => 'textarea', 'label' => 'Quote', 'default' => '' ),
                'author'  => array( 'type' => 'text', 'label' => 'Author', 'default' => '' ),
                'role'    => array( 'type' => 'text', 'label' => 'Role / Title', 'default' => '' ),
                'photo'   => array( 'type' => 'image_id', 'label' => 'Author Photo', 'default' => '' ),
                'rating'  => array( 'type' => 'select', 'label' => 'Star Rating', 'options' => array( '0', '1', '2', '3', '4', '5' ), 'default' => '0' ),
                'layout'  => array( 'type' => 'select', 'label' => 'Layout', 'options' => array( 'standard', 'card', 'centered' ), 'default' => 'standard' ),
            ),
            'render' => array( $this, 'render_testimonial' ),
        ) );

        // Card
        $blocks->register( 'idsc_card', array(
            'label'    => 'Card',
            'icon'     => 'id-alt',
            'category' => 'shortcodes',
            'fields'   => array(
                'image'       => array( 'type' => 'image_id', 'label' => 'Image', 'default' => '' ),
                'title'       => array( 'type' => 'text', 'label' => 'Title', 'default' => '' ),
                'content'     => array( 'type' => 'textarea', 'label' => 'Content', 'default' => '' ),
                'button_text' => array( 'type' => 'text', 'label' => 'Button Text', 'default' => '' ),
                'button_url'  => array( 'type' => 'text', 'label' => 'Button URL', 'default' => '' ),
                'image_pos'   => array( 'type' => 'select', 'label' => 'Image Position', 'options' => array( 'top', 'left', 'right' ), 'default' => 'top' ),
            ),
            'render' => array( $this, 'render_card' ),
        ) );

        // Progress Bar
        $blocks->register( 'idsc_progress', array(
            'label'    => 'Progress Bar',
            'icon'     => 'chart-bar',
            'category' => 'shortcodes',
            'fields'   => array(
                'value'      => array( 'type' => 'range', 'label' => 'Value (%)', 'default' => 75, 'min' => 0, 'max' => 100, 'step' => 1 ),
                'label'      => array( 'type' => 'text', 'label' => 'Label', 'default' => '' ),
                'color'      => array( 'type' => 'color', 'label' => 'Bar Color', 'default' => '#3b82f6' ),
                'bg_color'   => array( 'type' => 'color', 'label' => 'Background Color', 'default' => '#e5e7eb' ),
                'height'     => array( 'type' => 'text', 'label' => 'Height (px)', 'default' => '20' ),
                'show_pct'   => array( 'type' => 'select', 'label' => 'Show Percentage', 'options' => array( 'yes', 'no' ), 'default' => 'yes' ),
                'animated'   => array( 'type' => 'select', 'label' => 'Animated Fill', 'options' => array( 'yes', 'no' ), 'default' => 'no' ),
            ),
            'render' => array( $this, 'render_progress' ),
        ) );

        // Icon List
        $blocks->register( 'idsc_icon_list', array(
            'label'    => 'Icon List',
            'icon'     => 'list-view',
            'category' => 'shortcodes',
            'fields'   => array(
                'items'      => array( 'type' => 'textarea', 'label' => 'Items (one per line)', 'default' => '', 'tooltip' => 'One item per line. Prefix with icon name and pipe: check|Feature included' ),
                'icon'       => array( 'type' => 'select', 'label' => 'Default Icon', 'options' => array( 'check', 'x', 'arrow-right', 'star', 'heart', 'info', 'plus' ), 'default' => 'check' ),
                'icon_color' => array( 'type' => 'color', 'label' => 'Icon Color', 'default' => '#22c55e' ),
                'icon_size'  => array( 'type' => 'select', 'label' => 'Icon Size', 'options' => array( 'small', 'medium', 'large' ), 'default' => 'medium' ),
            ),
            'render' => array( $this, 'render_icon_list' ),
        ) );

        // Social Links
        $blocks->register( 'idsc_social_links', array(
            'label'    => 'Social Links',
            'icon'     => 'share',
            'category' => 'shortcodes',
            'fields'   => array(
                'links'     => array( 'type' => 'textarea', 'label' => 'Links (one per line)', 'default' => '', 'tooltip' => 'Format: platform|url (e.g. facebook|https://facebook.com/page)' ),
                'style'     => array( 'type' => 'select', 'label' => 'Style', 'options' => array( 'filled', 'outline', 'plain' ), 'default' => 'filled' ),
                'size'      => array( 'type' => 'select', 'label' => 'Size', 'options' => array( 'small', 'medium', 'large' ), 'default' => 'medium' ),
                'shape'     => array( 'type' => 'select', 'label' => 'Shape', 'options' => array( 'square', 'rounded', 'circle' ), 'default' => 'rounded' ),
                'color_mode' => array( 'type' => 'select', 'label' => 'Colors', 'options' => array( 'brand', 'custom' ), 'default' => 'brand' ),
                'custom_color' => array( 'type' => 'color', 'label' => 'Custom Color', 'default' => '#333333', 'tooltip' => 'Used when Colors is set to custom.' ),
                'alignment' => array( 'type' => 'select', 'label' => 'Alignment', 'options' => array( 'left', 'center', 'right' ), 'default' => 'center' ),
            ),
            'render' => array( $this, 'render_social_links' ),
        ) );

        // Accordion
        $blocks->register( 'idsc_accordion', array(
            'label'    => 'Accordion',
            'icon'     => 'list-view',
            'category' => 'shortcodes',
            'fields'   => array(
                'items'       => array( 'type' => 'textarea', 'label' => 'Items', 'default' => '', 'tooltip' => 'One item per line. Format: Title|Content' ),
                'open_first'  => array( 'type' => 'select', 'label' => 'Open First Item', 'options' => array( 'no', 'yes' ), 'default' => 'no' ),
                'icon_style'  => array( 'type' => 'select', 'label' => 'Icon Style', 'options' => array( 'chevron', 'plus-minus', 'none' ), 'default' => 'chevron' ),
                'border'      => array( 'type' => 'select', 'label' => 'Border Style', 'options' => array( 'bordered', 'separated', 'none' ), 'default' => 'bordered' ),
            ),
            'render' => array( $this, 'render_accordion' ),
        ) );

        // Gallery
        $blocks->register( 'idsc_gallery', array(
            'label'    => 'Gallery',
            'icon'     => 'format-gallery',
            'category' => 'shortcodes',
            'fields'   => array(
                'ids'           => array( 'type' => 'text', 'label' => 'Image IDs', 'default' => '', 'tooltip' => 'Comma-separated WordPress attachment IDs.' ),
                'columns'       => array( 'type' => 'select', 'label' => 'Columns', 'options' => array( '1', '2', '3', '4', '5', '6' ), 'default' => '3' ),
                'gap'           => array( 'type' => 'text', 'label' => 'Gap (px)', 'default' => '10' ),
                'aspect_ratio'  => array( 'type' => 'select', 'label' => 'Aspect Ratio', 'options' => array( 'original', 'square', '4:3', '16:9' ), 'default' => 'original' ),
                'border_radius' => array( 'type' => 'text', 'label' => 'Border Radius (px)', 'default' => '0' ),
                'link_to'       => array( 'type' => 'select', 'label' => 'Link To', 'options' => array( 'none', 'media', 'attachment' ), 'default' => 'none' ),
                'captions'      => array( 'type' => 'select', 'label' => 'Show Captions', 'options' => array( 'no', 'yes' ), 'default' => 'no' ),
            ),
            'render' => array( $this, 'render_gallery' ),
        ) );

        // Tabs
        $blocks->register( 'idsc_tabs', array(
            'label'    => 'Tabs',
            'icon'     => 'table-row-after',
            'category' => 'shortcodes',
            'fields'   => array(
                'items'       => array( 'type' => 'textarea', 'label' => 'Tabs', 'default' => '', 'tooltip' => 'One tab per line. Format: Title|Content' ),
                'layout'      => array( 'type' => 'select', 'label' => 'Layout', 'options' => array( 'horizontal', 'vertical' ), 'default' => 'horizontal' ),
                'alignment'   => array( 'type' => 'select', 'label' => 'Tab Alignment', 'options' => array( 'left', 'center', 'right' ), 'default' => 'left' ),
                'active_tab'  => array( 'type' => 'text', 'label' => 'Default Active Tab', 'default' => '1', 'tooltip' => 'Tab number (starting from 1).' ),
            ),
            'render' => array( $this, 'render_tabs' ),
        ) );

        // Counter
        $blocks->register( 'idsc_counter', array(
            'label'    => 'Counter',
            'icon'     => 'performance',
            'category' => 'shortcodes',
            'fields'   => array(
                'number'   => array( 'type' => 'text', 'label' => 'Target Number', 'default' => '100' ),
                'prefix'   => array( 'type' => 'text', 'label' => 'Prefix', 'default' => '', 'tooltip' => 'Text before the number, e.g. $' ),
                'suffix'   => array( 'type' => 'text', 'label' => 'Suffix', 'default' => '', 'tooltip' => 'Text after the number, e.g. + or %' ),
                'label'    => array( 'type' => 'text', 'label' => 'Label', 'default' => '' ),
                'duration' => array( 'type' => 'text', 'label' => 'Duration (ms)', 'default' => '2000' ),
            ),
            'render' => array( $this, 'render_counter' ),
        ) );

        // Table of Contents
        $blocks->register( 'idsc_toc', array(
            'label'    => 'Table of Contents',
            'icon'     => 'editor-ol',
            'category' => 'shortcodes',
            'fields'   => array(
                'levels'      => array( 'type' => 'text', 'label' => 'Heading Levels', 'default' => 'h2,h3', 'tooltip' => 'Comma-separated heading levels to include.' ),
                'title'       => array( 'type' => 'text', 'label' => 'Title', 'default' => 'On This Page' ),
                'list_style'  => array( 'type' => 'select', 'label' => 'Style', 'options' => array( 'numbered', 'bulleted' ), 'default' => 'numbered' ),
                'collapsible' => array( 'type' => 'select', 'label' => 'Collapsible', 'options' => array( 'no', 'yes' ), 'default' => 'no' ),
            ),
            'render' => array( $this, 'render_toc' ),
        ) );

        // Map Embed
        $blocks->register( 'idsc_map', array(
            'label'    => 'Map',
            'icon'     => 'location-alt',
            'category' => 'shortcodes',
            'fields'   => array(
                'address'  => array( 'type' => 'text', 'label' => 'Address', 'default' => '' ),
                'height'   => array( 'type' => 'text', 'label' => 'Height (px)', 'default' => '400' ),
                'zoom'     => array( 'type' => 'range', 'label' => 'Zoom', 'default' => 14, 'min' => 1, 'max' => 20, 'step' => 1 ),
                'provider' => array( 'type' => 'select', 'label' => 'Provider', 'options' => array( 'openstreetmap', 'google' ), 'default' => 'openstreetmap' ),
            ),
            'render' => array( $this, 'render_map' ),
        ) );
    }

    // ── Render functions output shortcode strings ──

    public function render_alert( $data, $settings ) {
        $atts  = ' type="' . esc_attr( $data['type'] ?? 'info' ) . '"';
        $atts .= ! empty( $data['title'] ) ? ' title="' . esc_attr( $data['title'] ) . '"' : '';
        $atts .= ( $data['dismissible'] ?? 'no' ) === 'yes' ? ' dismissible="yes"' : '';
        $atts .= ( $data['show_icon'] ?? 'yes' ) === 'no' ? ' icon="no"' : '';
        return '[idsc_alert' . $atts . ']' . esc_html( $data['message'] ?? '' ) . '[/idsc_alert]';
    }

    public function render_testimonial( $data, $settings ) {
        $atts  = ! empty( $data['author'] ) ? ' author="' . esc_attr( $data['author'] ) . '"' : '';
        $atts .= ! empty( $data['role'] ) ? ' role="' . esc_attr( $data['role'] ) . '"' : '';
        $atts .= ! empty( $data['photo'] ) ? ' photo="' . esc_attr( $data['photo'] ) . '"' : '';
        $atts .= ( $data['rating'] ?? '0' ) !== '0' ? ' rating="' . esc_attr( $data['rating'] ) . '"' : '';
        $atts .= ' layout="' . esc_attr( $data['layout'] ?? 'standard' ) . '"';
        return '[idsc_testimonial' . $atts . ']' . esc_html( $data['content'] ?? '' ) . '[/idsc_testimonial]';
    }

    public function render_card( $data, $settings ) {
        $atts  = ! empty( $data['image'] ) ? ' image="' . esc_attr( $data['image'] ) . '"' : '';
        $atts .= ! empty( $data['title'] ) ? ' title="' . esc_attr( $data['title'] ) . '"' : '';
        $atts .= ! empty( $data['button_text'] ) ? ' button_text="' . esc_attr( $data['button_text'] ) . '"' : '';
        $atts .= ! empty( $data['button_url'] ) ? ' button_url="' . esc_attr( $data['button_url'] ) . '"' : '';
        $atts .= ' image_pos="' . esc_attr( $data['image_pos'] ?? 'top' ) . '"';
        return '[idsc_card' . $atts . ']' . esc_html( $data['content'] ?? '' ) . '[/idsc_card]';
    }

    public function render_progress( $data, $settings ) {
        $atts  = ' value="' . esc_attr( $data['value'] ?? 75 ) . '"';
        $atts .= ! empty( $data['label'] ) ? ' label="' . esc_attr( $data['label'] ) . '"' : '';
        $atts .= ! empty( $data['color'] ) ? ' color="' . esc_attr( $data['color'] ) . '"' : '';
        $atts .= ! empty( $data['bg_color'] ) ? ' bg_color="' . esc_attr( $data['bg_color'] ) . '"' : '';
        $atts .= ! empty( $data['height'] ) ? ' height="' . esc_attr( $data['height'] ) . '"' : '';
        $atts .= ( $data['show_pct'] ?? 'yes' ) === 'no' ? ' show_pct="no"' : '';
        $atts .= ( $data['animated'] ?? 'no' ) === 'yes' ? ' animated="yes"' : '';
        return '[idsc_progress' . $atts . ']';
    }

    public function render_icon_list( $data, $settings ) {
        $items = $this->parse_lines( $data['items'] ?? '' );
        if ( empty( $items ) ) {
            return '';
        }
        $default_icon = esc_attr( $data['icon'] ?? 'check' );
        $icon_color   = ! empty( $data['icon_color'] ) ? ' icon_color="' . esc_attr( $data['icon_color'] ) . '"' : '';
        $icon_size    = ' icon_size="' . esc_attr( $data['icon_size'] ?? 'medium' ) . '"';

        $out = '[idsc_icon_list icon="' . $default_icon . '"' . $icon_color . $icon_size . ']' . "\n";
        foreach ( $items as $item ) {
            $parts = explode( '|', $item, 2 );
            if ( count( $parts ) === 2 ) {
                $out .= '[idsc_icon_list_item icon="' . esc_attr( trim( $parts[0] ) ) . '"]' . esc_html( trim( $parts[1] ) ) . '[/idsc_icon_list_item]' . "\n";
            } else {
                $out .= '[idsc_icon_list_item]' . esc_html( trim( $item ) ) . '[/idsc_icon_list_item]' . "\n";
            }
        }
        $out .= '[/idsc_icon_list]';
        return $out;
    }

    public function render_social_links( $data, $settings ) {
        $links = $this->parse_lines( $data['links'] ?? '' );
        if ( empty( $links ) ) {
            return '';
        }
        $atts  = ' style="' . esc_attr( $data['style'] ?? 'filled' ) . '"';
        $atts .= ' size="' . esc_attr( $data['size'] ?? 'medium' ) . '"';
        $atts .= ' shape="' . esc_attr( $data['shape'] ?? 'rounded' ) . '"';
        $atts .= ' color_mode="' . esc_attr( $data['color_mode'] ?? 'brand' ) . '"';
        if ( ( $data['color_mode'] ?? 'brand' ) === 'custom' && ! empty( $data['custom_color'] ) ) {
            $atts .= ' custom_color="' . esc_attr( $data['custom_color'] ) . '"';
        }
        $atts .= ' alignment="' . esc_attr( $data['alignment'] ?? 'center' ) . '"';

        $out = '[idsc_social_links' . $atts . ']' . "\n";
        foreach ( $links as $link ) {
            $parts = explode( '|', $link, 2 );
            if ( count( $parts ) === 2 ) {
                $out .= '[idsc_social_link platform="' . esc_attr( trim( $parts[0] ) ) . '" url="' . esc_attr( trim( $parts[1] ) ) . '"]' . "\n";
            }
        }
        $out .= '[/idsc_social_links]';
        return $out;
    }

    public function render_accordion( $data, $settings ) {
        $items = $this->parse_lines( $data['items'] ?? '' );
        if ( empty( $items ) ) {
            return '';
        }
        $atts  = ( $data['open_first'] ?? 'no' ) === 'yes' ? ' open_first="yes"' : '';
        $atts .= ' icon="' . esc_attr( $data['icon_style'] ?? 'chevron' ) . '"';
        $atts .= ' border="' . esc_attr( $data['border'] ?? 'bordered' ) . '"';

        $out = '[idsc_accordion' . $atts . ']' . "\n";
        foreach ( $items as $item ) {
            $parts = explode( '|', $item, 2 );
            if ( count( $parts ) === 2 ) {
                $out .= '[idsc_accordion_item title="' . esc_attr( trim( $parts[0] ) ) . '"]' . esc_html( trim( $parts[1] ) ) . '[/idsc_accordion_item]' . "\n";
            }
        }
        $out .= '[/idsc_accordion]';
        return $out;
    }

    public function render_gallery( $data, $settings ) {
        $atts  = ' ids="' . esc_attr( $data['ids'] ?? '' ) . '"';
        $atts .= ' columns="' . esc_attr( $data['columns'] ?? '3' ) . '"';
        $atts .= ! empty( $data['gap'] ) ? ' gap="' . esc_attr( $data['gap'] ) . '"' : '';
        $atts .= ' aspect_ratio="' . esc_attr( $data['aspect_ratio'] ?? 'original' ) . '"';
        $atts .= ! empty( $data['border_radius'] ) && $data['border_radius'] !== '0' ? ' border_radius="' . esc_attr( $data['border_radius'] ) . '"' : '';
        $atts .= ' link_to="' . esc_attr( $data['link_to'] ?? 'none' ) . '"';
        $atts .= ( $data['captions'] ?? 'no' ) === 'yes' ? ' captions="yes"' : '';
        return '[idsc_gallery' . $atts . ']';
    }

    public function render_tabs( $data, $settings ) {
        $items = $this->parse_lines( $data['items'] ?? '' );
        if ( empty( $items ) ) {
            return '';
        }
        $atts  = ' layout="' . esc_attr( $data['layout'] ?? 'horizontal' ) . '"';
        $atts .= ' alignment="' . esc_attr( $data['alignment'] ?? 'left' ) . '"';
        $atts .= ' active="' . esc_attr( $data['active_tab'] ?? '1' ) . '"';

        $out = '[idsc_tabs' . $atts . ']' . "\n";
        foreach ( $items as $item ) {
            $parts = explode( '|', $item, 2 );
            if ( count( $parts ) === 2 ) {
                $out .= '[idsc_tab title="' . esc_attr( trim( $parts[0] ) ) . '"]' . esc_html( trim( $parts[1] ) ) . '[/idsc_tab]' . "\n";
            }
        }
        $out .= '[/idsc_tabs]';
        return $out;
    }

    public function render_counter( $data, $settings ) {
        $atts  = ' number="' . esc_attr( $data['number'] ?? '100' ) . '"';
        $atts .= ! empty( $data['prefix'] ) ? ' prefix="' . esc_attr( $data['prefix'] ) . '"' : '';
        $atts .= ! empty( $data['suffix'] ) ? ' suffix="' . esc_attr( $data['suffix'] ) . '"' : '';
        $atts .= ! empty( $data['label'] ) ? ' label="' . esc_attr( $data['label'] ) . '"' : '';
        $atts .= ! empty( $data['duration'] ) ? ' duration="' . esc_attr( $data['duration'] ) . '"' : '';
        return '[idsc_counter' . $atts . ']';
    }

    public function render_toc( $data, $settings ) {
        $atts  = ' levels="' . esc_attr( $data['levels'] ?? 'h2,h3' ) . '"';
        $atts .= ! empty( $data['title'] ) ? ' title="' . esc_attr( $data['title'] ) . '"' : '';
        $atts .= ' style="' . esc_attr( $data['list_style'] ?? 'numbered' ) . '"';
        $atts .= ( $data['collapsible'] ?? 'no' ) === 'yes' ? ' collapsible="yes"' : '';
        return '[idsc_toc' . $atts . ']';
    }

    public function render_map( $data, $settings ) {
        $atts  = ' address="' . esc_attr( $data['address'] ?? '' ) . '"';
        $atts .= ! empty( $data['height'] ) ? ' height="' . esc_attr( $data['height'] ) . '"' : '';
        $atts .= ! empty( $data['zoom'] ) ? ' zoom="' . esc_attr( $data['zoom'] ) . '"' : '';
        $atts .= ' provider="' . esc_attr( $data['provider'] ?? 'openstreetmap' ) . '"';
        return '[idsc_map' . $atts . ']';
    }

    private function parse_lines( $text ) {
        if ( empty( $text ) ) {
            return array();
        }
        $lines = preg_split( '/\r\n|\r|\n/', $text );
        return array_filter( array_map( 'trim', $lines ), 'strlen' );
    }

    public function enqueue_editor_scripts() {
        wp_enqueue_script(
            'idsc-idve-previews',
            IDSC_PLUGIN_URL . 'idve-integration/idsc-idve-previews.js',
            array( 'idve-blocks-js' ),
            IDSC_VERSION,
            true
        );
    }
}
