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

class Jalpi_Element_Image_Carousel extends Jalpi_Element {
    public static function type(): string { return 'image-carousel'; }

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

        // Helper closures
        $dim = static fn( $v, $d = '' ) => ( $v !== '' && $v !== null ) ? (string) $v : $d;
        $col = static fn( $v, $d = '' ) => ( $v !== '' && $v !== null ) ? (string) $v : $d;

        // ── Layout & Behaviour ─────────────────────────────────────────────
        $layout   = $settings['ic_layout'] ?? 'classic';
        $def_cols = ( $layout === 'card' ) ? 3 : 1;
        $cols     = max( 1, (int) ( $settings['ic_cols']        ?? $def_cols ) );
        $cols_t   = max( 1, (int) ( $settings['ic_cols_tablet'] ?? max( 1, $cols - 1 ) ) );
        $cols_m   = max( 1, (int) ( $settings['ic_cols_mobile'] ?? 1 ) );
        $gap      = max( 0, (int) ( $settings['ic_gap']         ?? 16 ) );
        $effect   = in_array( $settings['ic_effect'] ?? 'slide', [ 'slide', 'fade' ], true ) ? ( $settings['ic_effect'] ?? 'slide' ) : 'slide';
        $speed    = max( 100, (int) ( $settings['ic_speed']    ?? 400 ) );
        $autoplay = max( 0,   (int) ( $settings['ic_autoplay'] ?? 0 ) );
        $loop     = ( $settings['ic_loop']     ?? '1' ) !== '0';
        $arrows   = ( $settings['ic_arrows']   ?? '1' ) !== '0';
        $dots     = ( $settings['ic_dots']     ?? '1' ) !== '0';
        $lightbox = ( $settings['ic_lightbox'] ?? '0' ) === '1';
        $is_masonry = ( $layout === 'masonry' );

        // ── Image Appearance ───────────────────────────────────────────────
        $img_h   = $dim( $settings['ic_img_height'] ?? '', '260px' );
        $img_fit = in_array( $settings['ic_img_fit'] ?? '', [ 'cover', 'contain', 'fill' ], true ) ? $settings['ic_img_fit'] : 'cover';
        $img_br  = $dim( $settings['ic_img_br']     ?? '', '' );

        // ── Hover ──────────────────────────────────────────────────────────
        $hover   = $settings['ic_hover'] ?? 'none';
        $ov_col  = $col( $settings['ic_hover_overlay_color'] ?? '', 'rgba(0,0,0,.4)' );

        // ── Caption ────────────────────────────────────────────────────────
        $cap_pos    = $settings['ic_caption_pos']   ?? 'below';
        $cap_color  = $col( $settings['ic_caption_color'] ?? '', '' );
        $cap_size   = $dim( $settings['ic_caption_size']  ?? '', '' );
        $desc_color = $col( $settings['ic_desc_color']    ?? '', '' );
        $desc_size  = $dim( $settings['ic_desc_size']     ?? '', '' );
        $cap_bg     = $col( $settings['ic_caption_bg']    ?? '', '' );

        // ── Arrow Style ────────────────────────────────────────────────────
        $arr_color = $col( $settings['ic_arrow_color'] ?? '', '#fff' );
        $arr_bg    = $col( $settings['ic_arrow_bg']    ?? '', 'rgba(0,0,0,.45)' );
        $arr_size  = $dim( $settings['ic_arrow_size']  ?? '', '20px' );
        $arr_br    = $dim( $settings['ic_arrow_br']    ?? '', '50%' );

        // ── Dot Style ──────────────────────────────────────────────────────
        $dot_col  = $col( $settings['ic_dot_color']        ?? '', 'rgba(0,0,0,.22)' );
        $dot_act  = $col( $settings['ic_dot_active_color'] ?? '', '#6366f1' );
        $dot_size = $dim( $settings['ic_dot_size']         ?? '', '8px' );

        // ── Card Style ─────────────────────────────────────────────────────
        $card_bg  = $col( $settings['ic_card_bg']     ?? '', '#fff' );
        $card_shd = $settings['ic_card_shadow']        ?? '0 2px 14px rgba(0,0,0,.09)';
        $card_br  = $dim( $settings['ic_card_br']     ?? '', '12px' );
        $card_pad = $dim( $settings['ic_card_pad']    ?? '', '' );

