<?php
$pseudo   = $pseudo   ?? $creator['username'];
$username = $username ?? $creator['username'];
$backUrl  = $backUrl  ?? BASE_URL . '/createur/' . urlencode($username) . '/boutique';
$avatarUrl = $creator['avatar_url'] ?? null;
$coverUrl  = $creator['cover_url']  ?? null;
$bio       = $creator['bio']        ?? null;
$cats      = $creator['categories'] ?? [];
$product   = $product  ?? [];
$variants  = $variants ?? [];
$images    = $images   ?? [];

// Photo principale → visible uniquement dans la colonne gauche
$allPhotos = [];
if (!empty($product['image_url'])) {
    $allPhotos[] = ['url' => $product['image_url'], 'color_name' => null, 'zone' => 'left'];
}
foreach ($images as $img) {
    $allPhotos[] = [
        'url'        => $img['image_url'],
        'color_name' => $img['color_name'] ?? null,
        'reference'  => $img['reference']  ?? null,
        'zone'       => $img['display_zone'] ?? 'both',
        'price'      => $img['price'] ?? null,
    ];
    if (count($allPhotos) >= 20) break;
}

// Filtres par zone — on conserve l'index original dans $allPhotos pour la sync JS
$leftPhotos   = [];
$rightPhotos  = [];
$columnPhotos = [];
foreach ($allPhotos as $i => $p) {
    $p['allIdx'] = $i;
    if (in_array($p['zone'], ['both','left'],  true)) $leftPhotos[]   = $p;
    if (in_array($p['zone'], ['both','right'], true)) $rightPhotos[]  = $p;
    if ($p['zone'] === 'column')                      $columnPhotos[] = $p;
}
$colVisible = 4; // nombre de lignes visibles avant "Plus ▼"

$price       = (float)($product['price'] ?? 0);
$hasVariants = !empty($variants);
$hasColors   = !empty(array_filter(array_column($variants, 'color')));

$resolveUrl = static fn(string $url): string =>
    (str_starts_with($url, 'http://') || str_starts_with($url, 'https://') || str_starts_with($url, '//'))
    ? $url : BASE_URL . $url;
?>
<style>
. /* ── Sidebar layout (same as boutique) ── */
/* (avatar global rule removed to preserve header avatar) */
.cshow-wrap {
    display: flex; gap: 0;
    min-height: calc(100vh - 110px);
    max-width: 1400px; margin: 2rem auto;
    border: 1px solid var(--color-border);
    border-radius: 14px; overflow: hidden;
    background: var(--color-bg-card);
}
.cshow-sidebar {
    display: none !important;
}
.cshow-content {
    width: 100%;
}
.cshow-back {
    display: flex; align-items: center; gap: .5rem;
    padding: .45rem .7rem; border-radius: 8px;
    color: var(--color-text-muted); font-size: .82rem;
    text-decoration: none; margin-bottom: 1.5rem;
    transition: background .15s, color .15s;
}
.cshow-back:hover { background: var(--color-accent-muted); color: var(--color-accent); }
.cshow-back i { font-size: .95rem; }
.cshow-sidebar-section {
    font-size: .7rem; font-weight: 700; letter-spacing: .08em;
    text-transform: uppercase; color: var(--color-text-muted);
    margin-bottom: .6rem; padding-left: .3rem;
}
.cshow-bio { font-size: .8rem; color: var(--color-text-muted); line-height: 1.55; margin-bottom: 1.1rem; }
.cshow-cats { display: flex; flex-wrap: wrap; gap: .35rem; }
.cshow-cat-pill {
    font-size: .72rem; padding: .2rem .55rem; border-radius: 999px;
    background: var(--color-accent-muted); color: var(--color-accent); font-weight: 500;
}
.cshow-content { flex: 1; min-width: 0; overflow: hidden; }

/* ── Product layout ── */
.cp-wrap { padding: 2rem 1.5rem 3rem; }
/* [photo principale] [vignettes droite] [panneau info] */
.cp-layout { display: flex; gap: 1rem; align-items: flex-start; }

