<?php
$portfolioV2Slides = [];
$portfolioV2BaseDir = dirname(__DIR__, 2) . '/assets/images/portfolios';
$portfolioV2ImageExtensions = ['webp', 'jpg', 'jpeg', 'png', 'jfif', 'gif'];

if (is_dir($portfolioV2BaseDir)) {
  $categories = scandir($portfolioV2BaseDir);
  sort($categories);

  foreach ($categories as $category) {
    if ($category === '.' || $category === '..') {
      continue;
    }

    $categoryPath = $portfolioV2BaseDir . '/' . $category;
    if (!is_dir($categoryPath)) {
      continue;
    }

    $images = [];
    foreach (scandir($categoryPath) as $file) {
      if ($file === '.' || $file === '..') {
        continue;
      }

      $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
      if (in_array($extension, $portfolioV2ImageExtensions, true)) {
        $images[] = $file;
      }
    }

    natsort($images);
    $categoryLabel = ucwords(str_replace('-', ' ', $category));

    foreach (array_values($images) as $file) {
      $portfolioV2Slides[] = [
        'src' => 'assets/images/portfolios/' . $category . '/' . $file,
        'alt' => $categoryLabel . ' book cover',
      ];
    }
  }
}

if (empty($portfolioV2Slides)) {
  $portfolioV2Slides = [
    ['src' => 'assets/images/port-top-left.webp', 'alt' => 'Simply More book cover'],
    ['src' => 'assets/images/port-top-right.webp', 'alt' => 'LOUD book cover'],
    ['src' => 'assets/images/port-top-left.webp', 'alt' => 'Featured book cover'],
    ['src' => 'assets/images/port-top-right.webp', 'alt' => 'Featured book cover'],
    ['src' => 'assets/images/port-top-left.webp', 'alt' => 'Featured book cover'],
    ['src' => 'assets/images/port-top-right.webp', 'alt' => 'Featured book cover'],
  ];
}

$portfolioV2GalleryJson = htmlspecialchars(json_encode($portfolioV2Slides), ENT_QUOTES, 'UTF-8');
?>

<section class="portfolio-v2" id="portfolio-v2">
  <div class="portfolio-v2__carousel">
    <div
      class="swiper portfolio-v2__swiper"
      data-portfolio-v2-gallery="<?= $portfolioV2GalleryJson ?>"
    >
      <div class="swiper-wrapper">
        <?php foreach ($portfolioV2Slides as $index => $slide): ?>
        <div class="swiper-slide">
          <article class="portfolio-v2__card">
            <a
              href="<?= htmlspecialchars($slide['src'], ENT_QUOTES, 'UTF-8') ?>"
              class="portfolio-v2__lightbox"
              data-fancybox="portfolio-v2"
              data-type="image"
              data-caption="<?= htmlspecialchars($slide['alt'], ENT_QUOTES, 'UTF-8') ?>"
            >
              <img
                src="<?= htmlspecialchars($slide['src'], ENT_QUOTES, 'UTF-8') ?>"
                alt="<?= htmlspecialchars($slide['alt'], ENT_QUOTES, 'UTF-8') ?>"
                class="portfolio-v2__img"
                loading="lazy"
              >
            </a>
          </article>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

    <div class="portfolio-v2__actions">
      <button class="portfolio-v2__control portfolio-v2__control--prev" type="button" aria-label="Previous portfolio item">
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M12.5 15L7.5 10L12.5 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
      <button class="portfolio-v2__control portfolio-v2__control--next" type="button" aria-label="Next portfolio item">
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M7.5 5L12.5 10L7.5 15" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
    </div>
  </div>
</section>

