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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;

class ProductW extends Widget_Base {

    public function get_name() { return 'productW'; }
    public function get_title() { return 'محصولات (منوی محصولات)'; }
    public function get_icon() { return 'eicon-products'; }
    public function get_categories() { return ['exclusive-widget']; }

    protected function register_controls() {
        $this->start_controls_section('help', [
            'label' => 'راهنما',
            'tab'   => Controls_Manager::TAB_CONTENT,
        ]);

        $url_general    = esc_url( admin_url('admin.php?page=caffito-general') );
        $url_categories = esc_url( admin_url('admin.php?page=caffito-categories') );
        $url_products   = esc_url( admin_url('admin.php?page=caffito-products') );

        $this->add_control('caffito_settings_note', [
            'type'  => Controls_Manager::RAW_HTML,
            'raw'   => '
            <div class="elementor-panel-alert elementor-panel-alert-info" dir="rtl" style="line-height:1.9">
                این ویجت فقط خروجی را نشان می‌دهد.برای تنظیم بخش‌های مختلف به موارد زیر مراجعه کنید:<br>
                • <a href="'.$url_general.'" target="_blank" rel="noopener">تنظیمات کلی کافیتو</a> (caffito-general.php)<br>
                • <a href="'.$url_categories.'" target="_blank" rel="noopener">مدیریت دسته‌بندی‌ها</a> (caffito-categories.php)<br>
                • <a href="'.$url_products.'" target="_blank" rel="noopener">ثبت و مدیریت محصولات</a> (caffito-products.php)
            </div>',
            'content_classes' => 'elementor-descriptor',
        ]);

        $this->end_controls_section();

        $this->start_controls_section('sort_section', [
            'label' => 'مرتب‌سازی',
            'tab'   => Controls_Manager::TAB_CONTENT,
        ]);

        $this->add_control('show_sort', [
            'label'        => 'نمایش دکمه مرتب‌سازی',
            'type'         => Controls_Manager::SWITCHER,
            'label_on'     => 'بله',
            'label_off'    => 'خیر',
            'return_value' => 'yes',
            'default'      => 'yes',
            'description'  => 'در صورت فعال بودن، دکمهٔ مرتب‌سازی در بالای محصولات نمایش داده می‌شود.',
        ]);

        $this->end_controls_section();
    }

    private function det(array $p): array {
        if (empty($p['details_accordion']) || !is_array($p['details_accordion'])) return [];
        $d = $p['details_accordion'];
        if (isset($d[0]) && is_array($d[0])) { $d = $d[0]; }
        if (isset($d['fields']) && is_array($d['fields'])) { $d = $d['fields']; }
        return is_array($d) ? $d : [];
    }

    private function build_blend_points(array $d): array {
        if (empty($d['blend_enable'])) return [];
        $labels = [0, 30, 50, 70, 100];
        $out = [];
        foreach ($labels as $lab) {
            $key  = 'blend_'.$lab;
            $item = isset($d[$key]) && is_array($d[$key]) ? $d[$key] : [];
            $mode = $item['mode'] ?? 'none';
            $price= isset($item['price']) && $item['price'] !== '' ? floatval($item['price']) : 0;
            $sign = ($mode==='plus' ? '+' : ($mode==='minus' ? '−' : ''));
            $out[] = [
                'label'  => $lab,
                'active' => ($mode!=='none'),
                'mode'   => $mode,
                'sign'   => $sign,
                'price'  => $price,
            ];
        }
        return $out;
    }

    private function svg_or_img( $media ) {
        if (empty($media['url'])) return '';
        $url = esc_url_raw($media['url']);
        return '<img src="'.esc_url($url).'" alt="" loading="lazy" decoding="async" />';
    }

    private function ensure_attachment_id_for_image( $media ) : int {
        $id  = 0;
        $url = '';

        if ( is_array($media) ) {
            $id  = !empty($media['id']) ? (int)$media['id'] : 0;
            $url = !empty($media['url']) ? $media['url'] : '';
        } elseif ( is_string($media) ) {
            $url = $media;
        }

        if ( $id && get_post($id) ) {
            return $id;
        }

        if ( ! $url ) {
            return 0;
        }

        $map = get_option('caffito_asset_map', []);
        if ( is_array($map) && isset($map[$url]) && get_post( (int)$map[$url] ) ) {
            return (int)$map[$url];
        }

        $maybe = attachment_url_to_postid( $url );
        if ( $maybe ) {
            $map[$url] = (int)$maybe;
            update_option('caffito_asset_map', $map);
            return (int)$maybe;
        }

        $theme_base = get_template_directory_uri();
        $ext = strtolower( pathinfo( parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION ) );
        if ( strpos($url, $theme_base) === 0 && in_array($ext, ['jpg','jpeg','png','webp','gif']) ) {
            if ( ! function_exists('media_sideload_image') ) {
                require_once ABSPATH . 'wp-admin/includes/media.php';
                require_once ABSPATH . 'wp-admin/includes/file.php';
                require_once ABSPATH . 'wp-admin/includes/image.php';
            }
            $sid = media_sideload_image( $url, 0, '', 'id' );
            if ( ! is_wp_error($sid) && $sid ) {
                $map[$url] = (int)$sid;
                update_option('caffito_asset_map', $map);
                return (int)$sid;
            }
        }

        return 0;
    }

    private function render_responsive_img( $media, string $alt = '', string $context = 'card' ) : string {
        $id = $this->ensure_attachment_id_for_image( $media );

        if ( $id ) {
            if ( $context === 'popup' ) {
                $size  = 'large';
                $sizes = '(max-width: 480px) 94vw, (max-width: 1024px) 70vw, 768px';
                $class = 'popup-img-el';
            } else {
                $size  = 'medium_large';
                $sizes = '(max-width: 480px) 92vw, (max-width: 768px) 44vw, (max-width: 1200px) 31vw, 360px';
                $class = 'product-card-img';
            }
            return wp_get_attachment_image(
                $id,
                $size,
                false,
                array(
                    'alt'      => $alt,
                    'class'    => $class,
                    'loading'  => 'lazy',
                    'decoding' => 'async',
                    'sizes'    => $sizes,
                )
            );
        }

        $url = is_array($media) ? ($media['url'] ?? '') : (is_string($media) ? $media : '');
        if ( ! $url ) return '';
        return '<img src="'.esc_url($url).'" alt="'.esc_attr($alt).'" loading="lazy" decoding="async" />';
    }

