<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

$list_json_path = EPA_ADDONS_PATH . 'includes/templates/elements/templates.json';
$templates = file_exists( $list_json_path )
    ? ( json_decode( file_get_contents( $list_json_path ), true ) ?? [] )
    : [];

$isPremium = Elementor_Pay_Addons\Shared\Security_Utils::is_pro();
?>

<!-- Lightbox overlay -->
<div id="epa-lightbox" class="hidden fixed inset-0 z-[99999] flex items-center justify-center bg-black/80" role="dialog" aria-modal="true">
  <button id="epa-lightbox-close" class="absolute top-4 right-6 text-white text-3xl leading-none hover:text-gray-300 focus:outline-none" aria-label="Close">&times;</button>
  <img id="epa-lightbox-img" src="" alt="" class="max-h-[90vh] max-w-[90vw] rounded-lg shadow-2xl object-contain" />
</div>

<div id="templates" class="epa-tab-panel p-8">
  <div class="mx-auto max-w-2xl py-4 px-4 sm:px-6 lg:max-w-7xl lg:px-8">
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
      <h2 class="text-2xl font-bold tracking-tight text-gray-900">Templates For Elementor</h2>
      <div class="relative w-full sm:w-64">
        <span class="absolute inset-y-0 right-3 flex items-center pointer-events-none text-gray-400">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
          </svg>
        </span>
        <input
          id="epa-template-search"
          type="search"
          autocomplete="off"
          class="w-full pl-4 pr-9 py-2 text-sm border border-gray-300 rounded-full bg-white shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition"
        />
      </div>
    </div>

    <!-- Filter Tags -->
    <div id="epa-template-filters" class="mt-4 flex flex-wrap items-center gap-2">
      <button type="button" class="epa-filter-tag active" data-filter="all">All</button>
      <button type="button" class="epa-filter-tag" data-filter="redirect">Redirect</button>
      <button type="button" class="epa-filter-tag" data-filter="credit-card">Credit Card</button>
      <button type="button" class="epa-filter-tag" data-filter="payment-element">Multiple Payment Methods</button>
      <button type="button" class="epa-filter-tag" data-filter="multiple-steps">Multiple Steps</button>
      <button type="button" class="epa-filter-tag" data-filter="subscription">Subscription</button>
      <button type="button" class="epa-filter-tag" data-filter="flex">Flex</button>
    </div>
    <p id="epa-template-no-results" class="hidden mt-10 text-center text-sm text-gray-400">No templates found.</p>
    <div class="mt-6 grid grid-cols-1 gap-y-8 gap-x-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8" id="epa-template-grid">
      <?php foreach ($templates as $template) {
        $is_pro   = $template['plan'] === 'pro';
        $demo_url = $template['demo_url'] ?? '';
        $preview  = $template['preview'] ?? '';
        $tags     = $template['tags'] ?? [];
      ?>
        <div
          class="group flex flex-col rounded-xl border border-gray-200 bg-white shadow-sm hover:shadow-md transition-shadow duration-200 overflow-hidden epa-template-card"
          data-name="<?php echo esc_attr( strtolower( $template['name'] ) ) ?>"
          data-plan="<?php echo esc_attr( $template['plan'] ) ?>"
          data-tags="<?php echo esc_attr( implode( ',', $tags ) ) ?>"
        >

          <!-- Image -->
          <div class="relative overflow-hidden bg-gray-100 cursor-zoom-in" style="height:180px">
            <?php if ( $is_pro ) { ?>
              <span class="absolute top-2 right-2 z-10 bg-amber-400 text-white text-[11px] font-semibold px-2 py-0.5 rounded-full shadow">PRO</span>
            <?php } ?>
            <img
              src="<?php echo esc_url( $preview ) ?>"
              alt="<?php echo esc_attr( $template['name'] ) ?>"
              class="epa-preview-img w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
              data-full="<?php echo esc_url( $preview ) ?>"
            />
            <!-- zoom icon overlay -->
            <div class="epa-preview-img-wrap absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 bg-black/20 cursor-zoom-in">
              <svg class="w-8 h-8 text-white drop-shadow" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                <line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/>
              </svg>
            </div>
          </div>

          <!-- Body -->
          <div class="flex flex-col flex-1 p-4">
            <h3 class="font-semibold text-gray-800 text-sm mb-1"><?php echo esc_html( $template['name'] ) ?></h3>
            <p class="text-xs text-gray-500 leading-relaxed line-clamp-3 flex-1" title="<?php echo esc_attr( $template['desc'] ) ?>">
              <?php echo esc_html( $template['desc'] ) ?>
            </p>

            <!-- Actions -->
            <div class="mt-4 flex items-center justify-between gap-2">
              <?php if ( $demo_url ) { ?>
              <a href="<?php echo esc_url( $demo_url ) ?>" target="_blank"
                 class="inline-flex items-center gap-1 text-xs font-medium text-gray-500 border border-gray-300 rounded-full px-3 py-1 hover:text-gray-800 hover:border-gray-500 transition-colors">
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                  <path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                  <path d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                </svg>
                Demo
              </a>
              <?php } else { ?>
              <span></span>
              <?php } ?>

              <?php if ( $isPremium || ! $is_pro ) { ?>
              <a href="<?php echo esc_url( $template['download_url'] ) ?>"
                 data-url="<?php echo esc_url( $template['download_url'] ) ?>"
                 class="link-template-download inline-flex items-center gap-1 text-xs font-semibold text-white hover:text-white  bg-blue-600 hover:bg-blue-700 rounded-full px-3 py-1 transition-colors">
                <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
                  <path clip-rule="evenodd" fill-rule="evenodd" d="M5.5 17a4.5 4.5 0 01-1.44-8.765 4.5 4.5 0 018.302-3.046 3.5 3.5 0 014.504 4.272A4 4 0 0115 17H5.5zm5.25-9.25a.75.75 0 00-1.5 0v4.59l-1.95-2.1a.75.75 0 10-1.1 1.02l3.25 3.5a.75.75 0 001.1 0l3.25-3.5a.75.75 0 10-1.1-1.02l-1.95 2.1V7.75z"/>
                </svg>
                Insert
              </a>
              <?php } else { ?>
              <span class="inline-flex items-center gap-1 text-xs font-semibold text-amber-600 border border-amber-300 bg-amber-50 rounded-full px-3 py-1">
                <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"/>
                </svg>
                Pro Only
              </span>
              <?php } ?>
            </div>
          </div>
        </div>
      <?php } ?>
    </div>
  </div>
  <div id="alert"></div>
