<?php
/**
 * Products Grid Template
 * 
 * Available variables: $atts (shortcode attributes)
 */

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

global $wpdb;

// Load card design settings
$saved_design = get_option('instinctor_card_design', []);
if (!is_array($saved_design)) {
    $saved_design = [];
}

$defaults = [
    'preset' => 'modern',
    'elements' => ['image', 'title', 'price', 'add_to_cart'],
    'card' => ['background' => '#ffffff', 'border_color' => '#e0e0e0', 'border_width' => 1, 'border_radius' => 8, 'shadow' => 'small', 'hover_effect' => 'lift', 'padding' => 0, 'hover_shadow_size' => 15],
    'image' => ['aspect_ratio' => 'square', 'border_radius' => 8, 'hover_effect' => 'zoom'],
    'title' => ['font_size' => 16, 'font_weight' => '600', 'color' => '#1d2327', 'margin_top' => 12, 'lines' => 2],
    'price' => ['font_size' => 18, 'font_weight' => '700', 'color' => '#1d2327', 'sale_color' => '#dc2626', 'margin_top' => 8],
    'add_to_cart' => ['style' => 'button', 'bg_color' => '#1d2327', 'text_color' => '#ffffff', 'border_radius' => 6, 'full_width' => true, 'margin_top' => 12, 'button_text' => 'Add to Cart'],
    'sale_badge' => ['enabled' => true, 'bg_color' => '#dc2626', 'text_color' => '#ffffff', 'text' => 'Sale'],
    'quick_view' => ['enabled' => false, 'style' => 'icon', 'bg_color' => '#ffffff', 'icon_color' => '#1d2327'],

    'description' => ['font_size' => 13, 'color' => '#666666', 'lines' => 2, 'margin_top' => 8],
    'sku' => ['font_size' => 12, 'color' => '#999999', 'prefix' => 'SKU:', 'margin_top' => 8],
    'stock' => ['font_size' => 13, 'in_stock_color' => '#22863a', 'out_of_stock_color' => '#dc2626', 'margin_top' => 8],
    'grid' => ['columns' => 4, 'gap' => 24, 'columns_tablet' => 3, 'columns_mobile' => 2]
];

// Deep merge function
if (!function_exists('instinctor_deep_merge_design')) {
    function instinctor_deep_merge_design($defaults, $saved) {
        $result = $defaults;
        foreach ($saved as $key => $value) {
            if (is_array($value) && isset($defaults[$key]) && is_array($defaults[$key])) {
                // Recursively merge arrays (except 'elements' which should replace)
                if ($key === 'elements') {
                    $result[$key] = $value;
                } else {
                    $result[$key] = array_merge($defaults[$key], $value);
                }
            } else {
                $result[$key] = $value;
            }
        }
        return $result;
    }
}

$design = instinctor_deep_merge_design($defaults, $saved_design);

// Ensure elements array is not empty and dedupe it
if (empty($design['elements']) || !is_array($design['elements'])) {
    $design['elements'] = $defaults['elements'];
} else {
    $design['elements'] = array_values(array_unique($design['elements']));
}

$table = $wpdb->prefix . 'instinctor_products';
$limit = intval($atts['limit']);
$columns = !empty($atts['columns']) ? intval($atts['columns']) : $design['grid']['columns'];

// Get current category filter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only filter
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only category display filter (not a form submission/state change), so no nonce applies; the value is sanitize_text_field+wp_unslash'd inline.
$currentCategory = isset($_GET['category']) ? sanitize_text_field(wp_unslash($_GET['category'])) : '';

// Get all categories with product counts
// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
$categories = $wpdb->get_results(
    "SELECT c.*, COUNT(pc.product_id) as product_count 
     FROM {$wpdb->prefix}instinctor_categories c
     LEFT JOIN {$wpdb->prefix}instinctor_product_categories pc ON c.id = pc.category_id
     LEFT JOIN {$wpdb->prefix}instinctor_products p ON pc.product_id = p.id AND p.status = 'published'
     GROUP BY c.id
     HAVING product_count > 0
     ORDER BY c.name ASC"
);

// Build query based on category filter
if ($currentCategory) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
    $category = $wpdb->get_row($wpdb->prepare(
        "SELECT id FROM {$wpdb->prefix}instinctor_categories WHERE slug = %s",
        $currentCategory
    ));
    
    if ($category) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
        $products = $wpdb->get_results($wpdb->prepare(
            "SELECT p.* FROM {$wpdb->prefix}instinctor_products p
             JOIN {$wpdb->prefix}instinctor_product_categories pc ON p.id = pc.product_id
             WHERE p.status = 'published' AND pc.category_id = %d
             ORDER BY p.created_at DESC LIMIT %d",
            $category->id,
            $limit
        ));
    } else {
        $products = [];
    }
} else {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
    $products = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}instinctor_products WHERE status = 'published' ORDER BY created_at DESC LIMIT %d",
        $limit
    ));
}

