<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

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

<!-- Lightbox overlay -->
<div id="cf7pa-lightbox" class="hidden fixed inset-0 z-[99999] flex items-center justify-center bg-black/80" role="dialog" aria-modal="true">
  <button id="cf7pa-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="cf7pa-lightbox-img" src="" alt="" class="max-h-[90vh] max-w-[90vw] rounded-lg shadow-2xl object-contain" />
</div>

<!-- Get Code Modal -->
<div id="cf7pa-code-modal" class="hidden fixed inset-0 z-[99998] flex items-center justify-center bg-black/75" role="dialog" aria-modal="true">
  <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4 p-6">
    <button id="cf7pa-code-modal-close" class="absolute top-3 right-4 text-gray-400 hover:text-gray-700 text-2xl leading-none focus:outline-none" aria-label="Close">&times;</button>
    <h3 id="cf7pa-code-modal-title" class="text-base font-semibold text-gray-900 mb-1"></h3>
    <p class="text-xs text-gray-500 mb-3">
      Paste this into the <strong>Form</strong> tab of a new Contact Form 7 form, then configure the <strong>Stripe Checkout</strong> tab to enable payment.
    </p>
    <div class="relative">
      <pre id="cf7pa-code-block" class="bg-gray-50 border border-gray-200 rounded-lg p-4 pr-16 text-xs text-gray-800 overflow-x-auto overflow-y-auto max-h-72 whitespace-pre-wrap break-words font-mono leading-relaxed"></pre>
      <button id="cf7pa-copy-btn" class="absolute top-2 right-2 inline-flex items-center gap-1 text-xs font-medium bg-white border border-gray-300 rounded-full px-2.5 py-1 text-gray-600 hover:text-blue-600 hover:border-blue-300 transition-colors shadow-sm">
        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>
        </svg>
        Copy
      </button>
    </div>
    <span id="cf7pa-copy-toast" class="hidden mt-2 inline-block text-xs text-green-600 font-medium">&#10003; Copied to clipboard!</span>
  </div>
</div>