<style>
  .portfolio-v2 {
    --pv2-primary: #881D1C;
    --pv2-primary-hover: #651c2b;
    --pv2-dark: #1a1a1a;
    --pv2-text: #555;
    --pv2-card-width: 280px;
    --pv2-actions-height: 120px;
    --pv2-font-serif: "Times New Roman", Times, serif;
    --pv2-font-sans: "Inter", system-ui, sans-serif;
    position: relative;
    padding: 0 0 80px;
    overflow: hidden;
    background: #fff;
  }

  .portfolio-v2__carousel {
    position: relative;
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .portfolio-v2__swiper {
    padding-bottom: var(--pv2-actions-height);
    overflow: visible;
  }

  .portfolio-v2__swiper .swiper-wrapper {
    align-items: flex-end;
  }

  .portfolio-v2__card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
  }

  .portfolio-v2__lightbox {
    display: block;
    width: var(--pv2-card-width);
    max-width: 100%;
    aspect-ratio: 2 / 3;
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 18px 40px rgba(0, 0, 0, 0.16);
    transform-origin: bottom center;
    transition: box-shadow 0.35s ease;
  }

  .portfolio-v2__lightbox:hover {
    box-shadow: 0 22px 48px rgba(0, 0, 0, 0.22);
  }

  .portfolio-v2__img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center top;
  }

  .portfolio-v2__actions {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: var(--pv2-actions-height);
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;
    pointer-events: none;
  }

  .portfolio-v2__control {
    pointer-events: auto;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 52px;
    height: 52px;
    border: 0;
    border-radius: 50%;
    background: var(--pv2-dark);
    color: #fff;
    cursor: pointer;
    transition: background-color 0.25s ease, transform 0.25s ease;
  }

  .portfolio-v2__control:hover {
    background: var(--pv2-primary);
    transform: scale(1.05);
  }

  .portfolio-v2__control.swiper-button-disabled {
    opacity: 0.35;
    cursor: default;
    transform: none;
  }

  @media (max-width: 1199px) {
    .portfolio-v2 {
      --pv2-card-width: 240px;
    }
  }

  @media (max-width: 767px) {
    .portfolio-v2 {
      --pv2-card-width: 210px;
      --pv2-actions-height: 100px;
      padding-bottom: 60px;
    }

    .portfolio-v2__control {
      width: 46px;
      height: 46px;
    }
  }
</style>

<script>
  (function () {
    function initPortfolioV2() {
      var root = document.getElementById('portfolio-v2');
      if (!root || root.dataset.portfolioV2Ready === 'true') {
        return;
      }

      var swiperEl = root.querySelector('.portfolio-v2__swiper');
      if (!swiperEl || typeof Swiper === 'undefined') {
        return;
      }

      var prevBtn = root.querySelector('.portfolio-v2__control--prev');
      var nextBtn = root.querySelector('.portfolio-v2__control--next');
      var creativeEffect = {
        perspective: true,
        limitProgress: 3,
        prev: {
          translate: ['-90%', '20%', -100],
          rotate: [0, 0, -20],
          origin: 'bottom',
        },
        next: {
          translate: ['90%', '20%', -100],
          rotate: [0, 0, 20],
          origin: 'bottom',
        },
      };

      var portfolioV2Swiper = new Swiper(swiperEl, {
        loop: true,
        grabCursor: true,
        centeredSlides: true,
        centeredSlidesBounds: true,
        speed: 600,
        slidesPerView: 1.15,
        spaceBetween: 16,
        effect: 'creative',
        creativeEffect: creativeEffect,
        navigation: {
          nextEl: nextBtn,
          prevEl: prevBtn,
        },
        breakpoints: {
          768: {
            slidesPerView: 2,
            spaceBetween: 24,
          },
          1200: {
            slidesPerView: 3,
            spaceBetween: 28,
          },
        },
      });

      swiperEl.addEventListener('click', function (event) {
        var link = event.target.closest('.portfolio-v2__lightbox');
        if (!link || portfolioV2Swiper.allowClick === false) {
          return;
        }

        event.preventDefault();

        if (typeof Fancybox !== 'undefined') {
          Fancybox.show([{ src: link.getAttribute('href'), type: 'image', caption: link.getAttribute('data-caption') || '' }]);
        }
      });

      root.dataset.portfolioV2Ready = 'true';
    }

    if (document.readyState === 'complete') {
      initPortfolioV2();
    } else {
      window.addEventListener('load', initPortfolioV2);
    }
  })();
</script>
