<!-- Breadcrumb Navigation -->
<nav aria-label="breadcrumb" class="mb-4">
  <ol class="breadcrumb small">
    <li class="breadcrumb-item"><a href="<?= url('/') ?>" class="text-decoration-none">หน้าแรก</a></li>
    <?php if (!empty($product['category_name'])): ?>
      <li class="breadcrumb-item"><a href="<?= url('/category/' . $product['category_slug']) ?>" class="text-decoration-none"><?= e($product['category_name']) ?></a></li>
    <?php endif; ?>
    <li class="breadcrumb-item active text-truncate" aria-current="page" style="max-width: 320px;"><?= e($product['name']) ?></li>
  </ol>
</nav>

<!-- 1. Main Product Purchase Card (Gallery + Purchasing Info) -->
<div class="cargoo-card p-4 p-md-5 mb-4">
  <div class="row g-4 g-lg-5">
    <!-- Left Column: Product Gallery -->
    <div class="col-lg-5 col-md-6">
      <div class="product-gallery-main mb-3 text-center bg-light rounded-3 p-2 position-relative" style="min-height: 380px; display: flex; align-items: center; justify-content: center;">
        <?php 
          $mainImg = !empty($product['main_image']) ? $product['main_image'] : (!empty($product['images'][0]['image_path']) ? $product['images'][0]['image_path'] : null);
        ?>
        <?php if ($mainImg): ?>
          <img src="<?= product_image_url($mainImg) ?>" alt="<?= e($product['name']) ?>" id="productMainImage" class="img-fluid rounded-2 shadow-sm" style="max-height: 380px; object-fit: contain;">
        <?php else: ?>
          <div class="text-muted text-center py-5">
            <i class="bi bi-image fs-1 text-secondary"></i>
            <p class="small mb-0 mt-2">ไม่มีรูปภาพสินค้า</p>
          </div>
        <?php endif; ?>
      </div>

      <!-- Thumbnail Strip -->
      <?php if (!empty($product['images'])): ?>
        <div class="d-flex gap-2 overflow-x-auto pb-2" id="galleryThumbnailStrip">
          <?php foreach ($product['images'] as $imgIndex => $img): ?>
            <div class="gallery-thumbnail-item <?= $imgIndex === 0 ? 'active' : '' ?> cursor-pointer border rounded-2 p-1 bg-white" data-image-url="<?= product_image_url($img['image_path']) ?>" style="width: 60px; height: 60px; flex-shrink: 0;">
              <img src="<?= product_image_url($img['image_path']) ?>" alt="Thumbnail" class="w-100 h-100 object-fit-cover rounded-1">
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>

    <!-- Right Column: Product Purchasing Area -->
    <div class="col-lg-7 col-md-6 d-flex flex-column justify-content-between">
      <div>
        <!-- Badges & Wishlist Header -->
        <div class="d-flex align-items-center justify-content-between mb-2">
          <div>
            <?php if (!empty($product['badges'])): ?>
              <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-2 py-1 small rounded-pill">
                <?= e($product['badges']) ?>
              </span>
            <?php endif; ?>
          </div>

          <!-- Wishlist Toggle -->
          <button type="button" class="btn btn-sm btn-outline-danger btn-wishlist-toggle rounded-pill px-3 py-1 d-flex align-items-center gap-1 <?= $isSaved ? 'active' : '' ?>" data-product-id="<?= (int)$product['id'] ?>">
            <i class="bi <?= $isSaved ? 'bi-heart-fill' : 'bi-heart' ?>"></i>
            <span class="small wishlist-text"><?= $isSaved ? 'บันทึกแล้ว' : 'บันทึก' ?></span>
          </button>
        </div>

        <h3 class="fw-bold text-dark mb-2"><?= e($product['name']) ?></h3>

        <!-- Rating & Review Count Header Indicator -->
        <div class="d-flex align-items-center gap-3 mb-3 small">
          <?php $avgR = (float)($reviewBreakdown['avg_rating'] ?? 0); $totR = (int)($reviewBreakdown['total_reviews'] ?? 0); ?>
          <div class="d-flex align-items-center gap-1">
            <span class="fw-bold text-dark fs-6 text-decoration-underline"><?= number_format($avgR, 1) ?></span>
            <div class="text-warning small d-flex">
              <?php for ($s = 1; $s <= 5; $s++): ?>
                <i class="bi <?= $s <= round($avgR) ? 'bi-star-fill' : 'bi-star' ?>" style="font-size: 0.85rem;"></i>
              <?php endfor; ?>
            </div>
          </div>
          <span class="text-muted">|</span>
          <a href="#customerReviewsSection" class="text-decoration-none text-muted">
            <strong class="text-dark"><?= number_format($totR) ?></strong> รีวิว
          </a>
          <?php if (!empty($product['stock_status']) && $product['stock_status'] === 'in_stock'): ?>
            <span class="text-muted">|</span>
            <span class="text-success"><i class="bi bi-check-circle-fill me-1"></i>พร้อมส่ง</span>
          <?php endif; ?>
        </div>

        <!-- Price Showcase Box -->
        <div class="p-3 bg-light rounded-3 mb-3 d-flex align-items-baseline gap-3">
          <span class="fs-2 fw-bold text-primary" id="displayProductPrice">฿<?= number_format((float)$product['price'], 2) ?></span>
          <?php if (!empty($product['original_price']) && (float)$product['original_price'] > (float)$product['price']): ?>
            <?php $discountPercent = round((((float)$product['original_price'] - (float)$product['price']) / (float)$product['original_price']) * 100); ?>
            <span class="text-muted text-decoration-line-through fs-5">฿<?= number_format((float)$product['original_price'], 2) ?></span>
            <span class="badge bg-danger fs-6">-<?= $discountPercent ?>%</span>
          <?php endif; ?>
        </div>

        <!-- Stock Status & Province -->
        <div class="row g-2 mb-3 small">
          <div class="col-sm-6">
            <span class="text-muted"><?= __('status') ?>:</span>
            <?php if ($product['stock_status'] === 'in_stock'): ?>
              <span class="text-success fw-bold ms-1"><i class="bi bi-check-circle-fill"></i> <?= __('in_stock') ?> (<?= (int)$product['stock'] ?> ชิ้น)</span>
            <?php elseif ($product['stock_status'] === 'low_stock'): ?>
              <span class="text-warning fw-bold ms-1"><i class="bi bi-exclamation-triangle-fill"></i> เหลือเพียง <?= (int)$product['stock'] ?> ชิ้น</span>
            <?php else: ?>
              <span class="text-danger fw-bold ms-1"><i class="bi bi-x-circle-fill"></i> <?= __('out_of_stock') ?></span>
            <?php endif; ?>
          </div>
          <div class="col-sm-6">
            <span class="text-muted"><?= __('delivery_from') ?>:</span>
            <span class="text-dark fw-medium ms-1"><i class="bi bi-geo-alt me-1 text-primary"></i><?= e($product['province'] ?? 'กรุงเทพมหานคร') ?></span>
          </div>
        </div>

        <!-- Product Variations (If Any) -->
        <!-- Product Variations (If Any) -->
        <?php if (!empty($product['variations'])): ?>
          <div class="mb-4 pt-3 border-top">
            <?php foreach ($product['variations'] as $variation): ?>
              <div class="mb-3">
                <label class="form-label fw-bold small text-dark mb-2"><?= e($variation['name']) ?>:</label>
                <div class="d-flex flex-wrap gap-2 variation-group" data-var-name="<?= e($variation['name']) ?>">
                  <?php foreach ($variation['options'] as $oIndex => $opt): ?>
                    <button type="button" 
                            class="variant-selector-btn d-inline-flex align-items-center gap-2 p-2 rounded-2 border <?= $oIndex === 0 ? 'active border-primary bg-primary-subtle text-primary fw-bold' : 'bg-white text-dark' ?>" 
                            data-option-id="<?= (int)$opt['id'] ?>" 
                            data-option-name="<?= e($opt['name']) ?>" 
                            data-price-modifier="<?= (float)$opt['price_modifier'] ?>" 
                            data-option-image="<?= !empty($opt['image']) ? product_image_url($opt['image']) : '' ?>"
                            style="cursor: pointer; font-size: 0.875rem;">
                      <?php if (!empty($opt['image'])): ?>
                        <img src="<?= product_image_url($opt['image']) ?>" alt="<?= e($opt['name']) ?>" class="rounded-1" style="width: 26px; height: 26px; object-fit: cover;">
                      <?php endif; ?>
                      <span><?= e($opt['name']) ?></span>
                      <?php if ((float)$opt['price_modifier'] != 0.00): ?>
                        <span class="badge bg-light text-secondary border fw-normal" style="font-size: 0.72rem;">
                          <?= (float)$opt['price_modifier'] > 0 ? '+' : '' ?>฿<?= number_format((float)$opt['price_modifier']) ?>
                        </span>
                      <?php endif; ?>
                    </button>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>

      <!-- Add to Cart & Buy Now Form -->
      <form action="<?= url('/cart/add') ?>" method="POST" class="pt-3 border-top" id="addToCartForm">
        <?= Security::csrfField() ?>
        <input type="hidden" name="product_id" value="<?= (int)$product['id'] ?>">
        <input type="hidden" name="variation_summary" id="inputVariationSummary" value="">
        <input type="hidden" name="unit_price" id="inputUnitPrice" value="<?= (float)$product['price'] ?>">
        <input type="hidden" name="sku_id" id="inputSkuId" value="">

        <div class="d-flex align-items-center gap-3 mb-4">
          <label class="form-label fw-bold small text-muted mb-0"><?= __('quantity') ?>:</label>
          <div class="input-group" style="width: 130px;">
            <button class="btn btn-outline-secondary btn-sm px-3" type="button" id="btnQtyMinus" <?= (int)$product['stock'] <= 0 ? 'disabled' : '' ?>>-</button>
            <input type="number" name="quantity" id="inputQuantity" class="form-control form-control-sm text-center fw-bold" value="1" min="1" max="<?= max(1, (int)$product['stock']) ?>" <?= (int)$product['stock'] <= 0 ? 'disabled' : '' ?>>
            <button class="btn btn-outline-secondary btn-sm px-3" type="button" id="btnQtyPlus" <?= (int)$product['stock'] <= 0 ? 'disabled' : '' ?>>+</button>
          </div>
          <small class="text-muted" id="displayProductStock"><?= (int)$product['stock'] ?> ชิ้นพร้อมส่ง</small>
        </div>

        <div class="d-flex flex-wrap gap-3">
          <?php if ((int)$product['stock'] > 0): ?>
            <button type="submit" class="btn btn-cargoo-outline px-4 py-2 flex-grow-1">
              <i class="bi bi-cart-plus"></i> <?= __('add_to_cart') ?>
            </button>
            <button type="submit" name="buy_now" value="1" class="btn btn-cargoo-primary px-4 py-2 flex-grow-1">
              <i class="bi bi-bag-check"></i> <?= __('buy_now') ?>
            </button>
          <?php else: ?>
            <button type="button" class="btn btn-secondary px-4 py-2 w-100 disabled" disabled>
              <i class="bi bi-x-circle"></i> สินค้าหมดชั่วคราว
            </button>
          <?php endif; ?>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- 2. Specifications, Description & Seller Information -->
