<?php
if (session_status() !== PHP_SESSION_ACTIVE) @session_start();
$_sessionOrderError = $_SESSION['order_error'] ?? null;
$_sessionOrderErrorProductId = (int)($_SESSION['order_error_product_id'] ?? 0);
$_sessionOrderErrorAvailable = $_SESSION['order_error_available_stock'] ?? null;
unset($_SESSION['order_error'], $_SESSION['order_error_product_id'], $_SESSION['order_error_available_stock']);
?>
<?php
/**
 * Product Page – COD Arha Style
 * Safe version
 */

use Core\App\Models\Settings;

if (!isset($product)) {
    return;
}

$_orderError = ($_sessionOrderErrorProductId > 0 && $_sessionOrderErrorProductId === (int)($product['id'] ?? 0)) ? $_sessionOrderError : null;
$_orderErrorAvailable = $_orderError ? $_sessionOrderErrorAvailable : null;

/* ========= Product Data ========= */
$productId = (int)($product['id'] ?? 0);
$reviewsEnabled = (int)($product['layout']['toggles']['reviews'] ?? 0);
$reviews = [];

if ($reviewsEnabled) {
    $reviewModel = new \Core\App\Models\ProductReviewModel();
    $reviews = $reviewModel->getApprovedByProduct($productId);
}

$title     = $product['title'] ?? '';
$badgeText = trim((string)($product['badge_text'] ?? ''));
$__badgeResolved = product_badge_resolve($badgeText);
$__badgeMeta = $__badgeResolved['meta'] ?? ['class'=>'badge-discount','emoji'=>'🏷️','fallback'=>$badgeText];
$__badgeLabel = (string)($__badgeResolved['label'] ?? $badgeText);
$shortDesc = $product['short_description'] ?? '';
$description = $product['description'] ?? '';

$price     = (float)($product['price'] ?? 0);
$salePrice = (float)($product['sale_price'] ?? 0); // (قد يكون مساويًا للسعر)
$image     = $product['featured_image'] ?? '';

/* ========= Variants (NEW) ========= */
$variants = [];

if (isset($product['variants'])) {
    if (is_string($product['variants'])) {
        $decoded = json_decode($product['variants'], true);
        if (is_array($decoded)) {
            $variants = $decoded;
        }
    } elseif (is_array($product['variants'])) {
        $variants = $product['variants'];
    }
}

$sizes  = (isset($variants['sizes'])  && is_array($variants['sizes']))  ? $variants['sizes']  : [];
$colors = (isset($variants['colors']) && is_array($variants['colors'])) ? $variants['colors'] : [];

// مخزون المنتج
$_stockQty    = (int)($product['stock_quantity'] ?? 0);
$_stockAlert  = (int)($product['stock_alert'] ?? 5);
$_hasVariants = !empty($sizes) || !empty($colors);