<div id="templates" class="cf7pa-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">

    <!-- Header row -->
    <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 Contact Form 7</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="cf7pa-template-search"
          type="search"
          autocomplete="off"
          placeholder="Search templates..."
          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>

    <!-- Plan filter tabs -->
    <div class="mt-4 flex flex-wrap gap-2">
      <button class="cf7pa-plan-filter cf7pa-plan-filter--active text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors" data-plan="all">All</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-green-400 hover:text-green-600" data-plan="free">Free</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-amber-400 hover:text-amber-600" data-plan="pro">Pro</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-blue-400 hover:text-blue-600" data-plan="redirect">Redirect</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-blue-400 hover:text-blue-600" data-plan="credit-card">Credit Card</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-blue-400 hover:text-blue-600" data-plan="payment-element">Payment Element</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-blue-400 hover:text-blue-600" data-plan="subscription">Subscription</button>
      <button class="cf7pa-plan-filter text-xs font-semibold rounded-full px-4 py-1.5 border transition-colors border-gray-300 text-gray-600 hover:border-blue-400 hover:text-blue-600" data-plan="flex">Flex</button>
    </div>

    <p id="cf7pa-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="cf7pa-template-grid">
      <?php foreach ( $templates as $index => $template ) {
        $is_pro    = $template['plan'] === 'pro';
        $demo_url  = $template['demo_url'] ?? '';
        $preview   = $template['preview'] ?? '';
        $form_code = $template['form_code'] ?? '';
        $type      = $template['type'] ?? '';
      ?>
        <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 cf7pa-template-card"
             data-name="<?php echo esc_attr( strtolower( $template['name'] . ' ' . $type ) ) ?>"
             data-plan="<?php echo esc_attr( $template['plan'] ) ?>"
             data-type="<?php echo esc_attr( $type ) ?>">

          <!-- 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 } else { ?>
              <span class="absolute top-2 right-2 z-10 bg-green-500 text-white text-[11px] font-semibold px-2 py-0.5 rounded-full shadow">FREE</span>
            <?php } ?>
            <img
              src="<?php echo esc_url( $preview ) ?>"
              alt="<?php echo esc_attr( $template['name'] ) ?>"
              class="cf7pa-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="cf7pa-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 pt-3 border-t border-gray-100">
              <?php if ( $isPremium || ! $is_pro ) { ?>
              <div class="flex gap-2">
                <button
                  data-name="<?php echo esc_attr( $template['name'] ) ?>"
                  data-code="<?php echo esc_attr( $form_code ) ?>"
                  class="cf7pa-get-code-btn flex-1 inline-flex items-center justify-center gap-1.5 text-xs font-semibold text-blue-600 bg-blue-50 hover:bg-blue-100 border border-blue-200 hover:border-blue-300 rounded-lg px-3 py-2 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1">
                  <svg class="w-3.5 h-3.5 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
                  </svg>
                  Code
                </button>
                <button
                  data-index="<?php echo esc_attr( $index ) ?>"
                  data-name="<?php echo esc_attr( $template['name'] ) ?>"
                  class="cf7pa-import-btn flex-1 inline-flex items-center justify-center gap-1.5 text-xs font-semibold text-green-700 bg-green-50 hover:bg-green-100 border border-green-200 hover:border-green-300 rounded-lg px-3 py-2 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-green-400 focus:ring-offset-1">
                  <svg class="w-3.5 h-3.5 shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path d="M12 4v16m-8-8h16"/>
                  </svg>
                  Import
                </button>
              </div>
              <?php if ( $demo_url ) { ?>
              <a href="<?php echo esc_url( $demo_url ) ?>" target="_blank" rel="noopener noreferrer"
                 class="mt-2 flex items-center justify-center gap-1 text-xs text-gray-400 hover:text-gray-600 transition-colors">
                <svg class="w-3 h-3" 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>
                View Demo
              </a>
              <?php } ?>
              <?php } else { ?>
              <div class="flex flex-col items-center gap-2">
                <span class="w-full inline-flex items-center justify-center gap-1.5 text-xs font-semibold text-amber-600 border border-amber-200 bg-amber-50 rounded-lg px-3 py-2">
                  <svg class="w-3.5 h-3.5 shrink-0" 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 if ( $demo_url ) { ?>
                <a href="<?php echo esc_url( $demo_url ) ?>" target="_blank" rel="noopener noreferrer"
                   class="flex items-center justify-center gap-1 text-xs text-gray-400 hover:text-gray-600 transition-colors">
                  <svg class="w-3 h-3" 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>
                  View Demo
                </a>
                <?php } ?>
              </div>
              <?php } ?>
            </div>
          </div>

        </div>
      <?php } ?>
    </div>

  </div>
</div>