$currency_symbol = '$';
$api_url = rest_url('instinctor/v1/');
$nonce = wp_create_nonce('wp_rest');

// Get current currency for price formatting
$currentCurrency = \Instinctor\Services\CurrencyService::getCurrentCurrency();
$shopUrl = \Instinctor\Services\PageService::resolveUrl('shop');

// Generate shadow CSS
$shadowMap = [
    'none' => 'none',
    'small' => '0 1px 3px rgba(0,0,0,0.1)',
    'medium' => '0 4px 6px rgba(0,0,0,0.1)',
    'large' => '0 10px 25px rgba(0,0,0,0.15)'
];
$cardShadow = $shadowMap[$design['card']['shadow']] ?? 'none';

// Image aspect ratio
$aspectMap = ['square' => '100%', 'portrait' => '133%', 'landscape' => '75%'];
$aspectRatio = $aspectMap[$design['image']['aspect_ratio']] ?? '100%';
?>

<?php if (!empty($categories)): ?>
<div class="instinctor-category-filter">
    <a href="<?php echo esc_url($shopUrl); ?>" class="instinctor-category-link <?php echo !$currentCategory ? 'active' : ''; ?>">
        <?php esc_html_e('All', 'instinctor'); ?>
    </a>
    <?php foreach ($categories as $prodCat): ?>
    <a href="<?php echo esc_url(add_query_arg('category', $prodCat->slug, $shopUrl)); ?>" 
       class="instinctor-category-link <?php echo $currentCategory === $prodCat->slug ? 'active' : ''; ?>">
        <?php echo esc_html($prodCat->name); ?>
        <span class="instinctor-category-count"><?php echo intval($prodCat->product_count); ?></span>
    </a>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php if (empty($products)): ?>
    <p class="instinctor-no-products"><?php esc_html_e('No products found.', 'instinctor'); ?></p>