        // ── CSS Generation ─────────────────────────────────────────────────
        $renderer->add_css( $prefix . '{' . $renderer->styles_to_css( $styles ) . '}' );
        $renderer->add_css( $prefix . ' .jalpi-ic__img{height:' . esc_attr( $img_h ) . ';object-fit:' . esc_attr( $img_fit ) . ';' . ( $img_br ? 'border-radius:' . esc_attr( $img_br ) . ';' : '' ) . '}' );

        if ( $is_masonry ) {
            $renderer->add_css( $prefix . ' .jalpi-ic__track{column-count:' . $cols   . ';column-gap:' . $gap . 'px;}' );
            $renderer->add_css( $prefix . ' .jalpi-ic__slide{margin-bottom:' . $gap   . 'px;}' );
            $renderer->add_tablet_css( $prefix . ' .jalpi-ic__track{column-count:' . $cols_t . ';}' );
            $renderer->add_mobile_css( $prefix . ' .jalpi-ic__track{column-count:' . $cols_m . ';}' );
        }

        if ( $hover === 'overlay' ) {
            $renderer->add_css( $prefix . ' .jalpi-ic__overlay{background:' . esc_attr( $ov_col ) . ';}' );
        }

        $cap_css = ( $cap_color ? 'color:' . esc_attr( $cap_color ) . ';' : '' ) . ( $cap_size ? 'font-size:' . esc_attr( $cap_size ) . ';' : '' );
        if ( $cap_css ) $renderer->add_css( $prefix . ' .jalpi-ic__caption{' . $cap_css . '}' );

        $desc_css = ( $desc_color ? 'color:' . esc_attr( $desc_color ) . ';' : '' ) . ( $desc_size ? 'font-size:' . esc_attr( $desc_size ) . ';' : '' );
        if ( $desc_css ) $renderer->add_css( $prefix . ' .jalpi-ic__desc{' . $desc_css . '}' );

        if ( $cap_pos === 'overlay' && $cap_bg ) {
            $renderer->add_css( $prefix . ' .jalpi-ic__caption-wrap--overlay{background:' . esc_attr( $cap_bg ) . ';}' );
        }

        $renderer->add_css( $prefix . ' .jalpi-ic__arrow{background:' . esc_attr( $arr_bg ) . ';color:' . esc_attr( $arr_color ) . ';border-radius:' . esc_attr( $arr_br ) . ';}' );
        $renderer->add_css( $prefix . ' .jalpi-ic__arrow svg{width:' . esc_attr( $arr_size ) . ';height:' . esc_attr( $arr_size ) . ';}' );
        $renderer->add_css( $prefix . ' .jalpi-ic__dot{background:' . esc_attr( $dot_col ) . ';width:' . esc_attr( $dot_size ) . ';height:' . esc_attr( $dot_size ) . ';}' );
        $renderer->add_css( $prefix . ' .jalpi-ic__dot.is-active{background:' . esc_attr( $dot_act ) . ';}' );

        if ( $layout === 'card' ) {
            $pad_rule = $card_pad ? 'padding:' . esc_attr( $card_pad ) . ';' : '';
            $renderer->add_css( $prefix . ' .jalpi-ic__slide-inner{background:' . esc_attr( $card_bg ) . ';border-radius:' . esc_attr( $card_br ) . ';box-shadow:' . esc_attr( $card_shd ) . ';' . $pad_rule . '}' );
        }

        // ── HTML Generation ────────────────────────────────────────────────
        $n = count( $items );
        $hover_cls  = $hover !== 'none' ? ' jalpi-ic--hover-' . esc_attr( $hover ) : '';
        $layout_cls = 'jalpi-ic--' . esc_attr( $layout );

        // Data attributes
        $data = ' data-ic-layout="'  . esc_attr( $layout ) . '"'
              . ' data-ic-cols="'    . $cols   . '"'
              . ' data-ic-cols-t="'  . $cols_t . '"'
              . ' data-ic-cols-m="'  . $cols_m . '"'
              . ' data-ic-gap="'     . $gap    . '"'
              . ' data-ic-effect="'  . esc_attr( $effect ) . '"'
              . ' data-ic-speed="'   . $speed  . '"'
              . ( $autoplay > 0 ? ' data-ic-autoplay="' . $autoplay . '"' : '' )
              . ( $loop       ? ' data-ic-loop="1"'     : '' )
              . ( $lightbox   ? ' data-ic-lightbox="1"' : '' );

