<?php

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

if ( ! class_exists( 'AIEO_Responsive_Controls', false ) ) {

class AIEO_Responsive_Controls {

    private static $n = 0;

    public static function register() {
        
        
        static $done = false;
        if ($done) { return; }
        $done = true;
        add_action('enqueue_block_editor_assets', array(__CLASS__, 'enqueue_editor'));
        add_filter('render_block', array(__CLASS__, 'filter_render'), 20, 2);
    }

    
    public static function block_attributes() {
        $a = array();
        foreach (array('aieoPadD', 'aieoPadM', 'aieoMarD', 'aieoMarM', 'aieoFsD', 'aieoFsM', 'aieoEdge', 'aieoSlider') as $k) {
            $a[$k] = array('type' => 'string', 'default' => '');
        }
        return $a;
    }

    public static function enqueue_editor() {
        $rel = 'assets/js/aieo-responsive-controls.js';
        $abs = AIEO_DIR . $rel;
        if (!file_exists($abs)) { return; }
        wp_enqueue_script(
            'aieo-responsive-controls',
            plugins_url($rel, AIEO_FILE),
            array('wp-hooks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-compose', 'wp-i18n'),
            (string) filemtime($abs),
            true
        );
    }

    
    private static function v($a, $k) {
        if (!isset($a[$k])) { return ''; }
        $val = trim((string) $a[$k]);
        if ($val === '') { return ''; }
        return preg_match('/^[0-9a-z%.\s\-,()]{1,60}$/i', $val) ? $val : '';
    }

    
    public static function filter_render($content, $block) {
        if (empty($block['blockName']) || strpos($block['blockName'], 'aieo/') !== 0) {
            return $content;
        }
        $a = (isset($block['attrs']) && is_array($block['attrs'])) ? $block['attrs'] : array();

        $padD = self::v($a, 'aieoPadD'); $padM = self::v($a, 'aieoPadM');
        $marD = self::v($a, 'aieoMarD'); $marM = self::v($a, 'aieoMarM');
        $fsD  = self::v($a, 'aieoFsD');  $fsM  = self::v($a, 'aieoFsM');

        
        
        
        $edge = isset($a['aieoEdge']) ? (string) $a['aieoEdge'] : '';
        $edge = in_array($edge, array('right', 'left', 'both'), true) ? $edge : '';

        $slider = isset($a['aieoSlider']) ? (string) $a['aieoSlider'] : '';

        $has_resp = ($padD !== '' || $padM !== '' || $marD !== '' || $marM !== '' || $fsD !== '' || $fsM !== '');
        if (!$has_resp && $edge === '' && $slider !== 'recos') {
            return $content;
        }

        $classes = array();
        $inline   = '';

        if ($has_resp) {
            self::$n++;
            $cls = 'aieo-rdev-' . self::$n;
            $classes[] = $cls;
            
            
            
            $d = '';
            if ($padD !== '') { $d .= 'padding:' . $padD . ' !important;'; }
            if ($marD !== '') { $d .= 'margin:' . $marD . ' !important;'; }
            if ($fsD  !== '') { $d .= 'font-size:' . $fsD . ' !important;'; }
            $m = '';
            if ($padM !== '') { $m .= 'padding:' . $padM . ' !important;'; }
            if ($marM !== '') { $m .= 'margin:' . $marM . ' !important;'; }
            if ($fsM  !== '') { $m .= 'font-size:' . $fsM . ' !important;'; }
            $css = '';
            if ($d !== '') { $css .= '.' . $cls . '{' . $d . '}'; }
            if ($m !== '') { $css .= '@media(max-width:767px){.' . $cls . '{' . $m . '}}'; }
            if ($css !== '') { $inline .= '<style>' . $css . '</style>'; }
        }

        if ($edge !== '') {
            $classes[] = 'aieo-edge-' . $edge;
            $inline   .= self::edge_css_once();
        }

        
        
        
        
        
        if ($slider === 'recos') {
            $classes[] = 'aieo-slider--recos';
            $inline   .= self::slider_css_once();
            $inline   .= self::slider_js_once();
        }

        if (empty($classes)) { return $content; }
        $cls_str = implode(' ', $classes);

        
        
        
        
        if (preg_match('/\bclass="/', $content)) {
            $content = preg_replace('/\bclass="/', 'class="' . $cls_str . ' ', $content, 1);
        } else {
            $content = '<div class="' . $cls_str . '">' . $content . '</div>';
        }
        return $inline . $content;
    }

    
    private static function edge_css_once() {
        static $done = false;
        if ($done) { return ''; }
        $done = true;
        return '<style id="aieo-edge-css">@media(max-width:767px){'
            . '.aieo-edge-right{margin-right:calc(50% - 50vw) !important;max-width:none !important}'
            . '.aieo-edge-left{margin-left:calc(50% - 50vw) !important;max-width:none !important}'
            . '.aieo-edge-both{margin-left:calc(50% - 50vw) !important;margin-right:calc(50% - 50vw) !important;max-width:100vw !important}'
            . '}</style>';
    }

    
    private static function slider_css_once() {
        static $done = false;
        if ($done) { return ''; }
        $done = true;
        $thumb = '#c82d52';
        $line  = '#1a1a1a';
        $s = get_option('aieo_dmm_product_card_settings', array());
        if (is_array($s)) {
            if (!empty($s['scroll_thumb_color'])) { $thumb = (string) $s['scroll_thumb_color']; }
            if (!empty($s['scroll_line_color']))  { $line  = (string) $s['scroll_line_color']; }
        }
        if (!preg_match('/^#[0-9a-f]{3,8}$/i', $thumb)) { $thumb = '#c82d52'; }
        if (!preg_match('/^#[0-9a-f]{3,8}$/i', $line))  { $line  = '#1a1a1a'; }
        
        
        
        return '<style id="aieo-slider-recos-css">'
            . '.aieo-slider--recos{position:relative}'
            . '.aieo-slider-progress{position:relative;height:9px;margin:12px 0 9px;background:transparent}'
            . '.aieo-slider-progress-thumb{position:absolute;top:0;bottom:0;left:0;width:25%;border-radius:99px;z-index:2;'
            .   'background:' . $thumb . ';transition:left .04s linear,width .04s linear}'
            . '.aieo-slider-progress::after{content:"";position:absolute;left:8px;right:0;bottom:0;height:1px;z-index:1;'
            .   'background:' . $line . '}'
            . '</style>';
    }

    
    private static function slider_js_once() {
        static $done = false;
        if ($done) { return ''; }
        $done = true;
        $js = "(function(){"
            . "function sc(r){var c=[r].concat([].slice.call(r.querySelectorAll('*')));"
            .   "for(var i=0;i<c.length;i++){var e=c[i];if(e.scrollWidth-e.clientWidth>4){var o=getComputedStyle(e).overflowX;if(o==='auto'||o==='scroll')return e;}}return null;}"
            . "function init(r){var s=sc(r);if(!s)return;"
            .   "var b=document.createElement('div');b.className='aieo-slider-progress';"
            .   "var t=document.createElement('span');t.className='aieo-slider-progress-thumb';b.appendChild(t);r.appendChild(b);"
            .   "function u(){var f=s.clientWidth/s.scrollWidth;if(!(f<1)){b.style.display='none';return;}b.style.display='';"
            .     "t.style.width=(f*100)+'%';var m=s.scrollWidth-s.clientWidth;var p=m>0?s.scrollLeft/m:0;"
            .     "t.style.left=(p*(1-f)*100)+'%';}"
            .   "u();setTimeout(u,400);s.addEventListener('scroll',u,{passive:true});window.addEventListener('resize',u);}"
            . "function run(){var r=document.querySelectorAll('.aieo-slider--recos');"
            .   "for(var i=0;i<r.length;i++){if(r[i].getAttribute('data-aieo-sl'))continue;r[i].setAttribute('data-aieo-sl','1');init(r[i]);}}"
            . "if(document.readyState!=='loading')run();else document.addEventListener('DOMContentLoaded',run);"
            . "})();";
        return '<script id="aieo-slider-recos-js">' . $js . '</script>';
    }
}
}