<?php else: ?>
<div class="instinctor-products instinctor-products-designed">
    <?php foreach ($products as $product): 
        // Parse images from JSON field
        $all_images = [];
        if (!empty($product->images)) {
            $images_data = json_decode($product->images, true);
            if (is_array($images_data)) {
                foreach ($images_data as $img) {
                    if (!empty($img['url'])) {
                        $all_images[] = $img['url'];
                    }
                }
            }
        }
        // Fallback to featured_image if no images array
        if (empty($all_images) && $product->featured_image) {
            $all_images[] = wp_get_attachment_image_url($product->featured_image, 'medium');
        }
        $image_url = !empty($all_images[0]) ? $all_images[0] : '';
        $has_slideshow = count($all_images) > 1;
        
        $price = floatval($product->price);
        $sale_price = $product->sale_price ? floatval($product->sale_price) : null;
        // Only consider it a "sale" if BOTH prices exist and sale < regular
        $has_sale = $sale_price && $price > 0 && $sale_price < $price;
        // Effective price: regular if exists, otherwise sale_price
        $effective_price = $price > 0 ? $price : ($sale_price ?: 0);
        
    ?>
        <div class="instinctor-product-card instinctor-card-designed">
            <?php foreach ($design['elements'] as $element): ?>
                <?php if ($element === 'image'): ?>
                <div class="instinctor-product-image<?php echo $has_slideshow ? ' has-slideshow' : ''; ?>" data-slideshow-count="<?php echo count($all_images); ?>">
                    <?php 
                    // Product badges (includes sale, new, bestseller, low stock, custom)
                    include INSTINCTOR_PLUGIN_DIR . 'templates/partials/product-badges.php';
                    ?>
                    
                    <?php
                    // Quick View icon button - only if enabled in Designer and icon style
                    if (in_array('quick_view', $design['elements']) && ($design['quick_view']['style'] ?? 'icon') === 'icon'):
                    ?>
                    <button type="button" 
                            class="instinctor-quick-view-btn instinctor-quick-view-icon"
                            data-product-id="<?php echo esc_attr($product->id); ?>"
                            title="<?php esc_attr_e('Quick View', 'instinctor'); ?>">
                        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                    </button>
                    <?php endif; ?>
                    
                    <?php if ($has_slideshow): ?>
                        <a href="<?php echo esc_url(home_url('/product/' . $product->slug)); ?>" class="instinctor-product-slideshow">
                            <?php foreach ($all_images as $idx => $img_url): ?>
                                <img class="instinctor-slide-img<?php echo $idx === 0 ? ' active' : ''; ?>" 
                                     data-slide-index="<?php echo (int) $idx; ?>"
                                     src="<?php echo esc_url($img_url); ?>" 
                                     alt="<?php echo esc_attr($product->name); ?>">
                            <?php endforeach; ?>
                            <div class="instinctor-slide-dots">
                                <?php foreach ($all_images as $idx => $img_url): ?>
                                    <span class="instinctor-slide-dot<?php echo $idx === 0 ? ' active' : ''; ?>" data-slide-index="<?php echo (int) $idx; ?>"></span>
                                <?php endforeach; ?>
                            </div>
                        </a>
                    <?php elseif ($image_url): ?>
                        <a href="<?php echo esc_url(home_url('/product/' . $product->slug)); ?>">
                            <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($product->name); ?>">
                        </a>
                    <?php else: ?>
                        <a href="<?php echo esc_url(home_url('/product/' . $product->slug)); ?>" class="instinctor-no-image">
                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                        </a>
                    <?php endif; ?>
                </div>
                
                <?php elseif ($element === 'title'): ?>
                <h3 class="instinctor-product-title">
                    <a href="<?php echo esc_url(home_url('/product/' . $product->slug)); ?>">
                        <?php echo esc_html($product->name); ?>
                    </a>
                </h3>
                
                <?php elseif ($element === 'price'): ?>
                <div class="instinctor-product-price">
                    <?php 
                    // Use per-product pricing when available
                    $displayPrice = \Instinctor\Services\CurrencyService::convertProductPrice($product, 'price');
                    $displaySalePrice = $sale_price ? \Instinctor\Services\CurrencyService::convertProductPrice($product, 'sale_price') : 0;
                    // Effective display price: regular if exists, otherwise sale
                    $displayEffective = $displayPrice > 0 ? $displayPrice : $displaySalePrice;
                    
                    // Only show sale formatting if BOTH prices exist and sale < regular
                    if ($displaySalePrice && $displayPrice > 0 && $displaySalePrice < $displayPrice): ?>
                        <span class="instinctor-price-sale"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($displaySalePrice)); ?></span>
                        <span class="instinctor-price-original"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($displayPrice)); ?></span>
                    <?php else: ?>
                        <span class="instinctor-price-regular"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($displayEffective)); ?></span>
                    <?php endif; ?>
                </div>
                
                <?php elseif ($element === 'add_to_cart'): ?>
                <div class="instinctor-product-actions">
                    <button type="button" 
                            class="instinctor-add-to-cart-btn"
                            data-product-id="<?php echo esc_attr($product->id); ?>">
                        <?php echo esc_html($design['add_to_cart']['button_text'] ?? __('Add to Cart', 'instinctor')); ?>
                    </button>
                </div>
                
                <?php elseif ($element === 'quick_view' && ($design['quick_view']['style'] ?? 'icon') === 'button'): ?>
                <button type="button" 
                        class="instinctor-quick-view-btn instinctor-quick-view-button"
                        data-product-id="<?php echo esc_attr($product->id); ?>">
                    <?php esc_html_e('Quick View', 'instinctor'); ?>
                </button>
                
                <?php elseif ($element === 'description' && !empty($product->short_description)): ?>
                <p class="instinctor-product-desc"><?php echo esc_html(wp_trim_words($product->short_description, 15, "\xE2\x80\xA6")); ?></p>
                
                <?php elseif ($element === 'sku' && !empty($product->sku)): ?>
                <p class="instinctor-product-sku"><?php echo esc_html($design['sku']['prefix'] ?? 'SKU:'); ?> <?php echo esc_html($product->sku); ?></p>
                
                <?php elseif ($element === 'stock'): ?>
                <p class="instinctor-product-stock <?php echo $product->stock_quantity > 0 ? 'in-stock' : 'out-of-stock'; ?>">
                    <?php echo $product->stock_quantity > 0 ? esc_html__('In Stock', 'instinctor') : esc_html__('Out of Stock', 'instinctor'); ?>
                </p>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php ob_start(); ?>