<div class="row g-4 mb-5">
  <!-- Left Side: Product Specifications & Description -->
  <div class="col-lg-8">
    <div class="cargoo-card p-4">
      <h5 class="fw-bold mb-3 text-dark"><i class="bi bi-card-text text-primary me-2"></i><?= __('product_detail') ?></h5>
      
      <!-- Specifications Table -->
      <div class="table-responsive mb-4">
        <table class="table table-bordered table-sm small align-middle mb-0">
          <tbody>
            <tr>
              <th class="bg-light" style="width: 25%;">หมวดหมู่สินค้า</th>
              <td><?= e($product['category_name'] ?? 'ทั่วไป') ?></td>
            </tr>
            <tr>
              <th class="bg-light">สถานที่จัดส่ง</th>
              <td><?= e($product['province'] ?? 'กรุงเทพมหานคร') ?></td>
            </tr>
            <tr>
              <th class="bg-light">จำนวนสต็อกคงเหลือ</th>
              <td><?= (int)$product['stock'] ?> ชิ้น</td>
            </tr>
            <tr>
              <th class="bg-light">สถานะสินค้า</th>
              <td>พร้อมจำหน่าย</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Description Content -->
      <h6 class="fw-bold mb-2 text-dark">รายละเอียดสินค้า</h6>
      <div class="text-secondary lh-lg small" style="white-space: pre-line;">
        <?= !empty($product['description']) ? e($product['description']) : 'ไม่มีข้อมูลรายละเอียดสินค้าเพิ่มเติม' ?>
      </div>
    </div>
  </div>

  <!-- Right Side: Seller Store Card -->
  <div class="col-lg-4">
    <div class="cargoo-card p-4">
      <h6 class="fw-bold mb-3 text-dark"><i class="bi bi-shop text-primary me-2"></i><?= __('store_info') ?></h6>
      
      <div class="d-flex align-items-center gap-3 mb-3">
        <?php if (!empty($product['store_logo'])): ?>
          <img src="<?= asset('/uploads/stores/' . e($product['store_logo'])) ?>" alt="Store Logo" class="rounded-circle border" style="width: 52px; height: 52px; object-fit: cover;">
        <?php else: ?>
          <div class="rounded-circle bg-primary-subtle text-primary d-flex align-items-center justify-content-center fw-bold" style="width: 52px; height: 52px;">
            <i class="bi bi-shop fs-4"></i>
          </div>
        <?php endif; ?>
        
        <div>
          <h6 class="fw-bold mb-0 text-dark"><?= e($product['store_name']) ?></h6>
          <?php if (!empty($product['store_verified'])): ?>
            <span class="badge bg-primary-subtle text-primary border border-primary-subtle small px-2 py-0" style="font-size: 0.7rem;">
              <i class="bi bi-patch-check-fill"></i> Official Store
            </span>
          <?php endif; ?>
        </div>
      </div>

      <?php if (!empty($product['store_address'])): ?>
        <p class="small text-muted mb-3"><i class="bi bi-geo-alt me-1 text-primary"></i><?= e($product['store_address']) ?></p>
      <?php endif; ?>

      <a href="<?= url('/shop/' . $product['store_slug']) ?>" class="btn btn-cargoo-outline btn-sm w-100 py-2">
        <i class="bi bi-shop me-1"></i> <?= __('visit_store') ?>
      </a>
    </div>
  </div>