<style>
  #cf7pa-lightbox { cursor: zoom-out; }
  .cf7pa-plan-filter--active { background-color: #3b82f6; border-color: #3b82f6; color: #fff; }
  .cf7pa-plan-filter--active:hover { background-color: #2563eb; border-color: #2563eb; color: #fff; }
</style>

<script>
(function () {
  // ── Lightbox ──────────────────────────────────────────────────────────────
  var lb      = document.getElementById('cf7pa-lightbox');
  var lbImg   = document.getElementById('cf7pa-lightbox-img');
  var lbClose = document.getElementById('cf7pa-lightbox-close');

  function openLightbox(src) {
    lbImg.src = src;
    lb.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }
  function closeLightbox() {
    lb.classList.add('hidden');
    lbImg.src = '';
    document.body.style.overflow = '';
  }

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

  lbClose.addEventListener('click', closeLightbox);
  lb.addEventListener('click', function (e) { if (e.target === lb) closeLightbox(); });

  // ── Code Modal ────────────────────────────────────────────────────────────
  var modal      = document.getElementById('cf7pa-code-modal');
  var modalTitle = document.getElementById('cf7pa-code-modal-title');
  var codeBlock  = document.getElementById('cf7pa-code-block');
  var modalClose = document.getElementById('cf7pa-code-modal-close');
  var copyBtn    = document.getElementById('cf7pa-copy-btn');
  var copyToast  = document.getElementById('cf7pa-copy-toast');

  function openCodeModal(name, code) {
    modalTitle.textContent = name;
    codeBlock.textContent  = code;
    copyToast.classList.add('hidden');
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }
  function closeCodeModal() {
    modal.classList.add('hidden');
    document.body.style.overflow = '';
  }

  document.querySelectorAll('.cf7pa-get-code-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      openCodeModal(btn.dataset.name, btn.dataset.code);
    });
  });

  modalClose.addEventListener('click', closeCodeModal);
  modal.addEventListener('click', function (e) { if (e.target === modal) closeCodeModal(); });

  copyBtn.addEventListener('click', function () {
    var text = codeBlock.textContent;
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).then(showCopyToast).catch(fallbackCopy.bind(null, text));
    } else {
      fallbackCopy(text);
    }
  });

  function fallbackCopy(text) {
    var ta = document.createElement('textarea');
    ta.value = text;
    ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none;';
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    try { document.execCommand('copy'); showCopyToast(); } catch (e) {}
    document.body.removeChild(ta);
  }

  function showCopyToast() {
    copyToast.classList.remove('hidden');
    setTimeout(function () { copyToast.classList.add('hidden'); }, 3000);
  }

  // ── Global keyboard ───────────────────────────────────────────────────────
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') { closeLightbox(); closeCodeModal(); }
  });

  // ── Import ────────────────────────────────────────────────────────────────
  document.querySelectorAll('.cf7pa-import-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var index       = parseInt(btn.dataset.index, 10);
      var originalHTML = btn.innerHTML;
      btn.disabled    = true;
      btn.textContent = 'Importing\u2026';
      fetch(cf7paSettings.root + 'admin/templates/import', {
        method:  'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce':   cf7paSettings.nonce
        },
        body: JSON.stringify({ index: index })
      })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        if (data && data.edit_url) {
          window.location.href = data.edit_url;
        } else {
          alert((data && data.message) ? data.message : 'Import failed. Please try again.');
          btn.disabled  = false;
          btn.innerHTML = originalHTML;
        }
      })
      .catch(function () {
        alert('Network error. Please try again.');
        btn.disabled  = false;
        btn.innerHTML = originalHTML;
      });
    });
  });

  // ── Search ────────────────────────────────────────────────────────────────
  var searchInput = document.getElementById('cf7pa-template-search');
  var noResults   = document.getElementById('cf7pa-template-no-results');
  var cards       = document.querySelectorAll('.cf7pa-template-card');
  var activePlan  = 'all';

  function applyFilters() {
    var query = searchInput.value.trim().toLowerCase();
    var visible = 0;
    cards.forEach(function (card) {
      var name = card.dataset.name || '';
      var plan = card.dataset.plan || '';
      var type = card.dataset.type || '';

      var planMatch = activePlan === 'all' || plan === activePlan || type === activePlan;

      var nameMatch = 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 show = planMatch && nameMatch;
      card.style.display = show ? '' : 'none';
      if (show) visible++;
    });
    noResults.classList.toggle('hidden', visible > 0);
  }

  searchInput.addEventListener('input', applyFilters);

  // ── Plan / Type filter tabs ───────────────────────────────────────────────
  document.querySelectorAll('.cf7pa-plan-filter').forEach(function (btn) {
    btn.addEventListener('click', function () {
      activePlan = btn.dataset.plan;

      document.querySelectorAll('.cf7pa-plan-filter').forEach(function (b) {
        b.classList.remove('cf7pa-plan-filter--active');
        b.style.backgroundColor = '';
        b.style.borderColor = '';
        b.style.color = '';
      });
      btn.classList.add('cf7pa-plan-filter--active');
      applyFilters();
    });
  });

})();
</script>