</div>

<style>
  #epa-lightbox { cursor: zoom-out; }
  .line-clamp-3 { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }

  .epa-filter-tag {
    display: inline-flex;
    align-items: center;
    padding: 6px 18px;
    font-size: 14px;
    font-weight: 500;
    color: #4b5563;
    background: #f3f4f6;
    border: 1px solid #e5e7eb;
    border-radius: 9999px;
    cursor: pointer;
    transition: all 0.15s ease;
    white-space: nowrap;
  }
  .epa-filter-tag:hover {
    background: #e5e7eb;
    color: #1f2937;
  }
  .epa-filter-tag.active {
    background: #4f6af6;
    color: #ffffff;
    border-color: #4f6af6;
  }
</style>

<script>
(function () {
  var lightbox  = document.getElementById('epa-lightbox');
  var lightImg  = document.getElementById('epa-lightbox-img');
  var closeBtn  = document.getElementById('epa-lightbox-close');

  function openLightbox(src) {
    lightImg.src = src;
    lightbox.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }

  function closeLightbox() {
    lightbox.classList.add('hidden');
    lightImg.src = '';
    document.body.style.overflow = '';
  }

  // Click on image or overlay
  document.querySelectorAll('.epa-preview-img, .epa-preview-img-wrap').forEach(function (el) {
    el.addEventListener('click', function () {
      var img = el.classList.contains('epa-preview-img') ? el : el.closest('.relative').querySelector('.epa-preview-img');
      openLightbox(img.dataset.full || img.src);
    });
  });

  closeBtn.addEventListener('click', closeLightbox);
  lightbox.addEventListener('click', function (e) {
    if (e.target === lightbox) closeLightbox();
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') closeLightbox();
  });

  // Search / filter
  var searchInput  = document.getElementById('epa-template-search');
  var noResults    = document.getElementById('epa-template-no-results');
  var cards        = document.querySelectorAll('.epa-template-card');
  var filterBtns   = document.querySelectorAll('.epa-filter-tag');
  var activeFilter = 'all';

  function filterCards() {
    var query = searchInput.value.trim().toLowerCase();
    var visible = 0;
    cards.forEach(function (card) {
      var name = card.dataset.name || '';
      var plan = card.dataset.plan || '';
      var tags = card.dataset.tags && card.dataset.tags !== '' ? card.dataset.tags.split(',') : [];

      // Tag filter
      var tagMatch = activeFilter === 'all'
        || activeFilter === plan
        || tags.indexOf(activeFilter) !== -1;

      // Search filter
      var searchMatch = query === '' || (function () {
        var ni = 0;
        for (var i = 0; i < query.length; i++) {
          ni = name.indexOf(query[i], ni);
          if (ni === -1) return false;
          ni++;
        }
        return true;
      })();

      var match = tagMatch && searchMatch;
      card.style.display = match ? '' : 'none';
      if (match) visible++;
    });
    noResults.classList.toggle('hidden', visible > 0);
  }

  searchInput.addEventListener('input', filterCards);

  filterBtns.forEach(function (btn) {
    btn.addEventListener('click', function () {
      filterBtns.forEach(function (b) { b.classList.remove('active'); });
      btn.classList.add('active');
      activeFilter = btn.dataset.filter;
      filterCards();
    });
  });
})();
</script>