</div>

<!-- 3. Customer Reviews & Ratings Dashboard Section -->
<div class="cargoo-card p-4 p-md-5 mb-5" id="customerReviewsSection">
  <h5 class="fw-bold mb-4 text-dark d-flex align-items-center gap-2">
    <i class="bi bi-star-fill text-warning"></i> คะแนนและรีวิวจากผู้ซื้อ (Customer Reviews)
  </h5>

  <!-- Rating Summary Box (Overall + Breakdown + Filter Buttons) -->
  <div class="p-4 rounded-3 border bg-light mb-4">
    <div class="row g-4 align-items-center">
      <!-- Overall Rating Score -->
      <div class="col-md-3 text-center border-end-md">
        <div class="display-3 fw-bold text-primary mb-1">
          <?= number_format((float)($reviewBreakdown['avg_rating'] ?? 0), 1) ?>
        </div>
        <div class="d-flex justify-content-center gap-1 mb-2">
          <?php 
            $overallStars = round((float)($reviewBreakdown['avg_rating'] ?? 0));
            for ($s = 1; $s <= 5; $s++): 
          ?>
            <i class="bi <?= $s <= $overallStars ? 'bi-star-fill text-warning fs-5' : 'bi-star text-secondary fs-5' ?>"></i>
          <?php endfor; ?>
        </div>
        <p class="text-muted small mb-0">จากทั้งหมด <?= number_format((int)($reviewBreakdown['total_reviews'] ?? 0)) ?> รีวิว</p>
      </div>

      <!-- Star Breakdown Bars -->
      <div class="col-md-5 border-end-md">
        <?php for ($s = 5; $s >= 1; $s--): ?>
          <?php 
            $starCount = (int)($reviewBreakdown['star_' . $s] ?? 0);
            $pct = (int)($reviewBreakdown['star_percentages'][$s] ?? 0);
          ?>
          <div class="d-flex align-items-center gap-2 mb-1 small">
            <span style="width: 45px;" class="fw-semibold text-dark"><?= $s ?> ดาว</span>
            <div class="progress flex-grow-1" style="height: 6px;">
              <div class="progress-bar bg-warning" role="progressbar" style="width: <?= $pct ?>%;" aria-valuenow="<?= $pct ?>" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
            <span style="width: 40px;" class="text-muted text-end"><?= $starCount ?></span>
          </div>
        <?php endfor; ?>
      </div>

      <!-- Filter Buttons (All, 5, 4, 3, 2, 1) -->
      <div class="col-md-4">
        <label class="form-label small fw-bold text-muted mb-2">กรองตามคะแนน:</label>
        <div class="d-flex flex-wrap gap-2" id="starFilterButtons">
          <button type="button" class="btn btn-sm btn-primary review-filter-btn active" data-rating="0">
            ทั้งหมด (<?= (int)($reviewBreakdown['total_reviews'] ?? 0) ?>)
          </button>
          <?php for ($s = 5; $s >= 1; $s--): ?>
            <button type="button" class="btn btn-sm btn-outline-secondary review-filter-btn" data-rating="<?= $s ?>">
              <?= $s ?> ดาว (<?= (int)($reviewBreakdown['star_' . $s] ?? 0) ?>)
            </button>
          <?php endfor; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- Reviews List Container -->
  <div id="reviewsListContainer">
    <?php if (empty($reviews)): ?>
      <div class="text-center py-5">
        <i class="bi bi-chat-square-text text-muted" style="font-size: 3rem;"></i>
        <h6 class="mt-3 fw-bold text-dark">ยังไม่มีรีวิวสำหรับสินค้านี้</h6>
        <p class="text-muted small mb-0">เป็นคนแรกที่รีวิวสินค้านี้หลังจากได้รับสินค้าแล้ว!</p>
      </div>
    <?php else: ?>
      <div class="d-flex flex-column gap-3" id="reviewsListWrapper">
        <?php foreach ($reviews as $rev): ?>
          <div class="p-3 border rounded-3 bg-white review-item-card">
            <!-- Review Header -->
            <div class="d-flex justify-content-between align-items-start mb-2">
              <div class="d-flex align-items-center gap-3">
                <div class="rounded-circle bg-primary-subtle text-primary d-flex align-items-center justify-content-center fw-bold flex-shrink-0" style="width: 40px; height: 40px;">
                  <i class="bi bi-person-fill"></i>
                </div>
                <div>
                  <div class="d-flex align-items-center gap-2">
                    <span class="fw-bold text-dark small"><?= e($rev['display_name']) ?></span>
                    <span class="badge bg-success-subtle text-success border border-success-subtle small px-2 py-0" style="font-size: 0.65rem;">
                      <i class="bi bi-patch-check-fill me-1"></i>ผู้ซื้อจริง (Verified Buyer)
                    </span>
                  </div>
                  <div class="d-flex align-items-center gap-2 small text-muted">
                    <div class="d-flex text-warning">
                      <?php for ($s = 1; $s <= 5; $s++): ?>
                        <i class="bi <?= $s <= (int)$rev['rating'] ? 'bi-star-fill' : 'bi-star text-secondary' ?>" style="font-size: 0.75rem;"></i>
                      <?php endfor; ?>
                    </div>
                    <span>&bull;</span>
                    <span><?= date('d/m/Y H:i', strtotime($rev['created_at'])) ?></span>
                    <?php if (!empty($rev['variation_summary'])): ?>
                      <span>&bull; ตัวเลือก: <?= e($rev['variation_summary']) ?></span>
                    <?php endif; ?>
                  </div>
                </div>
              </div>

              <!-- Report Action Button -->
              <?php if (Auth::check()): ?>
                <button type="button" class="btn btn-link text-muted btn-sm p-0 text-decoration-none btn-report-review" data-review-id="<?= (int)$rev['id'] ?>" title="รายงานรีวิวที่ไม่เหมาะสม">
                  <i class="bi bi-flag"></i> <span class="small" style="font-size: 0.75rem;">รายงาน</span>
                </button>
              <?php endif; ?>
            </div>

            <!-- Review Text -->
            <?php if (!empty($rev['review_text'])): ?>
              <p class="text-secondary small mb-2 ps-sm-5" style="white-space: pre-line;"><?= e($rev['review_text']) ?></p>
            <?php endif; ?>

            <!-- Review Attached Photos Gallery -->
            <?php if (!empty($rev['images'])): ?>
              <div class="d-flex flex-wrap gap-2 pt-2 ps-sm-5">
                <?php foreach ($rev['images'] as $img): ?>
                  <div class="rounded-2 overflow-hidden border bg-light" style="width: 72px; height: 72px;">
                    <a href="<?= asset('/' . ltrim($img['image_path'], '/')) ?>" target="_blank">
                      <img src="<?= asset('/' . ltrim($img['image_path'], '/')) ?>" class="w-100 h-100 object-fit-cover" alt="Review Photo">
                    </a>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- Report Review Modal -->