/* Category Filter */
.instinctor-category-filter { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 24px; }
.instinctor-category-link { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; background: #f5f5f7; border-radius: 20px; text-decoration: none; color: #1d1d1f; font-size: 14px; transition: all 0.2s; }
.instinctor-category-link:hover { background: #e8e8ed; }
.instinctor-category-link.active { background: #1d1d1f; color: #fff; }
.instinctor-category-count { font-size: 12px; opacity: 0.7; }

/* Products Grid - Card Designer Styles */
.instinctor-products-designed {
    display: grid !important;
    grid-template-columns: repeat(<?php echo intval($design['grid']['columns']); ?>, 1fr) !important;
    gap: <?php echo intval($design['grid']['gap']); ?>px !important;
    grid-auto-rows: 1fr;
}

@media (max-width: 1024px) {
    .instinctor-products-designed {
        grid-template-columns: repeat(<?php echo intval($design['grid']['columns_tablet']); ?>, 1fr) !important;
    }
}

@media (max-width: 640px) {
    .instinctor-products-designed {
        grid-template-columns: repeat(<?php echo intval($design['grid']['columns_mobile']); ?>, 1fr) !important;
    }
}

.instinctor-card-designed {
    background: <?php echo esc_attr($design['card']['background']); ?> !important;
    border: <?php echo intval($design['card']['border_width']); ?>px solid <?php echo esc_attr($design['card']['border_color']); ?> !important;
    border-radius: <?php echo intval($design['card']['border_radius']); ?>px !important;
    box-shadow: <?php echo esc_attr($cardShadow); ?> !important;
    overflow: hidden !important;
    transition: all 0.3s ease-in-out !important;
    display: flex !important;
    flex-direction: column !important;
    height: 100% !important;
    padding: 0 !important;
    margin: 0 !important;
}

<?php 
$hoverShadow = $design['card']['hover_shadow_size'] ?? 15;
$hoverShadowY = round($hoverShadow * 0.5);
?>
<?php if ($design['card']['hover_effect'] === 'lift'): ?>
.instinctor-card-designed:hover { transform: translateY(-4px) !important; box-shadow: 0 <?php echo intval($hoverShadowY); ?>px <?php echo intval($hoverShadow); ?>px rgba(0,0,0,0.15) !important; }
<?php elseif ($design['card']['hover_effect'] === 'shadow'): ?>
.instinctor-card-designed:hover { box-shadow: 0 <?php echo intval($hoverShadowY); ?>px <?php echo intval($hoverShadow); ?>px rgba(0,0,0,0.15) !important; }
<?php elseif ($design['card']['hover_effect'] === 'border'): ?>
.instinctor-card-designed:hover { border-color: <?php echo esc_attr($design['add_to_cart']['bg_color']); ?> !important; }
<?php endif; ?>

.instinctor-card-designed .instinctor-product-image {
    position: relative;
    padding-bottom: <?php echo esc_attr($aspectRatio); ?> !important;
    overflow: hidden !important;
    border-radius: <?php echo intval($design['image']['border_radius']); ?>px <?php echo intval($design['image']['border_radius']); ?>px 0 0 !important;
    flex-shrink: 0 !important;
    background: #f8f8f8 !important;
}

.instinctor-card-designed .instinctor-product-image img {
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100% !important;
    object-fit: contain !important;
    transition: transform 0.3s ease-in-out !important;
}

<?php if ($design['image']['hover_effect'] === 'zoom'): ?>
.instinctor-card-designed:hover .instinctor-product-image img { transform: scale(1.05) !important; }
<?php endif; ?>

.instinctor-card-designed .instinctor-no-image {
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100% !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    background: #f5f5f5 !important;
}

/* Badges container and styling from product-badges.php */
.instinctor-card-designed .instinctor-product-badges {
    position: absolute !important;
    top: 12px !important;
    left: 12px !important;
    display: flex !important;
    flex-direction: column !important;
    gap: 6px !important;
    z-index: 2 !important;
}

.instinctor-card-designed .instinctor-product-badge {
    display: inline-block !important;
    padding: 4px 10px !important;
    font-size: 11px !important;
    font-weight: 600 !important;
    text-transform: uppercase !important;
    letter-spacing: 0.3px !important;
    border-radius: 4px !important;
    line-height: 1.3 !important;
}

.instinctor-card-designed .instinctor-badge-new {
    background: #22863a !important;
    color: #fff !important;
}

.instinctor-card-designed .instinctor-badge-sale {
    background: <?php echo esc_attr($design['sale_badge']['bg_color']); ?> !important;
    color: <?php echo esc_attr($design['sale_badge']['text_color']); ?> !important;
}

.instinctor-card-designed .instinctor-badge-bestseller {
    background: #f59e0b !important;
    color: #fff !important;
}

.instinctor-card-designed .instinctor-badge-featured {
    background: #1d2327 !important;
    color: #fff !important;
}

.instinctor-card-designed .instinctor-badge-low-stock {
    background: #ef4444 !important;
    color: #fff !important;
}

.instinctor-card-designed .instinctor-badge-preorder {
    background: #6366f1 !important;
    color: #fff !important;
}

.instinctor-card-designed .instinctor-product-title {
    padding: 0 16px !important;
    margin: <?php echo intval($design['title']['margin_top']); ?>px 0 0 !important;
    font-size: <?php echo intval($design['title']['font_size']); ?>px !important;
    font-weight: <?php echo esc_attr($design['title']['font_weight']); ?> !important;
    line-height: 1.4 !important;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: <?php echo intval($design['title']['lines']); ?>;
    -webkit-box-orient: vertical;
}

.instinctor-card-designed .instinctor-product-title a {
    color: <?php echo esc_attr($design['title']['color']); ?> !important;
    text-decoration: none !important;
}

.instinctor-card-designed .instinctor-product-title a:hover { text-decoration: underline !important; }

.instinctor-card-designed .instinctor-product-price {
    padding: 0 16px !important;
    margin-top: <?php echo intval($design['price']['margin_top']); ?>px !important;
    font-size: <?php echo intval($design['price']['font_size']); ?>px !important;
    font-weight: <?php echo esc_attr($design['price']['font_weight']); ?> !important;
    color: <?php echo esc_attr($design['price']['color']); ?> !important;
}

.instinctor-card-designed .instinctor-price-sale {
    color: <?php echo esc_attr($design['price']['sale_color']); ?> !important;
}

.instinctor-card-designed .instinctor-price-original {
    text-decoration: line-through !important;
    color: #999 !important;
    font-size: 0.8em !important;
    font-weight: 400 !important;
    margin-left: 8px !important;
}




.instinctor-card-designed .instinctor-product-actions {
    padding: 0 16px 16px !important;
    margin-top: auto !important;
    padding-top: <?php echo intval($design['add_to_cart']['margin_top'] ?? 12); ?>px !important;
}

.instinctor-card-designed .instinctor-add-to-cart-btn {
    <?php if ($design['add_to_cart']['full_width']): ?>width: 100% !important;<?php endif; ?>
    padding: 10px 20px !important;
    background: <?php echo esc_attr($design['add_to_cart']['bg_color']); ?> !important;
    color: <?php echo esc_attr($design['add_to_cart']['text_color']); ?> !important;
    border: none !important;
    border-radius: <?php echo intval($design['add_to_cart']['border_radius']); ?>px !important;
    font-size: 14px !important;
    font-weight: 500 !important;
    cursor: pointer;
    transition: all 0.2s;
}

.instinctor-card-designed .instinctor-add-to-cart-btn:hover {
    opacity: 0.9 !important;
}

.instinctor-card-designed .instinctor-product-desc {
    padding: 0 16px !important;
    margin-top: <?php echo intval($design['description']['margin_top'] ?? 8); ?>px !important;
    font-size: <?php echo intval($design['description']['font_size'] ?? 13); ?>px !important;
    color: <?php echo esc_attr($design['description']['color'] ?? '#666666'); ?> !important;
    line-height: 1.5 !important;
    display: -webkit-box !important;
    -webkit-line-clamp: <?php echo intval($design['description']['lines'] ?? 2); ?> !important;
    -webkit-box-orient: vertical !important;
    overflow: hidden !important;
}

.instinctor-card-designed .instinctor-product-sku {
    padding: 0 16px !important;
    margin-top: <?php echo intval($design['sku']['margin_top'] ?? 8); ?>px !important;
    font-size: <?php echo intval($design['sku']['font_size'] ?? 12); ?>px !important;
    color: <?php echo esc_attr($design['sku']['color'] ?? '#999999'); ?> !important;
}

.instinctor-card-designed .instinctor-product-stock {
    padding: 0 16px !important;
    margin-top: <?php echo intval($design['stock']['margin_top'] ?? 8); ?>px !important;
    font-size: <?php echo intval($design['stock']['font_size'] ?? 13); ?>px !important;
    font-weight: 500 !important;
}

.instinctor-card-designed .instinctor-product-stock.in-stock { color: <?php echo esc_attr($design['stock']['in_stock_color'] ?? '#22863a'); ?> !important; }
.instinctor-card-designed .instinctor-product-stock.out-of-stock { color: <?php echo esc_attr($design['stock']['out_of_stock_color'] ?? '#dc2626'); ?> !important; }

/* Mobile padding adjustments */
@media (max-width: 640px) {
    .instinctor-card-designed .instinctor-product-title,
    .instinctor-card-designed .instinctor-product-price,
    .instinctor-card-designed .instinctor-product-actions {
        padding-left: 12px !important;
        padding-right: 12px !important;
    }
}

/* Quick View Button - Icon Style (in image container) */
.instinctor-card-designed .instinctor-quick-view-icon {
    position: absolute !important;
    bottom: 12px !important;
    right: 12px !important;
    width: 36px !important;
    height: 36px !important;
    padding: 0 !important;
    border-radius: 50% !important;
    background: <?php echo esc_attr($design['quick_view']['bg_color'] ?? '#ffffff'); ?> !important;
    color: <?php echo esc_attr($design['quick_view']['icon_color'] ?? '#1d2327'); ?> !important;
    border: 1px solid #e0e0e0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    cursor: pointer !important;
    transition: all 0.2s !important;
    z-index: 3 !important;
    opacity: 0 !important;
}
.instinctor-card-designed:hover .instinctor-quick-view-icon {
    opacity: 1 !important;
}
.instinctor-card-designed .instinctor-quick-view-icon:hover {
    background: #f5f5f5 !important;
    transform: scale(1.1) !important;
}
.instinctor-card-designed .instinctor-quick-view-icon svg {
    stroke: <?php echo esc_attr($design['quick_view']['icon_color'] ?? '#1d2327'); ?> !important;
}

/* Quick View Button - Button Style (below card content) */
.instinctor-card-designed .instinctor-quick-view-button {
    width: calc(100% - 32px) !important;
    margin: 8px 16px 16px !important;
    padding: 10px 16px !important;
    border-radius: 6px !important;
    background: <?php echo esc_attr($design['quick_view']['bg_color'] ?? '#ffffff'); ?> !important;
    color: <?php echo esc_attr($design['quick_view']['icon_color'] ?? '#1d2327'); ?> !important;
    border: 1px solid #e0e0e0 !important;
    cursor: pointer !important;
    transition: all 0.2s !important;
    font-size: 13px !important;
    font-weight: 500 !important;
}
.instinctor-card-designed .instinctor-quick-view-button:hover {
    background: #f5f5f5 !important;
}

/* Quick View Modal */
.instinctor-quick-view-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 99999;
    align-items: center;
    justify-content: center;
    padding: 20px;
    box-sizing: border-box;
}
.instinctor-quick-view-modal.active { display: flex; }
.instinctor-quick-view-content {
    background: #fff;
    border-radius: 12px;
    max-width: 900px;
    width: 100%;
    max-height: 90vh;
    overflow: auto;
    position: relative;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0;
}
@media (max-width: 768px) {
    .instinctor-quick-view-content { grid-template-columns: 1fr; }
}
.instinctor-quick-view-close {
    position: absolute;
    top: 12px;
    right: 12px;
    width: 36px;
    height: 36px;
    background: #fff;
    border: none;
    border-radius: 50%;
    font-size: 24px;
    cursor: pointer;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.instinctor-quick-view-close:hover { background: #f5f5f5; }
.instinctor-quick-view-image {
    background: #f5f5f7;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 300px;
}
.instinctor-quick-view-image img {
    max-width: 100%;
    max-height: 500px;
    object-fit: contain;
}
.instinctor-quick-view-details {
    padding: 32px;
}
.instinctor-quick-view-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 12px 0;
    color: #1d2327;
}
.instinctor-quick-view-price {
    font-size: 22px;
    font-weight: 700;
    margin-bottom: 16px;
}
.instinctor-quick-view-price .sale { color: #dc2626; margin-right: 8px; }
.instinctor-quick-view-price .original { color: #999; text-decoration: line-through; font-size: 16px; }
.instinctor-quick-view-desc {
    color: #666;
    line-height: 1.6;
    margin-bottom: 24px;
}
.instinctor-quick-view-meta {
    font-size: 13px;
    color: #999;
    margin-bottom: 24px;
}
.instinctor-quick-view-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}
.instinctor-quick-view-qty {
    display: flex;
    align-items: center;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
}
.instinctor-quick-view-qty button {
    width: 36px;
    height: 36px;
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
}
.instinctor-quick-view-qty input {
    width: 50px;
    height: 36px;
    border: none;
    text-align: center;
    font-size: 14px;
}
.instinctor-quick-view-add {
    flex: 1;
    padding: 12px 24px;
    background: #1d2327;
    color: #fff;
    border: none;
    border-radius: 6px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
}
.instinctor-quick-view-add:hover { background: #2c3338; }
.instinctor-quick-view-link {
    display: block;
    text-align: center;
    margin-top: 16px;
    color: #666;
    font-size: 13px;
}
.instinctor-quick-view-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 80px;
    grid-column: 1 / -1;
}
/* Quick View Gallery */
.instinctor-quick-view-gallery {
    background: #f5f5f7;
    display: flex;
    flex-direction: column;
    min-height: 300px;
}
.instinctor-quick-view-main-image {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}
.instinctor-quick-view-main-image img {
    max-width: 100%;
    max-height: 400px;
    object-fit: contain;
}
.instinctor-quick-view-thumbs {
    display: flex;
    gap: 8px;
    padding: 12px;
    background: rgba(0,0,0,0.03);
    overflow-x: auto;
}
.instinctor-quick-view-thumb {
    width: 60px;
    height: 60px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    border: 2px solid transparent;
    flex-shrink: 0;
    transition: border-color 0.2s ease-in-out;
}
.instinctor-quick-view-thumb.active {
    border-color: #1d2327;
}
.instinctor-quick-view-thumb:hover {
    border-color: #999;
}
.instinctor-quick-view-thumb img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
/* Product Card Slideshow */
.instinctor-product-slideshow {
    position: relative;
    display: block;
    width: 100%;
}
.instinctor-product-slideshow .instinctor-slide-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: contain;
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
}
.instinctor-product-slideshow .instinctor-slide-img.active {
    position: relative;
    opacity: 1;
}
.instinctor-slide-dots {
    position: absolute;
    bottom: 8px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    gap: 4px;
    z-index: 3;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
}
.instinctor-product-image:hover .instinctor-slide-dots {
    opacity: 1;
}
.instinctor-slide-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: rgba(255,255,255,0.5);
    cursor: pointer;
    transition: background 0.3s ease-in-out;
}
.instinctor-slide-dot.active {
    background: rgba(255,255,255,1);
}
.instinctor-slide-dot:hover {
    transform: scale(1.2);
}
<?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>

<?php ob_start(); ?>
(function() {
    const apiUrl = '<?php echo esc_js($api_url); ?>';
    const nonce = '<?php echo esc_js($nonce); ?>';

    document.querySelectorAll('.instinctor-add-to-cart-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            const productId = this.dataset.productId;
            const originalText = this.textContent;
            
            this.disabled = true;
            this.textContent = 'Adding...';

            try {
                const response = await fetch(apiUrl + 'cart/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': nonce
                    },
                    body: JSON.stringify({ product_id: parseInt(productId), quantity: 1 })
                });

                const data = await response.json();
                
                if (data.success) {
                    this.textContent = 'Added!';
                    setTimeout(() => {
                        this.textContent = originalText;
                        this.disabled = false;
                    }, 1500);
                } else {
                    this.textContent = data.error || 'Error';
                    setTimeout(() => {
                        this.textContent = originalText;
                        this.disabled = false;
                    }, 2000);
                }
            } catch (error) {
                this.textContent = 'Error';
                setTimeout(() => {
                    this.textContent = originalText;
                    this.disabled = false;
                }, 2000);
            }
        });
    });
})();
<?php $_inst_ljs = ob_get_clean(); wp_add_inline_script('instinctor-frontend-js', $_inst_ljs, 'after'); ?>