    private function o() {
        $gen = get_option('caffito_general', []);
        $gen = is_array($gen) ? $gen : [];

        $currency     = (isset($gen['currency_unit']) && $gen['currency_unit']==='rial') ? 'ریال' : 'تومان';
        $show_search  = ! empty($gen['show_search']);
        $show_filters = ! empty($gen['show_filters']);

        $btn_avail = isset($gen['btn_label_available'])  && $gen['btn_label_available']  !== '' ? sanitize_text_field($gen['btn_label_available'])  : 'مشاهده جزییات و افزودنی‌ها';
        $btn_unav  = isset($gen['btn_label_unavailable'])&& $gen['btn_label_unavailable']!== '' ? sanitize_text_field($gen['btn_label_unavailable']): 'ناموجود';

        $cats_opt = get_option('caffito_categories', []);
        $cats_opt = is_array($cats_opt) ? $cats_opt : [];
        $cats = isset($cats_opt['categories']) ? (array)$cats_opt['categories'] : [];
        if ( empty($cats) ) { $cats = [ ['label'=>'همه'] ]; }

        $prod_opt = get_option('caffito_products', []);
        $prod_opt = is_array($prod_opt) ? $prod_opt : [];
        $prods_raw = isset($prod_opt['products']) ? (array)$prod_opt['products'] : [];

        $ordered   = array_reverse($prods_raw, false);
        $available = []; $unavail = [];
        foreach ($ordered as $p) {
            if ( !is_array($p) ) { continue; }
            if (!empty($p['enabled'])) $available[] = $p; else $unavail[] = $p;
        }
        $prods = array_merge($available, $unavail);

        return compact('currency','show_search','show_filters','cats','prods','btn_avail','btn_unav');
    }