// بيانات المخزون للـ JavaScript
$_pmStock   = new \Core\App\Models\ProductModel();
$_allVS     = $_pmStock->getAllVariantStock((int)$product['id']);
$_stockMap  = [];
foreach ($_allVS as $_vs) {
    $_key = ($_vs['size'] ?? '') . '||' . ($_vs['color'] ?? '');
    $_stockMap[$_key] = (int)$_vs['quantity'];
}
$_stockDataJson = json_encode([
    'global'  => $_stockQty,
    'alert'   => $_stockAlert,
    'map'     => $_stockMap,
    'enabled' => $_stockQty > 0 || !empty($_allVS)
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT);

/* ========= Currency (ONLY FROM settings table) ========= */
$settingsModel = new Settings();
$currency = (string)$settingsModel->get('currency', '');
$whatsappNumber = preg_replace('/\D+/', '', (string)$settingsModel->get('contact_whatsapp', ''));
$autoImageRotate = 0;

/* ========= Smart Variant Filter ========= */
$_smartFilter = true;

/* ========= Offers / Quantity Pricing ========= */
$_offersRaw  = $product['offers'] ?? null;
$_offersData = [];
if ($_offersRaw) {
    $_offersData = is_string($_offersRaw)
        ? (json_decode($_offersRaw, true) ?: [])
        : (is_array($_offersRaw) ? $_offersRaw : []);
}
$_offersEnabled = !empty($_offersData['enabled']) && !empty($_offersData['type']);
$_offersJson    = json_encode($_offersData ?: new \stdClass, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG);

/* ========= Discount Logic (based on discount_* fields + time window) ========= */
$now = date('Y-m-d H:i:s');

$hasDiscount = false;
$finalPrice  = $price;

$discountType  = $product['discount_type'] ?? null;          // fixed | percent
$discountValue = (float)($product['discount_value'] ?? 0);
$discountStart = $product['discount_start'] ?? null;         // datetime string
$discountEnd   = $product['discount_end'] ?? null;           // datetime string

if (
    $discountType &&
    $discountValue > 0 &&
    $discountStart &&
    $discountEnd &&
    $now >= $discountStart &&
    $now <= $discountEnd
) {
    if ($discountType === 'fixed') {
        $finalPrice  = max(0, $price - $discountValue);
        $hasDiscount = true;
    } elseif ($discountType === 'percent') {
        $finalPrice  = max(0, $price - ($price * ($discountValue / 100)));
        $hasDiscount = true;
    }
}

/* fallback (optional): إذا كان sale_price أقل من price اعتبره سعر نهائي */
if (!$hasDiscount && $salePrice > 0 && $salePrice < $price) {
    $finalPrice  = $salePrice;
    $hasDiscount = true;
}
/* ========= COUNTDOWN LOGIC ========= */
$showCountdown = false;
$countdownEnd  = null;

$toggleCountdown = (int)($product['layout']['toggles']['countdown'] ?? 0);

if (
    $toggleCountdown === 1 &&
    $hasDiscount &&
    !empty($discountEnd) &&
    strtotime($discountEnd) > time()
) {
    $showCountdown = true;
    $countdownEnd  = $discountEnd;
}
$serverNow      = time();
$endTimestamp   = strtotime($discountEnd);
$remainingSecs  = max(0, $endTimestamp - $serverNow);

?>

<div class="product-page">


<style>
/* Full width Editor.js rendered description (after hero) */
.product-description-full{
    padding: 40px 0;
}
.product-description-full .container{
    max-width: 1100px;
    margin: 0 auto;
    padding: 0 16px;
}
.product-description-full img{
    max-width: 100%;
    height: auto;
}

.stock-status-wrap{
    min-height:44px;
    display:flex;
    justify-content:center;
    align-items:center;
    margin: 06px auto 06px;
    text-align:center;
    width:100%;
}
.stock-status-pill{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:7px 12px;
    border-radius:999px;
    font-size:13px;
    font-weight:700;
    line-height:1;
    border:1px solid transparent;
}
.stock-status-icon{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    font-size:14px;
}
.stock-status-pill--success{
    color:#0f766e;
    background:#ecfdf5;
    border-color:#bbf7d0;
}
.stock-status-pill--warning{
    color:#92400e;
    background:#fffbeb;
    border-color:#fde68a;
}
.stock-status-pill--danger{
    color:#b91c1c;
    background:#fef2f2;
    border-color:#fecaca;
}

</style>



    <!-- ================= PRODUCT HERO ================= -->
    <section class="product-hero">
        <div class="product-hero-inner">

            <div class="product-hero-grid">

                <!-- ===== HERO SUMMARY ===== -->
                <div class="hero-summary product-info">

                    <!-- TITLE + BADGE -->
                    <div class="product-title-row">
                        <h1 class="product-title">
                            <?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>
                        </h1>

                        <?php if ($badgeText): ?>
                            <span class="product-badge <?= htmlspecialchars($__badgeMeta['class'], ENT_QUOTES, 'UTF-8') ?>">
                                <span class="badge-emoji"><?= htmlspecialchars($__badgeMeta['emoji'], ENT_QUOTES, 'UTF-8') ?></span>
                                <span><?= htmlspecialchars($__badgeLabel, ENT_QUOTES, 'UTF-8') ?></span>
                            </span>
                        <?php endif; ?>
                        <?php if ($showCountdown): ?>
<div class="product-countdown"
     data-remaining="<?= (int)$remainingSecs ?>">

        
        <div class="countdown-inner">
            <span class="countdown-label">
                <?= __('product.offer_ends_in', 'Offer ends in') ?>
            </span>

            <div class="countdown-timer">
                <div class="time-box">
                    <span class="num" data-days>00</span>
                    <small><?= __('countdown.days','Days') ?></small>
                </div>

                <div class="time-box">
                    <span class="num" data-hours>00</span>
                    <small><?= __('countdown.hours','Hours') ?></small>
                </div>

                <div class="time-box">
                    <span class="num" data-minutes>00</span>
                    <small><?= __('countdown.minutes','Minutes') ?></small>
                </div>

                <div class="time-box">
                    <span class="num" data-seconds>00</span>
                    <small><?= __('countdown.seconds','Seconds') ?></small>
                </div>
            </div>
        </div>

    </div>
<?php endif; ?>

                    </div>

                    <!-- PRICE -->
                    <div class="product-price">
                        <?php if ($hasDiscount): ?>
                            <span class="price-old">
                                <?= number_format($price) ?>
                                <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span class="price-new">
                                <?= number_format($finalPrice) ?>
                                <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php else: ?>
                            <span class="price-current">
                                <?= number_format($price) ?>
                                <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                    </div>

                    <!-- VARIANTS (REDESIGNED) -->
                    <?php if (!empty($sizes) || !empty($colors)): ?>
                        <div class="product-variants">

                            <?php if (!empty($sizes)): ?>
                                <div class="variant-group" id="vg-size">
                                    <span class="variant-label"><?= __('product.size', 'Size') ?></span>
                                    <div class="variant-options" id="vo-size">
                                        <?php foreach ($sizes as $s): ?>
                                            <?php
                                            if (!is_array($s)) continue;
                                            $val = $s['value'] ?? '';
                                            if ($val === '') continue;
                                            ?>
                                            <button type="button"
                                                    class="variant-item variant-size"
                                                    data-variant="size"
                                                    data-value="<?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>">
                                                <?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>
                                            </button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if (!empty($colors)): ?>
                                <div class="variant-group" id="vg-color">
                                    <span class="variant-label"><?= __('product.color', 'Color') ?></span>
                                    <div class="variant-options" id="vo-color">
                                        <?php foreach ($colors as $c): ?>
                                            <?php
                                            if (!is_array($c)) continue;
                                            $code = $c['code'] ?? '';
                                            if ($code === '') continue;
                                            $name = $c['name'] ?? '';
                                            ?>
                                            <span class="variant-color-wrap">
                                                <button type="button"
                                                        class="variant-color"
                                                        data-variant="color"
                                                        data-value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>"
                                                        data-code="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>"
                                                        style="background:<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>;"
                                                        title="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>">
                                                </button>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>

                        </div>
                    <?php endif; ?>

                    <!-- SHORT DESCRIPTION -->
                    <?php if ($shortDesc): ?>
                        <p class="product-short-description">
                            <?= nl2br(htmlspecialchars($shortDesc, ENT_QUOTES, 'UTF-8')) ?>
                        </p>
                    <?php endif; ?>

                    <!-- ================= PRICING TIERS / OFFERS ================= -->
<?php if ($_offersEnabled): ?>
<div class="offer-tiers-box" id="offerTiersBox">
    <div class="offer-tiers-head">
        <div class="offer-tiers-title-line">
            <div class="offer-tiers-title"><i class="bi bi-stars"></i> <?= __('product.offer_selected', 'Selected offer') ?></div>
            <div class="offer-tiers-subtitle"><?= __('product.offer_choose', 'Choose the offer that suits you') ?></div>
        </div>
    </div>
    <?php if ($_offersData['type'] === 'quantity_pricing' && !empty($_offersData['tiers'])): ?>
    <div class="offer-tiers-grid">
        <?php foreach ($_offersData['tiers'] as $tier):
            $_tierQty = (int)($tier['qty'] ?? 1);
            $_tierPrice = (float)($tier['price'] ?? 0);
            $_regularTotal = $finalPrice * max(1, $_tierQty);
            $_saving = max(0, $_regularTotal - $_tierPrice);
        ?>
        <button type="button" class="offer-tier" data-offer-type="quantity_pricing" data-qty="<?= $_tierQty ?>" data-price="<?= $_tierPrice ?>">
            <span class="offer-tier-badge"><?= $_tierQty ?> <?= __('product.units','units') ?></span>
            <span class="offer-tier-price"><?= number_format($_tierPrice) ?> <?= htmlspecialchars($currency) ?></span>
            <?php if ($_saving > 0): ?>
                <span class="offer-tier-saving"><?= __('product.instead_of','Instead of') ?> <?= number_format($_regularTotal) ?> <?= htmlspecialchars($currency) ?></span>
            <?php endif; ?>
        </button>
        <?php endforeach; ?>
    </div>
    <?php elseif ($_offersData['type'] === 'bundle_free'): ?>
    <?php $_bundleQty = (int)($_offersData['buy'] ?? 2) + (int)($_offersData['free'] ?? 1); ?>
    <button type="button" class="offer-bundle-card" id="bundleOfferCard" data-offer-type="bundle_free" data-qty="<?= $_bundleQty ?>">
        <span class="offer-bundle-icon"><i class="bi bi-gift-fill"></i></span>
        <span class="offer-bundle-copy">
            <strong><?= __('product.buy','Buy') ?> <?= (int)($_offersData['buy'] ?? 2) ?></strong>
            <span><?= __('product.get_free','Get') ?> <?= (int)($_offersData['free'] ?? 1) ?> <?= __('product.for_free','Free') ?></span>
        </span>
        <span class="offer-bundle-cta"><?= __('product.offer_activate','Activate offer') ?></span>
    </button>
    <?php endif; ?>
</div>
<style>
.offer-tiers-box {
    background: #fff;
    border: 1px solid rgba(148,163,184,.24);
    border-radius: 16px;
    padding: 14px 16px;
    margin: 8px 0 10px;
}
.offer-tiers-head {
    margin-bottom: 12px;
}
.offer-tiers-title-line{
    display:flex;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
}
.offer-tiers-title,
.offer-tiers-subtitle{
    display:inline-flex;
    align-items:center;
    gap:6px;
    font-size:13px;
    font-weight:800;
    color: var(--dark-color, var(--dark, #16161d));
}
.offer-tiers-subtitle{ color: var(--secondary-color, var(--secondary, #f7182e)); }
.offer-tiers-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 10px;
}
.offer-tiers-grid > *{min-width:0;}
.offer-tier,
.offer-bundle-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    min-height: 108px;
    width: 100%;
    padding: 12px 14px;
    background: #fff;
    border: 1px solid var(--light-color, var(--light, #f6f4f4));
    border-radius: 14px;
    cursor: pointer;
    transition: border-color .15s, background .15s, transform .15s, box-shadow .15s;
}
.offer-tier:hover,
.offer-tier.active,
.offer-bundle-card:hover,
.offer-bundle-card.active {
    border-color: var(--primary-color, var(--primary, #598aee));
    background: color-mix(in srgb, #fff 94%, var(--primary-color, var(--primary, #598aee)) 6%);
    box-shadow: 0 10px 24px rgba(0,0,0,.07);
    transform: translateY(-1px);
}
.offer-tier-badge,
.offer-tier-qty,
.offer-bundle-copy {
    font-size: 14px;
    font-weight: 800;
    color: var(--dark-color, var(--dark, #16161d));
}
.offer-tier-price {
    font-size: 18px;
    font-weight: 900;
    color: var(--primary-color, var(--primary, #598aee));
    margin-top: 4px;
}
.offer-tier-saving,
.offer-bundle-cta {
    margin-top: 6px;
    font-size: 12px;
    font-weight: 700;
    color: var(--secondary-color, var(--secondary, #f7182e));
}
.offer-bundle-icon{font-size:22px;color:var(--warning-color, var(--warning, #ced062));margin-bottom:6px;}
.offer-bundle-copy{display:flex;flex-direction:column;gap:4px;}
.offer-bundle-copy strong{font-size:16px;color:var(--primary-color, #598aee);}
@media (min-width: 992px){
  .offer-tiers-grid > *{max-width:none;}
}
</style>
<?php endif; ?>

                    <!-- ================= ORDER BOX ================= -->
<style>
#default-shipping-fields,
#maystro-shipping-fields {
    display: contents;
}
@media (max-width: 768px) {
    #default-shipping-fields,
    #maystro-shipping-fields {
        display: block;
    }
}
</style>
<form action="/submit-order" method="post" class="order-box" id="checkout" onsubmit="return validateVariantForm(event)">
<?= \Core\System\Csrf::field(); ?>
                        <h3 class="order-box-title">
                            <?= __('checkout.box_title', 'Add your information below to order') ?>
                        </h3>

                        <div class="order-fields">

                            <div class="field-icon">
                                <i class="bi bi-person"></i>
                                <input type="text"
                                       name="full_name"
                                       placeholder="<?= __('checkout.full_name', 'Full Name') ?>"
                                       required>
                            </div>

<?php
$_shippingSettings = \Core\App\Support\ShippingSettings::load();
$_shippingSelectionMode = (string)($_shippingSettings['provider_selection_mode'] ?? 'manual_admin');
$_shippingForcedProvider = (string)($_shippingSettings['forced_provider'] ?? '');
$_activeShippingIntegrations = (new \Core\App\Models\ShippingIntegrationModel())->getAllIndexed();
$_maystroIntegrationActive = isset($_activeShippingIntegrations['maystro']) && (int)($_activeShippingIntegrations['maystro']['is_active'] ?? 0) === 1;
$_frontendMaystroEnabled = $_maystroIntegrationActive;
$_frontendMaystroAllowExpress = $_maystroIntegrationActive;
$_frontendMaystroAllowStopdesk = $_maystroIntegrationActive;
$_frontendMaystroAllowPickup = $_maystroIntegrationActive;
$_frontendShippingProviders = [];
foreach ($_activeShippingIntegrations as $__providerKey => $__providerRow) {
    if ((int)($__providerRow['is_active'] ?? 0) !== 1) continue;
    $_frontendShippingProviders[] = [
        'key' => (string)$__providerKey,
        'label' => (string)($__providerRow['display_name'] ?? $__providerKey),
    ];
}
$_showFrontendProviderSelect = $_shippingSelectionMode === 'customer_choice' && !empty($_shippingSettings['allow_customer_provider_choice']);
$_frontendResolvedProvider = ($_shippingSelectionMode === 'forced_provider' && !empty($_shippingSettings['allow_customer_provider_choice'])) ? $_shippingForcedProvider : '';
?>
                            <div class="field-icon">
                                <i class="bi bi-telephone"></i>
                                <input type="tel"
                                       name="phone"
                                       placeholder="<?= __('checkout.phone', 'Phone Number') ?>"
                                       required>
                            </div>

                            <?php if ($_showFrontendProviderSelect): ?>
                            <div class="field-icon">
                                <i class="bi bi-truck"></i>
                                <select id="shipping-provider-select">
                                    <option value=""><?= __('checkout.choose_shipping_provider', 'Choose shipping company') ?></option>
                                    <?php foreach ($_frontendShippingProviders as $_providerRow): ?>
                                        <option value="<?= htmlspecialchars($_providerRow['key']) ?>"><?= htmlspecialchars($_providerRow['label']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>

                            <div id="default-shipping-fields" style="<?= ($_frontendResolvedProvider === 'maystro') ? 'display:none' : '' ?>">
                                <div class="field-icon">
                                    <i class="bi bi-geo-alt"></i>
                                    <select id="state" disabled required>
                                        <option value=""><?= __('checkout.state', 'State') ?></option>
                                    </select>
                                </div>

                                <div class="field-icon">
                                    <i class="bi bi-building"></i>
                                    <select id="city" disabled required>
                                        <option value=""><?= __('checkout.city', 'City') ?></option>
                                    </select>
                                </div>

                                <div class="field-icon">
                                    <i class="bi bi-truck"></i>
                                    <select id="shipping-type" required>
                                        <option value="home"><?= __('checkout.shipping_home', 'Home Delivery') ?></option>
                                        <option value="desk"><?= __('checkout.shipping_desk', 'Office Delivery') ?></option>
                                    </select>
                                </div>
                            </div>

                            <div id="maystro-shipping-fields" style="<?= ($_frontendResolvedProvider === 'maystro' && $_frontendMaystroEnabled) ? '' : 'display:none' ?>">
                                <div class="field-icon">
                                    <i class="bi bi-geo-alt"></i>
                                    <select id="maystro-state" <?= $_frontendMaystroEnabled ? "" : "disabled" ?> data-loaded="0">
                                        <option value=""><?= __('checkout.state', 'State') ?></option>
                                    </select>
                                </div>

                                <div class="field-icon">
                                    <i class="bi bi-building"></i>
                                    <select id="maystro-city" disabled>
                                        <option value=""><?= __('checkout.city', 'City') ?></option>
                                    </select>
                                </div>

                                <div class="field-icon">
                                    <i class="bi bi-truck"></i>
                                    <select id="maystro-delivery-type">
                                        <option value="1"><?= __('checkout.shipping_home', 'Home Delivery') ?></option>
                                        <?php if ($_frontendMaystroAllowStopdesk): ?><option value="2"><?= __('checkout.shipping_desk', 'Office Delivery') ?></option><?php endif; ?>
                                        <?php if ($_frontendMaystroAllowPickup): ?><option value="3"><?= __('checkout.shipping_pickup', 'Pickup Point') ?></option><?php endif; ?>
                                    </select>
                                </div>

                                <div class="field-icon" id="maystro-pickup-wrap" style="display:none">
                                    <i class="bi bi-shop"></i>
                                    <select id="maystro-pickup-point" disabled>
                                        <option value=""><?= __('checkout.pickup_point', 'Pickup Point') ?></option>
                                    </select>
                                </div>

                                <?php if ($_frontendMaystroAllowExpress): ?>
                                <div class="field-icon">
                                    <i class="bi bi-lightning-charge"></i>
                                    <label style="display:flex;align-items:center;gap:8px;width:100%;padding:0 12px;min-height:44px;">
                                        <input type="checkbox" id="maystro-express">
                                        <span><?= __('checkout.express_delivery', 'Express Delivery') ?></span>
                                    </label>
                                </div>
                                <?php endif; ?>
                            </div>

                        </div>

                        <!-- QUANTITY -->
                        <div class="order-qty">
                            <button type="button" id="qty-minus">−</button>
                            <input type="text" id="quantity" value="1" readonly>
                            <button type="button" id="qty-plus">+</button>
                        </div>

                        <!-- SUMMARY -->
                        <div class="order-summary">
                            <div class="summary-row">
                                <span><?= __('checkout.product_price', 'Product Price') ?></span>
                                <span id="summary-product-price"></span>
                            </div>
                            <div class="summary-row">
                                <span><?= __('checkout.shipping', 'Shipping') ?></span>
                                <span id="summary-shipping-price"></span>
                            </div>
                            <div class="summary-row total">
                                <span><?= __('checkout.total', 'Total') ?></span>
                                <span id="summary-total-price"></span>
                            </div>
                        </div>

                       <!-- HIDDEN -->

<input type="hidden" name="product_id" value="<?= $productId ?>">

<input type="hidden" name="quantity" id="quantity-input" value="1">
<input type="hidden" name="selected_offer" id="selected-offer-input" value="">
<input type="hidden" name="selected_offer_label" id="selected-offer-label-input" value="">
<input type="hidden" name="selected_offer_paid_qty" id="selected-offer-paid-qty-input" value="">
<input type="hidden" name="selected_offer_free_qty" id="selected-offer-free-qty-input" value="">
<input type="hidden" name="selected_offer_total" id="selected-offer-total-input" value="">
<input type="hidden" name="total_amount" id="total-amount-input" value="">

<input type="hidden" name="shipping_price" id="shipping-price-input" value="0">
<input type="hidden" name="state_code" id="state-code-input" value="">
<input type="hidden" name="state_name" id="state-name-input" value="">
<input type="hidden" name="city_id" id="city-id-input" value="">
<input type="hidden" name="city_name" id="city-name-input" value="">
<input type="hidden" name="shipping_type" id="shipping-type-input" value="home">
<input type="hidden" name="shipping_provider" id="shipping-provider-input" value="<?= htmlspecialchars($_frontendResolvedProvider, ENT_QUOTES, 'UTF-8') ?>">
<input type="hidden" name="shipping_delivery_type" id="shipping-delivery-type-input" value="1">
<input type="hidden" name="shipping_pickup_point" id="shipping-pickup-point-input" value="">
<input type="hidden" name="shipping_express" id="shipping-express-input" value="0">
<input type="hidden" name="shipping_provider_state_id" id="shipping-provider-state-id-input" value="">
<input type="hidden" name="shipping_provider_state_name" id="shipping-provider-state-name-input" value="">
<input type="hidden" name="shipping_provider_commune_id" id="shipping-provider-commune-id-input" value="">
<input type="hidden" name="shipping_provider_commune_name" id="shipping-provider-commune-name-input" value="">

<input type="hidden" name="variant_size" id="variant-size-input" value="">
<input type="hidden" name="variant_color" id="variant-color-input" value="">
<input type="hidden" name="variant_color_code" id="variant-color-code-input" value="">




                        <div id="variant-inline-error" class="checkout-inline-error" <?php if (!$_orderError): ?>style="display:none;"<?php endif; ?>>
                            <span class="checkout-inline-error-icon">&#9888;</span>
                            <span class="checkout-inline-error-text">
                                <?php if ($_orderError === 'missing_size'): ?>
                                    <?= __('checkout.please_select_size', 'يرجى اختيار المقاس أولاً') ?>
                                <?php elseif ($_orderError === 'missing_color'): ?>
                                    <?= __('checkout.please_select_color', 'يرجى اختيار اللون أولاً') ?>
                                <?php elseif ($_orderError === 'invalid_size'): ?>
                                    <?= __('checkout.invalid_size', 'المقاس المختار غير صالح لهذا المنتج.') ?>
                                <?php elseif ($_orderError === 'invalid_color'): ?>
                                    <?= __('checkout.invalid_color', 'اللون المختار غير صالح لهذا المنتج.') ?>
                                <?php elseif ($_orderError === 'phone_banned'): ?>
                                    <?= __('checkout.phone_banned', 'عذراً، لا يمكن إتمام الطلب بهذا الرقم.') ?>
                                <?php elseif ($_orderError === 'suspicious'): ?>
                                    <?= __('checkout.suspicious', 'طلبات كثيرة جداً، يرجى المحاولة لاحقاً.') ?>
                                <?php elseif ($_orderError === 'out_of_stock'): ?>
                                    <?= __('checkout.out_of_stock', 'عذراً، هذا المنتج نفد من المخزون.') ?>
                                    <?php if ($_orderErrorAvailable !== null && $_orderErrorAvailable !== ''): ?>
                                        (<?= __('checkout.available', 'المتاح') ?>: <?= (int)$_orderErrorAvailable ?>)
                                    <?php endif; ?>
                                <?php elseif ($_orderError === 'missing_required_fields'): ?>
                                    <?= __('checkout.missing_required_fields', 'يرجى تعبئة جميع الحقول المطلوبة.') ?>
                                <?php else: ?>
                                    <?= __('checkout.order_error', 'حدث خطأ، يرجى المحاولة مرة أخرى.') ?>
                                <?php endif; ?>
                            </span>
                        </div>


                        <!-- ACTIONS -->
                        <button type="submit" class="btn-confirm"<?php if (!$_hasVariants && $_stockQty <= 0): ?> disabled<?php endif; ?>>
                            <?= __('actions.confirm_order', 'Confirm Order') ?>
                        </button>

                        <a href="https://wa.me/" class="btn-whatsapp">
                            <?= __('actions.order_whatsapp', 'Order via WhatsApp') ?>
                        </a>

                    </form>

                    




</div>

                <!-- ===== HERO MEDIA ===== -->
<?php if ($image):

/* ── جمع كل صور المنتج: الصورة الرئيسية + الإضافية ── */
$_allImages = [];
$_allImages[] = $image; // الصورة الرئيسية دائماً أولاً

$_extraImages = $product['images'] ?? [];
if (is_string($_extraImages)) {
    $_extraImages = json_decode($_extraImages, true) ?? [];
}
if (is_array($_extraImages)) {
    foreach ($_extraImages as $_extraImg) {
        $__src = is_array($_extraImg) ? ($_extraImg['src'] ?? $_extraImg['url'] ?? '') : $_extraImg;
        if ($__src && $__src !== $image) {
            $_allImages[] = $__src;
        }
    }
}
$_showThumbs = count($_allImages) > 1;
?>
<div class="hero-media product-media" data-sticky-image data-auto-rotate="<?= (int)$autoImageRotate ?>">

    <!-- ZOOM CONTAINER -->
    <div class="product-image-zoom">
        <img id="product-main-image"
             src="<?= htmlspecialchars($image, ENT_QUOTES, 'UTF-8') ?>"
             alt="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>">
    </div>

    <?php if ($_showThumbs): ?>
    <!-- ── THUMBNAILS STRIP ── -->
    <style>
    /* wrapper: نفس عرض الصورة الرئيسية تماماً */
    .gal-thumbs-wrapper{display:flex!important;flex-direction:row!important;align-items:center!important;gap:8px;margin-top:8px;width:100%;box-sizing:border-box}
    .gal-thumbs-track-outer{flex:1 1 0!important;overflow:hidden!important;min-width:0!important}
    .gal-thumbs-track{display:flex!important;flex-direction:row!important;flex-wrap:nowrap!important;gap:6px!important;transition:transform .3s ease}
    /* كل صورة = ربع العرض المتاح بالضبط بعد طرح الـ gaps الثلاثة */
    .gal-thumb{flex:0 0 calc(25% - 4.5px)!important;width:calc(25% - 4.5px)!important;aspect-ratio:1/1!important;height:auto!important;border:2px solid transparent;border-radius:8px;overflow:hidden;cursor:pointer;background:#eee;padding:0;box-sizing:border-box;display:inline-flex!important}
    .gal-thumb img{width:100%!important;height:100%!important;object-fit:cover!important;display:block!important}
    .gal-thumb.is-active{border-color:#0d6efd!important;box-shadow:0 0 0 2px rgba(13,110,253,.3)!important}
    .gal-thumb:hover:not(.is-active){border-color:#aaa!important}
    .thumb-arrow{flex:0 0 28px!important;width:28px!important;height:28px!important;border-radius:50%!important;border:1px solid #ccc!important;background:#fff!important;font-size:20px!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;cursor:pointer!important;color:#333!important;padding:0!important;line-height:1!important;user-select:none!important;box-sizing:border-box!important}
    .thumb-arrow:hover{background:#f0f0f0!important}
    </style>
    <div class="gal-thumbs-wrapper" id="gal-thumbs-wrapper">
        <button class="thumb-arrow thumb-arrow--prev" id="gal-prev" aria-label="السابق" type="button" style="display:none">&#8249;</button>

        <div class="gal-thumbs-track-outer">
            <div class="gal-thumbs-track" id="gal-track">
                <?php foreach ($_allImages as $_i => $_src): ?>
                <button class="gal-thumb<?= $_i === 0 ? ' is-active' : '' ?>"
                        type="button"
                        aria-label="صورة <?= $_i + 1 ?>"
                        data-src="<?= htmlspecialchars($_src, ENT_QUOTES, 'UTF-8') ?>">
                    <img src="<?= htmlspecialchars($_src, ENT_QUOTES, 'UTF-8') ?>"
                         alt="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?> - <?= $_i + 1 ?>">
                </button>
                <?php endforeach; ?>
            </div>
        </div>

        <button class="thumb-arrow thumb-arrow--next" id="gal-next" aria-label="التالي" type="button" style="display:none">&#8250;</button>
    </div>
    <?php endif; ?>

</div>

<?php endif; ?>

            </div>
        </div>
    </section>


<?php if (!empty($description)): ?>
<section class="product-description-full">
    <div class="container">
        <?php
        $descRaw = $description;
        $descData = null;

        if (is_string($descRaw)) {
            $descData = json_decode($descRaw, true);
        } elseif (is_array($descRaw)) {
            $descData = $descRaw;
        }

        if (is_array($descData) && !empty($descData['blocks'])) {
            echo \Core\System\EditorJsRenderer::render($descData);
        } else {
            // Sanitize raw HTML to prevent Stored XSS before outputting to public frontend
            $safeHtml = \Core\System\HtmlSanitizer::sanitize((string)$descRaw);
            echo '<div class="product-desc-html">' . $safeHtml . '</div>';
        }
        ?>
    </div>
</section>
<?php endif; ?>



</div>


<?php
/* ═══════════════════════════════════════════════════════════════════
   LANDING PAGE BUILDER — Section Renderer  (redesigned)
   Reads from $product['layout']['sections']
═══════════════════════════════════════════════════════════════════ */
$lpbSections = [];
if (!empty($product['layout']['sections']) && is_array($product['layout']['sections'])) {
    $lpbSections = $product['layout']['sections'];
}

if (!empty($lpbSections)):
$lpbEsc = function($v) { return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8'); };
$lpbHasCountdown = !empty(array_filter($lpbSections, function($s) { return ($s['type'] ?? '') === 'countdown'; }));
// Extract deadline from first countdown section
$lpbCountdownDeadline = '';
foreach ($lpbSections as $_s) {
    if (($_s['type'] ?? '') === 'countdown' && !empty($_s['settings']['deadline'])) {
        $lpbCountdownDeadline = $_s['settings']['deadline'];
        break;
    }
}
?>

<div class="lpb-sections-wrap">

<?php foreach ($lpbSections as $lpbIdx => $lpbSec):
    $lpbType = $lpbSec['type'] ?? '';
    $lpbS    = $lpbSec['settings'] ?? [];
    $lpbBg   = $lpbEsc($lpbS['bg_color'] ?? '');
    $lpbBgStyle = $lpbBg ? "background:{$lpbBg};" : '';
?>

<?php /* ─────── IMAGE + TEXT ─────── */ ?>
<?php if ($lpbType === 'image_text'): ?>
<div class="lpb-s lpb-image-text <?= ($lpbS['img_position'] ?? 'left') === 'right' ? 'lpb-img-right' : '' ?>" style="<?= $lpbBgStyle ?>">
    <div class="lpb-it-media">
        <?php if (!empty($lpbS['image'])): ?>
        <img src="<?= $lpbEsc($lpbS['image']) ?>" alt="<?= $lpbEsc($lpbS['heading'] ?? '') ?>" loading="lazy">
        <?php else: ?>
        <div class="lpb-it-placeholder">🖼</div>
        <?php endif; ?>
    </div>
    <div class="lpb-it-body">
        <?php if (!empty($lpbS['heading'])): ?>
        <h2 class="lpb-it-heading" style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
        <?php endif; ?>
        <?php if (!empty($lpbS['text'])): ?>
        <p class="lpb-it-text" style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= nl2br($lpbEsc($lpbS['text'])) ?></p>
        <?php endif; ?>
        <?php if (!empty($lpbS['btn_text'])): ?>
        <a href="<?= $lpbEsc($lpbS['btn_url'] ?? '#') ?>" class="lpb-btn" style="<?= !empty($lpbS['btn_bg']) ? "background:{$lpbEsc($lpbS['btn_bg'])};" : '' ?><?= !empty($lpbS['btn_color']) ? "color:{$lpbEsc($lpbS['btn_color'])};" : '' ?>">
            <?= $lpbEsc($lpbS['btn_text']) ?>
        </a>
        <?php endif; ?>
    </div>
</div>

<?php /* ─────── FEATURES ─────── */ ?>
<?php elseif ($lpbType === 'features'): ?>
<div class="lpb-s lpb-features" style="<?= $lpbBgStyle ?>">
    <div class="lpb-section-header">
        <?php if (!empty($lpbS['heading'])): ?>
        <h2 style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
        <?php endif; ?>
        <?php if (!empty($lpbS['subheading'])): ?>
        <p class="lpb-subhead"><?= $lpbEsc($lpbS['subheading']) ?></p>
        <?php endif; ?>
    </div>
    <div class="lpb-features-grid" data-cols="<?= min(6, max(1, count($lpbS['items'] ?? []))) ?>">
        <?php foreach (($lpbS['items'] ?? []) as $lpbItem): ?>
        <div class="lpb-feature-card">
            <div class="lpb-feature-icon-wrap" style="<?= !empty($lpbS['icon_bg']) ? "background:{$lpbEsc($lpbS['icon_bg'])};" : '' ?>">
                <span class="lpb-feature-icon"><?= $lpbEsc($lpbItem['icon'] ?? '✨') ?></span>
            </div>
            <?php if (!empty($lpbItem['title'])): ?><h3><?= $lpbEsc($lpbItem['title']) ?></h3><?php endif; ?>
            <?php if (!empty($lpbItem['desc'])): ?><p><?= $lpbEsc($lpbItem['desc']) ?></p><?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php /* ─────── TESTIMONIALS ─────── */ ?>
<?php elseif ($lpbType === 'testimonials'): ?>
<div class="lpb-s lpb-testimonials" style="<?= $lpbBgStyle ?>">
    <div class="lpb-section-header">
        <?php if (!empty($lpbS['heading'])): ?>
        <h2 style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
        <?php endif; ?>
        <?php if (!empty($lpbS['subheading'])): ?><p class="lpb-subhead"><?= $lpbEsc($lpbS['subheading']) ?></p><?php endif; ?>
    </div>
    <div class="lpb-testimonials-grid">
        <?php foreach (($lpbS['items'] ?? []) as $lpbItem):
            $lpbStars   = min(5, max(1, (int)($lpbItem['stars'] ?? 5)));
            $lpbInitials = mb_strtoupper(mb_substr(preg_replace('/[^\p{L}\s]/u', '', $lpbItem['name'] ?? '?'), 0, 2, 'UTF-8'), 'UTF-8');
            $lpbAvatarColors = ['#6366f1','#8b5cf6','#ec4899','#14b8a6','#f59e0b','#10b981','#3b82f6'];
            $lpbAvatarBg = $lpbAvatarColors[crc32($lpbItem['name'] ?? '') % count($lpbAvatarColors)];
        ?>
        <div class="lpb-testimonial-card">
            <div class="lpb-tc-top">
                <div class="lpb-tc-stars">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                    <span class="<?= $i <= $lpbStars ? 'filled' : '' ?>">★</span>
                    <?php endfor; ?>
                </div>
                <span class="lpb-tc-verified">✓ <?= __('lpb.verified','Verified') ?></span>
            </div>
            <p class="lpb-tc-text"><?= $lpbEsc($lpbItem['text'] ?? '') ?></p>
            <div class="lpb-tc-author">
                <div class="lpb-tc-avatar" style="background:<?= $lpbAvatarBg ?>">
                    <?= $lpbEsc($lpbInitials) ?>
                </div>
                <div>
                    <div class="lpb-tc-name"><?= $lpbEsc($lpbItem['name'] ?? '') ?></div>
                    <?php if (!empty($lpbItem['role'])): ?><div class="lpb-tc-role"><?= $lpbEsc($lpbItem['role']) ?></div><?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php /* ─────── FAQ ─────── */ ?>
<?php elseif ($lpbType === 'faq'): ?>
<div class="lpb-s lpb-faq" style="<?= $lpbBgStyle ?>">
    <div class="lpb-section-header">
        <?php if (!empty($lpbS['heading'])): ?>
        <h2 style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
        <?php endif; ?>
        <?php if (!empty($lpbS['subheading'])): ?><p class="lpb-subhead"><?= $lpbEsc($lpbS['subheading']) ?></p><?php endif; ?>
    </div>
    <div class="lpb-faq-list">
        <?php foreach (($lpbS['items'] ?? []) as $lpbFi => $lpbItem): ?>
        <div class="lpb-faq-item" id="faq-<?= $lpbIdx ?>-<?= $lpbFi ?>">
            <button class="lpb-faq-q" type="button" aria-expanded="false" onclick="lpbFaqToggle(this)">
                <span><?= $lpbEsc($lpbItem['q'] ?? '') ?></span>
                <span class="lpb-faq-chevron">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                </span>
            </button>
            <div class="lpb-faq-a" role="region">
                <div class="lpb-faq-a-inner"><?= nl2br($lpbEsc($lpbItem['a'] ?? '')) ?></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php /* ─────── COUNTDOWN ─────── */ ?>
<?php elseif ($lpbType === 'countdown'): ?>
<?php
$lpbDeadlineTs = 0;
if (!empty($lpbS['deadline'])) {
    $lpbDeadlineTs = strtotime($lpbS['deadline']);
}
?>
<div class="lpb-s lpb-countdown" style="<?= $lpbBgStyle ?>" data-deadline="<?= $lpbDeadlineTs ?>">
    <?php if (!empty($lpbS['heading'])): ?>
    <h2 style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
    <?php endif; ?>
    <?php if (!empty($lpbS['subheading'])): ?>
    <p class="lpb-countdown-sub" style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['subheading']) ?></p>
    <?php endif; ?>
    <div class="lpb-countdown-timer">
        <?php foreach ([['d','days'],['h','hours'],['m','minutes'],['s','seconds']] as [$unit, $label]): ?>
        <div class="lpb-cdu" style="<?= !empty($lpbS['timer_bg']) ? "background:{$lpbEsc($lpbS['timer_bg'])};" : '' ?>">
            <span class="lpb-cdu-n lpb-cdu-<?= $unit ?>" style="<?= !empty($lpbS['timer_color']) ? "color:{$lpbEsc($lpbS['timer_color'])};" : '' ?>">00</span>
            <span class="lpb-cdu-l" style="<?= !empty($lpbS['timer_color']) ? "color:{$lpbEsc($lpbS['timer_color'])};" : '' ?>"><?= __('countdown.'.$label, $label) ?></span>
        </div>
        <?php if ($unit !== 's'): ?><span class="lpb-cdu-sep">:</span><?php endif; ?>
        <?php endforeach; ?>
    </div>
</div>

<?php /* ─────── TRUST BADGES ─────── */ ?>
<?php elseif ($lpbType === 'trust'): ?>
<div class="lpb-s lpb-trust" style="<?= $lpbBgStyle ?>">
    <?php if (!empty($lpbS['heading'])): ?>
    <div class="lpb-section-header">
        <h2 style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
    </div>
    <?php endif; ?>
    <div class="lpb-trust-row">
        <?php foreach (($lpbS['items'] ?? []) as $lpbItem): ?>
        <div class="lpb-trust-item">
            <span class="lpb-trust-icon"><?= $lpbEsc($lpbItem['icon'] ?? '✅') ?></span>
            <span class="lpb-trust-text"><?= $lpbEsc($lpbItem['text'] ?? '') ?></span>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php /* ─────── CTA ─────── */ ?>
<?php elseif ($lpbType === 'cta'): ?>
<div class="lpb-s lpb-cta" style="<?= $lpbBgStyle ?>">
    <div class="lpb-cta-inner">
        <?php if (!empty($lpbS['heading'])): ?>
        <h2 style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['heading']) ?></h2>
        <?php endif; ?>
        <?php if (!empty($lpbS['subheading'])): ?>
        <p style="<?= !empty($lpbS['text_color']) ? "color:{$lpbEsc($lpbS['text_color'])};" : '' ?>"><?= $lpbEsc($lpbS['subheading']) ?></p>
        <?php endif; ?>
        <?php if (!empty($lpbS['btn_text'])): ?>
        <a href="<?= $lpbEsc($lpbS['btn_url'] ?? '#') ?>" class="lpb-btn lpb-btn-lg" style="<?= !empty($lpbS['btn_bg']) ? "background:{$lpbEsc($lpbS['btn_bg'])};" : '' ?><?= !empty($lpbS['btn_color']) ? "color:{$lpbEsc($lpbS['btn_color'])};" : '' ?>">
            <?= $lpbEsc($lpbS['btn_text']) ?>
        </a>
        <?php endif; ?>
    </div>
</div>

<?php /* ─────── DIVIDER ─────── */ ?>
<?php elseif ($lpbType === 'divider'): ?>
<?php $lpbDivStyle = $lpbS['style'] ?? 'line'; ?>
<div class="lpb-s lpb-divider lpb-divider-<?= $lpbEsc($lpbDivStyle) ?>" style="<?= $lpbBgStyle ?>">
    <?php if ($lpbDivStyle === 'dots'): ?>
    <div class="lpb-divider-dots"><span></span><span></span><span></span></div>
    <?php elseif ($lpbDivStyle === 'space'): ?>
    <div class="lpb-divider-space"></div>
    <?php else: ?>
    <div class="lpb-divider-line"></div>
    <?php endif; ?>
</div>

<?php /* ─────── CUSTOM HTML ─────── */ ?>
<?php elseif ($lpbType === 'custom'): ?>
<div class="lpb-s lpb-custom" style="<?= $lpbBgStyle ?>">
    <?= \Core\System\HtmlSanitizer::sanitize($lpbS['html'] ?? '') ?>
</div>

<?php endif; ?>
<?php endforeach; ?>
</div><!-- /lpb-sections-wrap -->


<style>
/* ═══════════════════════════════════════════════════════════════════
   LPB — Artistic Frontend Styles  ✦  Built for ar-script.com
   Theme-aware: uses CSS custom properties from Theme Customizer
   Author: ar-script LPB Engine
═══════════════════════════════════════════════════════════════════ */

/* ── Theme bridge ────────────────────────────────────────────────── */
.lpb-sections-wrap {
    --c-primary:       var(--primary-color, var(--primary, #5b6ef5));
    --c-secondary:     var(--secondary-color, var(--secondary, #f72585));
    --c-dark:          var(--dark, #0f1117);
    --c-light:         var(--light, #f8f9ff);
    --c-text:          var(--text-primary, #1a1a2e);
    --c-muted:         var(--text-secondary, #64748b);
    --c-bg:            var(--background, #ffffff);
    --c-border:        rgba(0,0,0,.07);

    /* derived */
    --c-primary-10:    color-mix(in srgb, var(--c-primary) 10%, white);
    --c-primary-15:    color-mix(in srgb, var(--c-primary) 15%, white);
    --c-primary-20:    color-mix(in srgb, var(--c-primary) 20%, white);
    --c-primary-rgb:   var(--c-primary);

    --radius-sm:  10px;
    --radius-md:  16px;
    --radius-lg:  24px;
    --radius-xl:  32px;

    width: 100%;
    overflow: hidden;
    font-family: inherit;
}

/* ── Shared section base ─────────────────────────────────────────── */
.lpb-s {
    width: 100%;
    box-sizing: border-box;
    font-family: inherit;
    position: relative;
}

/* scroll reveal (JS adds .lpb-in) */
@media (prefers-reduced-motion: no-preference) {
    .lpb-s { opacity: 0; transform: translateY(32px); transition: opacity .65s cubic-bezier(.22,1,.36,1), transform .65s cubic-bezier(.22,1,.36,1); }
    .lpb-s.lpb-in { opacity: 1; transform: none; }
    .lpb-s.lpb-in .lpb-feature-card    { animation: lpb-pop .5s cubic-bezier(.34,1.56,.64,1) both; }
    .lpb-s.lpb-in .lpb-testimonial-card { animation: lpb-rise .5s ease both; }
    .lpb-s.lpb-in .lpb-faq-item        { animation: lpb-rise .4s ease both; }
    .lpb-s.lpb-in .lpb-trust-item      { animation: lpb-pop .45s cubic-bezier(.34,1.56,.64,1) both; }
    .lpb-s.lpb-in .lpb-cdu             { animation: lpb-pop .6s cubic-bezier(.34,1.56,.64,1) both; }

    .lpb-s.lpb-in .lpb-feature-card:nth-child(1)    { animation-delay: .05s; }
    .lpb-s.lpb-in .lpb-feature-card:nth-child(2)    { animation-delay: .12s; }
    .lpb-s.lpb-in .lpb-feature-card:nth-child(3)    { animation-delay: .19s; }
    .lpb-s.lpb-in .lpb-feature-card:nth-child(4)    { animation-delay: .26s; }
    .lpb-s.lpb-in .lpb-feature-card:nth-child(5)    { animation-delay: .33s; }
    .lpb-s.lpb-in .lpb-feature-card:nth-child(6)    { animation-delay: .40s; }
    .lpb-s.lpb-in .lpb-testimonial-card:nth-child(1) { animation-delay: .05s; }
    .lpb-s.lpb-in .lpb-testimonial-card:nth-child(2) { animation-delay: .13s; }
    .lpb-s.lpb-in .lpb-testimonial-card:nth-child(3) { animation-delay: .21s; }
    .lpb-s.lpb-in .lpb-faq-item:nth-child(1) { animation-delay: .04s; }
    .lpb-s.lpb-in .lpb-faq-item:nth-child(2) { animation-delay: .10s; }
    .lpb-s.lpb-in .lpb-faq-item:nth-child(3) { animation-delay: .16s; }
    .lpb-s.lpb-in .lpb-faq-item:nth-child(4) { animation-delay: .22s; }
    .lpb-s.lpb-in .lpb-faq-item:nth-child(5) { animation-delay: .28s; }
    .lpb-s.lpb-in .lpb-trust-item:nth-child(1) { animation-delay: .04s; }
    .lpb-s.lpb-in .lpb-trust-item:nth-child(2) { animation-delay: .09s; }
    .lpb-s.lpb-in .lpb-trust-item:nth-child(3) { animation-delay: .14s; }
    .lpb-s.lpb-in .lpb-trust-item:nth-child(4) { animation-delay: .19s; }
    .lpb-s.lpb-in .lpb-trust-item:nth-child(5) { animation-delay: .24s; }
    .lpb-s.lpb-in .lpb-cdu:nth-child(odd)  { animation-delay: .05s; }
    .lpb-s.lpb-in .lpb-cdu:nth-child(even) { animation-delay: .15s; }
}
@keyframes lpb-pop  { from { opacity:0; transform:scale(.82) translateY(14px); } to { opacity:1; transform:none; } }
@keyframes lpb-rise { from { opacity:0; transform:translateY(20px); } to { opacity:1; transform:none; } }

/* ── Section header ──────────────────────────────────────────────── */
.lpb-section-header {
    text-align: center;
    margin-bottom: clamp(32px, 5vw, 56px);
    position: relative;
}
.lpb-section-header h2 {
    font-size: clamp(24px, 4.5vw, 38px);
    font-weight: 800;
    color: var(--c-text);
    margin: 0 0 12px;
    line-height: 1.15;
    font-family: inherit;
    letter-spacing: -.5px;
}
.lpb-section-header h2::after {
    content: '';
    display: block;
    width: 48px;
    height: 4px;
    background: var(--c-primary);
    border-radius: 99px;
    margin: 14px auto 0;
}
.lpb-subhead {
    font-size: 16px;
    color: var(--c-muted);
    margin: 0;
    line-height: 1.65;
    max-width: 560px;
    margin-inline: auto;
}

/* ── Button ──────────────────────────────────────────────────────── */
.lpb-btn {
    display: inline-flex;
    align-items: center;
    gap: 9px;
    background: var(--c-primary);
    color: #fff;
    padding: 14px 30px;
    border-radius: var(--radius-sm);
    font-size: 15px;
    font-weight: 700;
    text-decoration: none;
    font-family: inherit;
    letter-spacing: .2px;
    transition: transform .2s cubic-bezier(.34,1.56,.64,1), box-shadow .2s, filter .2s;
    box-shadow: 0 6px 20px color-mix(in srgb, var(--c-primary) 40%, transparent);
    position: relative;
    overflow: hidden;
}
.lpb-btn::after {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, rgba(255,255,255,.18) 0%, transparent 60%);
    pointer-events: none;
}
.lpb-btn:hover {
    transform: translateY(-3px) scale(1.02);
    box-shadow: 0 12px 32px color-mix(in srgb, var(--c-primary) 50%, transparent);
    color: #fff;
    filter: brightness(1.06);
}
.lpb-btn-lg { padding: 17px 42px; font-size: 17px; border-radius: var(--radius-md); }


/* ═══════════════════════════════════════════════════════
   ① IMAGE + TEXT
═══════════════════════════════════════════════════════ */
.lpb-image-text {
    display: grid;
    grid-template-columns: 1fr 1fr;
    min-height: 420px;
    background: var(--c-bg);
    overflow: hidden;
}
.lpb-image-text.lpb-img-right { direction: rtl; }
.lpb-image-text.lpb-img-right > * { direction: ltr; }

.lpb-it-media {
    position: relative;
    overflow: hidden;
    min-height: 300px;
}
.lpb-it-media img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    transition: transform 6s ease;
}
.lpb-it-media:hover img { transform: scale(1.04); }
.lpb-it-placeholder {
    width: 100%; height: 100%; min-height: 300px;
    background: var(--c-light);
    display: flex; align-items: center; justify-content: center;
    font-size: 64px;
}
.lpb-it-body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: clamp(32px, 6vw, 72px) clamp(28px, 5vw, 64px);
    gap: 20px;
}
.lpb-it-heading {
    font-size: clamp(22px, 3.5vw, 34px);
    font-weight: 800;
    color: var(--c-text);
    margin: 0;
    line-height: 1.2;
    font-family: inherit;
    letter-spacing: -.3px;
}
.lpb-it-text {
    font-size: 16px;
    line-height: 1.8;
    color: var(--c-muted);
    margin: 0;
}
@media (max-width: 700px) {
    .lpb-image-text { grid-template-columns: 1fr; direction: ltr; }
    .lpb-it-media { min-height: 240px; }
}


/* ═══════════════════════════════════════════════════════
   ② FEATURES
═══════════════════════════════════════════════════════ */
.lpb-features {
    padding: clamp(48px, 7vw, 80px) clamp(20px, 5vw, 80px);
    background: var(--c-light);
    position: relative;
}
.lpb-features::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--c-primary), var(--c-secondary, var(--c-primary)));
}
.lpb-features-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 24px;
}
.lpb-feature-card {
    background: var(--c-bg);
    border-radius: var(--radius-md);
    padding: 32px 24px 28px;
    text-align: center;
    border: 1.5px solid var(--c-border);
    position: relative;
    overflow: hidden;
    transition: transform .28s cubic-bezier(.34,1.56,.64,1), box-shadow .28s, border-color .2s;
    cursor: default;
}
.lpb-feature-card::before {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, var(--c-primary-10) 0%, transparent 60%);
    opacity: 0;
    transition: opacity .3s;
}
.lpb-feature-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 20px 48px rgba(0,0,0,.1);
    border-color: var(--c-primary);
}
.lpb-feature-card:hover::before { opacity: 1; }
.lpb-feature-icon-wrap {
    width: 64px; height: 64px;
    border-radius: var(--radius-sm);
    background: var(--c-primary-15);
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 18px;
    font-size: 28px;
    line-height: 1;
    position: relative;
    transition: background .2s, transform .28s cubic-bezier(.34,1.56,.64,1);
}
.lpb-feature-card:hover .lpb-feature-icon-wrap {
    background: var(--c-primary);
    transform: scale(1.1) rotate(-4deg);
    box-shadow: 0 8px 20px color-mix(in srgb, var(--c-primary) 35%, transparent);
}
.lpb-feature-card h3 {
    font-size: 15px; font-weight: 700;
    color: var(--c-text); margin: 0 0 8px;
    font-family: inherit; position: relative;
}
.lpb-feature-card p {
    font-size: 13px; color: var(--c-muted);
    margin: 0; line-height: 1.65; position: relative;
}


/* ═══════════════════════════════════════════════════════
   ③ TESTIMONIALS
═══════════════════════════════════════════════════════ */
.lpb-testimonials {
    padding: clamp(48px, 7vw, 80px) clamp(20px, 5vw, 80px);
    background: var(--c-bg);
    position: relative;
    overflow: hidden;
}
.lpb-testimonials::after {
    content: '"';
    position: absolute;
    font-size: 320px;
    font-weight: 900;
    line-height: 1;
    color: var(--c-primary);
    opacity: .04;
    top: -40px;
    inset-inline-end: 40px;
    pointer-events: none;
    font-family: serif;
}
.lpb-testimonials-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 22px;
    position: relative;
    z-index: 1;
}
.lpb-testimonial-card {
    background: var(--c-light);
    border-radius: var(--radius-md);
    padding: 28px;
    border: 1.5px solid var(--c-border);
    display: flex; flex-direction: column; gap: 16px;
    position: relative;
    overflow: hidden;
    transition: transform .28s cubic-bezier(.34,1.56,.64,1), box-shadow .28s;
}
.lpb-testimonial-card::before {
    content: '"';
    position: absolute;
    top: 16px; inset-inline-end: 20px;
    font-size: 80px;
    font-weight: 900;
    line-height: 1;
    color: var(--c-primary);
    opacity: .08;
    font-family: serif;
    pointer-events: none;
}
.lpb-testimonial-card:hover {
    transform: translateY(-6px);
    box-shadow: 0 16px 48px rgba(0,0,0,.09);
}
.lpb-tc-top { display: flex; align-items: center; gap: 12px; }
.lpb-tc-stars { display: flex; gap: 3px; font-size: 17px; line-height: 1; }
.lpb-tc-stars span { color: #d1d5db; transition: color .15s; }
.lpb-tc-stars span.filled { color: #f59e0b; }
.lpb-tc-verified {
    font-size: 11px; font-weight: 700; letter-spacing: .4px;
    color: #059669;
    background: #d1fae5;
    padding: 3px 9px; border-radius: 99px;
    display: inline-flex; align-items: center; gap: 4px;
    margin-inline-start: auto;
}
.lpb-tc-text {
    font-size: 15px; color: var(--c-text);
    line-height: 1.75; margin: 0; flex-grow: 1;
    font-style: italic;
    position: relative;
}
.lpb-tc-author {
    display: flex; align-items: center; gap: 12px;
    padding-top: 14px;
    border-top: 1px solid var(--c-border);
}
.lpb-tc-avatar {
    width: 44px; height: 44px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 15px; font-weight: 800; color: #fff;
    flex-shrink: 0;
    box-shadow: 0 4px 12px rgba(0,0,0,.15);
}
.lpb-tc-name { font-size: 14px; font-weight: 700; color: var(--c-text); font-family: inherit; }
.lpb-tc-role { font-size: 12px; color: var(--c-muted); margin-top: 1px; }


/* ═══════════════════════════════════════════════════════
   ④ FAQ
═══════════════════════════════════════════════════════ */
.lpb-faq {
    padding: clamp(48px, 7vw, 80px) clamp(20px, 5vw, 80px);
    background: var(--c-light);
    position: relative;
}
.lpb-faq::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 4px;
    background: linear-gradient(90deg, transparent, var(--c-primary), transparent);
}
.lpb-faq-list {
    max-width: 780px;
    margin: 0 auto;
    display: flex; flex-direction: column; gap: 12px;
}
.lpb-faq-item {
    background: var(--c-bg);
    border-radius: var(--radius-md);
    border: 1.5px solid var(--c-border);
    overflow: hidden;
    transition: box-shadow .25s, border-color .25s, transform .25s;
}
.lpb-faq-item:hover {
    box-shadow: 0 8px 28px rgba(0,0,0,.07);
    transform: translateY(-2px);
}
.lpb-faq-item.lpb-open {
    border-color: var(--c-primary);
    box-shadow: 0 8px 32px color-mix(in srgb, var(--c-primary) 18%, transparent);
}
.lpb-faq-q {
    width: 100%;
    display: flex; align-items: center;
    justify-content: space-between; gap: 18px;
    background: none; border: none;
    padding: 20px 24px;
    cursor: pointer;
    text-align: start;
    font-size: 15px; font-weight: 600;
    color: var(--c-text);
    line-height: 1.4;
    font-family: inherit;
    transition: background .2s;
}
.lpb-faq-q:hover { background: var(--c-primary-10); }
.lpb-faq-item.lpb-open .lpb-faq-q { background: var(--c-primary-10); color: var(--c-primary); }
.lpb-faq-chevron {
    flex-shrink: 0;
    width: 32px; height: 32px;
    border-radius: 50%;
    background: var(--c-light);
    border: 1.5px solid var(--c-border);
    display: flex; align-items: center; justify-content: center;
    color: var(--c-muted);
    transition: transform .3s cubic-bezier(.34,1.56,.64,1), background .2s, color .2s, border-color .2s;
}
.lpb-faq-item.lpb-open .lpb-faq-chevron {
    transform: rotate(180deg);
    background: var(--c-primary);
    border-color: var(--c-primary);
    color: #fff;
    box-shadow: 0 4px 12px color-mix(in srgb, var(--c-primary) 40%, transparent);
}
.lpb-faq-a {
    max-height: 0;
    overflow: hidden;
    transition: max-height .4s cubic-bezier(.4,0,.2,1);
}
.lpb-faq-item.lpb-open .lpb-faq-a { max-height: 800px; }
.lpb-faq-a-inner {
    padding: 6px 24px 22px;
    font-size: 15px;
    color: var(--c-muted);
    line-height: 1.8;
}
.lpb-faq-a-inner p { margin: 0; }


/* ═══════════════════════════════════════════════════════
   ⑤ COUNTDOWN
═══════════════════════════════════════════════════════ */
.lpb-countdown {
    padding: clamp(48px, 7vw, 80px) clamp(20px, 5vw, 80px);
    background: var(--c-dark);
    text-align: center;
    position: relative;
    overflow: hidden;
}
.lpb-countdown::before {
    content: '';
    position: absolute; inset: 0;
    background:
        radial-gradient(ellipse 70% 50% at 20% 50%, color-mix(in srgb, var(--c-primary) 25%, transparent) 0%, transparent 65%),
        radial-gradient(ellipse 50% 40% at 80% 80%, color-mix(in srgb, var(--c-secondary,var(--c-primary)) 20%, transparent) 0%, transparent 60%);
    pointer-events: none;
}
.lpb-countdown::after {
    content: '';
    position: absolute; inset: 0;
    background-image: radial-gradient(rgba(255,255,255,.06) 1px, transparent 1px);
    background-size: 28px 28px;
    pointer-events: none;
}
.lpb-countdown h2 {
    font-size: clamp(24px, 4.5vw, 36px);
    font-weight: 800; color: #fff;
    margin: 0 0 12px;
    font-family: inherit;
    position: relative; z-index: 1;
    text-shadow: 0 2px 20px rgba(0,0,0,.3);
}
.lpb-countdown-sub {
    font-size: 15px;
    color: rgba(255,255,255,.65);
    margin: 0 0 36px;
    position: relative; z-index: 1;
}
.lpb-countdown-timer {
    display: inline-flex;
    align-items: center; gap: 8px;
    flex-wrap: wrap; justify-content: center;
    position: relative; z-index: 1;
}
.lpb-cdu {
    display: flex; flex-direction: column; align-items: center;
    background: rgba(255,255,255,.08);
    border: 1px solid rgba(255,255,255,.12);
    border-radius: var(--radius-md);
    padding: 20px 26px;
    min-width: 84px;
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    position: relative;
    overflow: hidden;
    transition: transform .2s, background .2s;
}
.lpb-cdu::before {
    content: '';
    position: absolute; top: 0; left: 0; right: 0; height: 1px;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,.3), transparent);
}
.lpb-cdu:hover {
    background: rgba(255,255,255,.14);
    transform: translateY(-4px);
}
.lpb-cdu-n {
    font-size: clamp(36px, 7vw, 56px);
    font-weight: 900; color: #fff;
    line-height: 1;
    font-variant-numeric: tabular-nums;
    letter-spacing: -2px;
    display: block; min-width: 2ch; text-align: center;
    font-family: inherit;
    text-shadow: 0 0 30px rgba(255,255,255,.3);
}
.lpb-cdu-l {
    font-size: 10px; font-weight: 700;
    letter-spacing: 2px; text-transform: uppercase;
    color: rgba(255,255,255,.45);
    margin-top: 8px; display: block;
}
.lpb-cdu-sep {
    font-size: 40px; font-weight: 900;
    color: rgba(255,255,255,.25);
    line-height: 1; padding-bottom: 22px;
    text-shadow: none;
}


/* ═══════════════════════════════════════════════════════
   ⑥ TRUST BADGES
═══════════════════════════════════════════════════════ */
.lpb-trust {
    padding: clamp(28px, 4vw, 44px) clamp(20px, 5vw, 80px);
    background: var(--c-bg);
    border-top: 1px solid var(--c-border);
    border-bottom: 1px solid var(--c-border);
    position: relative;
    overflow: hidden;
}
.lpb-trust::before {
    content: '';
    position: absolute; inset: 0;
    background: linear-gradient(90deg, var(--c-primary-10) 0%, transparent 40%, transparent 60%, var(--c-primary-10) 100%);
    pointer-events: none;
}
.lpb-trust-row {
    display: flex; flex-wrap: wrap;
    gap: 12px 16px;
    justify-content: center; align-items: center;
    position: relative;
}
.lpb-trust-item {
    display: flex; align-items: center; gap: 10px;
    padding: 12px 20px;
    background: var(--c-bg);
    border-radius: 99px;
    border: 1.5px solid var(--c-border);
    box-shadow: 0 2px 8px rgba(0,0,0,.04);
    transition: transform .22s cubic-bezier(.34,1.56,.64,1), box-shadow .22s, border-color .2s, background .2s;
    cursor: default;
}
.lpb-trust-item:hover {
    transform: translateY(-4px) scale(1.03);
    box-shadow: 0 8px 24px color-mix(in srgb, var(--c-primary) 18%, transparent);
    border-color: var(--c-primary);
    background: var(--c-primary-10);
}
.lpb-trust-icon { font-size: 20px; line-height: 1; flex-shrink: 0; }
.lpb-trust-text { font-size: 13px; font-weight: 700; color: var(--c-text); font-family: inherit; white-space: nowrap; }


/* ═══════════════════════════════════════════════════════
   ⑦ CTA
═══════════════════════════════════════════════════════ */
.lpb-cta {
    background: var(--c-dark);
    padding: clamp(56px, 8vw, 96px) clamp(20px, 5vw, 80px);
    text-align: center;
    position: relative;
    overflow: hidden;
}
/* layered background effects */
.lpb-cta::before {
    content: '';
    position: absolute; inset: 0;
    background:
        radial-gradient(ellipse 80% 60% at 50% -10%, color-mix(in srgb, var(--c-primary) 40%, transparent) 0%, transparent 70%),
        radial-gradient(ellipse 40% 40% at 90% 100%, color-mix(in srgb, var(--c-secondary,var(--c-primary)) 30%, transparent) 0%, transparent 65%);
    pointer-events: none;
}
.lpb-cta::after {
    content: '';
    position: absolute; inset: 0;
    background-image:
        linear-gradient(rgba(255,255,255,.03) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255,255,255,.03) 1px, transparent 1px);
    background-size: 40px 40px;
    pointer-events: none;
}
.lpb-cta-inner {
    position: relative; z-index: 1;
    max-width: 640px;
    margin: 0 auto;
}
.lpb-cta h2 {
    font-size: clamp(26px, 5vw, 44px);
    font-weight: 800; color: #fff;
    margin: 0 0 14px;
    line-height: 1.15;
    font-family: inherit;
    letter-spacing: -.5px;
    text-shadow: 0 2px 24px rgba(0,0,0,.3);
}
.lpb-cta p {
    font-size: 17px;
    color: rgba(255,255,255,.75);
    margin: 0 0 34px;
    line-height: 1.7;
}


/* ═══════════════════════════════════════════════════════
   ⑧ DIVIDER
═══════════════════════════════════════════════════════ */
.lpb-divider { padding: 12px clamp(20px, 5vw, 80px); background: var(--c-bg); }
.lpb-divider-line {
    border: none;
    height: 1.5px;
    background: linear-gradient(90deg, transparent, var(--c-border) 20%, var(--c-border) 80%, transparent);
}
.lpb-divider-space { height: 48px; }
.lpb-divider-dots {
    display: flex; gap: 10px;
    justify-content: center; padding: 8px 0;
}
.lpb-divider-dots span {
    width: 8px; height: 8px;
    border-radius: 50%;
    background: var(--c-primary);
    display: block;
    opacity: .3;
}
.lpb-divider-dots span:nth-child(2) { opacity: .6; transform: scale(1.25); }
.lpb-divider-dots span:nth-child(3) { opacity: .3; }


/* ═══════════════════════════════════════════════════════
   ⑨ CUSTOM HTML
═══════════════════════════════════════════════════════ */
.lpb-custom { padding: clamp(28px, 5vw, 56px) clamp(20px, 5vw, 80px); }


/* ── RTL / LTR safety ────────────────────────────────────────────── */
[dir="rtl"] .lpb-it-body { text-align: right; }
[dir="ltr"] .lpb-it-body { text-align: left; }
[dir="rtl"] .lpb-faq-q  { text-align: right; }
[dir="ltr"] .lpb-faq-q  { text-align: left;  }


/* ── Responsive ──────────────────────────────────────────────────── */
@media (max-width: 600px) {
    .lpb-features-grid    { grid-template-columns: repeat(2, 1fr); }
    .lpb-testimonials-grid { grid-template-columns: 1fr; }
    .lpb-countdown-timer  { gap: 4px; }
    .lpb-cdu              { padding: 14px 18px; min-width: 68px; }
    .lpb-cdu-sep          { font-size: 28px; padding-bottom: 16px; }
    .lpb-trust-item       { padding: 10px 14px; }
}
</style>

<script>
(function () {

    /* ── FAQ accordion ── */
    window.lpbFaqToggle = function(btn) {
        var item  = btn.closest('.lpb-faq-item');
        var isOpen = item.classList.contains('lpb-open');
        // close all in same list
        var list = item.closest('.lpb-faq-list');
        if (list) {
            list.querySelectorAll('.lpb-faq-item.lpb-open').forEach(function(el) {
                el.classList.remove('lpb-open');
                el.querySelector('.lpb-faq-q').setAttribute('aria-expanded', 'false');
            });
        }
        if (!isOpen) {
            item.classList.add('lpb-open');
            btn.setAttribute('aria-expanded', 'true');
        }
    };

    /* ── Countdown timers ── */
    document.querySelectorAll('.lpb-countdown[data-deadline]').forEach(function(wrap) {
        var deadline = parseInt(wrap.dataset.deadline, 10) * 1000;
        if (!deadline) return;
        function tick() {
            var diff = deadline - Date.now();
            if (diff <= 0) { diff = 0; }
            var d = Math.floor(diff / 86400000);
            var h = Math.floor((diff % 86400000) / 3600000);
            var m = Math.floor((diff % 3600000) / 60000);
            var s = Math.floor((diff % 60000) / 1000);
            var p = function(n) { return String(n).padStart(2, '0'); };
            var dEl = wrap.querySelector('.lpb-cdu-d');
            var hEl = wrap.querySelector('.lpb-cdu-h');
            var mEl = wrap.querySelector('.lpb-cdu-m');
            var sEl = wrap.querySelector('.lpb-cdu-s');
            if (dEl) dEl.textContent = p(d);
            if (hEl) hEl.textContent = p(h);
            if (mEl) mEl.textContent = p(m);
            if (sEl) sEl.textContent = p(s);
            if (diff > 0) requestAnimationFrame(function() { setTimeout(tick, 1000); });
        }
        tick();
    });

    /* ── Scroll fade-in ── */
    if ('IntersectionObserver' in window) {
        var obs = new IntersectionObserver(function(entries) {
            entries.forEach(function(e) {
                if (e.isIntersecting) {
                    e.target.classList.add('lpb-in');
                    obs.unobserve(e.target);
                }
            });
        }, { threshold: 0.08 });
        document.querySelectorAll('.lpb-s').forEach(function(el) { obs.observe(el); });
    } else {
        document.querySelectorAll('.lpb-s').forEach(function(el) { el.classList.add('lpb-in'); });
    }

})();
</script>

<?php endif; /* end lpbSections */ ?>


<?php if ($reviewsEnabled): ?>
<section class="product-reviews" id="reviews">

    <!-- SECTION TITLE -->
    <div class="section-head section-head--styled">
        <h2><?= __('reviews.title', 'Customer Reviews') ?></h2>
    </div>

    <!-- REVIEWS SLIDER -->
<div class="products-row-wrapper">

    <!-- ARROWS (ONLY WHEN SLIDER) -->
    <button class="reviews-arrow reviews-arrow-prev" aria-label="Previous">
        &#10094;
    </button>

    <button class="reviews-arrow reviews-arrow-next" aria-label="Next">
        &#10095;
    </button>

    <div class="products-cards-grid <?= count($reviews) > 4 ? 'is-slider' : '' ?>">


            <?php if (!empty($reviews)): ?>
            <?php foreach ($reviews as $review): ?>

                <div class="review-card-arhasoft">

                    <!-- IMAGE -->
                    <div class="product-thumb">
                        <?php if (!empty($review['images'][0])): ?>
                            <img src="<?= htmlspecialchars($review['images'][0], ENT_QUOTES, 'UTF-8') ?>"
                                 alt="review image">
                        <?php else: ?>
                            <img src="<?= htmlspecialchars($image, ENT_QUOTES, 'UTF-8') ?>"
                                 alt="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>">
                        <?php endif; ?>
                    </div>

                    <!-- BODY -->
                    <div class="product-body">

                        <div class="product-body-top">

                            <!-- NAME -->
                            <div class="product-name">
                                <?= htmlspecialchars($review['name'], ENT_QUOTES, 'UTF-8') ?>
                            </div>

                            <!-- RATING -->
                            <div class="product-rating review-stars"
                                 data-rating="<?= (int)$review['rating'] ?>">
                            </div>

                            <!-- COMMENT -->
                            <div class="review-comment">
                                <?= nl2br(htmlspecialchars($review['comment'], ENT_QUOTES, 'UTF-8')) ?>
                            </div>

                        </div>

                    </div>

                </div>

            <?php endforeach; ?>
            <?php else: ?>

                <p class="no-reviews">
                    <?= __('reviews.no_reviews', 'No reviews yet') ?>
                </p>

            <?php endif; ?>

        </div>

    </div>

    <!-- ADD REVIEW TITLE -->
    <div class="section-head section-head--styled" style="margin-top:80px">
        <h2><?= __('reviews.add_title', 'Add Your Review') ?></h2>
    </div>

    <!-- ADD REVIEW FORM -->
    <div class="product-review-form">

        <?php if (!empty($_SESSION['review_success'])): ?>
            <div class="alert alert-success">
                <?= htmlspecialchars($_SESSION['review_success'], ENT_QUOTES, 'UTF-8') ?>
            </div>
            <?php unset($_SESSION['review_success']); ?>
        <?php endif; ?>

        <?php if (!empty($_SESSION['review_error'])): ?>
            <div class="alert alert-danger">
                <?= htmlspecialchars($_SESSION['review_error'], ENT_QUOTES, 'UTF-8') ?>
            </div>
            <?php unset($_SESSION['review_error']); ?>
        <?php endif; ?>

        <form id="review-form"
              method="post"
              action="/product-review/store"
              enctype="multipart/form-data">

            <?= \Core\System\Csrf::field(); ?>
            <input type="hidden" name="product_id" value="<?= $productId ?>">

            <div class="form-row">
                <input type="text"
                       name="name"
                       placeholder="<?= __('reviews.name', 'Name') ?>"
                       required>

                <input type="email"
                       name="email"
                       placeholder="<?= __('reviews.email', 'Email') ?>"
                       required>
            </div>

            <!-- STAR RATING -->
            <div class="rating-input" id="ratingInput">
                <input type="hidden" name="rating" id="ratingValue" value="0">
                <span data-value="1">★</span>
                <span data-value="2">★</span>
                <span data-value="3">★</span>
                <span data-value="4">★</span>
                <span data-value="5">★</span>
            </div>

            <textarea name="comment"
                      rows="4"
                      placeholder="<?= __('reviews.comment_placeholder', 'Write your review here...') ?>"
                      required></textarea>

            <div class="review-upload">
                <label>
                    <input type="file" name="images[]" multiple accept="image/*">
                    <span><?= __('reviews.upload_images', 'Add images (optional)') ?></span>
                </label>
            </div>

            <button type="submit" class="review-btn">
                <?= __('reviews.submit', 'Submit Review') ?>
            </button>

        </form>

    </div>

</section>
<?php endif; ?>

<?php
$stickyBuy = (int)($product['layout']['toggles']['sticky_buy'] ?? 0);

$stickyWa  = (int)($product['layout']['toggles']['whatsapp'] ?? 0);

if ($stickyBuy || $stickyWa):
?>
<div class="product-sticky-bar"
     data-sticky-buy="<?= $stickyBuy ?>"
     data-sticky-wa="<?= $stickyWa ?>">

    <?php if ($stickyBuy): ?>
        <button type="button"
                class="sticky-btn sticky-buy"
                data-scroll-to="#checkout">
            <?= __('actions.confirm_order', 'Buy Now') ?>
        </button>
    <?php endif; ?>
</div>
<?php endif; ?>
<?php if ($stickyWa && $whatsappNumber): ?>
<a href="https://wa.me/<?= $whatsappNumber ?>"
   class="floating-whatsapp"
   target="_blank"
   rel="noopener"
   aria-label="WhatsApp">
    <i class="bi bi-whatsapp"></i>
</a>
<?php endif; ?>


<script>
(function () {
    const sizeInput      = document.getElementById('variant-size-input');
    const colorInput     = document.getElementById('variant-color-input');
    const colorCodeInput = document.getElementById('variant-color-code-input');
    const inlineError    = document.getElementById('variant-inline-error');
    const inlineErrorText = inlineError ? inlineError.querySelector('.checkout-inline-error-text') : null;

    const sizeBtns  = document.querySelectorAll('.variant-size');
    const colorBtns = document.querySelectorAll('.variant-color');
    const colorWraps = document.querySelectorAll('.variant-color-wrap');

    /* Smart filter enabled? */
    const SMART_FILTER = <?= $_smartFilter ? 'true' : 'false' ?>;

    /* Stock map from PHP (size||color → qty) */
    var stockMapForFilter = <?= json_encode($_stockMap, JSON_UNESCAPED_UNICODE) ?>;

    /* ── Smart filter helpers ── */
    function getAllAvailableColors() {
        var available = new Set();
        Object.keys(stockMapForFilter).forEach(function(key) {
            var parts = key.split('||');
            var c = parts[1] || '';
            if (stockMapForFilter[key] > 0 && c) available.add(c);
        });
        return available;
    }

    function getAllAvailableSizes() {
        var available = new Set();
        Object.keys(stockMapForFilter).forEach(function(key) {
            var parts = key.split('||');
            var s = parts[0] || '';
            if (stockMapForFilter[key] > 0 && s) available.add(s);
        });
        return available;
    }

    function getAvailableColorsForSize(sizeVal) {
        if (!sizeVal) return getAllAvailableColors();
        var available = new Set();
        Object.keys(stockMapForFilter).forEach(function(key) {
            var parts = key.split('||');
            var s = parts[0] || '', c = parts[1] || '';
            if (s === sizeVal && stockMapForFilter[key] > 0 && c) available.add(c);
        });
        return available;
    }

    function getAvailableSizesForColor(colorVal) {
        if (!colorVal) return getAllAvailableSizes();
        var available = new Set();
        Object.keys(stockMapForFilter).forEach(function(key) {
            var parts = key.split('||');
            var s = parts[0] || '', c = parts[1] || '';
            if (c === colorVal && stockMapForFilter[key] > 0 && s) available.add(s);
        });
        return available;
    }

    function setForcedDisplay(el, visible, displayValue) {
        if (!el) return;
        if (visible) {
            el.hidden = false;
            el.style.setProperty('display', displayValue || 'inline-flex', 'important');
        } else {
            el.hidden = true;
            el.style.setProperty('display', 'none', 'important');
        }
    }

    function applyColorFilter(availColors) {
        colorBtns.forEach(function(cb) {
            var colorName = cb.getAttribute('data-value') || '';
            var ok = availColors.has(colorName);
            cb.classList.toggle('variant-unavailable', !ok);
            var wrap = cb.closest('.variant-color-wrap');
            setForcedDisplay(wrap, ok, 'inline-flex');
            if (!ok && cb.classList.contains('active')) {
                cb.classList.remove('active');
                if (colorInput) colorInput.value = '';
                if (colorCodeInput) colorCodeInput.value = '';
            }
        });
    }

    function applySizeFilter(availSizes) {
        sizeBtns.forEach(function(sb) {
            var sizeVal = sb.getAttribute('data-value') || '';
            var ok = availSizes.has(sizeVal);
            sb.classList.toggle('variant-unavailable', !ok);
            setForcedDisplay(sb, ok, 'inline-flex');
            if (!ok && sb.classList.contains('active')) {
                sb.classList.remove('active');
                if (sizeInput) sizeInput.value = '';
            }
        });
    }

    function syncVariantFilters() {
        if (!SMART_FILTER) {
            sizeBtns.forEach(function(b) { b.classList.remove('variant-unavailable'); setForcedDisplay(b, true, 'inline-flex'); });
            colorBtns.forEach(function(b) { b.classList.remove('variant-unavailable'); });
            colorWraps.forEach(function(w) { setForcedDisplay(w, true, 'inline-flex'); });
            return;
        }

        var selectedSize = sizeInput ? sizeInput.value : '';
        var selectedColor = colorInput ? colorInput.value : '';

        applyColorFilter(getAvailableColorsForSize(selectedSize));
        applySizeFilter(getAvailableSizesForColor(selectedColor));

        selectedSize = sizeInput ? sizeInput.value : '';
        selectedColor = colorInput ? colorInput.value : '';

        applyColorFilter(getAvailableColorsForSize(selectedSize));
        applySizeFilter(getAvailableSizesForColor(selectedColor));
    }

    function hideInlineError() {
        if (inlineError && inlineErrorText) {
            inlineError.style.display = 'none';
            inlineError.classList.remove('is-visible');
            inlineErrorText.textContent = '';
        }
    }

    /* ── Size click ── */
    sizeBtns.forEach(function(btn) {
        btn.addEventListener('click', function () {
            if (this.classList.contains('variant-unavailable')) return;
            sizeBtns.forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');
            var val = this.getAttribute('data-value') || '';
            if (sizeInput) sizeInput.value = val;
            var group = this.closest('.variant-group');
            if (group) group.classList.remove('variant-required');

            syncVariantFilters();

            var hasColors = !!document.querySelector('.variant-color');
            var colorOk = !hasColors || ((colorInput ? colorInput.value : '') !== '');
            if (colorOk) hideInlineError();
        });
    });

    /* ── Color click ── */
    colorBtns.forEach(function(btn) {
        btn.addEventListener('click', function () {
            if (this.classList.contains('variant-unavailable')) return;
            colorBtns.forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');
            var val  = this.getAttribute('data-value') || '';
            var code = this.getAttribute('data-code') || '';
            if (colorInput) colorInput.value = val;
            if (colorCodeInput) colorCodeInput.value = code;
            var group = this.closest('.variant-group');
            if (group) group.classList.remove('variant-required');

            syncVariantFilters();

            var hasSizes = !!document.querySelector('.variant-size');
            var sizeOk = !hasSizes || ((sizeInput ? sizeInput.value : '') !== '');
            if (sizeOk) hideInlineError();
        });
    });

    syncVariantFilters();
})();
</script>
<script>
(function () {
    const qtyMinus  = document.getElementById('qty-minus');
    const qtyPlus   = document.getElementById('qty-plus');
    const qtyInput  = document.getElementById('quantity');
    const qtyHidden = document.getElementById('quantity-input');

    const summaryProduct  = document.getElementById('summary-product-price');
    const summaryShipping = document.getElementById('summary-shipping-price');
    const summaryTotal    = document.getElementById('summary-total-price');
    const totalInput      = document.getElementById('total-amount-input');
    const shippingPriceInput = document.getElementById('shipping-price-input');
    const offerInput = document.getElementById('selected-offer-input');
    const offerLabelInput = document.getElementById('selected-offer-label-input');
    const offerPaidQtyInput = document.getElementById('selected-offer-paid-qty-input');
    const offerFreeQtyInput = document.getElementById('selected-offer-free-qty-input');
    const offerTotalInput = document.getElementById('selected-offer-total-input');
    const offerTierButtons = Array.from(document.querySelectorAll('.offer-tier'));
    const bundleOfferCard = document.getElementById('bundleOfferCard');

    const state = document.getElementById('state');
    const city  = document.getElementById('city');
    const shippingSelect = document.getElementById('shipping-type');
    const shippingHidden = document.getElementById('shipping-type-input');
    const providerSelect = document.getElementById('shipping-provider-select');
    const providerHidden = document.getElementById('shipping-provider-input');
    const defaultWrap = document.getElementById('default-shipping-fields');
    const maystroWrap = document.getElementById('maystro-shipping-fields');
    const maystroState = document.getElementById('maystro-state');
    const maystroCity = document.getElementById('maystro-city');
    const maystroType = document.getElementById('maystro-delivery-type');
    const maystroPickupWrap = document.getElementById('maystro-pickup-wrap');
    const maystroPickup = document.getElementById('maystro-pickup-point');
    const maystroExpress = document.getElementById('maystro-express');
    const maystroDeliveryTypeInput = document.getElementById('shipping-delivery-type-input');
    const maystroPickupInput = document.getElementById('shipping-pickup-point-input');
    const maystroExpressInput = document.getElementById('shipping-express-input');
    const maystroStateIdInput = document.getElementById('shipping-provider-state-id-input');
    const maystroStateNameInput = document.getElementById('shipping-provider-state-name-input');
    const maystroCommuneIdInput = document.getElementById('shipping-provider-commune-id-input');
    const maystroCommuneNameInput = document.getElementById('shipping-provider-commune-name-input');

    const BASE_PRICE  = <?= (float)$finalPrice ?>;
    const OFFERS      = <?= $_offersJson ?>;
    const currency    = <?= json_encode($currency) ?>;
    const maystroEnabled = <?= json_encode((bool)$_frontendMaystroEnabled) ?>;
    let selectedOffer = null;

    function formatMoney(n) {
        const num = Number(n || 0);
        return (Math.round(num * 100) / 100).toString().replace(/\.00$/, '');
    }

    function clearOfferSelection(syncUi = true) {
        selectedOffer = null;
        if (syncUi) {
            offerTierButtons.forEach(function(el){ el.classList.remove('active'); });
            if (bundleOfferCard) bundleOfferCard.classList.remove('active');
        }
        if (offerInput) offerInput.value = '';
        if (offerLabelInput) offerLabelInput.value = '';
        if (offerPaidQtyInput) offerPaidQtyInput.value = '';
        if (offerFreeQtyInput) offerFreeQtyInput.value = '';
        if (offerTotalInput) offerTotalInput.value = '';
    }

    function syncOfferSelectionFromQty(qty) {
        if (!OFFERS || !OFFERS.enabled || !OFFERS.type) { clearOfferSelection(); return; }
        if (OFFERS.type === 'quantity_pricing') {
            const match = offerTierButtons.find(function(el){ return parseInt(el.dataset.qty || '0', 10) === qty; });
            offerTierButtons.forEach(function(el){ el.classList.toggle('active', !!match && el === match); });
            if (match) {
                selectedOffer = {
                    type: 'quantity_pricing',
                    qty: qty,
                    paid_qty: qty,
                    free_qty: 0,
                    total: parseFloat(match.dataset.price || '0'),
                    label: qty + ' × ' + formatMoney(parseFloat(match.dataset.price || '0')) + ' ' + currency
                };
                if (offerInput) offerInput.value = selectedOffer.type;
                if (offerLabelInput) offerLabelInput.value = selectedOffer.label;
                if (offerPaidQtyInput) offerPaidQtyInput.value = String(selectedOffer.paid_qty);
                if (offerFreeQtyInput) offerFreeQtyInput.value = '0';
                if (offerTotalInput) offerTotalInput.value = String(selectedOffer.total);
            } else {
                clearOfferSelection(false);
                offerTierButtons.forEach(function(el){ el.classList.remove('active'); });
            }
            if (bundleOfferCard) bundleOfferCard.classList.remove('active');
            return;
        }
        if (OFFERS.type === 'bundle_free') {
            const buy = parseInt(OFFERS.buy || 2, 10);
            const free = parseInt(OFFERS.free || 1, 10);
            const bundleQty = buy + free;
            const active = qty === bundleQty;
            if (bundleOfferCard) bundleOfferCard.classList.toggle('active', active);
            if (active) {
                selectedOffer = {
                    type: 'bundle_free',
                    qty: bundleQty,
                    paid_qty: buy,
                    free_qty: free,
                    total: buy * BASE_PRICE,
                    label: '<?= __('product.buy','Buy') ?> ' + buy + ' + ' + free + ' <?= __('product.for_free','Free') ?>'
                };
                if (offerInput) offerInput.value = selectedOffer.type;
                if (offerLabelInput) offerLabelInput.value = selectedOffer.label;
                if (offerPaidQtyInput) offerPaidQtyInput.value = String(selectedOffer.paid_qty);
                if (offerFreeQtyInput) offerFreeQtyInput.value = String(selectedOffer.free_qty);
                if (offerTotalInput) offerTotalInput.value = String(selectedOffer.total);
            } else {
                clearOfferSelection(false);
            }
            offerTierButtons.forEach(function(el){ el.classList.remove('active'); });
        }
    }

    /* ── Effective product total based on qty + offers ── */
    function effectiveProductTotal(qty) {
        if (!OFFERS || !OFFERS.enabled || !OFFERS.type) return BASE_PRICE * qty;

        if (OFFERS.type === 'quantity_pricing') {
            var tiers = (OFFERS.tiers || []).slice().sort(function(a, b) { return a.qty - b.qty; });
            var exact = tiers.find(function(t){ return parseInt(t.qty, 10) === qty; });
            if (exact) return parseFloat(exact.price || 0);
            return BASE_PRICE * qty;
        }

        if (OFFERS.type === 'bundle_free') {
            var buy = parseInt(OFFERS.buy || 2, 10);
            var free = parseInt(OFFERS.free || 1, 10);
            var bundleQty = buy + free;
            if (qty === bundleQty) return buy * BASE_PRICE;
            return BASE_PRICE * qty;
        }

        return BASE_PRICE * qty;
    }

    /* Expose productPrice for compatibility with stock script below */
    var productPrice = BASE_PRICE;
    const maystroPreloadedWilayas = [];
    const maystroPreloadedWilayasCount = Array.isArray(maystroPreloadedWilayas) ? maystroPreloadedWilayas.length : 0;
    const textState = <?= json_encode(__('checkout.state','State')) ?>;
    const textCity = <?= json_encode(__('checkout.city','City')) ?>;
    const textPickupPoint = <?= json_encode(__('checkout.pickup_point', 'Pickup Point')) ?>;

    let shippingPrice = 0;
    let shippingDisplayText = null;
    let shippingUsesCustomText = false;
    let currentProvider = providerHidden ? (providerHidden.value || '') : '';

    function updateSummary() {
        const q = parseInt(qtyInput.value || '1', 10);
        syncOfferSelectionFromQty(q);
        const p = effectiveProductTotal(q);
        const t = p + shippingPrice;
        summaryProduct.textContent  = formatMoney(p) + ' ' + currency;
        summaryShipping.textContent = shippingDisplayText ? shippingDisplayText : (shippingPrice === 0 ? <?= json_encode(__('shipping.free','Free')) ?> : (formatMoney(shippingPrice) + ' ' + currency));
        summaryTotal.textContent    = shippingUsesCustomText ? <?= json_encode(__('shipping.total_pending_with_shipping','Total after shipping confirmation')) ?> : (formatMoney(t) + ' ' + currency);
        qtyHidden.value = q;
        totalInput.value = t;
        shippingPriceInput.value = shippingPrice;
        if (offerTotalInput && selectedOffer) offerTotalInput.value = String(p);
    }

    function recalcDefaultShipping() {
        if (!state || !shippingSelect) return;
        const typeVal = shippingSelect.value || 'home';
        if (shippingHidden) shippingHidden.value = typeVal;
        if (!state.value) { shippingPrice = 0; shippingDisplayText = null; shippingUsesCustomText = false; updateSummary(); return; }
        fetch('/api/shipping/price/' + encodeURIComponent(state.value) + '/' + encodeURIComponent(city.value || 0) + '?shipping_type=' + encodeURIComponent(typeVal))
            .then(r => r.json())
            .then(data => {
                shippingDisplayText = data && data.display_text ? String(data.display_text) : null;
                shippingUsesCustomText = !!(data && data.uses_custom_text);
                shippingPrice = (data && data.price !== null && data.price !== undefined && data.price !== '') ? (parseInt(data.price, 10) || 0) : 0;
                updateSummary();
            }).catch(() => { shippingPrice = 0; updateSummary(); });
    }

    function loadDefaultStates() {
        if (!state) return;
        fetch('/api/dz/states')
            .then(r => r.json())
            .then(data => {
                state.innerHTML = '<option value="">' + textState + '</option>';
                (data || []).forEach(s => {
                    const code = String(s.code).padStart(2, '0');
                    const label = `${code} ${s.name} - ${s.ar_name || ''}`.trim();
                    state.innerHTML += `<option value="${code}" data-state-name="${s.name}" data-state-ar-name="${s.ar_name || ''}">${label}</option>`;
                });
                state.disabled = false;
            });
    }

    function setProvider(provider) {
        currentProvider = provider || '';
        if (providerHidden) providerHidden.value = currentProvider;
        const useMaystro = currentProvider === 'maystro' && maystroEnabled;
        if (defaultWrap) defaultWrap.style.display = useMaystro ? 'none' : '';
        if (maystroWrap) maystroWrap.style.display = useMaystro ? '' : 'none';
        if (state) { state.required = !useMaystro; state.disabled = useMaystro ? true : state.disabled; }
        if (city) { city.required = !useMaystro; city.disabled = useMaystro ? true : city.disabled; }
        if (!useMaystro) {
            if (state) state.disabled = false;
            if (maystroState) maystroState.required = false;
            if (maystroCity) maystroCity.required = false;
            maystroPickupInput.value = '';
            maystroExpressInput.value = '0';
            maystroDeliveryTypeInput.value = '1';
            recalcDefaultShipping();
            return;
        }
        if (maystroState) {
            maystroState.required = true;
            maystroState.disabled = false;
            if (maystroState.options.length > 1) {
                maystroState.dataset.loaded = '1';
            }
        }
        if (maystroCity) maystroCity.required = true;
        loadMaystroWilayas(true).then((count) => {
            if ((!count || count < 1) && maystroState) {
                setTimeout(() => { loadMaystroWilayas(true); }, 1200);
            }
        }).finally(() => {
            if (maystroState) maystroState.disabled = false;
        });
        recalcMaystroShipping();
    }

    function fillMaystroWilayas(rows) {
        if (!maystroState) return;
        maystroState.innerHTML = '<option value="">' + textState + '</option>';
        (Array.isArray(rows) ? rows : []).forEach(row => {
            const id = Array.isArray(row) ? row[0] : (row && row.id !== undefined ? row.id : '');
            const name = Array.isArray(row) ? row[1] : (row && (row.name ?? row.name_lt) ? (row.name ?? row.name_lt) : '');
            if (id === '' || name === '') return;
            const option = document.createElement('option');
            option.value = String(id);
            option.dataset.name = String(name);
            option.textContent = String(name);
            maystroState.appendChild(option);
        });
        maystroState.disabled = false;
        maystroState.dataset.loaded = maystroState.options.length > 1 ? '1' : '0';
    }

    function loadMaystroWilayas(forceReload = false) {
        if (!maystroState) return Promise.resolve(0);
        if (!forceReload && maystroState.options.length > 1) {
            maystroState.disabled = false;
            maystroState.dataset.loaded = '1';
            return Promise.resolve(maystroState.options.length - 1);
        }

        maystroState.innerHTML = '<option value="">' + textState + '</option>';
        maystroState.disabled = true;
        maystroState.dataset.loaded = '0';

        return fetch('/api/frontend/shipping/maystro/wilayas', {headers: {'Accept': 'application/json'}})
            .then(r => r.text())
            .then(raw => {
                let res = {};
                try { res = JSON.parse(raw); } catch (_) { res = {}; }
                const rows = Array.isArray(res) ? res : (Array.isArray(res.data) ? res.data : []);
                fillMaystroWilayas(rows);
                return rows.length;
            })
            .catch(() => {
                fillMaystroWilayas([]);
                return 0;
            })
            .finally(() => { maystroState.disabled = false; });
    }

    function loadMaystroCommunes() {
        if (!maystroState || !maystroCity) return;
        const wilayaId = maystroState.value || '';
        maystroStateIdInput.value = wilayaId;
        maystroStateNameInput.value = maystroState.options[maystroState.selectedIndex]?.dataset.name || maystroState.options[maystroState.selectedIndex]?.text || '';
        maystroCommuneIdInput.value = '';
        maystroCommuneNameInput.value = '';
        if (!wilayaId) {
            maystroCity.innerHTML = '<option value="">' + textCity + '</option>';
            maystroCity.disabled = true;
            recalcMaystroShipping();
            return;
        }
        fetch('/api/frontend/shipping/maystro/communes?wilaya_id=' + encodeURIComponent(wilayaId), {headers: {'Accept': 'application/json'}})
            .then(r => r.json())
            .then(res => {
                const rows = Array.isArray(res) ? res : (Array.isArray(res.data) ? res.data : []);
                maystroCity.innerHTML = '<option value="">' + textCity + '</option>';
                rows.forEach(row => {
                    if (!row || row.id === undefined || row.name === undefined) return;
                    maystroCity.innerHTML += `<option value="${row.id}" data-name="${row.name}">${row.name}</option>`;
                });
                maystroCity.disabled = false;
            })
            .catch(() => {
                maystroCity.innerHTML = '<option value="">' + textCity + '</option>';
                maystroCity.disabled = false;
            });
    }

    function loadMaystroPickupPoints() {
        if (!maystroPickup || !maystroCity) return;
        const communeId = maystroCity.value || '';
        maystroPickup.innerHTML = '<option value="">' + textPickupPoint + '</option>';
        maystroPickup.disabled = true;
        if (!communeId) return;
        fetch('/api/frontend/shipping/maystro/pickup-points/' + encodeURIComponent(communeId), {headers: {'Accept': 'application/json'}})
            .then(r => r.json())
            .then(res => {
                const rows = Array.isArray(res) ? res : (Array.isArray(res.data) ? res.data : []);
                rows.forEach(row => {
                    if (!row || !row.pickup_point) return;
                    const label = row.name_ar || row.name_lt || ('Point #' + row.pickup_point);
                    maystroPickup.innerHTML += `<option value="${row.pickup_point}">${label}</option>`;
                });
                maystroPickup.disabled = false;
            })
            .catch(() => {
                maystroPickup.disabled = false;
            });
    }

    function syncMaystroType() {
        if (!maystroType || !shippingHidden) return;
        const typeVal = String(maystroType.value || '1');
        maystroDeliveryTypeInput.value = typeVal;
        shippingHidden.value = ({'1':'home','2':'desk','3':'pickup'})[typeVal] || 'home';
        if (maystroPickupWrap) maystroPickupWrap.style.display = typeVal === '3' ? '' : 'none';
        if (typeVal !== '3') {
            maystroPickupInput.value = '';
            if (maystroPickup) maystroPickup.value = '';
        }
    }

    function recalcMaystroShipping() {
        if (currentProvider !== 'maystro') return;
        syncMaystroType();
        maystroExpressInput.value = maystroExpress && maystroExpress.checked ? '1' : '0';
        if (!maystroCity || !maystroCity.value) {
            shippingPrice = 0;
            shippingDisplayText = null;
            shippingUsesCustomText = false;
            updateSummary();
            return;
        }
        const typeVal = maystroDeliveryTypeInput.value || '1';
        fetch('/api/frontend/shipping/maystro/delivery-price/' + encodeURIComponent(maystroCity.value) + '?delivery_type=' + encodeURIComponent(typeVal), {headers: {'Accept': 'application/json'}})
            .then(r => r.json())
            .then(res => {
                const p = res && res.price !== null && res.price !== undefined && res.price !== '' ? parseFloat(res.price) : 0;
                shippingPrice = isNaN(p) ? 0 : p;
                shippingDisplayText = null;
                shippingUsesCustomText = false;
                updateSummary();
                if (typeVal === '3') loadMaystroPickupPoints();
            }).catch(() => { shippingPrice = 0; updateSummary(); });
    }

    qtyPlus && qtyPlus.addEventListener('click', function () {
        var current = parseInt(qtyInput.value, 10);
        var maxQty  = parseInt(qtyInput.dataset.max || '9999', 10);
        if (current < maxQty) qtyInput.value = String(current + 1);
        updateSummary();
    });

    qtyMinus && qtyMinus.addEventListener('click', function () {
        const v = parseInt(qtyInput.value, 10);
        if (v > 1) qtyInput.value = String(v - 1);
        updateSummary();
    });

    offerTierButtons.forEach(function(btn){
        btn.addEventListener('click', function(){
            var qty = parseInt(this.dataset.qty || '1', 10);
            qtyInput.value = String(Math.max(1, qty));
            selectedOffer = {
                type: 'quantity_pricing',
                qty: qty,
                paid_qty: qty,
                free_qty: 0,
                total: parseFloat(this.dataset.price || '0'),
                label: qty + ' × ' + formatMoney(parseFloat(this.dataset.price || '0')) + ' ' + currency
            };
            updateSummary();
        });
    });

    if (bundleOfferCard) {
        bundleOfferCard.addEventListener('click', function(){
            var qty = parseInt(this.dataset.qty || '1', 10);
            qtyInput.value = String(Math.max(1, qty));
            selectedOffer = {
                type: 'bundle_free',
                qty: qty,
                paid_qty: parseInt(OFFERS.buy || 2, 10),
                free_qty: parseInt(OFFERS.free || 1, 10),
                total: parseInt(OFFERS.buy || 2, 10) * BASE_PRICE,
                label: '<?= __('product.buy','Buy') ?> ' + (parseInt(OFFERS.buy || 2, 10)) + ' + ' + (parseInt(OFFERS.free || 1, 10)) + ' <?= __('product.for_free','Free') ?>'
            };
            updateSummary();
        });
    }

    if (shippingSelect) shippingSelect.addEventListener('change', recalcDefaultShipping);
    if (state) state.addEventListener('change', function () {
        document.getElementById('state-code-input').value = String(this.value || '').padStart(2, '0');
        const selected = this.options[this.selectedIndex];
        document.getElementById('state-name-input').value = selected ? (selected.dataset.stateName || '') : '';
        document.getElementById('city-id-input').value = '';
        document.getElementById('city-name-input').value = '';
        fetch('/api/dz/cities/' + encodeURIComponent(this.value))
            .then(r => r.json())
            .then(data => {
                city.innerHTML = '<option value="">' + textCity + '</option>';
                (data || []).forEach(c => {
                    city.innerHTML += `<option value="${c.id}" data-city-name="${c.name}">${c.name}</option>`;
                });
                city.disabled = false;
            });
        recalcDefaultShipping();
    });

    if (city) city.addEventListener('change', function () {
        const selectedCity = this.options[this.selectedIndex];
        const cityName = selectedCity ? (selectedCity.dataset.cityName || selectedCity.text || '') : '';
        document.getElementById('city-id-input').value = this.value || '';
        document.getElementById('city-name-input').value = cityName;
        recalcDefaultShipping();
    });

    if (providerSelect) providerSelect.addEventListener('change', function(){ setProvider(this.value || ''); });
    if (maystroState) maystroState.addEventListener('change', loadMaystroCommunes);
    if (maystroCity) maystroCity.addEventListener('change', function(){
        maystroCommuneIdInput.value = this.value || '';
        maystroCommuneNameInput.value = this.options[this.selectedIndex]?.dataset.name || this.options[this.selectedIndex]?.text || '';
        document.getElementById('city-id-input').value = this.value || '';
        document.getElementById('city-name-input').value = maystroCommuneNameInput.value;
        document.getElementById('state-code-input').value = String(maystroState.value || '').padStart(2, '0');
        document.getElementById('state-name-input').value = maystroStateNameInput.value;
        recalcMaystroShipping();
    });
    if (maystroType) maystroType.addEventListener('change', recalcMaystroShipping);
    if (maystroPickup) maystroPickup.addEventListener('change', function(){ maystroPickupInput.value = this.value || ''; });
    if (maystroExpress) maystroExpress.addEventListener('change', recalcMaystroShipping);

    loadDefaultStates();
    setProvider(currentProvider);
    updateSummary();
})();
</script>

<script>
(function () {
    const media = document.querySelector('.hero-media');
    if (!media) return;

    const img = media.querySelector('img');
    if (!img) return;

    if (window.matchMedia('(hover: hover)').matches) {
        media.addEventListener('mousemove', function (e) {
            const rect = media.getBoundingClientRect();
            const x = ((e.clientX - rect.left) / rect.width) * 100;
            const y = ((e.clientY - rect.top) / rect.height) * 100;

            img.style.transformOrigin = x + '% ' + y + '%';
            img.style.transform = 'scale(1.8)';
        });

        media.addEventListener('mouseleave', function () {
            img.style.transform = 'scale(1)';
            img.style.transformOrigin = 'center center';
        });
    }
})();
</script>
<script>
(function () {
    const stars = document.querySelectorAll('#ratingInput span');
    const ratingInput = document.getElementById('ratingValue');

    stars.forEach(star => {
        star.addEventListener('click', function () {
            const value = parseInt(this.dataset.value, 10);
            ratingInput.value = value;

            stars.forEach(s => {
                s.classList.toggle('active', parseInt(s.dataset.value, 10) <= value);
            });
        });
    });
})();
</script>

<?php if ($reviewsEnabled): ?>
<script>
(function () {
    const grid = document.querySelector('.products-cards-grid.is-slider');
    if (!grid) {
        return;
    }

    const prev = document.querySelector('.reviews-arrow-prev');
    const next = document.querySelector('.reviews-arrow-next');

    const step = grid.querySelector('.review-card-arhasoft')?.offsetWidth + 20 || 300;

    next && next.addEventListener('click', () => {
        grid.scrollLeft += step;
    });

    prev && prev.addEventListener('click', () => {
        grid.scrollLeft -= step;
    });

        scrollWidth: grid.scrollWidth,
        clientWidth: grid.clientWidth
    });
})();
</script>
<?php endif; ?>

<script>
(function () {
    const bar = document.querySelector('.product-sticky-bar');
    if (!bar) return;

    const hasBuy = bar.dataset.stickyBuy === '1';
    const hasWa  = bar.dataset.stickyWa === '1';

    // واتساب دائم
    if (hasWa) {
        bar.classList.add('is-visible');
        document.body.classList.add('has-sticky-bar');
    }

    // لو زر شراء غير مفعّل لا نراقب شيء
    if (!hasBuy) return;

    const reviews = document.querySelector('#reviews');
    if (!reviews) return;

    const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                bar.classList.add('is-visible');
                document.body.classList.add('has-sticky-bar');
            } else {
                // نخفي فقط زر الشراء إذا الواتساب غير مفعّل
                if (!hasWa) {
                    bar.classList.remove('is-visible');
                    document.body.classList.remove('has-sticky-bar');
                }
            }
        });
    }, {
        threshold: 0.2
    });

    observer.observe(reviews);
})();
</script>
<script>
document.addEventListener('click', function (e) {
    const btn = e.target.closest('[data-scroll-to]');
    if (!btn) return;

    const target = document.querySelector(btn.dataset.scrollTo);
    if (!target) return;

    target.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
    });
});
</script>
<script>
(function () {
    const stickyBar = document.querySelector('.product-sticky-bar');
    const reviewsSection = document.querySelector('#reviews');

    if (!stickyBar || !reviewsSection) return;

    const observer = new IntersectionObserver(
        ([entry]) => {
            if (entry.isIntersecting) {
                stickyBar.classList.add('is-visible');
                document.body.classList.add('has-sticky-bar');
            } else {
                stickyBar.classList.remove('is-visible');
                document.body.classList.remove('has-sticky-bar');
            }
        },
        {
            root: null,
            threshold: 0.15
        }
    );

    observer.observe(reviewsSection);
})();
</script>
<script>
(function () {
    const countdown = document.querySelector('.product-countdown');
    if (!countdown) return;

    let remaining = parseInt(countdown.dataset.remaining, 10);
    if (isNaN(remaining) || remaining <= 0) {
        countdown.remove();
        return;
    }

    const dEl = countdown.querySelector('[data-days]');
    const hEl = countdown.querySelector('[data-hours]');
    const mEl = countdown.querySelector('[data-minutes]');
    const sEl = countdown.querySelector('[data-seconds]');

    function pad(n) {
        return n < 10 ? '0' + n : n;
    }

    function tick() {
        if (remaining <= 0) {
            countdown.remove();
            return;
        }

        const days    = Math.floor(remaining / 86400);
        const hours   = Math.floor((remaining % 86400) / 3600);
        const minutes = Math.floor((remaining % 3600) / 60);
        const seconds = remaining % 60;

        dEl.textContent = pad(days);
        hEl.textContent = pad(hours);
        mEl.textContent = pad(minutes);
        sEl.textContent = pad(seconds);

        /* آخر 24 ساعة */
        if (remaining <= 86400) {
            countdown.classList.add('is-ending');
        }

        remaining--;
    }

    tick();
    setInterval(tick, 1000);
})();

</script>



<!-- ── Thumbnails Strip Logic ── -->
<script>
(function () {
    var mainImg  = document.getElementById('product-main-image');
    var wrapper = document.getElementById('gal-thumbs-wrapper');
    var media = document.querySelector('.hero-media[data-auto-rotate]');
    if (!mainImg || !wrapper) return;

    var track   = document.getElementById('gal-track');
    var thumbs  = Array.from(wrapper.querySelectorAll('.gal-thumb'));
    var prevBtn = document.getElementById('gal-prev');
    var nextBtn = document.getElementById('gal-next');
    var VISIBLE = 4;
    var offset  = 0;
    var activeIndex = Math.max(0, thumbs.findIndex(function(t){ return t.classList.contains('is-active'); }));
    var autoRotate = (media?.dataset.autoRotate || '1') === '1';
    var timer = null;

    if (thumbs.length > VISIBLE) {
        if (prevBtn) prevBtn.style.display = '';
        if (nextBtn) nextBtn.style.display = '';
    }

    function getThumbWidth() {
        if (!thumbs[0]) return 0;
        return thumbs[0].offsetWidth + 6;
    }

    function updateTrack() {
        var px  = offset * getThumbWidth();
        var dir = document.documentElement.dir || 'rtl';
        track.style.transform = dir === 'rtl'
            ? 'translateX(' + px + 'px)'
            : 'translateX(-' + px + 'px)';
    }

    function syncOffset() {
        if (activeIndex < offset) offset = activeIndex;
        if (activeIndex > offset + VISIBLE - 1) offset = activeIndex - VISIBLE + 1;
        if (offset < 0) offset = 0;
        if (offset > Math.max(0, thumbs.length - VISIBLE)) offset = Math.max(0, thumbs.length - VISIBLE);
        updateTrack();
    }

    function setActive(btn, fromUser) {
        thumbs.forEach(function(t){ t.classList.remove('is-active'); });
        btn.classList.add('is-active');
        activeIndex = Math.max(0, thumbs.indexOf(btn));
        mainImg.src = btn.dataset.src || mainImg.src;
        mainImg.style.transform = '';
        syncOffset();
        if (fromUser) restartAuto();
    }

    thumbs.forEach(function(btn) {
        btn.addEventListener('click', function() { setActive(btn, true); });
    });

    if (prevBtn) prevBtn.addEventListener('click', function() {
        activeIndex = activeIndex <= 0 ? thumbs.length - 1 : activeIndex - 1;
        setActive(thumbs[activeIndex], true);
    });

    if (nextBtn) nextBtn.addEventListener('click', function() {
        activeIndex = activeIndex >= thumbs.length - 1 ? 0 : activeIndex + 1;
        setActive(thumbs[activeIndex], true);
    });

    function stopAuto(){ if (timer) { clearInterval(timer); timer = null; } }
    function startAuto(){
        stopAuto();
        if (!autoRotate || thumbs.length < 2) return;
        timer = setInterval(function(){
            activeIndex = activeIndex >= thumbs.length - 1 ? 0 : activeIndex + 1;
            setActive(thumbs[activeIndex], false);
        }, 2800);
    }
    function restartAuto(){ stopAuto(); startAuto(); }

    wrapper.addEventListener('mouseenter', stopAuto);
    wrapper.addEventListener('mouseleave', startAuto);
    window.addEventListener('resize', function() { syncOffset(); });
    syncOffset();
    startAuto();
})();
</script>

<script>
<?php
$_hasSizes  = !empty($sizes);
$_hasColors = !empty($colors);
?>
function showInlineOrderError(message) {
    var box = document.getElementById('variant-inline-error');
    if (!box) return;
    var text = box.querySelector('.checkout-inline-error-text');
    if (text) text.textContent = message || '';
    box.style.display = message ? 'flex' : 'none';
    box.classList.toggle('is-visible', !!message);
}

function validateVariantForm(e) {
    var hasSizes  = <?= $_hasSizes  ? 'true' : 'false' ?>;
    var hasColors = <?= $_hasColors ? 'true' : 'false' ?>;

    if (hasSizes) {
        var sizeVal = document.getElementById('variant-size-input') ? document.getElementById('variant-size-input').value : '';
        if (!sizeVal) {
            e.preventDefault();
            showInlineOrderError('<?= __("checkout.please_select_size", "يرجى اختيار المقاس أولاً") ?>');
            document.querySelector('.variant-size')?.closest('.variant-group')?.classList.add('variant-required');
            return false;
        }
    }

    if (hasColors) {
        var colorVal = document.getElementById('variant-color-input') ? document.getElementById('variant-color-input').value : '';
        if (!colorVal) {
            e.preventDefault();
            showInlineOrderError('<?= __("checkout.please_select_color", "يرجى اختيار اللون أولاً") ?>');
            document.querySelector('.variant-color')?.closest('.variant-group')?.classList.add('variant-required');
            return false;
        }
    }

    showInlineOrderError('');
    return true;
}

document.querySelectorAll('.variant-size, .variant-color').forEach(function(btn) {
    btn.addEventListener('click', function() {
        this.closest('.variant-group')?.classList.remove('variant-required');
        var sizeOk = !<?= $_hasSizes  ? 'true' : 'false' ?> || (document.getElementById('variant-size-input') && document.getElementById('variant-size-input').value);
        var colorOk = !<?= $_hasColors ? 'true' : 'false' ?> || (document.getElementById('variant-color-input') && document.getElementById('variant-color-input').value);
        if (sizeOk && colorOk) showInlineOrderError('');
    });
});
</script>

<style>
.checkout-inline-error{
    display:flex;
    align-items:flex-start;
    gap:10px;
    margin:12px 0 16px;
    padding:12px 14px;
    border-radius:12px;
    background:#fff7ed;
    border:1px solid #fdba74;
    color:#9a3412;
    font-size:14px;
    line-height:1.6;
}
.checkout-inline-error-icon{
    flex:0 0 auto;
    font-size:16px;
    line-height:1.2;
}
.checkout-inline-error.is-visible{
    animation: fadeInUp .18s ease-out;
}
@keyframes fadeInUp{
    from{opacity:0; transform:translateY(4px);}
    to{opacity:1; transform:none;}
}
</style>

<style id="variant-size-shape-lock">
.product-page .product-variants {
    display: flex !important;
    flex-direction: column !important;
    gap: 10px !important;
}
.product-page .variant-group {
    display: grid !important;
    grid-template-columns: max-content 1fr !important;
    align-items: center !important;
    column-gap: 10px !important;
    margin-bottom: 0 !important;
}
.product-page .variant-label {
    margin: 0 !important;
    min-width: 64px !important;
    justify-content: flex-start !important;
    white-space: nowrap !important;
}
.product-page .variant-options {
    display: flex !important;
    flex-wrap: wrap !important;
    gap: 6px !important;
    align-items: center !important;
    min-height: 44px !important;
}
.product-page #vg-size .variant-item.variant-size,
.product-page #vg-size .variant-size,
.product-page #vg-size button.variant-size,
.product-page #vg-color .variant-color,
.product-page #vg-color button.variant-color {
    width: 44px !important;
    min-width: 44px !important;
    max-width: 44px !important;
    height: 44px !important;
    min-height: 44px !important;
    max-height: 44px !important;
    flex: 0 0 44px !important;
    aspect-ratio: 1 / 1 !important;
    padding: 0 !important;
    border-radius: 8px !important;
    box-sizing: border-box !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    line-height: 1 !important;
}
.product-page #vg-color .variant-color-wrap {
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
}
@media (max-width: 575.98px) {
    .product-page .variant-group {
        grid-template-columns: 56px 1fr !important;
        column-gap: 8px !important;
    }
    .product-page .variant-label {
        min-width: 56px !important;
        font-size: 11px !important;
    }
}
</style>