<!-- Quick View Modal -->
<div class="instinctor-quick-view-modal" id="instinctor-quick-view-modal">
    <div class="instinctor-quick-view-content">
        <button type="button" class="instinctor-quick-view-close">&times;</button>
        <div class="instinctor-quick-view-body">
            <div class="instinctor-quick-view-loading">Loading...</div>
        </div>
    </div>
</div>

<?php ob_start(); ?>
(function() {
    const modal = document.getElementById('instinctor-quick-view-modal');
    if (!modal) return;
    
    const closeBtn = modal.querySelector('.instinctor-quick-view-close');
    const body = modal.querySelector('.instinctor-quick-view-body');
    const apiUrl = '<?php echo esc_js($api_url); ?>';
    const nonce = '<?php echo esc_js($nonce); ?>';
    
    // Open modal
    document.querySelectorAll('.instinctor-quick-view-btn').forEach(btn => {
        btn.addEventListener('click', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            const productId = this.dataset.productId;
            
            modal.classList.add('active');
            document.body.style.overflow = 'hidden';
            body.innerHTML = '<div class="instinctor-quick-view-loading">Loading...</div>';
            
            try {
                const response = await fetch(apiUrl + 'products/' + productId);
                const product = await response.json();
                
                if (product && product.id) {
                    const regPrice = parseFloat(product.price) || 0;
                    const saleP = parseFloat(product.sale_price) || 0;
                    // Only show sale format if BOTH prices exist and sale < regular
                    const hasSale = saleP > 0 && regPrice > 0 && saleP < regPrice;
                    // Effective price: regular if exists, otherwise sale_price
                    const effectivePrice = regPrice > 0 ? regPrice : saleP;
                    
                    // Parse images from JSON string
                    let images = [];
                    try {
                        const parsedImages = typeof product.images === 'string' ? JSON.parse(product.images) : product.images;
                        if (Array.isArray(parsedImages)) {
                            images = parsedImages.filter(img => img && img.url).map(img => img.url);
                        }
                    } catch (e) {}
                    
                    // Fallback to single image_url
                    if (images.length === 0 && product.image_url) {
                        images = [product.image_url];
                    }
                    
                    let priceHtml;
                    if (hasSale) {
                        priceHtml = `<span class="sale">$${saleP.toFixed(2)}</span><span class="original">$${regPrice.toFixed(2)}</span>`;
                    } else {
                        priceHtml = `$${effectivePrice.toFixed(2)}`;
                    }
                    
                    // Build gallery HTML
                    let galleryHtml = '';
                    if (images.length > 0) {
                        galleryHtml = `<div class="instinctor-quick-view-gallery">
                            <div class="instinctor-quick-view-main-image">
                                <img src="${images[0]}" alt="${product.name}" id="qv-main-img">
                            </div>`;
                        if (images.length > 1) {
                            galleryHtml += `<div class="instinctor-quick-view-thumbs">`;
                            images.forEach((img, idx) => {
                                galleryHtml += `<div class="instinctor-quick-view-thumb${idx === 0 ? ' active' : ''}" data-img="${img}"><img src="${img}" alt=""></div>`;
                            });
                            galleryHtml += `</div>`;
                        }
                        galleryHtml += `</div>`;
                    } else {
                        galleryHtml = `<div class="instinctor-quick-view-image">
                            <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1"><rect x="3" y="3" width="18" height="18" rx="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                        </div>`;
                    }
                    
                    body.innerHTML = `
                        ${galleryHtml}
                        <div class="instinctor-quick-view-details">
                            <h2 class="instinctor-quick-view-title">${product.name}</h2>
                            <div class="instinctor-quick-view-price">${priceHtml}</div>
                            ${product.short_description ? `<p class="instinctor-quick-view-desc">${product.short_description}</p>` : ''}
                            ${product.sku ? `<p class="instinctor-quick-view-meta">SKU: ${product.sku}</p>` : ''}
                            <div class="instinctor-quick-view-actions">
                                <div class="instinctor-quick-view-qty">
                                    <button type="button" class="qty-minus">-</button>
                                    <input type="number" value="1" min="1" class="qty-input">
                                    <button type="button" class="qty-plus">+</button>
                                </div>
                                <button type="button" class="instinctor-quick-view-add" data-product-id="${product.id}">Add to Cart</button>
                            </div>
                            <a href="/product/${product.slug}" class="instinctor-quick-view-link">View full details</a>
                        </div>
                    `;
                    
                    // Thumbnail click handler for gallery
                    body.querySelectorAll('.instinctor-quick-view-thumb').forEach(thumb => {
                        thumb.onclick = function() {
                            const mainImg = document.getElementById('qv-main-img');
                            if (mainImg) {
                                mainImg.src = this.dataset.img;
                            }
                            body.querySelectorAll('.instinctor-quick-view-thumb').forEach(t => t.classList.remove('active'));
                            this.classList.add('active');
                        };
                    });
                    
                    // Qty controls
                    const qtyInput = body.querySelector('.qty-input');
                    body.querySelector('.qty-minus').onclick = () => { if (qtyInput.value > 1) qtyInput.value--; };
                    body.querySelector('.qty-plus').onclick = () => { qtyInput.value++; };
                    
                    // Add to cart
                    body.querySelector('.instinctor-quick-view-add').onclick = async function() {
                        const btn = this;
                        const qty = parseInt(qtyInput.value) || 1;
                        btn.disabled = true;
                        btn.textContent = 'Adding...';
                        
                        try {
                            const res = await fetch(apiUrl + 'cart/add', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
                                body: JSON.stringify({ product_id: product.id, quantity: qty })
                            });
                            const data = await res.json();
                            if (data.success) {
                                btn.textContent = 'Added!';
                                setTimeout(() => modal.classList.remove('active'), 1000);
                            } else {
                                btn.textContent = data.error || 'Error';
                            }
                        } catch (err) {
                            btn.textContent = 'Error';
                        }
                        setTimeout(() => { btn.disabled = false; btn.textContent = 'Add to Cart'; }, 2000);
                    };
                } else {
                    body.innerHTML = '<div class="instinctor-quick-view-loading">Product not found</div>';
                }
            } catch (error) {
                body.innerHTML = '<div class="instinctor-quick-view-loading">Error loading product</div>';
            }
        });
    });
    
    // Close modal
    closeBtn.onclick = () => { modal.classList.remove('active'); document.body.style.overflow = ''; };
    modal.onclick = (e) => { if (e.target === modal) { modal.classList.remove('active'); document.body.style.overflow = ''; } };
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { modal.classList.remove('active'); document.body.style.overflow = ''; } });
    
    // Product Card Slideshow
    const slideshowIntervals = {};
    
    document.querySelectorAll('.instinctor-product-image.has-slideshow').forEach(container => {
        const productCard = container.closest('.instinctor-product-card');
        const cardId = productCard ? productCard.dataset.productId || Math.random() : Math.random();
        const slideCount = parseInt(container.dataset.slideshowCount) || 2;
        
        container.addEventListener('mouseenter', function() {
            let currentIndex = 0;
            slideshowIntervals[cardId] = setInterval(() => {
                currentIndex = (currentIndex + 1) % slideCount;
                showSlide(container, currentIndex);
            }, 2000);
        });
        
        container.addEventListener('mouseleave', function() {
            if (slideshowIntervals[cardId]) {
                clearInterval(slideshowIntervals[cardId]);
                delete slideshowIntervals[cardId];
            }
            showSlide(container, 0);
        });
        
        // Dot click handlers
        container.querySelectorAll('.instinctor-slide-dot').forEach(dot => {
            dot.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const index = parseInt(this.dataset.slideIndex) || 0;
                
                if (slideshowIntervals[cardId]) {
                    clearInterval(slideshowIntervals[cardId]);
                }
                
                showSlide(container, index);
                
                let currentIndex = index;
                slideshowIntervals[cardId] = setInterval(() => {
                    currentIndex = (currentIndex + 1) % slideCount;
                    showSlide(container, currentIndex);
                }, 2000);
            });
        });
    });
    
    function showSlide(container, index) {
        const images = container.querySelectorAll('.instinctor-slide-img');
        const dots = container.querySelectorAll('.instinctor-slide-dot');
        
        images.forEach((img, i) => {
            img.classList.toggle('active', i === index);
            img.style.opacity = i === index ? '1' : '0';
        });
        
        dots.forEach((dot, i) => {
            dot.classList.toggle('active', i === index);
        });
    }
})();
<?php $_inst_ljs = ob_get_clean(); wp_add_inline_script('instinctor-frontend-js', $_inst_ljs, 'after'); ?>