/* Grande photo - flex:1 */
    .cp-thumbs { flex: 0 0 72px; }
    .cp-main-wrap { flex: 0 0 calc(50% - 72px - 1rem); min-width: 0; }
    .cp-main-box {
        position: relative; width: 100%;
        aspect-ratio: 1 / 1; max-height: 520px;
    border-radius: 14px; overflow: hidden;
    background: var(--color-bg-secondary);
    border: 1px solid var(--color-border);
}
.cp-main-box img { width: 100%; height: 100%; object-fit: contain; object-position: center; display: block; cursor: zoom-in; }
.cp-zoom-lens {
    position: absolute; width: 180px; height: 180px;
    border: 2px solid rgba(255,255,255,.85);
    border-radius: 50%; box-shadow: 0 0 30px rgba(0,0,0,.25);
    pointer-events: none; z-index: 3;
    background-repeat: no-repeat; background-size: 720%;
    transform: translate(-50%, -50%);
}
.cp-lightbox {
    position: fixed; inset: 0; z-index: 9999;
    background: rgba(0,0,0,.92);
    display: none; align-items: center; justify-content: center;
}
.cp-lightbox.active { display: flex; }
.cp-lightbox-box { position: relative; max-width: 92vw; max-height: 92vh; }
.cp-lightbox-box img { max-width: 92vw; max-height: 92vh; object-fit: contain; display: block; cursor: zoom-in; }
.cp-lightbox-close {
    position: absolute; top: -2.5rem; right: 0;
    background: none; border: none; color: #fff; font-size: 2rem;
    line-height: 1; cursor: pointer; opacity: .8;
}
.cp-lightbox-close:hover { opacity: 1; }
.cp-lightbox-zoom-lens {
    position: absolute; width: 220px; height: 220px;
    border: 2px solid rgba(255,255,255,.85);
    border-radius: 50%; box-shadow: 0 0 30px rgba(0,0,0,.4);
    pointer-events: none; z-index: 3;
    background-repeat: no-repeat; background-size: 500%;
    transform: translate(-50%, -50%);
}
.cp-main-placeholder {
    width: 100%; height: 100%;
    display: flex; align-items: center; justify-content: center;
    color: var(--color-text-muted); font-size: 4rem; opacity: .25;
}
.cp-nav-btn {
    position: absolute; top: 50%; transform: translateY(-50%);
    background: rgba(0,0,0,.55); border: none; color: #fff;
    width: 38px; height: 38px; border-radius: 50%; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    transition: background .15s; z-index: 2;
}
.cp-nav-btn:hover { background: rgba(0,0,0,.8); }
.cp-nav-prev { left: .7rem; }
.cp-nav-next { right: .7rem; }

/* Vignettes verticales à droite de la photo */
.cp-thumbs {
    display: flex; flex-direction: column; gap: .4rem;
    width: 72px; flex-shrink: 0; max-height: 480px; overflow-y: auto;
    scrollbar-width: thin;
}
.cp-thumb {
    width: 72px; height: 72px; border-radius: 8px; overflow: hidden;
    cursor: pointer; border: 2px solid transparent;
    background: var(--color-bg-secondary);
    display: flex; align-items: center; justify-content: center;
    transition: border-color .18s, opacity .18s; flex-shrink: 0;
}
.cp-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.cp-thumb.active { border-color: var(--color-accent); opacity: 1; }
.cp-thumb:not(.active) { opacity: .55; }
.cp-thumb:hover:not(.active) { opacity: 1; border-color: var(--color-border-hover); }

/* Grille mini-vignettes dans le panneau info (sous Quantité) */
.cp-mini-strip {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: .3rem;
    margin-bottom: .75rem;
}
.cp-mini-thumb {
    aspect-ratio: 1 / 1;
    border-radius: 7px; overflow: hidden;
    cursor: pointer; border: 2px solid transparent;
    transition: border-color .15s, opacity .15s;
    opacity: .6;
}
.cp-mini-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.cp-mini-thumb.active { border-color: var(--color-accent); opacity: 1; }
.cp-mini-thumb:hover { opacity: 1; }

/* Panneau info à droite */
    .cp-info { width: 50%; min-width: 300px; flex: 0 0 50%; }