        // SVG arrows
        $svg_prev = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';
        $svg_next = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';

        // Slides
        $slides_html = '';
        foreach ( $items as $item ) {
            $url      = esc_url(  $item['url']         ?? '' );
            $alt      = esc_attr( $item['alt']         ?? '' );
            $caption  = esc_html( $item['caption']     ?? '' );
            $desc     = esc_html( $item['description'] ?? '' );
            $lnk_url  = esc_url(  $item['linkUrl']     ?? '' );
            $new_tab  = ! empty( $item['linkNewTab'] ) ? ' target="_blank" rel="noopener"' : '';
            if ( ! $url ) continue;

            $img_tag  = '<img class="jalpi-ic__img" src="' . $url . '" alt="' . $alt . '" loading="lazy">';
            $overlay  = $hover === 'overlay' ? '<div class="jalpi-ic__overlay"></div>' : '';
            $img_wrap = '<div class="jalpi-ic__img-wrap">' . $img_tag . $overlay . '</div>';

            if ( $lightbox ) {
                $media = '<a class="jalpi-ic__link" href="' . $url . '" data-lb aria-label="' . $alt . '">' . $img_wrap . '</a>';
            } elseif ( $lnk_url ) {
                $media = '<a class="jalpi-ic__link" href="' . $lnk_url . '"' . $new_tab . '>' . $img_wrap . '</a>';
            } else {
                $media = $img_wrap;
            }

            $cap_html = '';
            if ( $cap_pos !== 'none' && ( $caption || $desc ) ) {
                $cap_class = 'jalpi-ic__caption-wrap jalpi-ic__caption-wrap--' . esc_attr( $cap_pos );
                $cap_html  = '<div class="' . $cap_class . '">'
                           . ( $caption ? '<div class="jalpi-ic__caption">' . $caption . '</div>' : '' )
                           . ( $desc    ? '<div class="jalpi-ic__desc">'    . $desc    . '</div>' : '' )
                           . '</div>';
            }

            $slides_html .= '<div class="jalpi-ic__slide"><div class="jalpi-ic__slide-inner">' . $media . $cap_html . '</div></div>';
        }

        // Arrows
        $arrows_html = '';
        if ( $arrows && ! $is_masonry ) {
            $arrows_html = '<button class="jalpi-ic__arrow jalpi-ic__arrow--prev" aria-label="' . esc_attr__( 'Previous', 'jalpi-page-builder' ) . '">' . $svg_prev . '</button>'
                         . '<button class="jalpi-ic__arrow jalpi-ic__arrow--next" aria-label="' . esc_attr__( 'Next', 'jalpi-page-builder' ) . '">' . $svg_next . '</button>';
        }

        // Dots
        $dots_html = '';
        if ( $dots && ! $is_masonry && $n > 0 ) {
            $d = '';
            for ( $i = 0; $i < $n; $i++ ) {
                /* translators: %d: slide number */
                $d .= '<button class="jalpi-ic__dot' . ( $i === 0 ? ' is-active' : '' ) . '" aria-label="' . esc_attr( sprintf( __( 'Slide %d', 'jalpi-page-builder' ), $i + 1 ) ) . '"></button>';
            }
            $dots_html = '<div class="jalpi-ic__dots" role="tablist">' . $d . '</div>';
        }

        if ( $is_masonry ) {
            $inner = '<div class="jalpi-ic__track">' . $slides_html . '</div>';
        } else {
            $inner = '<div class="jalpi-ic__viewport"><div class="jalpi-ic__track">' . $slides_html . '</div></div>'
                   . $arrows_html . $dots_html;
        }

        $cls = 'jalpi-el jalpi-ic ' . $layout_cls . $hover_cls . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        $renderer->set_needs_js( 'image_carousel' );
        return '<div class="' . $cls . '"' . $a['id_attr'] . $data . '>' . $inner . '</div>';
    }
}
