<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Element_Accordion extends Jalpi_Element {
    public static function type(): string { return 'accordion'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id       = sanitize_html_class( $node['id'] ?? '' );
        $content  = $node['content']  ?? [];
        $settings = $node['settings'] ?? [];
        $styles   = $node['styles']   ?? [];
        $items    = $content['items'] ?? [];
        $a        = $renderer->get_css_attrs( $node );
        $prefix   = '.jalpi-' . $id;

        // Content settings
        $item_pos      = sanitize_key( $content['itemPosition']  ?? 'left' );
        $icon_pos      = sanitize_key( $content['iconPosition']  ?? 'right' );
        $expand_icon   = sanitize_key( $content['expandIcon']    ?? 'default' );
        $collapse_icon = sanitize_key( $content['collapseIcon']  ?? 'default' );

        // Helper: sanitize and normalise a CSS dimension — appends px for unitless values
        $dim = static function( $v ) {
            $v = trim( sanitize_text_field( (string) $v ) );
            if ( $v === '' ) return '';
            if ( preg_match( '/^-?[\d.]+(px|em|rem|%|vh|vw|ch|ex)$/', $v ) ) return $v;
            if ( preg_match( '/^-?[\d.]+$/', $v ) ) return $v . 'px'; // unitless → px
            return '';
        };
        $color = static function( $v ) {
            $v = sanitize_text_field( (string) $v );
            return preg_match( '/^#[0-9a-fA-F]{3,8}$|^rgba?\(/', $v ) ? $v : '';
        };

        // Wrapper gap
        $item_gap = $dim( $settings['acc_item_gap'] ?? '' );
        $renderer->add_css( '.jalpi-el' . $prefix . '{display:flex;flex-direction:column;gap:' . ( $item_gap ?: '8px' ) . ';' . $renderer->styles_to_css( $styles ) . '}' );

        // Item border (global)
        $bd_type  = sanitize_key( $settings['acc_bdType'] ?? '' );
        $bd_color = $color( $settings['acc_bdColor'] ?? '' ) ?: '#e5e7eb';
        $bd_wt    = $dim( $settings['acc_bdw_top']    ?? '' ) ?: '1px';
        $bd_wr    = $dim( $settings['acc_bdw_right']  ?? '' ) ?: '1px';
        $bd_wb    = $dim( $settings['acc_bdw_bottom'] ?? '' ) ?: '1px';
        $bd_wl    = $dim( $settings['acc_bdw_left']   ?? '' ) ?: '1px';
        $br_tl    = $dim( $settings['acc_br_top']    ?? '' ) ?: '8px';
        $br_tr    = $dim( $settings['acc_br_right']  ?? '' ) ?: $br_tl;
        $br_br    = $dim( $settings['acc_br_bottom'] ?? '' ) ?: $br_tl;
        $br_bl    = $dim( $settings['acc_br_left']   ?? '' ) ?: $br_tl;
        $pad_t    = $dim( $settings['acc_pad_top']    ?? '' );
        $pad_r    = $dim( $settings['acc_pad_right']  ?? '' );
        $pad_b    = $dim( $settings['acc_pad_bottom'] ?? '' );
        $pad_l    = $dim( $settings['acc_pad_left']   ?? '' );

        // Build item CSS
        $item_css = '';
        if ( ! $bd_type || $bd_type === 'default' ) {
            $item_css .= 'border:1px solid ' . $bd_color . ';';
        } elseif ( $bd_type === 'none' ) {
            $item_css .= 'border:none;';
        } else {
            if ( $bd_wt === $bd_wr && $bd_wr === $bd_wb && $bd_wb === $bd_wl ) {
                $item_css .= 'border:' . $bd_wt . ' ' . $bd_type . ' ' . $bd_color . ';';
            } else {
                $item_css .= 'border-style:' . $bd_type . ';border-color:' . $bd_color . ';border-width:' . "$bd_wt $bd_wr $bd_wb $bd_wl" . ';';
            }
        }
        $item_css .= 'border-radius:' . "$br_tl $br_tr $br_br $br_bl" . ';overflow:hidden;';
        if ( $pad_t || $pad_r || $pad_b || $pad_l ) {
            $item_css .= 'padding:' . ( $pad_t ?: '0' ) . ' ' . ( $pad_r ?: '0' ) . ' ' . ( $pad_b ?: '0' ) . ' ' . ( $pad_l ?: '0' ) . ';';
        }
        $bg_normal = $color( $settings['acc_bg_normal'] ?? '' );
        if ( $bg_normal ) $item_css .= 'background:' . $bg_normal . ';';
        $renderer->add_css( $prefix . ' .jalpi-acc__item{' . $item_css . '}' );

        // Active (open) item background
        $bg_active = $color( $settings['acc_bg_active'] ?? '' );
        if ( $bg_active ) {
            $renderer->add_css( $prefix . ' .jalpi-acc__item[open]{background:' . $bg_active . ';}' );
        }

        // Header CSS
        $hdr_css = '';
        $justify = match ( $item_pos ) { 'center' => 'center', 'right' => 'flex-end', default => 'space-between' };
        $hdr_css .= 'justify-content:' . $justify . ';';
        if ( $icon_pos === 'left' ) $hdr_css .= 'flex-direction:row-reverse;';
        $hdr_bg    = $color( $settings['acc_hdr_bg']       ?? '' );
        $hdr_color = $color( $settings['acc_hdr_color']    ?? '' );
        $hdr_fs    = $dim(   $settings['acc_hdr_fontSize'] ?? '' );
        $hdr_pt    = $dim( $settings['acc_hdr_pad_top']    ?? '' );
        $hdr_pr    = $dim( $settings['acc_hdr_pad_right']  ?? '' );
        $hdr_pb    = $dim( $settings['acc_hdr_pad_bottom'] ?? '' );
        $hdr_pl    = $dim( $settings['acc_hdr_pad_left']   ?? '' );
        if ( $hdr_bg )    $hdr_css .= 'background:' . $hdr_bg . ';';
        if ( $hdr_color ) $hdr_css .= 'color:' . $hdr_color . ';';
        if ( $hdr_fs )    $hdr_css .= 'font-size:' . $hdr_fs . ';';
        if ( $hdr_pt || $hdr_pr || $hdr_pb || $hdr_pl ) {
            $hdr_css .= 'padding:' . ( $hdr_pt ?: '16px' ) . ' ' . ( $hdr_pr ?: '20px' ) . ' ' . ( $hdr_pb ?: '16px' ) . ' ' . ( $hdr_pl ?: '20px' ) . ';';
        }
        if ( $hdr_css ) $renderer->add_css( $prefix . ' .jalpi-acc__head{' . $hdr_css . '}' );

        // Body CSS
        $body_css   = '';
        $body_bg    = $color( $settings['acc_body_bg']       ?? '' );
        $body_color = $color( $settings['acc_body_color']    ?? '' );
        $body_fs    = $dim(   $settings['acc_body_fontSize'] ?? '' );
        $body_pt    = $dim( $settings['acc_body_pad_top']    ?? '' );
        $body_pr    = $dim( $settings['acc_body_pad_right']  ?? '' );
        $body_pb    = $dim( $settings['acc_body_pad_bottom'] ?? '' );
        $body_pl    = $dim( $settings['acc_body_pad_left']   ?? '' );
        if ( $body_bg )    $body_css .= 'background:' . $body_bg . ';';
        if ( $body_color ) $body_css .= 'color:' . $body_color . ';';
        if ( $body_fs )    $body_css .= 'font-size:' . $body_fs . ';';
        if ( $body_pt || $body_pr || $body_pb || $body_pl ) {
            $body_css .= 'padding:' . ( $body_pt ?: '0' ) . ' ' . ( $body_pr ?: '20px' ) . ' ' . ( $body_pb ?: '16px' ) . ' ' . ( $body_pl ?: '20px' ) . ';';
        }
        if ( $body_css ) $renderer->add_css( $prefix . ' .jalpi-acc__body{' . $body_css . '}' );

        // Build icon HTML
        $icon_html = '';
        if ( $expand_icon !== 'none' || $collapse_icon !== 'none' ) {
            if ( $expand_icon === 'plus' || $collapse_icon === 'minus' ) {
                $icon_html = '<span class="jalpi-acc__icon jalpi-acc__icon--pm" aria-hidden="true">'
                           . '<span class="jalpi-acc__icon-e">+</span>'
                           . '<span class="jalpi-acc__icon-c">&#8722;</span>'
                           . '</span>';
            } else {
                $icon_html = '<span class="jalpi-acc__icon" aria-hidden="true"></span>';
            }
        }

        // Render items
        $html  = '';
        $first = true;
        foreach ( (array) $items as $item ) {
            $title = esc_html( $item['title'] ?? '' );
            $body  = wp_kses_post( $item['body'] ?? '' );
            $open  = $first ? ' open' : '';
            $html .= '<details class="jalpi-acc__item"' . $open . '>'
                   . '<summary class="jalpi-acc__head">'
                   .   '<span class="jalpi-acc__title">' . $title . '</span>'
                   .   $icon_html
                   . '</summary>'
                   . '<div class="jalpi-acc__body">' . $body . '</div>'
                   . '</details>';
            $first = false;
        }

        return '<div class="jalpi-el jalpi-accordion jalpi-' . esc_attr( $id ) . $a['extra_cls'] . '"' . $a['id_attr'] . '>' . $html . '</div>';
    }
}
