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

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

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id       = sanitize_html_class( $node['id'] ?? '' );
        $content  = $node['content']  ?? [];
        $settings = $node['settings'] ?? [];
        $styles   = $node['styles']   ?? [];
        $url      = sanitize_text_field( $content['url'] ?? '' );
        $a        = $renderer->get_css_attrs( $node );
        $cls      = 'jalpi-el jalpi-video jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        $pfx      = '.jalpi-' . $id;

        if ( ! $url ) return '';

        // Dimension / color helpers
        $dim = static function( $v, $fb = '' ) {
            $v = trim( sanitize_text_field( (string) $v ) );
            if ( $v === '' ) return $fb;
            if ( preg_match( '/^-?[\d.]+(px|em|rem|%|vh|vw)$/', $v ) ) return $v;
            if ( preg_match( '/^-?[\d.]+$/', $v ) ) return $v . 'px';
            return $fb;
        };
        $col = static function( $v, $fb = '' ) {
            $v = sanitize_text_field( (string) $v );
            return preg_match( '/^#[0-9a-fA-F]{3,8}$|^rgba?\(/', $v ) ? $v : $fb;
        };

        // Aspect ratio → padding-bottom
        $aspect_map = [ '16:9' => '56.25%', '4:3' => '75%', '1:1' => '100%', '9:16' => '177.78%', '21:9' => '42.86%', '3:4' => '133.33%' ];
        $aspect      = sanitize_text_field( $settings['vid_aspect'] ?? '16:9' );
        $pad_pct     = $aspect_map[ $aspect ] ?? '56.25%';
        // Border / radius CSS; width comes from node styles (styles_to_css below)
        $wrapper_css = 'display:block;max-width:100%;';
        $bd_type     = sanitize_key( $settings['vid_bdType'] ?? '' );
        if ( $bd_type && $bd_type !== 'default' && $bd_type !== 'none' ) {
            $bd_w = $dim( $settings['vid_bdw_top'] ?? '', '1px' );
            $bd_c = $col( $settings['vid_bdColor'] ?? '', '#e5e7eb' );
            $wrapper_css .= 'border:' . $bd_w . ' ' . $bd_type . ' ' . $bd_c . ';';
        } elseif ( $bd_type === 'none' ) {
            $wrapper_css .= 'border:none;';
        }
        $br_tl = $dim( $settings['vid_br_top']    ?? '', '' );
        if ( $br_tl ) {
            $br_tr = $dim( $settings['vid_br_right']  ?? '', $br_tl );
            $br_br = $dim( $settings['vid_br_bottom'] ?? '', $br_tl );
            $br_bl = $dim( $settings['vid_br_left']   ?? '', $br_tl );
            $wrapper_css .= 'border-radius:' . "$br_tl $br_tr $br_br $br_bl" . ';overflow:hidden;';
        }

        $renderer->add_css( '.jalpi-el' . $pfx . '{' . $wrapper_css . $renderer->styles_to_css( $styles ) . '}' );

        $inner_style  = 'position:relative;padding-bottom:' . $pad_pct . ';height:0;overflow:hidden;';
        $iframe_style = 'position:absolute;top:0;left:0;width:100%;height:100%;border:0;';
        $lazy         = ( $content['lazyLoad'] ?? true ) ? ' loading="lazy"' : '';

        // Detect source
        $source = sanitize_key( $content['source'] ?? '' );
        if ( ! $source ) {
            $source = preg_match( '/youtube\.com|youtu\.be/', $url ) ? 'youtube'
                    : ( preg_match( '/vimeo\.com/', $url ) ? 'vimeo' : 'self' );
        }

        // YouTube
        if ( $source === 'youtube' && preg_match( '/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/', $url, $m ) ) {
            $params = [];
            if ( ! empty( $content['autoplay'] ) )              $params[] = 'autoplay=1';
            if ( ! empty( $content['muted'] ) )                 $params[] = 'mute=1';
            if ( ! empty( $content['loop'] ) )                  $params[] = 'loop=1&playlist=' . $m[1];
            if ( empty( $content['controls'] ) )                $params[] = 'controls=0';
            if ( ! empty( $content['captions'] ) )              $params[] = 'cc_load_policy=1';
            if ( ( $content['suggestedVideos'] ?? 'current' ) !== 'any' ) $params[] = 'rel=0';
            if ( ! empty( $content['startTime'] ) )             $params[] = 'start=' . absint( $content['startTime'] );
            if ( ! empty( $content['endTime'] ) )               $params[] = 'end='   . absint( $content['endTime'] );
            $domain = ! empty( $content['privacyMode'] ) ? 'www.youtube-nocookie.com' : 'www.youtube.com';
            $src    = 'https://' . $domain . '/embed/' . $m[1] . ( $params ? '?' . implode( '&', $params ) : '' );
            return '<div class="' . $cls . '"' . $a['id_attr'] . '>'
                 . '<div style="' . $inner_style . '">'
                 . '<iframe src="' . esc_url( $src ) . '" style="' . $iframe_style . '" allowfullscreen' . $lazy . ' title="Video"></iframe>'
                 . '</div></div>';
        }

        // Vimeo
        if ( $source === 'vimeo' && preg_match( '/vimeo\.com\/(\d+)/', $url, $m ) ) {
            $params = [];
            if ( ! empty( $content['autoplay'] ) )   $params[] = 'autoplay=1';
            if ( ! empty( $content['muted'] ) )      $params[] = 'muted=1';
            if ( ! empty( $content['loop'] ) )       $params[] = 'loop=1';
            if ( ! empty( $content['privacyMode'] )) $params[] = 'dnt=1';
            if ( ! empty( $content['startTime'] ) )  $params[] = '#t=' . absint( $content['startTime'] ) . 's';
            $src = 'https://player.vimeo.com/video/' . $m[1] . ( $params ? '?' . implode( '&', $params ) : '' );
            return '<div class="' . $cls . '"' . $a['id_attr'] . '>'
                 . '<div style="' . $inner_style . '">'
                 . '<iframe src="' . esc_url( $src ) . '" style="' . $iframe_style . '" allowfullscreen' . $lazy . ' title="Video"></iframe>'
                 . '</div></div>';
        }

        // Self-hosted
        $vattrs = $lazy;
        if ( $content['controls'] ?? true )          $vattrs .= ' controls';
        if ( ! empty( $content['autoplay'] ) )       $vattrs .= ' autoplay';
        if ( ! empty( $content['muted'] ) )          $vattrs .= ' muted';
        if ( ! empty( $content['loop'] ) )           $vattrs .= ' loop';
        return '<div class="' . $cls . '"' . $a['id_attr'] . '>'
             . '<video style="width:100%;height:auto;display:block;"' . $vattrs . '>'
             . '<source src="' . esc_url( $url ) . '">'
             . '</video></div>';
    }
}