    protected function render() {
        $D = $this->o();
        $currency     = $D['currency'];
        $show_search  = $D['show_search'];
        $show_filters = $D['show_filters'];
        $cats         = $D['cats'];
        $prods        = $D['prods'];
        $btn_avail    = $D['btn_avail'];
        $btn_unav     = $D['btn_unav'];

        if ( empty($prods) ) {
            return;
        }

        $S             = $this->get_settings_for_display();
        $show_sort_btn = !empty($S['show_sort']);
        $wid           = $this->get_id();

        ?>
        <section class="products-section" id="products" data-pw-id="<?php echo esc_attr( $wid ); ?>">
            <div class="search-and-filter-section">
                <?php if ( $show_filters ) : ?>
                    <div class="filter-menu">
                        <button class="filter-btn active" data-filter="all">همه</button>
                        <?php
                        $seen = [];
                        foreach ( $cats as $c ) {
                            $label = isset($c['label']) ? trim( sanitize_text_field($c['label']) ) : '';
                            if ($label === '' || $label === 'همه') continue;
                            $slug = sanitize_title( $label );
                            if ( isset($seen[$slug]) ) continue;
                            $seen[$slug] = true;
                            echo '<button class="filter-btn" data-filter="'.esc_attr($slug).'">'.esc_html($label).'</button>';
                        }
                        ?>
                    </div>
                <?php endif; ?>

                <?php if ( $show_search ) : ?>
                    <div class="search-section">
                        <form action="/search" method="get">
                            <input type="search" name="q" placeholder="<?php echo esc_attr('جستجو...'); ?>">
                            <button type="submit" class="search-section-button" aria-label="<?php echo esc_attr('جستجو'); ?>">
                                <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 256 256"><path d="M229.66,218.34l-50.07-50.06a88.11,88.11,0,1,0-11.31,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z"></path></svg>
                            </button>
                        </form>
                    </div>
                <?php endif; ?>

                <?php if ( $show_sort_btn ) : ?>
                    <div class="sort-wrap" dir="rtl">
                        <button
                                type="button"
                                class="sort-btn"
                                aria-expanded="false"
                                aria-controls="sort-dd-<?php echo esc_attr($wid); ?>"
                                aria-haspopup="listbox"
                                aria-label="مرتب‌سازی محصولات"
                                title="مرتب‌سازی محصولات"
                        >
                            <i class="ph-bold ph-sort-ascending" aria-hidden="true"></i>
                            <span>مرتب‌سازی</span>
                        </button>
                        <div class="sort-dropdown" id="sort-dd-<?php echo esc_attr($wid); ?>" hidden>
                            <button type="button" class="sort-opt" data-sort="default">پیش‌فرض</button>
                            <button type="button" class="sort-opt" data-sort="newest">جدیدترین</button>
                            <button type="button" class="sort-opt" data-sort="cheap">ارزان‌ترین</button>
                            <button type="button" class="sort-opt" data-sort="expensive">گران‌ترین</button>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <div class="product-cards">
                <?php foreach ( $prods as $i => $p ) :
                    if ( !is_array($p) ) continue;
                    $enabled = ! empty($p['enabled']);
                    $title   = isset($p['title']) ? esc_html($p['title']) : '';
                    $img     = isset($p['image']) ? (array)$p['image'] : [];
                    $det     = $this->det($p);

                    $caption = isset($det['caption']) ? esc_html($det['caption']) : '';
                    $price_v = isset($det['price'])   ? floatval($det['price']) : 0;
                    $price   = number_format_i18n( $price_v );
                    $popup_id= 'popup-'.($i+1);

                    $pcats = [];
                    if ( isset($det['cats']) && is_array($det['cats']) ) {
                        if ( array_values($det['cats']) === $det['cats'] ) {
                            foreach ( $det['cats'] as $maybe_slug ) $pcats[] = sanitize_title( $maybe_slug );
                        } else {
                            foreach ( $det['cats'] as $slug => $on ) if ($on) $pcats[] = sanitize_title( $slug );
                        }
                    }
                    $pcats = array_slice( array_values( array_unique($pcats) ), 0, 5 );

                    $card_cls = 'product-card' . ( $enabled ? '' : ' outsell' );
                    $btn_attr = $enabled ? '' : ' disabled aria-disabled="true"';
                    $btn_text = $enabled ? $btn_avail : $btn_unav;

                    if ( empty($img['url']) ) {
                        $img = array(
                            'id'  => 0,
                            'url' => get_template_directory_uri() . '/assets/images/sizes/CoffeeSizeP.svg'
                        );
                    }

                    $price_k_card = number_format_i18n( $price_v );
                    $unit_k       = ($currency === 'ریال') ? 'هزار ریال' : 'هزار تومان';
                    ?>
                    <section class="<?php echo esc_attr($card_cls); ?>"
                             data-cats="<?php echo esc_attr(implode(' ', $pcats)); ?>"
                             data-price="<?php echo esc_attr( $price_v ); ?>"
                             data-index="<?php echo esc_attr( $i ); ?>">
                        <div class="product-card-upper">
                            <div class="product-image">
                                <?php
                                echo $this->render_responsive_img( $img, $title, 'card' );
                                ?>
                            </div>
                            <div class="price-caption-section">
                                <div class="name-caption-section">
                                    <span class="name-phrase"><?php echo $title; ?></span>
                                    <span class="caption-phrase"><?php echo $caption; ?></span>
                                </div>
                                <div class="price-section">
                                    <span class="price-phrase">قیمت:</span>
                                    <div class="number-toman-section">
                                        <span class="number-phrase"><?php echo esc_html($price_k_card); ?></span>
                                        <span class="toman-phrase"><?php echo esc_html($unit_k); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <button class="product-card-button" data-popup-id="<?php echo esc_attr($popup_id); ?>"<?php echo $btn_attr; ?>>
                            <?php echo esc_html($btn_text); ?>
                        </button>

                        <!-- پاپ‌آپ -->
                        <div class="popup" id="<?php echo esc_attr($popup_id); ?>" role="dialog" aria-modal="true" aria-labelledby="<?php echo esc_attr($popup_id); ?>-title">
                            <div class="popup-content container">
                                <div class="popup-container">
                                    <div class="popup-upper">
                                        <div class="popup-right">
                                            <div class="popup-img">
                                                <?php
                                                $popup_media = $img;
                                                if ( empty($popup_media['url']) || strpos($popup_media['url'], 'CoffeeSizeP') !== false ) {
                                                    $popup_media = array(
                                                        'id'  => 0,
                                                        'url' => get_template_directory_uri() . '/assets/images/sizes/CoffeeSizePG.svg'
                                                    );
                                                }
                                                echo $this->render_responsive_img( $popup_media, $title, 'popup' );
                                                ?>
                                            </div>
                                            <div class="popup-price-caption-section">
                                                <div class="popup-name-caption-section">
                                                    <span class="popup-name-phrase" id="<?php echo esc_attr($popup_id); ?>-title"><?php echo $title; ?></span>
                                                    <span class="popup-caption-phrase"><?php echo $caption; ?></span>
                                                </div>
                                                <div class="popup-price-section">
                                                    <span class="popup-price-phrase">قیمت:</span>
                                                    <div class="popup-number-toman-section">
                                                        <?php $price_k_popup = number_format_i18n( $price_v ); ?>
                                                        <span class="popup-number-phrase"><?php echo esc_html($price_k_popup); ?></span>
                                                        <span class="popup-toman-phrase"><?php echo esc_html($unit_k); ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="popup-left">
                                            <div class="close-btn" role="button" tabindex="0" aria-label="<?php echo esc_attr('بستن'); ?>"><i class="ph ph-x"></i></div>
                                        </div>
                                    </div>

                                    <div class="popup-mid">
                                        <?php
                                        if ( !empty($det['sizes_enable']) && !empty($det['sizes']) ) {
                                            echo '<div class="coffee-size"><span>سایز لیوان</span><div class="popup-mid-item">';
                                            foreach ( (array)$det['sizes'] as $sz ) {
                                                $name  = isset($sz['name']) ? esc_html($sz['name']) : '';
                                                $icon  = isset($sz['icon']) ? (array)$sz['icon'] : [];
                                                $mode  = isset($sz['price_mode']) ? $sz['price_mode'] : 'none';
                                                $delta = ($mode!=='none' && isset($sz['price_delta'])) ? floatval($sz['price_delta']) : 0;
                                                $sign  = ($mode==='plus' ? '+' : ($mode==='minus' ? '−' : ''));
                                                echo '<div class="popup-mid-container"
               data-name="'.esc_attr($name).'"
               data-price="'.esc_attr($delta).'"
               data-unit="'.esc_attr($currency).'"
               data-sign="'.esc_attr($mode==='none' ? '' : ($mode==='plus' ? '+' : '-')).'">';
                                                echo '<div class="icon">'.$this->svg_or_img($icon).'</div>';
                                                echo '<div class="hover-popup-mid-container">
                <span class="hover-popup-mid-container-toman">'.esc_html($currency).'</span>
                <div class="plus-price-name">
                  <div class="plus-price">
                    <span>'.esc_html($sign).'</span>
                    <span>'.($mode==='none' ? esc_html('رایگان') : esc_html($delta)).'</span>
                  </div>
                  <span>'.$name.'</span>
                </div>
              </div>';
                                                echo '</div>';
                                            }
                                            echo '</div></div>';
                                        }

                                        if ( !empty($det['companions_enable']) && !empty($det['companions']) ) {
                                            echo '<div class="coffee-ad"><span>آیتم‌های همراه</span><div class="popup-mid-item">';
                                            foreach ( (array)$det['companions'] as $cm ) {
                                                $name = isset($cm['name']) ? esc_html($cm['name']) : '';
                                                $icon = isset($cm['icon']) ? (array)$cm['icon'] : [];
                                                $pm   = isset($cm['price_mode']) ? $cm['price_mode'] : 'free';
                                                $val  = ($pm==='paid' && isset($cm['price'])) ? floatval($cm['price']) : 0;

                                                $icon_url = !empty($icon['url'])
                                                    ? esc_url($icon['url'])
                                                    : esc_url( get_template_directory_uri() . '/assets/images/coffeeAD/CoffeeAdP.svg' );

                                                echo '<div class="popup-mid-container"
               data-name="'.esc_attr($name).'"
               data-price="'.esc_attr($val).'"
               data-unit="'.esc_attr($currency).'"
               data-sign="'.esc_attr($pm==='paid' ? '+' : '').'">';
                                                echo '<div class="icon"><img src="'.$icon_url.'" alt="" loading="lazy" decoding="async" /></div>';
                                                echo '<div class="hover-popup-mid-container">
                <span class="hover-popup-mid-container-toman">'.esc_html($currency).'</span>
                <div class="plus-price-name">
                  <div class="plus-price">
                    <span>'.($pm==='paid' ? '+' : '').'</span>
                    <span>'.($pm==='paid' ? esc_html($val) : esc_html('رایگان')).'</span>
                  </div>
                  <span>'.$name.'</span>
                </div>
              </div>';
                                                echo '</div>';
                                            }
                                            echo '</div></div>';
                                        }

                                        if ( !empty($det['addons_enable']) && !empty($det['addons']) ) {
                                            echo '<div class="coffee-item"><span>افزودنی‌ها</span><div class="popup-mid-items">';
                                            foreach ( (array)$det['addons'] as $ad ) {
                                                $name = isset($ad['name']) ? esc_html($ad['name']) : '';
                                                $pm   = isset($ad['price_mode']) ? $ad['price_mode'] : 'paid';
                                                $val  = ($pm==='paid' && isset($ad['price'])) ? floatval($ad['price']) : 0;
                                                echo '<div class="popup-item-container"
               data-name="'.esc_attr($name).'"
               data-price="'.esc_attr($val).'"
               data-unit="'.esc_attr($currency).'"
               data-sign="'.esc_attr($pm==='paid' ? '+' : '').'">
                <div class="hover-popup-mid-container">
                  <span class="hover-popup-mid-container-toman">'.esc_html($currency).'</span>
                  <div class="plus-price-name">
                    <div class="plus-price">
                      <span>'.($pm==='paid' ? '+' : '').'</span>
                      <span>'.($pm==='paid' ? esc_html($val) : esc_html('رایگان')).'</span>
                    </div>
                    <span>'.$name.'</span>
                  </div>
                </div>
              </div>';
                                            }
                                            echo '</div></div>';
                                        }

                                        $blend_points = $this->build_blend_points($det);
                                        if ( !empty($det['blend_enable']) && !empty($blend_points) ) {
                                            echo '<div class="coffee-percent">
                                            <span>ترکیب قهوه</span>
                                            <div class="slider-container">
                                              <div class="slider-container-2">
                                                <div class="value-display" id="valueDisplay"></div>
                                                <div class="slider-track" id="sliderTrack">';
                                            foreach ($blend_points as $bp) {
                                                $cls = 'point point-'.$bp['label'].($bp['active'] ? '' : ' disabled');
                                                echo '<div class="'.$cls.'" data-name="'.esc_attr($bp['sign']).'" data-price="'.esc_attr($bp['price']).'"></div>';
                                            }
                                            echo '     <div class="slider-thumb" id="sliderThumb"></div>
                                                </div>
                                                <div class="labels"><span>عربیکا</span><span>روبوستا</span></div>
                                              </div>
                                              <div class="slider-container-price-toman">
                                                <div class="slider-container-price">
                                                  <span class="slider-container-price-price">۰</span>
                                                  <span class="slider-container-price-plus"></span>
                                                </div>
                                                <span class="slider-container-toman">'.esc_html($currency).'</span>
                                              </div>
                                            </div>
                                          </div>';
                                        }
                                        ?>
                                    </div>

                                    <div class="popup-lower"></div>
                                </div>
                            </div>
                        </div>
                    </section>
                <?php endforeach; ?>
            </div>
        </section>


        <script>
            /* === 1) سورت کارت‌ها (بدون تغییر منطقی) === */
            (function(){
                var root = document.querySelector('[data-pw-id="<?php echo esc_js($wid); ?>"]');
                if (!root) return;

                var cardsWrap = root.querySelector('.product-cards');
                var sortBtn   = root.querySelector('.sort-btn');
                var sortDD    = root.querySelector('#sort-dd-<?php echo esc_js($wid); ?>');

                function toNum(v){ v = parseFloat(v); return isNaN(v) ? 0 : v; }
                function toInt(v){ v = parseInt(v,10); return isNaN(v) ? 0 : v; }

                function getCards(){
                    if(!cardsWrap) return [];
                    var nodes = Array.prototype.slice.call(cardsWrap.children||[]);
                    return nodes.filter(function(el){ return el && el.classList && el.classList.contains('product-card'); });
                }

                function sortAndRender(mode){
                    var cards = getCards();
                    if(!cards.length) return;
                    var arr = cards.slice();

                    if(mode==='cheap'){
                        arr.sort(function(a,b){ return toNum(a.getAttribute('data-price')) - toNum(b.getAttribute('data-price')); });
                    }else if(mode==='expensive'){
                        arr.sort(function(a,b){ return toNum(b.getAttribute('data-price')) - toNum(a.getAttribute('data-price')); });
                    }else{
                        arr.sort(function(a,b){ return toInt(a.getAttribute('data-index')) - toInt(b.getAttribute('data-index')); });
                    }
                    arr.forEach(function(el){ cardsWrap.appendChild(el); });
                }

                if(sortBtn && sortDD){
                    var firstOpt = sortDD.querySelector('.sort-opt[data-sort="default"]');
                    if(firstOpt) firstOpt.classList.add('active');

                    sortBtn.addEventListener('click', function(){
                        var open = !sortDD.hasAttribute('hidden');
                        if(open){ sortDD.setAttribute('hidden',''); sortBtn.setAttribute('aria-expanded','false'); }
                        else    { sortDD.removeAttribute('hidden');  sortBtn.setAttribute('aria-expanded','true');  }
                    });

                    document.addEventListener('click', function(ev){
                        if(!root.contains(ev.target)){
                            if(!sortDD.hasAttribute('hidden')){
                                sortDD.setAttribute('hidden',''); sortBtn.setAttribute('aria-expanded','false');
                            }
                        }
                    });

                    sortDD.addEventListener('click', function(ev){
                        var opt  = ev.target.closest('.sort-opt'); if(!opt) return;
                        var mode = opt.getAttribute('data-sort') || 'default';
                        sortAndRender(mode);
                        sortDD.querySelectorAll('.sort-opt.active').forEach(function(el){ el.classList.remove('active'); });
                        opt.classList.add('active');
                        sortDD.setAttribute('hidden',''); sortBtn.setAttribute('aria-expanded','false');
                    });
                }
            })();
        </script>
        <script>
            /* === 2) پاپ‌آپ محصولات: انتخاب گزینه‌ها، جمع نهایی، افزودن به یادداشت (به‌همراه thumb) === */
            (function(){
                var root = document.querySelector('[data-pw-id="<?php echo esc_js($wid); ?>"]');
                if(!root) return;

                // Helpers
                function qsa(sel, ctx){ return Array.prototype.slice.call((ctx||document).querySelectorAll(sel)); }
                function qs(sel, ctx){ return (ctx||document).querySelector(sel); }
                function normSign(s){ if(!s) return ''; s=s.trim(); return (s==='−'||s==='–')?'-':(s==='+'?'+':(s==='-'?'-':'')); }
                function fmt(n){ try{ return Math.round(n).toLocaleString('fa-IR'); }catch(e){ return String(Math.round(n)); } }
                function toNum(v){ v = parseFloat(v); return isNaN(v) ? 0 : v; }
                // تبدیل اعداد فارسی/عربی برای parseFloat
                function toNumText(s){
                    if(s==null) return 0;
                    s = String(s);
                    var map = {'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9','٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9'};
                    s = s.replace(/[۰-۹٠-٩]/g, function(d){ return map[d] || d; }).replace(/[,٬\s]/g,'');
                    var n = parseFloat(s); return isNaN(n) ? 0 : n;
                }

                // --- فقط همین هِلپر اضافه شده: اولویت با window.CAFFITO.unitPhrase ---
                function getUnitPhrase(popup){
                    if (window.CAFFITO && window.CAFFITO.unitPhrase) return String(window.CAFFITO.unitPhrase);
                    var node = qs('.popup-toman-phrase', popup) || qs('.slider-container-toman', popup);
                    return node ? node.textContent.trim() : 'هزار تومان';
                }

                function initPopups(){
                    qsa('.product-card', root).forEach(function(card, idx){
                        var popup = card.querySelector('.popup'); if(!popup) return;

                        var lower = popup.querySelector('.popup-lower');
                        if(!lower || popup.__ctaInjected) return;

                        // واحد نمایش (داینامیک از CAFFITO یا DOM)
                        var unitText = getUnitPhrase(popup);

                        // CTA: قیمت نهایی + افزودن به یادداشت
                        var cta = document.createElement('div');
                        cta.className = 'wishlist-cta';
                        cta.setAttribute('dir','rtl');
                        cta.innerHTML =
                            '<button type="button" class="wishlist-add-btn" aria-label="افزودن به یادداشت">'
                            + '<span class="wishlist-cta-price-label">قیمت نهایی </span>'
                            + '<span class="wishlist-cta-price-number">0</span> '
                            + '<span class="wishlist-cta-price-unit">'+ unitText +'</span>'
                            + '<span class="wishlist-cta-sep"> - </span>'
                            + '<span class="wishlist-cta-add">افزودن به یادداشت</span>'
                            + '</button>';
                        lower.appendChild(cta);
                        popup.__ctaInjected = true;

                        // همگام‌سازی با نمایش کنار اسلایدر + بروزرسانی فوری جمع
                        (function setupBlendObservers(){
                            var dispNum  = qs('.slider-container-price-price', popup);
                            var dispSign = qs('.slider-container-price-plus',  popup);
                            if(!dispNum) return;
                            var mo = new MutationObserver(function(){
                                syncBlendActiveFromDisplay(popup);
                                updateTotal(card, popup);
                            });
                            mo.observe(dispNum,  {characterData:true, subtree:true, childList:true});
                            if(dispSign) mo.observe(dispSign, {characterData:true, subtree:true, childList:true});

                            var track = qs('.slider-track', popup);
                            if(track){
                                ['pointermove','mousemove','touchmove'].forEach(function(evName){
                                    track.addEventListener(evName, function(){ updateTotal(card, popup); }, {passive:true});
                                });
                            }
                        })();

                        // کلیک‌ها
                        popup.addEventListener('click', function(ev){
                            var t = ev.target;

                            // سایز (تکی)
                            var sizeItem = t.closest('.coffee-size .popup-mid-container');
                            if(sizeItem && popup.contains(sizeItem)){
                                qsa('.coffee-size .popup-mid-container.activeX', popup).forEach(function(el){
                                    el.classList.remove('activeX'); el.setAttribute('aria-checked','false');
                                });
                                sizeItem.classList.add('activeX'); sizeItem.setAttribute('aria-checked','true');
                                updateTotal(card, popup);
                                return;
                            }

                            // آیتم‌های همراه (چندتایی)
                            var compItem = t.closest('.coffee-ad .popup-mid-container');
                            if(compItem && popup.contains(compItem)){
                                compItem.classList.toggle('activeX');
                                compItem.setAttribute('aria-checked', compItem.classList.contains('activeX') ? 'true':'false');
                                updateTotal(card, popup);
                                return;
                            }

                            // افزودنی‌ها (چندتایی)
                            var addonItem = t.closest('.coffee-item .popup-item-container');
                            if(addonItem && popup.contains(addonItem)){
                                addonItem.classList.toggle('activeX');
                                addonItem.setAttribute('aria-checked', addonItem.classList.contains('activeX') ? 'true':'false');
                                updateTotal(card, popup);
                                return;
                            }

                            // ترکیب قهوه (نقطه فعال)
                            var point = t.closest('.coffee-percent .point');
                            if(point && popup.contains(point) && !point.classList.contains('disabled')){
                                qsa('.coffee-percent .point.activeX', popup).forEach(function(el){
                                    el.classList.remove('activeX'); el.removeAttribute('aria-checked');
                                });
                                point.classList.add('activeX'); point.setAttribute('aria-checked','true');

                                var pNum = qs('.slider-container-price-price', popup);
                                var pSign= qs('.slider-container-price-plus', popup);
                                if(pNum)  pNum.textContent  = fmt( toNum(point.getAttribute('data-price')) );
                                if(pSign) pSign.textContent = normSign(point.getAttribute('data-name'));
                                updateTotal(card, popup);
                                return;
                            }

                            // افزودن به یادداشت
                            if(t.closest('.wishlist-add-btn')){
                                addToWishlist(card, popup, idx);
                            }
                        });

                        // مقدار اولیه
                        updateTotal(card, popup);
                    });
                }

                // هم‌سویی activeX با نمایش کنار اسلایدر
                function syncBlendActiveFromDisplay(popup){
                    var pNumEl = qs('.slider-container-price-price', popup); if(!pNumEl) return;
                    var pSignEl= qs('.slider-container-price-plus',  popup);
                    var valD = toNumText(pNumEl.textContent);
                    var signD= normSign(pSignEl ? pSignEl.textContent : '');

                    var pts = qsa('.coffee-percent .point', popup).filter(function(el){ return !el.classList.contains('disabled'); });
                    var match = null;
                    for(var i=0;i<pts.length;i++){
                        var sgn = normSign(pts[i].getAttribute('data-name'));
                        var val = toNum(pts[i].getAttribute('data-price'));
                        if(sgn===signD && Math.abs(val-valD)<0.0001){ match = pts[i]; break; }
                    }
                    qsa('.coffee-percent .point.activeX', popup).forEach(function(el){
                        el.classList.remove('activeX'); el.removeAttribute('aria-checked');
                    });
                    if(match){ match.classList.add('activeX'); match.setAttribute('aria-checked','true'); }
                }

                function updateTotal(card, popup){
                    var base = toNum(card.getAttribute('data-price')); // واحد «هزار»
                    var total = base;

                    // سایز
                    var sizeSel = qs('.coffee-size .popup-mid-container.activeX', popup);
                    if(sizeSel){
                        var sgn = normSign(sizeSel.getAttribute('data-sign'));
                        var val = toNum(sizeSel.getAttribute('data-price'));
                        if(sgn === '+') total += val;
                        else if(sgn === '-') total -= val;
                    }

                    // همراه‌ها
                    qsa('.coffee-ad .popup-mid-container.activeX', popup).forEach(function(el){
                        var sgn = normSign(el.getAttribute('data-sign'));
                        var val = toNum(el.getAttribute('data-price'));
                        if(sgn === '+') total += val;
                    });

                    // افزودنی‌ها
                    qsa('.coffee-item .popup-item-container.activeX', popup).forEach(function(el){
                        var sgn = normSign(el.getAttribute('data-sign'));
                        var val = toNum(el.getAttribute('data-price'));
                        if(sgn === '+') total += val;
                    });

                    // ترکیب قهوه (اولویت با نمایش کنار اسلایدر)
                    var dispNum = qs('.slider-container-price-price', popup);
                    var dispSign= qs('.slider-container-price-plus',  popup);
                    var usedBlend = false;
                    if(dispNum){
                        var valD = toNumText(dispNum.textContent);
                        var sgnD = normSign(dispSign ? dispSign.textContent : '');
                        if(sgnD==='+' || sgnD==='-'){
                            total += (sgnD==='+') ? valD : -valD;
                            usedBlend = true;
                        }
                    }
                    if(!usedBlend){
                        var blendSel = qs('.coffee-percent .point.activeX', popup);
                        if(blendSel){
                            var s2 = normSign(blendSel.getAttribute('data-name'));
                            var v2 = toNum(blendSel.getAttribute('data-price'));
                            if(s2 === '+') total += v2;
                            else if(s2 === '-') total -= v2;
                        }
                    }

                    var numEl = qs('.wishlist-cta .wishlist-cta-price-number', popup);
                    if(numEl) numEl.textContent = fmt(total);
                }

                function resetSelections(card, popup){
                    qsa('.coffee-size .popup-mid-container.activeX, .coffee-ad .popup-mid-container.activeX, .coffee-item .popup-item-container.activeX, .coffee-percent .point.activeX', popup)
                        .forEach(function(el){ el.classList.remove('activeX'); el.removeAttribute('aria-checked'); });

                    var dispNum = qs('.slider-container-price-price', popup);
                    var dispSign= qs('.slider-container-price-plus', popup);
                    if(dispNum) dispNum.textContent = fmt(0);
                    if(dispSign) dispSign.textContent = '';

                    updateTotal(card, popup);
                }

                function addToWishlist(card, popup, idx){
                    var title = (qs('.popup-name-phrase', popup) || {}).textContent || '';
                    var base  = toNum(card.getAttribute('data-price'));

                    // واحد را همیشه از CAFFITO (یا در صورت نبود از DOM) بگیر
                    var unit  = getUnitPhrase(popup);

                    var wid   = root.getAttribute('data-pw-id') || '';
                    var pid   = card.getAttribute('data-index') || String(idx);

                    function pickName(el){ return el ? (el.getAttribute('data-name') || '').trim() : ''; }

                    var sizeSel = qs('.coffee-size .popup-mid-container.activeX', popup);
                    var size = sizeSel ? {
                        name: pickName(sizeSel),
                        sign: normSign(sizeSel.getAttribute('data-sign')),
                        delta: toNum(sizeSel.getAttribute('data-price'))
                    } : null;

                    var companions = qsa('.coffee-ad .popup-mid-container.activeX', popup).map(function(el){
                        return { name: pickName(el), sign: normSign(el.getAttribute('data-sign')), delta: toNum(el.getAttribute('data-price')) };
                    });

                    var addons = qsa('.coffee-item .popup-item-container.activeX', popup).map(function(el){
                        return { name: pickName(el), sign: normSign(el.getAttribute('data-sign')), delta: toNum(el.getAttribute('data-price')) };
                    });

                    // ترکیب قهوه از نمایش کنار اسلایدر
                    var dispNum  = qs('.slider-container-price-price', popup);
                    var dispSign = qs('.slider-container-price-plus',  popup);
                    var blend = null;
                    if(dispNum){
                        var valD = toNumText(dispNum.textContent);
                        var sgnD = normSign(dispSign ? dispSign.textContent : '');
                        var act  = qs('.coffee-percent .point.activeX', popup);
                        var lbl  = '';
                        if(act){ var m = (act.className||'').match(/point-(\d+)/); lbl = m ? m[1] : ''; }
                        blend = { point: lbl, sign: sgnD, delta: valD };
                    }

                    // تصویر
                    var thumbUrl = '';
                    var imgEl = popup.querySelector('.popup-img .popup-img-el, .popup-img img')
                        || card.querySelector('.product-image .product-card-img, .product-image img');
                    if(imgEl){ thumbUrl = imgEl.currentSrc || imgEl.src || ''; }

                    // جمع نهایی
                    var total = base;
                    if(size) total += (size.sign==='+'? size.delta : size.sign==='-'? -size.delta : 0);
                    companions.forEach(function(c){ if(c.sign==='+') total += c.delta; });
                    addons.forEach(function(a){ if(a.sign==='+') total += a.delta; });
                    if(blend){
                        if(blend.sign==='+') total += blend.delta;
                        else if(blend.sign==='-') total -= blend.delta;
                    }

                    try{
                        var key = 'caffito_wishlist';
                        var list = [];
                        try{ list = JSON.parse(localStorage.getItem(key) || '[]'); }catch(e){}
                        list.push({
                            id: 'productW:'+wid+':'+pid+':'+Date.now(),
                            widgetId: wid,
                            index: pid,
                            title: (title||'').trim(),
                            base: base,
                            currency: unit.trim(),  // ← اینجا با واحد داینامیک ذخیره میشه
                            size: size,
                            companions: companions,
                            addons: addons,
                            blend: blend,
                            total: total,
                            thumb: thumbUrl,
                            ts: Date.now()
                        });
                        localStorage.setItem(key, JSON.stringify(list));
                        try { window.dispatchEvent(new Event('caffito_wishlist_changed')); } catch(e){}

                        var btn = qs('.wishlist-add-btn', popup);
                        if(btn){
                            var old = btn.innerHTML;
                            btn.classList.add('activeX');
                            btn.innerHTML = '<span>به یادداشت اضافه شد</span>';
                            resetSelections(card, popup);
                            setTimeout(function(){ btn.classList.remove('activeX'); btn.innerHTML = old; }, 1200);
                        }else{
                            resetSelections(card, popup);
                        }
                    }catch(e){ console.warn('wishlist save failed', e); }
                }

                // اجرا
                initPopups();
            })();
        </script>
        <script>
            /* === 3) دراور «یادداشت‌ها» + قفل اسکرول + رندر هنگام بازشدن === */
            (function(){
                if(document.getElementById('caffito-notes-toggle')) return;

                // دکمه شناور
                var btn = document.createElement('button');
                btn.id = 'caffito-notes-toggle';
                btn.type = 'button';
                btn.className = 'notes-toggle-btn';
                btn.setAttribute('aria-expanded','false');
                btn.setAttribute('aria-controls','caffito-notes-drawer');
                btn.innerHTML = '<span class="notes-toggle-label">یادداشت‌ها</span>';
                document.body.appendChild(btn);

                // دراور و اوورلی
                var drawer = document.createElement('div');
                drawer.id = 'caffito-notes-drawer';
                drawer.className = 'notes-drawer';
                drawer.setAttribute('aria-hidden','true');

                var overlay = document.createElement('div');
                overlay.className = 'notes-overlay';
                drawer.appendChild(overlay);

                var panel = document.createElement('div');
                panel.className = 'notes-panel';
                panel.setAttribute('role','dialog');
                panel.setAttribute('aria-modal','true');
                panel.setAttribute('aria-label','یادداشت‌ها');
                panel.tabIndex = -1;

                var header = document.createElement('div');
                header.className = 'notes-header';
                header.innerHTML = '<span class="notes-title">یادداشت‌ها</span><button type="button" class="notes-close" aria-label="بستن">&times;</button>';

                var body  = document.createElement('div');
                body.className = 'notes-body';

                panel.appendChild(header);
                panel.appendChild(body);
                drawer.appendChild(panel);
                document.body.appendChild(drawer);

                // قفل/آزاد اسکرول
                var prev = { bodyOverflow:'', htmlOverflow:'', bodyTouch:'', htmlTouch:'' };
                function lockScroll(){
                    prev.bodyOverflow = document.body.style.overflow;
                    prev.htmlOverflow = document.documentElement.style.overflow;
                    prev.bodyTouch    = document.body.style.touchAction;
                    prev.htmlTouch    = document.documentElement.style.touchAction;
                    document.body.style.overflow = 'hidden';
                    document.documentElement.style.overflow = 'hidden';
                    document.body.style.touchAction = 'none';
                    document.documentElement.style.touchAction = 'none';
                }
                function unlockScroll(){
                    document.body.style.overflow = prev.bodyOverflow || '';
                    document.documentElement.style.overflow = prev.htmlOverflow || '';
                    document.body.style.touchAction = prev.bodyTouch || '';
                    document.documentElement.style.touchAction = prev.htmlTouch || '';
                }

                function openDrawer(){
                    document.body.appendChild(drawer); // همیشه آخر body
                    lockScroll();
                    drawer.classList.add('open','activeX');
                    btn.classList.add('activeX');
                    drawer.setAttribute('aria-hidden','false');
                    btn.setAttribute('aria-expanded','true');
                    // رندر زنده در زمان بازشدن
                    try { window.dispatchEvent(new Event('caffito_wishlist_changed')); } catch(e){}
                    panel.focus();
                }
                function closeDrawer(){
                    drawer.classList.remove('open','activeX');
                    btn.classList.remove('activeX');
                    drawer.setAttribute('aria-hidden','true');
                    btn.setAttribute('aria-expanded','false');
                    unlockScroll();
                }

                btn.addEventListener('click', function(){
                    if(drawer.classList.contains('open')) closeDrawer(); else openDrawer();
                });
                overlay.addEventListener('click', closeDrawer);
                drawer.addEventListener('click', function(e){
                    if(e.target.closest('.notes-close')) closeDrawer();
                });
                document.addEventListener('keydown', function(e){
                    if(e.key==='Escape') closeDrawer();
                });
            })();
        </script>
        <script>
            /* === 4) رندر محتوای «یادداشت‌ها» + جمع کل + حذف آیتم + شمارنده دکمه === */
            (function(){
                var key = 'caffito_wishlist';

                // Utils
                function readList(){ try{ return JSON.parse(localStorage.getItem(key)||'[]'); }catch(e){ return []; } }
                function writeList(list){ localStorage.setItem(key, JSON.stringify(list||[])); }
                function fmt(n){ try{ return Math.round(+n||0).toLocaleString('fa-IR'); }catch(e){ return String(Math.round(+n||0)); } }
                function byId(id){ return document.getElementById(id); }
                function esc(s){
                    return String(s||'')
                        .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
                        .replace(/"/g,'&quot;').replace(/'/g,'&#039;');
                }
                // اگر thumb نبود، از کارت صفحه حدس بزن
                function findThumbByTitle(title){
                    if(!title) return '';
                    var cards = document.querySelectorAll('.product-card');
                    for(var i=0;i<cards.length;i++){
                        var t = cards[i].querySelector('.name-phrase');
                        if(t && t.textContent.trim() === title.trim()){
                            var img = cards[i].querySelector('.product-image img, .product-card-img');
                            if(img) return img.currentSrc || img.src || '';
                        }
                    }
                    return '';
                }

                // --- helper: واحد را از تنظیم سایت بگیر؛ اگر نبود از آیتم/پیش‌فرض ---
                function getSiteUnitPhrase(items){
                    if (window.CAFFITO && window.CAFFITO.unitPhrase) return String(window.CAFFITO.unitPhrase);
                    if (items && items[0] && items[0].currency) return String(items[0].currency);
                    return 'هزار تومان';
                }

                function renderNotes(){
                    var drawer = byId('caffito-notes-drawer');
                    var btn    = byId('caffito-notes-toggle');
                    if(!drawer) return;
                    var bodyEl = drawer.querySelector('.notes-body');
                    if(!bodyEl) return;

                    // یک‌بار بایند رویدادهای دراور (حذف آیتم و ...)
                    if(!drawer.__notesBound){
                        drawer.addEventListener('click', onDrawerClick);
                        drawer.__notesBound = true;
                    }

                    var items = readList();

                    // شمارنده روی دکمه
                    if(btn){
                        if(!btn.querySelector('.notes-count')){
                            var span = document.createElement('span');
                            span.className = 'notes-count';
                            btn.appendChild(span);
                        }
                        btn.querySelector('.notes-count').textContent = items.length ? '('+items.length+')' : '';
                    }

                    // واحد: همیشه اولویت با تنظیم سایت
                    var unit = getSiteUnitPhrase(items);

                    var html = '';
                    if(!items.length){
                        html += '<div class="notes-scroll" dir="rtl"><div class="notes-empty">هنوز یادداشتی اضافه نشده است.</div></div>';
                    } else {
                        html += '<div class="notes-scroll" dir="rtl"><div class="notes-list">';
                        items.forEach(function(it){
                            var lines = [];

                            // سایز
                            if(it.size && it.size.name){
                                var sgn = it.size.sign==='-' ? '−' : (it.size.sign==='+' ? '+' : '');
                                var val = it.size.delta ? fmt(it.size.delta) : '۰';
                                lines.push(
                                    '<li class="note-line">' +
                                    '<span class="note-line-title">سایز لیوان '+ esc(it.size.name) +'</span>' +
                                    '<span class="note-dots"></span>' +
                                    '<span class="note-line-price">'+ sgn + val +'</span> <span class="note-unit">'+ unit +'</span>' +
                                    '</li>'
                                );
                            }
                            // آیتم‌های همراه
                            (it.companions||[]).forEach(function(c){
                                var sgn = c.sign==='-' ? '−' : (c.sign==='+' ? '+' : '');
                                var val = c.delta ? fmt(c.delta) : '۰';
                                lines.push(
                                    '<li class="note-line">' +
                                    '<span class="note-line-title">'+ esc(c.name) +'</span>' +
                                    '<span class="note-dots"></span>' +
                                    '<span class="note-line-price">'+ sgn + val +'</span> <span class="note-unit">'+ unit +'</span>' +
                                    '</li>'
                                );
                            });
                            // افزودنی‌ها
                            (it.addons||[]).forEach(function(a){
                                var sgn = a.sign==='-' ? '−' : (a.sign==='+' ? '+' : '');
                                var val = a.delta ? fmt(a.delta) : '۰';
                                lines.push(
                                    '<li class="note-line">' +
                                    '<span class="note-line-title">'+ esc(a.name) +'</span>' +
                                    '<span class="note-dots"></span>' +
                                    '<span class="note-line-price">'+ sgn + val +'</span> <span class="note-unit">'+ unit +'</span>' +
                                    '</li>'
                                );
                            });
                            // ترکیب قهوه
                            if(it.blend && (it.blend.sign==='+' || it.blend.sign==='-')){
                                var sgnB = it.blend.sign==='-' ? '−' : '+';
                                var valB = fmt(it.blend.delta||0);
                                var lbl  = it.blend.point ? ('ترکیب قهوه '+ it.blend.point +'%') : 'ترکیب قهوه';
                                lines.push(
                                    '<li class="note-line">' +
                                    '<span class="note-line-title">'+ lbl +'</span>' +
                                    '<span class="note-dots"></span>' +
                                    '<span class="note-line-price">'+ sgnB + valB +'</span> <span class="note-unit">'+ unit +'</span>' +
                                    '</li>'
                                );
                            }

                            var base  = fmt(it.base||0);
                            var tot   = fmt(it.total||0);
                            var thumb = it.thumb || findThumbByTitle(it.title);

                            // فقط وقتی لازم است «قیمت نهایی» را نشان بده
                            var showFinalRow = (lines.length > 0) || (+it.total !== +it.base);

                            html += ''
                                + '<div class="note-item" data-id="'+ (it.id||'') +'">'
                                +   '<div class="note-head">'
                                +     '<div class="note-title-wrap">'
                                +       '<strong class="note-title">'+ esc(it.title||'محصول') +'</strong>'
                                +       (thumb ? '<img class="note-thumb" src="'+ thumb +'" alt="" loading="lazy"/>' : '')
                                +     '</div>'
                                +     '<button class="note-remove" type="button" aria-label="حذف">×</button>'
                                +   '</div>'

                                // --- قیمت پایه با نقطه‌چین ---
                                +   '<div class="note-row note-base" dir="rtl">'
                                +     '<span class="note-row-title">قیمت پایه</span>'
                                +     '<span class="note-dots" aria-hidden="true"></span>'
                                +     '<span class="note-row-price"><b>'+ base +'</b> <span class="note-unit">'+ unit +'</span></span>'
                                +   '</div>'

                                +   '<ul class="note-lines">'+ lines.join('') +'</ul>'

                                // --- قیمت نهایی فقط اگر لازم بود ---
                                +   (showFinalRow
                                    ? ('<div class="note-row note-total" dir="rtl">'
                                        + '<span class="note-row-title">قیمت نهایی</span>'
                                        + '<span class="note-dots" aria-hidden="true"></span>'
                                        + '<span class="note-row-price"><b>'+ tot +'</b> <span class="note-unit">'+ unit +'</span></span>'
                                        + '</div>')
                                    : '')

                                +   '<hr class="note-sep"/>'
                                + '</div>';
                        });
                        html += '</div></div>'; // .notes-list + .notes-scroll
                    }

                    // فوتر چسبان
                    var totalAll = 0; items.forEach(function(it){ totalAll += +it.total||0; });
                    var totalAllTxt = fmt(totalAll);
                    html += ''
                        + '<div class="notes-footer" dir="rtl">'
                        +   '<div class="notes-grand">قیمت نهایی سفارش: <b>'+ totalAllTxt +'</b> <span class="note-unit">'+ unit +'</span></div>'
                        +   '<div class="notes-controls">'
                        +     '<label class="table-label" for="notes-table-input">شماره میز</label>'
                        +     '<input id="notes-table-input" class="notes-table-input" type="number" inputmode="numeric" pattern="[0-9]*" placeholder="شماره میز" min="1" />'
                        +     '<button type="button" class="notes-call" disabled>صدا کردن گارسون</button>'
                        +   '</div>'
                        +   '<div class="notes-status" aria-live="polite"></div>'
                        + '</div>';

                    bodyEl.innerHTML = html;
                    bindFooter();
                }
                function onDrawerClick(e){
                    var rm = e.target.closest('.note-remove');
                    if(rm){
                        var wrap = rm.closest('.note-item');
                        var id   = wrap ? wrap.getAttribute('data-id') : '';
                        if(!id) return;
                        var list = readList().filter(function(x){ return x.id !== id; });
                        writeList(list);
                        try { window.dispatchEvent(new Event('caffito_wishlist_changed')); } catch(err){}
                        renderNotes();
                    }
                }

                function bindFooter(){
                    var drawer  = byId('caffito-notes-drawer'); if(!drawer) return;
                    var tableIn = drawer.querySelector('#notes-table-input');
                    var callBtn = drawer.querySelector('.notes-call');
                    var status  = drawer.querySelector('.notes-status');

                    if(tableIn && callBtn){
                        tableIn.addEventListener('input', function(){
                            callBtn.disabled = !(parseInt(tableIn.value,10) > 0);
                        });
                        callBtn.addEventListener('click', function(){
                            var n = parseInt(tableIn.value,10); if(!(n>0)) return;
                            var code = 'T' + n + '-' + Date.now().toString(36).toUpperCase();
                            try { localStorage.setItem('caffito_waiter_last', JSON.stringify({table:n, code:code, ts:Date.now()})); } catch(e){}
                            if(status){
                                status.textContent = 'درخواست شما ثبت شد. کد: ' + code;
                                status.classList.add('activeX');
                                setTimeout(function(){ status.classList.remove('activeX'); }, 2500);
                            }
                        });
                    }
                }

                // رندر اولیه + آپدیت زنده
                renderNotes();
                window.addEventListener('storage', function(e){ if(e.key===key) renderNotes(); });
                window.addEventListener('caffito_wishlist_changed', renderNotes);
            })();
        </script>
        <?php
    }

    public function get_script_depends(){ return ['jquery']; }
    public function get_style_depends(){ return []; }
}

add_action('elementor/widgets/register', function($widgets_manager){
    $widgets_manager->register( new \ProductW() );
});