<?php if (Auth::check()): ?>
<div class="modal fade" id="reportReviewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow">
      <form action="<?= url('/reviews/0/report') ?>" method="POST" id="reportReviewForm">
        <?= Security::csrfField() ?>
        <div class="modal-header border-bottom">
          <h6 class="modal-title fw-bold text-dark">
            <i class="bi bi-flag-fill text-danger me-2"></i>รายงานรีวิวที่ไม่เหมาะสม
          </h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body p-4">
          <div class="mb-3">
            <label class="form-label small fw-bold text-dark">เหตุผลในการรายงาน <span class="text-danger">*</span></label>
            <select name="reason" class="form-select form-select-sm" required>
              <option value="">-- เลือกเหตุผล --</option>
              <option value="มีข้อความหยาบคายหรือไม่เหมาะสม">มีข้อความหยาบคายหรือไม่เหมาะสม</option>
              <option value="รีวิวไม่เกี่ยวข้องกับสินค้า">รีวิวไม่เกี่ยวข้องกับสินค้า</option>
              <option value="มีโฆษณาหรือลิงก์ภายนอก">มีโฆษณาหรือลิงก์ภายนอก</option>
              <option value="ข้อมูลส่วนตัวหรือการคุกคาม">ข้อมูลส่วนตัวหรือการคุกคาม</option>
              <option value="รูปภาพประกอบไม่เหมาะสม">รูปภาพประกอบไม่เหมาะสม</option>
              <option value="อื่นๆ">อื่นๆ</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label small fw-bold text-dark">รายละเอียดเพิ่มเติม (ไม่บังคับ)</label>
            <textarea name="description" class="form-control form-control-sm" rows="3" placeholder="ระบุข้อมูลเพิ่มเติมให้ทีมงาน..."></textarea>
          </div>
        </div>

        <div class="modal-footer border-top py-2">
          <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-danger btn-sm px-4 fw-bold">ส่งรายงาน</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const productId = <?= (int)$product['id'] ?>;
  const mainImageElem = document.getElementById('productMainImage');
  const variationSummaryInput = document.getElementById('inputVariationSummary');

  // Gallery Thumbnail Clicks
  document.querySelectorAll('.gallery-thumbnail-item').forEach(item => {
    item.addEventListener('click', function() {
      document.querySelectorAll('.gallery-thumbnail-item').forEach(i => i.classList.remove('active', 'border-primary'));
      this.classList.add('active', 'border-primary');
      const imgUrl = this.getAttribute('data-image-url');
      if (imgUrl && mainImageElem) {
        mainImageElem.src = imgUrl;
      }
    });
  });

  const baseProductPrice = <?= (float)$product['price'] ?>;
  const productSkus = <?= json_encode($product['skus'] ?? []) ?>;
  const displayPriceElem = document.getElementById('displayProductPrice');
  const unitPriceInput = document.getElementById('inputUnitPrice');
  const skuIdInput = document.getElementById('inputSkuId');
  const stockDisplayElem = document.getElementById('displayProductStock');
  const qtyInputElem = document.getElementById('inputQuantity');

  function calculateActiveVariationPrice() {
    const selectedOptions = [];
    const selectedTokens = [];
    let totalModifiers = 0;

    document.querySelectorAll('.variation-group').forEach(group => {
      let activeBtn = group.querySelector('.variant-selector-btn.active');
      if (!activeBtn) {
        activeBtn = group.querySelector('.variant-selector-btn');
        if (activeBtn) {
          activeBtn.classList.add('active', 'border-primary', 'bg-primary-subtle', 'text-primary', 'fw-bold');
          activeBtn.classList.remove('bg-white', 'text-dark');
        }
      }
      if (activeBtn) {
        const optName = (activeBtn.getAttribute('data-option-name') || '').trim();
        const priceMod = parseFloat(activeBtn.getAttribute('data-price-modifier')) || 0;
        if (optName) {
          selectedOptions.push(optName);
          selectedTokens.push(optName.toLowerCase());
          totalModifiers += priceMod;
        }
      }
    });

    const summaryText = selectedOptions.join(', ');
    if (variationSummaryInput) {
      variationSummaryInput.value = summaryText;
    }

    const calculatedFromModifiers = baseProductPrice + totalModifiers;
    let finalPrice = calculatedFromModifiers;
    let matchedSku = null;

    // Find matching SKU with token-based comparison (order-insensitive)
    if (productSkus && productSkus.length > 0 && selectedTokens.length > 0) {
      matchedSku = productSkus.find(s => {
        if (!s.variation_summary) return false;
        const skuTokens = s.variation_summary.split(/[,/]+/).map(t => t.trim().toLowerCase()).filter(t => t.length > 0);
        if (skuTokens.length !== selectedTokens.length) return false;
        return selectedTokens.every(st => skuTokens.includes(st));
      });

      if (!matchedSku) {
        matchedSku = productSkus.find(s => (s.variation_summary || '').trim().toLowerCase() === summaryText.toLowerCase());
      }
    }

    if (matchedSku) {
      const skuPrice = parseFloat(matchedSku.price) || 0;
      if (skuPrice > 0) {
        if (totalModifiers === 0) {
          // If no option-level modifiers, use SKU price
          finalPrice = skuPrice;
        } else if (Math.abs(skuPrice - baseProductPrice) > 0.01) {
          // SKU price has distinct customized price
          finalPrice = skuPrice;
        } else {
          // SKU price was flat base price, so use base + totalModifiers
          finalPrice = calculatedFromModifiers;
        }
      }
      if (skuIdInput) {
        skuIdInput.value = matchedSku.id || '';
      }
      if (stockDisplayElem && typeof matchedSku.stock !== 'undefined') {
        const sStock = parseInt(matchedSku.stock) || 0;
        stockDisplayElem.textContent = sStock + ' ชิ้นพร้อมส่ง';
        if (qtyInputElem) {
          qtyInputElem.max = Math.max(1, sStock);
        }
      }
    } else {
      if (skuIdInput) skuIdInput.value = '';
    }

    finalPrice = Math.max(0, finalPrice);

    if (displayPriceElem) {
      displayPriceElem.textContent = '฿' + finalPrice.toLocaleString('th-TH', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }
    if (unitPriceInput) {
      unitPriceInput.value = finalPrice.toFixed(2);
    }
  }

  // Variation Option Selector Clicks
  document.querySelectorAll('.variant-selector-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      const parentGroup = this.closest('.variation-group');
      if (parentGroup) {
        parentGroup.querySelectorAll('.variant-selector-btn').forEach(b => {
          b.classList.remove('active', 'border-primary', 'bg-primary-subtle', 'text-primary', 'fw-bold');
          b.classList.add('bg-white', 'text-dark');
        });
      }
      this.classList.add('active', 'border-primary', 'bg-primary-subtle', 'text-primary', 'fw-bold');
      this.classList.remove('bg-white', 'text-dark');

      const optImage = this.getAttribute('data-option-image');
      if (optImage && mainImageElem) {
        mainImageElem.src = optImage;
      }

      calculateActiveVariationPrice();
    });
  });

  // Run on initial page load
  calculateActiveVariationPrice();

  const filterBtns = document.querySelectorAll('.review-filter-btn');
  const reviewsContainer = document.getElementById('reviewsListContainer');

  // Report review modal setup
  const reportModalElem = document.getElementById('reportReviewModal');
  let reportModal = null;
  if (reportModalElem) {
    reportModal = new bootstrap.Modal(reportModalElem);
    const reportForm = document.getElementById('reportReviewForm');

    document.querySelectorAll('.btn-report-review').forEach(btn => {
      btn.addEventListener('click', function() {
        const revId = this.getAttribute('data-review-id');
        reportForm.action = '<?= url('/reviews') ?>/' + revId + '/report';
        reportModal.show();
      });
    });
  }

  // AJAX Filter reviews by star
  filterBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      filterBtns.forEach(b => {
        b.classList.remove('btn-primary', 'active');
        b.classList.add('btn-outline-secondary');
      });
      this.classList.remove('btn-outline-secondary');
      this.classList.add('btn-primary', 'active');

      const starRating = this.getAttribute('data-rating');
      loadReviews(starRating);
    });
  });

  function loadReviews(starRating) {
    let url = '<?= url('/api/v1/products/' . (int)$product['id'] . '/reviews') ?>?page=1';
    if (starRating && starRating > 0) {
      url += '&rating=' + starRating;
    }

    reviewsContainer.innerHTML = '<div class="text-center py-4"><span class="spinner-border spinner-border-sm text-primary"></span> กำลังโหลดรีวิว...</div>';

    fetch(url)
      .then(res => res.json())
      .then(res => {
        if (!res.success || !res.data.reviews || res.data.reviews.length === 0) {
          reviewsContainer.innerHTML = '<div class="text-center py-5"><i class="bi bi-chat-square-text text-muted" style="font-size: 2.5rem;"></i><h6 class="mt-3 fw-bold text-dark">ไม่พบรีวิวในหมวดคะแนนนี้</h6></div>';
          return;
        }

        let html = '<div class="d-flex flex-column gap-3">';
        res.data.reviews.forEach(rev => {
          let starsHtml = '';
          for (let s = 1; s <= 5; s++) {
            starsHtml += '<i class="bi ' + (s <= parseInt(rev.rating) ? 'bi-star-fill text-warning' : 'bi-star text-secondary') + '" style="font-size: 0.75rem;"></i>';
          }

          let imagesHtml = '';
          if (rev.images && rev.images.length > 0) {
            imagesHtml = '<div class="d-flex flex-wrap gap-2 pt-2 ps-sm-5">';
            rev.images.forEach(img => {
              imagesHtml += '<div class="rounded-2 overflow-hidden border bg-light" style="width: 72px; height: 72px;">' +
                            '<a href="<?= asset('/') ?>' + img.image_path.replace(/^\//, '') + '" target="_blank">' +
                            '<img src="<?= asset('/') ?>' + img.image_path.replace(/^\//, '') + '" class="w-100 h-100 object-fit-cover">' +
                            '</a></div>';
            });
            imagesHtml += '</div>';
          }

          let reviewTextHtml = rev.review_text ? '<p class="text-secondary small mb-2 ps-sm-5" style="white-space: pre-line;">' + escapeHtml(rev.review_text) + '</p>' : '';
          let variantHtml = rev.variation_summary ? '<span>&bull; ตัวเลือก: ' + escapeHtml(rev.variation_summary) + '</span>' : '';

          html += '<div class="p-3 border rounded-3 bg-white review-item-card">' +
                    '<div class="d-flex justify-content-between align-items-start mb-2">' +
                      '<div class="d-flex align-items-center gap-3">' +
                        '<div class="rounded-circle bg-primary-subtle text-primary d-flex align-items-center justify-content-center fw-bold flex-shrink-0" style="width: 40px; height: 40px;"><i class="bi bi-person-fill"></i></div>' +
                        '<div>' +
                          '<div class="d-flex align-items-center gap-2"><span class="fw-bold text-dark small">' + escapeHtml(rev.display_name) + '</span>' +
                          '<span class="badge bg-success-subtle text-success border border-success-subtle small px-2 py-0" style="font-size: 0.65rem;"><i class="bi bi-patch-check-fill me-1"></i>ผู้ซื้อจริง (Verified Buyer)</span></div>' +
                          '<div class="d-flex align-items-center gap-2 small text-muted"><div class="d-flex text-warning">' + starsHtml + '</div><span>&bull;</span><span>' + rev.created_at + '</span>' + variantHtml + '</div>' +
                        '</div>' +
                      '</div>' +
                    '</div>' +
                    reviewTextHtml +
                    imagesHtml +
                  '</div>';
        });
        html += '</div>';
        reviewsContainer.innerHTML = html;
      })
      .catch(() => {
        reviewsContainer.innerHTML = '<div class="alert alert-danger small">ไม่สามารถโหลดข้อมูลรีวิวได้ กรุณาลองใหม่อีกครั้ง</div>';
      });
  }

  function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>"']/g, function(m) {
      return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'}[m];
    });
  }
});
</script>

<!-- 4. Related Products Section (Reusing unified product_card.php) -->
<?php if (!empty($relatedProducts)): ?>
  <div class="mb-4">
    <h5 class="fw-bold mb-3 text-dark">
      <i class="bi bi-grid-3x3-gap text-primary me-2"></i><?= __('related_products') ?>
    </h5>
    <div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-6 g-3">
      <?php foreach ($relatedProducts as $rp): ?>
        <?php $product = $rp; require __DIR__ . '/../components/product_card.php'; ?>
      <?php endforeach; ?>
    </div>
  </div>
<?php endif; ?>