/* Liste colonne (zone ↓) */
.cp-col-list { display: flex; flex-direction: column; gap: .35rem; margin-bottom: .75rem; }
.cp-col-row {
    display: flex; align-items: center; gap: .6rem;
    padding: .5rem .65rem; border-radius: 10px;
    background: var(--color-bg-secondary);
    border: 1px solid var(--color-border);
    transition: border-color .15s;
}
.cp-col-row:hover { border-color: var(--color-border-hover); }
.cp-col-thumb {
    width: 52px; height: 52px; border-radius: 8px;
    object-fit: cover; flex-shrink: 0; cursor: pointer;
    border: 2px solid transparent; transition: border-color .15s;
}
.cp-col-thumb:hover { border-color: var(--color-accent); }
.cp-col-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: .3rem; }
.cp-col-label { font-size: .83rem; font-weight: 600;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cp-col-ref { font-size: .68rem; font-weight: 400; font-family: monospace;
    color: var(--color-text-muted); margin-left: .35rem; opacity: .75; }
.cp-col-footer { display: flex; align-items: center; gap: .5rem; }
.cp-col-price { font-size: .8rem; font-weight: 700; color: var(--color-accent);
    white-space: nowrap; flex: 1; }
.cp-col-qty { display: flex; align-items: center; gap: .25rem; flex-shrink: 0; }
.cp-col-btn {
    width: 26px; height: 26px; border-radius: 50%;
    border: 1px solid var(--color-border); background: var(--color-bg-card);
    color: var(--color-text); cursor: pointer; font-size: .88rem;
    display: flex; align-items: center; justify-content: center;
    transition: background .12s, border-color .12s; line-height: 1;
}
.cp-col-btn:hover { background: var(--color-accent-muted); border-color: var(--color-accent); }
.cp-col-val { min-width: 22px; text-align: center; font-weight: 700; font-size: .83rem; }
.cp-col-more {
    width: 100%; padding: .4rem; font-size: .78rem; font-weight: 700;
    border: 1px solid var(--color-border); border-radius: 8px;
    background: var(--color-bg-card); color: var(--color-accent);
    cursor: pointer; transition: background .15s;
    display: flex; align-items: center; justify-content: center; gap: .35rem;
}
.cp-col-more:hover { background: var(--color-accent-muted); }
.cp-section-lbl {
    font-size: .72rem; font-weight: 700; text-transform: uppercase;
    letter-spacing: .09em; color: var(--color-text-muted); margin-bottom: .5rem;
}
.cp-color-swatches { display: flex; gap: .45rem; flex-wrap: wrap; }
.cp-cswatch {
    width: 46px; height: 46px; border-radius: 9px; overflow: hidden;
    cursor: pointer; border: 2.5px solid transparent;
    transition: border-color .15s, transform .12s; flex-shrink: 0;
}
.cp-cswatch img { width: 100%; height: 100%; object-fit: cover; display: block; }
.cp-cswatch.active { border-color: var(--color-accent); }
.cp-cswatch:hover:not(.active) { transform: scale(1.06); }
.cp-cswatch-text {
    min-width: 46px; height: 32px; padding: 0 .6rem; border-radius: 20px;
    font-size: .74rem; font-weight: 600;
    background: var(--color-bg-secondary); border: 1.5px solid var(--color-border);
    color: var(--color-text-muted); cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    transition: background .15s, border-color .15s, color .15s;
}
.cp-cswatch-text.active {
    background: var(--color-accent-muted);
    border-color: var(--color-accent); color: var(--color-accent);
}
.cp-size-rows { display: flex; flex-direction: column; gap: .35rem; }
.cp-size-row {
    display: flex; align-items: center; gap: .55rem;
    padding: .5rem .7rem; border-radius: 9px;
    background: var(--color-bg-secondary);
    border: 1px solid var(--color-border); transition: border-color .15s;
}
.cp-size-row.oos { opacity: .45; }
.cp-size-lbl { font-weight: 600; min-width: 52px; font-size: .86rem; }
.cp-size-price { font-size: .8rem; color: var(--color-text-muted); flex: 1; }
.cp-qty-ctrl { display: flex; align-items: center; gap: .3rem; }
.cp-qty-btn {
    width: 26px; height: 26px; border-radius: 50%;
    border: 1px solid var(--color-border); background: var(--color-bg-card);
    color: var(--color-text); cursor: pointer; font-size: .9rem;
    display: flex; align-items: center; justify-content: center;
    transition: background .12s, border-color .12s; line-height: 1;
}
.cp-qty-btn:hover:not(:disabled) { background: var(--color-accent-muted); border-color: var(--color-accent); }
.cp-qty-btn:disabled { opacity: .35; cursor: not-allowed; }
.cp-qty-val { min-width: 22px; text-align: center; font-weight: 700; font-size: .86rem; }
.cp-stock-lbl { font-size: .68rem; white-space: nowrap; min-width: 52px; text-align: right; }
.cp-btn-cart {
    width: 100%; padding: .85rem 1rem;
    font-size: 1rem; font-weight: 700; border: none; border-radius: 12px;
    background: var(--color-accent); color: #fff; cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: .55rem;
    transition: background .18s, transform .1s;
}
.cp-btn-cart:hover { opacity: .88; }
.cp-heart-btn {
    display: inline-flex; align-items: center; gap: .6rem;
    padding: 1.1rem 1.4rem; border: 1px solid var(--color-border);
    border-radius: 16px; background: var(--color-bg-secondary);
    color: var(--color-text); font-weight: 700; font-size: 1.05rem;
    cursor: pointer; transition: background .18s, border-color .18s, transform .1s;
}
.cp-heart-btn:hover { background: var(--color-accent-muted); border-color: var(--color-accent); }
.cp-heart-btn i { color: #eb4d4b; font-size: 1.4rem; }
.cp-heart-btn span { min-width: 28px; text-align: center; font-size: 1.05rem; }
.cp-btn-cart:active { transform: scale(.985); }
.cp-btn-cart:disabled { opacity: .5; cursor: not-allowed; }

/* ── Responsive ── */
@media (max-width: 900px) {
    .cp-info { width: 260px; min-width: 220px; }
}
@media (max-width: 700px) {
    .cshow-wrap { flex-direction: column; margin: 0; border-radius: 0; border: none; }
    .cshow-sidebar { width: 100%; min-width: unset; position: static; max-height: none; padding: 1rem; }
    .cp-wrap { padding: 1rem .75rem 2rem; }
    .cp-layout { flex-direction: column; }
    /* Sur mobile : vignettes verticales → horizontales sous la photo */
    .cp-thumbs {
        flex-direction: row; width: 100%; max-height: none;
        overflow-x: auto; overflow-y: hidden;
    }
    .cp-thumb { width: 60px; height: 60px; }
    .cp-info { width: 100%; min-width: unset; }
    .cp-main-box { max-height: 320px; }
}
</style>

<div class="cshow-wrap">

    <!-- ══ CONTENU ══ -->
    <div class="cshow-content">
        <div class="cp-wrap">

            <!-- Fil d'ariane -->
            <nav class="mb-4" style="font-size:.82rem; display:flex; gap:.6rem; align-items:center;">
                <a href="<?= $backUrl ?>" style="color:var(--color-accent);text-decoration:none;font-weight:600;">← Retour</a>
                <div style="color:var(--color-accent);font-weight:700;display:flex;align-items:center;gap:.35rem;">
                    <i class="bi bi-shop"></i>
                    Boutique de <?= htmlspecialchars($pseudo) ?>
                </div>
                <span style="color:var(--color-text-muted);margin:0 .5rem;">/</span>
                <span style="color:var(--color-text-muted);"><?= htmlspecialchars($product['name'] ?? '') ?></span>
            </nav>

            <div class="cp-layout">

                <!-- Vignettes gauche (miniatures verticales) -->
                <?php if (!empty($leftPhotos)): ?>
                <div class="cp-thumbs" id="cpThumbs">
                    <?php foreach ($leftPhotos as $photo): ?>
                    <div class="cp-thumb <?= $photo['allIdx'] === 0 ? 'active' : '' ?>" data-idx="<?= $photo['allIdx'] ?>"
                         onclick="cpCurrentZone='left'; cpShowPhoto(<?= $photo['allIdx'] ?>)">
                        <img src="<?= htmlspecialchars($resolveUrl($photo['url'])) ?>"
                             alt="<?= !empty($photo['color_name']) ? htmlspecialchars($photo['color_name']) : '' ?>"
                             loading="<?= $photo['allIdx'] === 0 ? 'eager' : 'lazy' ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- Photo principale -->
                <div class="cp-main-wrap">
                    <div class="cp-main-box">
                        <?php if (!empty($allPhotos)): ?>
                        <img id="cpMainPhoto"
                             src="<?= htmlspecialchars($resolveUrl($allPhotos[0]['url'])) ?>"
                             alt="<?= htmlspecialchars($product['name'] ?? '') ?>"
                             onclick="cpOpenLightbox()">
                        <?php else: ?>
                        <div class="cp-main-placeholder"><i class="bi bi-box-seam"></i></div>
                        <?php endif; ?>

                        <?php if (count($allPhotos) > 1): ?>
                        <button class="cp-nav-btn cp-nav-prev" onclick="cpPrev()">
                            <i class="bi bi-chevron-left"></i>
                        </button>
                        <button class="cp-nav-btn cp-nav-next" onclick="cpNext()">
                            <i class="bi bi-chevron-right"></i>
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Infos produit -->
                <div class="cp-info">
                
                    <h1 style="font-family:var(--font-heading);font-size:1.3rem;line-height:1.3;margin-bottom:.4rem;font-weight:700;">
                        <?= htmlspecialchars($product['name'] ?? '') ?>
                    </h1>

                    <?php if (!empty($product['reference'])): ?>
                    <div style="font-size:.72rem;color:var(--color-text-muted);font-family:monospace;margin-bottom:.6rem;">
                        <?= htmlspecialchars($product['reference']) ?>
                    </div>
                    <?php endif; ?>

                    <div style="font-size:1.8rem;font-weight:800;color:var(--color-accent);margin-bottom:.85rem;line-height:1;">
                        <?= number_format($price, 2) ?> €
                    </div>

                    <?php if (!empty($product['short_description'])): ?>
                    <p style="font-size:.86rem;color:var(--color-text-muted);line-height:1.6;margin-bottom:.85rem;">
                        <?= nl2br(htmlspecialchars($product['short_description'])) ?>
                    </p>
                    <?php endif; ?>

                    <?php if ($hasColors): ?>
                    <div class="mb-3" id="cpColorSection">
                        <div class="cp-section-lbl">
                            Couleur :
                            <span id="cpColorLabel" style="text-transform:none;font-weight:700;color:var(--color-text);"></span>
                        </div>
                        <div class="cp-color-swatches" id="cpColorSwatches"></div>
                    </div>
                    <?php endif; ?>

                    <hr style="border-color:var(--color-border);margin:.85rem 0;">

                    <?php if ($hasVariants): ?>
                    <div class="cp-size-rows mb-3" id="cpSizeRows"></div>
                    <?php else: ?>
                    <div class="d-flex align-items-center gap-3 mb-3">
                        <div class="cp-section-lbl mb-0">Quantité</div>
                        <div class="cp-qty-ctrl">
                            <button class="cp-qty-btn" onclick="cpChangeSimpleQty(-1)">−</button>
                            <span class="cp-qty-val" id="cpSimpleQtyVal">1</span>
                            <button class="cp-qty-btn" onclick="cpChangeSimpleQty(1)">+</button>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($columnPhotos)): ?>
                    <div class="cp-col-list" id="cpColList">
                        <?php foreach ($columnPhotos as $ci => $col): ?>
                        <?php
                            $colPrice    = isset($col['price']) && $col['price'] !== null ? (float)$col['price'] : $price;
                            $colLabel    = $col['color_name'] ?? ('Option ' . ($ci + 1));
                            $colRef      = $col['reference'] ?? null;
                            $priceLabel  = number_format($colPrice, 2) . ' €';
                            $isDefault   = !isset($col['price']) || $col['price'] === null;
                        ?>
                        <div class="cp-col-row" data-col-idx="<?= $ci ?>"
                             style="<?= $ci >= $colVisible ? 'display:none;' : '' ?>">
                            <img src="<?= htmlspecialchars($resolveUrl($col['url'])) ?>"
                                 class="cp-col-thumb"
                                 alt="<?= htmlspecialchars($colLabel) ?>"
                                 title="Voir la photo"
                                 onclick="cpShowPhoto(<?= $col['allIdx'] ?>)">
                            <div class="cp-col-body">
                                <div class="cp-col-label" title="<?= htmlspecialchars($colLabel) ?>">
                                    <?= htmlspecialchars($colLabel) ?>
                                    <?php if ($colRef): ?>
                                    <span class="cp-col-ref"><?= htmlspecialchars($colRef) ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="cp-col-footer">
                                    <span class="cp-col-price">
                                        <?= $priceLabel ?>
                                        <?php if ($isDefault): ?>
                                        <span style="font-size:.68rem;font-weight:400;opacity:.55;">(prix de base)</span>
                                        <?php endif; ?>
                                    </span>
                                    <div class="cp-col-qty">
                                        <button class="cp-col-btn" onclick="cpColQty(<?= $ci ?>, -1, <?= $colPrice ?>)">−</button>
                                        <span class="cp-col-val" id="cpColVal-<?= $ci ?>">0</span>
                                        <button class="cp-col-btn" onclick="cpColQty(<?= $ci ?>, 1, <?= $colPrice ?>)">+</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php if (count($columnPhotos) > $colVisible): ?>
                    <button class="cp-col-more mb-3" id="cpColMoreBtn" onclick="cpColExpand()">
                        <i class="bi bi-chevron-down"></i>
                        Plus (<?= count($columnPhotos) - $colVisible ?> autres)
                    </button>
                    <?php endif; ?>
                    <?php endif; ?>

                    <?php if (!empty($rightPhotos)): ?>
                    <div class="cp-mini-strip" id="cpMiniStrip">
                        <?php foreach ($rightPhotos as $photo): ?>
                        <div class="cp-mini-thumb <?= $photo['allIdx'] === 0 ? 'active' : '' ?>"
                             onclick="cpCurrentZone='right'; cpShowPhoto(<?= $photo['allIdx'] ?>)"
                             data-idx="<?= $photo['allIdx'] ?>">
                            <img src="<?= htmlspecialchars($resolveUrl($photo['url'])) ?>"
                                 alt="<?= !empty($photo['color_name']) ? htmlspecialchars($photo['color_name']) : '' ?>"
                                 title="<?= !empty($photo['color_name']) ? htmlspecialchars($photo['color_name']) : '' ?>"
                                 loading="<?= $photo['allIdx'] === 0 ? 'eager' : 'lazy' ?>">
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <div class="d-flex align-items-center justify-content-between mb-3 px-1"
                         style="font-size:.9rem;">
                        <span style="color:var(--color-text-muted);">
                            Total <span id="cpTotalCount" style="color:var(--color-text);"></span>
                        </span>
                        <span style="font-size:1.25rem;font-weight:800;" id="cpTotalPrice">0.00 €</span>
                    </div>

                    <div class="d-flex align-items-center gap-3 mb-3">
                        <button class="cp-btn-cart" id="cpAddCartBtn" onclick="cpAddToCart()">
                            <i class="bi bi-bag-plus"></i>Ajouter au panier
                        </button>
                        <button class="cp-heart-btn" id="cpHeartBtn" onclick="cpToggleHeart()" type="button">
                            <i class="bi bi-heart-fill"></i>
                            <span id="cpHeartCount">0</span>
                        </button>
                    </div>

                    <div id="cpToast" class="alert d-none mt-3" style="font-size:.84rem;"></div>

                    <?php if (!empty($product['description'])): ?>
                    <div class="mt-4 pt-3" style="border-top:1px solid var(--color-border);">
                        <div class="cp-section-lbl">Description</div>
                        <div style="font-size:.86rem;line-height:1.7;color:var(--color-text-muted);">
                            <?= nl2br(htmlspecialchars($product['description'])) ?>
                        </div>
                    </div>
                    <?php endif; ?>

                </div><!-- /cp-info -->
            </div><!-- /cp-layout -->
        </div><!-- /cp-wrap -->
    </div><!-- /cshow-content -->
</div><!-- /cshow-wrap -->

<div class="cp-lightbox" id="cpLightbox" onclick="if(event.target===this) cpCloseLightbox()">
    <div class="cp-lightbox-box">
        <button class="cp-lightbox-close" onclick="cpCloseLightbox()" title="Fermer">&times;</button>
        <img id="cpLightboxImg" src="" alt="">
        <div class="cp-lightbox-zoom-lens d-none" id="cpLightboxZoomLens"></div>
    </div>
</div>

<script>
const CP_BASE    = '<?= BASE_URL ?>';
const cpProduct  = <?= json_encode($product,  JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
const cpVariants = <?= json_encode($variants, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
const cpPhotos    = <?= json_encode($allPhotos, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
const cpLeftIdxs  = <?= json_encode(array_column($leftPhotos, 'allIdx')) ?>;
const cpRightIdxs = <?= json_encode(array_column($rightPhotos, 'allIdx')) ?>;

let cpCurrentZone  = 'left'; // zone active pour la navigation précédent/suivant
let cpPhotoIdx     = 0;
let cpSelColor     = null;
let cpSimpleQtyVal = 1;
const cpQtys       = {};
const cpColQtys    = {}; // colIdx → qty
const cpColPrices  = {}; // colIdx → price (set on first interaction)

function cpResolveUrl(url) {
    if (!url) return '';
    if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('//')) return url;
    return CP_BASE + url;
}
function cpCsrf() { return document.querySelector('meta[name="csrf-token"]')?.content ?? ''; }
function cpEsc(s) { return String(s).replace(/\\/g,'\\\\').replace(/'/g,"\\'"); }

function cpShowPhoto(idx) {
    if (!cpPhotos.length) return;
    cpPhotoIdx = (idx + cpPhotos.length) % cpPhotos.length;
    const main = document.getElementById('cpMainPhoto');
    if (main) {
        main.src = cpResolveUrl(cpPhotos[cpPhotoIdx].url);
    }
    const lb = document.getElementById('cpLightbox');
    if (lb && lb.classList.contains('active')) {
        const lbImg = document.getElementById('cpLightboxImg');
        if (lbImg) lbImg.src = cpResolveUrl(cpPhotos[cpPhotoIdx].url);
        cpLbUpdateZoomBackground();
    }
    // Synchronise les deux strips via data-idx (chaque strip peut avoir un sous-ensemble)
    document.querySelectorAll('.cp-thumb[data-idx], .cp-mini-thumb[data-idx]').forEach(el => {
        el.classList.toggle('active', parseInt(el.dataset.idx) === cpPhotoIdx);
    });
}
function cpZoneList() { return cpCurrentZone === 'right' ? cpRightIdxs : cpLeftIdxs; }

function cpStep(dir) {
    const list = cpZoneList();
    if (!list.length) return;
    let pos = list.indexOf(cpPhotoIdx);
    if (pos === -1) pos = 0;
    pos = (pos + dir + list.length) % list.length;
    cpShowPhoto(list[pos]);
}
function cpPrev() { cpStep(-1); }
function cpNext() { cpStep(1); }

function cpBuildColors() {
    const wrap = document.getElementById('cpColorSwatches');
    if (!wrap) return;
    const colors = [...new Set(cpVariants.filter(v => v.color).map(v => v.color))];
    wrap.innerHTML = colors.map(c => {
        const pi = cpPhotos.findIndex(p => p.color_name === c);
        if (pi >= 0) {
            return `<div class="cp-cswatch" onclick="cpSelectColor('${cpEsc(c)}')" data-color="${cpEsc(c)}" title="${cpEsc(c)}">
                        <img src="${cpResolveUrl(cpPhotos[pi].url)}" alt="${cpEsc(c)}">
                    </div>`;
        }
        return `<div class="cp-cswatch-text" onclick="cpSelectColor('${cpEsc(c)}')" data-color="${cpEsc(c)}">${c}</div>`;
    }).join('');
    if (colors.length) cpSelectColor(colors[0]);
}

function cpSelectColor(color) {
    cpSelColor = color;
    document.querySelectorAll('[data-color]').forEach(el => el.classList.toggle('active', el.dataset.color === color));
    const lbl = document.getElementById('cpColorLabel');
    if (lbl) lbl.textContent = color;
    const pi = cpPhotos.findIndex(p => p.color_name === color);
    if (pi >= 0) cpShowPhoto(pi);
    cpBuildSizeRows();
}

function cpBuildSizeRows() {
    const wrap = document.getElementById('cpSizeRows');
    if (!wrap) return;
    const list = cpSelColor ? cpVariants.filter(v => v.color === cpSelColor) : cpVariants;
    if (!list.length) { wrap.innerHTML = '<p class="text-muted small mb-0">Aucune variante disponible.</p>'; return; }
    wrap.innerHTML = list.map(v => {
        const stock   = parseInt(v.stock)           || 0;
        const thresh  = parseInt(v.stock_threshold) || 5;
        const inStock = stock > 0;
        const sClr    = !inStock ? '#f87171' : (stock <= thresh ? '#f59e0b' : '#4ade80');
        const sTxt    = !inStock ? 'Rupture' : (stock <= thresh ? stock + ' restants' : '');
        const lbl     = v.size || (list.length === 1 ? 'Taille unique' : 'Sans taille');
        const curQty  = cpQtys[v.id] ?? 0;
        return `<div class="cp-size-row${!inStock ? ' oos' : ''}" data-variant="${v.id}">
            <span class="cp-size-lbl">${lbl}</span>
            <span class="cp-size-price">${parseFloat(cpProduct.price).toFixed(2)} €</span>
            <div class="cp-qty-ctrl">
                <button class="cp-qty-btn" onclick="cpChangeQty(${v.id},-1)"${!inStock?' disabled':''}>−</button>
                <span class="cp-qty-val" id="cpQty-${v.id}">${curQty}</span>
                <button class="cp-qty-btn" onclick="cpChangeQty(${v.id},1)"${!inStock?' disabled':''}>+</button>
            </div>
            ${sTxt ? `<span class="cp-stock-lbl" style="color:${sClr};">${sTxt}</span>` : '<span class="cp-stock-lbl"></span>'}
        </div>`;
    }).join('');
    cpUpdateTotal();
}

function cpChangeQty(vid, delta) {
    const v = cpVariants.find(x => x.id == vid);
    if (!v) return;
    cpQtys[vid] = Math.max(0, Math.min(parseInt(v.stock), (cpQtys[vid] ?? 0) + delta));
    const el = document.getElementById('cpQty-' + vid);
    if (el) el.textContent = cpQtys[vid];
    cpUpdateTotal();
}

function cpChangeSimpleQty(delta) {
    const maxStock = parseInt(cpProduct.stock || 9999);
    cpSimpleQtyVal = Math.max(1, Math.min(maxStock, cpSimpleQtyVal + delta));
    const el = document.getElementById('cpSimpleQtyVal');
    if (el) el.textContent = cpSimpleQtyVal;
    cpUpdateTotal();
}

function cpColQty(colIdx, delta, price) {
    cpColPrices[colIdx] = price;
    cpColQtys[colIdx]   = Math.max(0, (cpColQtys[colIdx] ?? 0) + delta);
    const el = document.getElementById('cpColVal-' + colIdx);
    if (el) el.textContent = cpColQtys[colIdx];
    cpUpdateTotal();
}

function cpColExpand() {
    document.querySelectorAll('#cpColList .cp-col-row').forEach(row => row.style.display = '');
    const btn = document.getElementById('cpColMoreBtn');
    if (btn) btn.style.display = 'none';
}

function cpUpdateTotal() {
    let qty = 0, total = 0;
    const basePrice = parseFloat(cpProduct.price) || 0;

    if (cpVariants.length > 0) {
        Object.entries(cpQtys).forEach(([, q]) => { qty += q; total += q * basePrice; });
    } else {
        const colTotal = Object.values(cpColQtys).reduce((s, q) => s + q, 0);
        if (colTotal > 0) {
            Object.entries(cpColQtys).forEach(([ci, q]) => {
                qty   += q;
                total += q * (cpColPrices[ci] ?? basePrice);
            });
        } else {
            qty = cpSimpleQtyVal; total = cpSimpleQtyVal * basePrice;
        }
    }

    const countEl = document.getElementById('cpTotalCount');
    const priceEl = document.getElementById('cpTotalPrice');
    if (countEl) countEl.textContent = qty > 0 ? '— ' + qty + ' article' + (qty > 1 ? 's' : '') : '';
    if (priceEl) priceEl.textContent = total.toFixed(2) + ' €';
}

async function cpAddToCart() {
    if (cpVariants.length > 0) {
        const entries = Object.entries(cpQtys).filter(([, q]) => q > 0);
        if (!entries.length) { cpToast('Sélectionnez une quantité.', false); return; }
        let ok = true;
        for (const [vid, qty] of entries) {
            ok = (await cpDoAdd(cpProduct.id, qty, vid)) && ok;
        }
        if (ok) {
            cpToast('Ajouté au panier !');
            Object.keys(cpQtys).forEach(k => { cpQtys[k] = 0; });
            cpBuildSizeRows();
        }
    } else {
        // Colonnes : chaque ligne est ajoutée séparément (qty indépendante)
        const colEntries = Object.entries(cpColQtys).filter(([, q]) => q > 0);
        if (colEntries.length > 0) {
            let ok = true;
            for (const [ci, qty] of colEntries) {
                ok = (await cpDoAdd(cpProduct.id, qty, null)) && ok;
            }
            if (ok) {
                cpToast('Ajouté au panier !');
                Object.keys(cpColQtys).forEach(k => { cpColQtys[k] = 0; });
                document.querySelectorAll('[id^="cpColVal-"]').forEach(el => el.textContent = '0');
                cpUpdateTotal();
            }
        } else {
            if (await cpDoAdd(cpProduct.id, cpSimpleQtyVal, null)) {
                cpToast('Ajouté au panier !');
                cpUpdateTotal();
            }
        }
    }
}

async function cpDoAdd(productId, qty, variantId) {
    const fd = new FormData();
    fd.append('product_id', productId);
    fd.append('quantity',   qty);
    if (variantId) fd.append('variant_id', variantId);
    const r    = await fetch(CP_BASE + '/api/cart/add', {
        method: 'POST',
        headers: {'X-CSRF-Token': cpCsrf()},
        body: fd,
    });
    const data = await r.json();
    if (!r.ok) { cpToast(data.message ?? 'Erreur.', false); return false; }
    return true;
}

function cpSaveLikes(likes) {
    try { localStorage.setItem('newdear_likes', JSON.stringify(likes)); } catch (e) { console.warn(e); }
}
function cpGetLikes() {
    try { return JSON.parse(localStorage.getItem('newdear_likes') || '{}'); } catch { return {}; }
}
function cpGetLikeCount(productId) {
    const likes = cpGetLikes();
    return parseInt(likes[productId] || 0, 10);
}
function cpSetLikeCount(productId, count) {
    const likes = cpGetLikes();
    likes[productId] = count;
    cpSaveLikes(likes);
}
function cpToggleHeart() {
    const productId = cpProduct.id ? String(cpProduct.id) : cpProduct.slug || '';
    const current = cpGetLikeCount(productId);
    const next = current + 1;
    cpSetLikeCount(productId, next);
    cpRenderHeartCount(next);
    cpToast('❤️ Cœur ajouté !', true);
}
function cpRenderHeartCount(count) {
    const el = document.getElementById('cpHeartCount');
    if (el) el.textContent = count;
}
function cpInitHeart() {
    const productId = cpProduct.id ? String(cpProduct.id) : cpProduct.slug || '';
    cpRenderHeartCount(cpGetLikeCount(productId));
}

function cpToast(msg, ok = true) {
    const el = document.getElementById('cpToast');
    if (!el) return;
    el.className = 'alert mt-3 ' + (ok ? 'alert-success' : 'alert-danger');
    el.textContent = msg;
    el.classList.remove('d-none');
    clearTimeout(el._t);
    el._t = setTimeout(() => el.classList.add('d-none'), 4000);
}

/* ── Lightbox : agrandissement au clic, zoom loupe actif dans la lightbox ── */
function cpOpenLightbox() {
    const lb    = document.getElementById('cpLightbox');
    const lbImg = document.getElementById('cpLightboxImg');
    if (!lb || !lbImg || !cpPhotos.length) return;
    lbImg.src = cpResolveUrl(cpPhotos[cpPhotoIdx].url);
    lb.classList.add('active');
    document.body.style.overflow = 'hidden';
}
function cpCloseLightbox() {
    const lb = document.getElementById('cpLightbox');
    if (lb) lb.classList.remove('active');
    document.body.style.overflow = '';
    cpLbZoomHide();
}
function cpLbUpdateZoomBackground() {
    const lens = document.getElementById('cpLightboxZoomLens');
    if (!lens || !cpPhotos.length) return;
    lens.style.backgroundImage = `url('${cpResolveUrl(cpPhotos[cpPhotoIdx].url)}')`;
}
function cpLbZoomMove(evt) {
    const img  = document.getElementById('cpLightboxImg');
    const lens = document.getElementById('cpLightboxZoomLens');
    if (!img || !lens) return;

    const rect = img.getBoundingClientRect();
    const x = evt.clientX - rect.left;
    const y = evt.clientY - rect.top;
    if (x < 0 || y < 0 || x > rect.width || y > rect.height) {
        lens.classList.add('d-none');
        return;
    }

    cpLbUpdateZoomBackground();
    lens.classList.remove('d-none');
    lens.style.left = `${x}px`;
    lens.style.top = `${y}px`;

    const bgX = (x / rect.width) * 100;
    const bgY = (y / rect.height) * 100;
    lens.style.backgroundPosition = `${bgX}% ${bgY}%`;
}
function cpLbZoomHide() {
    const lens = document.getElementById('cpLightboxZoomLens');
    if (lens) lens.classList.add('d-none');
}

document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('cpColorSwatches')) {
        cpBuildColors();
    } else if (cpVariants.length) {
        cpBuildSizeRows();
    } else {
        cpUpdateTotal();
    }

    const lbImg = document.getElementById('cpLightboxImg');
    if (lbImg) {
        lbImg.addEventListener('mousemove', cpLbZoomMove);
        lbImg.addEventListener('mouseenter', cpLbZoomMove);
        lbImg.addEventListener('mouseleave', cpLbZoomHide);
    }
    document.addEventListener('keydown', e => { if (e.key === 'Escape') cpCloseLightbox(); });
    cpInitHeart();
});
</script>
