<%
  var blockMeta = blockTypes.find(function(t) { return t.type === type; });
  var d = typeof data !== 'undefined' && data ? data : {};
%>
<section class="project-form-shell">
  <div class="admin-header">
    <h1><%= block ? 'Edit block' : 'Add block' %>: <%= blockMeta ? blockMeta.label : type %></h1>
    <a class="button button-secondary" href="/admin/pages/<%= page.id %>/edit">Back to page</a>
  </div>

  <form method="POST" action="<%= block ? '/admin/pages/' + page.id + '/blocks/' + block.id + '?_method=PUT' : '/admin/pages/' + page.id + '/blocks' %>" id="block-form">
    <% if (!block) { %><input type="hidden" name="type" value="<%= type %>"><% } %>

    <div class="form-grid">
      <div class="form-main">

        <% if (type === 'hero') { %>
          <div class="form-section">
            <h3 class="form-section-title">Hero content</h3>
            <label>Eyebrow <span class="hint">(optional)</span>
              <input type="text" name="eyebrow" value="<%= d.eyebrow || '' %>">
            </label>
            <label>Headline
              <input type="text" name="headline" value="<%= d.headline || '' %>" required>
            </label>
            <label>Subheading <span class="hint">(optional)</span>
              <textarea name="subheading" rows="3"><%= d.subheading || '' %></textarea>
            </label>
          </div>
          <div class="form-section">
            <h3 class="form-section-title">Button</h3>
            <p class="hint">Optional. Leave blank to hide.</p>
            <label>Button label
              <input type="text" name="ctaLabel" value="<%= d.ctaLabel || '' %>">
            </label>
            <label>Button link
              <input type="text" name="ctaUrl" value="<%= d.ctaUrl || '' %>">
            </label>
          </div>
        <% } %>

        <% if (type === 'rich_text') { %>
          <div class="form-section">
            <h3 class="form-section-title">Content</h3>
            <div id="editor-body" class="rich-editor"><%- d.body || '' %></div>
            <textarea name="body" id="input-body" hidden></textarea>
          </div>
        <% } %>

        <% if (type === 'text_image') { %>
          <div class="form-section">
            <h3 class="form-section-title">Content</h3>
            <label>Heading <span class="hint">(optional)</span>
              <input type="text" name="heading" value="<%= d.heading || '' %>">
            </label>
            <div id="editor-body" class="rich-editor rich-editor-compact"><%- d.body || '' %></div>
            <textarea name="body" id="input-body" hidden></textarea>
          </div>
          <div class="form-section">
            <h3 class="form-section-title">Layout</h3>
            <label>Image position
              <select name="imagePosition">
                <option value="left" <%= (d.imagePosition || 'left') === 'left' ? 'selected' : '' %>>Image on the left</option>
                <option value="right" <%= d.imagePosition === 'right' ? 'selected' : '' %>>Image on the right</option>
              </select>
            </label>
          </div>
        <% } %>

        <% if (type === 'columns_3') { %>
          <div class="form-section">
            <h3 class="form-section-title">Section heading</h3>
            <label>Heading <span class="hint">(optional)</span>
              <input type="text" name="heading" value="<%= d.heading || '' %>">
            </label>
          </div>
          <% for (var i = 1; i <= 3; i++) { var col = (d.columns && d.columns[i-1]) || {}; %>
            <div class="form-section">
              <h3 class="form-section-title">Column <%= i %></h3>
              <label>Title
                <input type="text" name="col<%= i %>Title" value="<%= col.title || '' %>">
              </label>
              <label>Text
                <textarea name="col<%= i %>Body" rows="3"><%= col.body || '' %></textarea>
              </label>
            </div>
          <% } %>
        <% } %>

        <% if (type === 'cta') { %>
          <div class="form-section">
            <h3 class="form-section-title">Call to action</h3>
            <label>Heading
              <input type="text" name="heading" value="<%= d.heading || '' %>" required>
            </label>
            <label>Message
              <textarea name="body" rows="3"><%= d.body || '' %></textarea>
            </label>
            <label>Button label
              <input type="text" name="buttonLabel" value="<%= d.buttonLabel || '' %>">
            </label>
            <label>Button link
              <input type="text" name="buttonUrl" value="<%= d.buttonUrl || '' %>">
            </label>
          </div>
        <% } %>

        <% if (type === 'testimonial') { %>
          <div class="form-section">
            <h3 class="form-section-title">Testimonial</h3>
            <label>Quote
              <textarea name="quote" rows="4" required><%= d.quote || '' %></textarea>
            </label>
            <label>Name
              <input type="text" name="name" value="<%= d.name || '' %>">
            </label>
            <label>Role / company <span class="hint">(optional)</span>
              <input type="text" name="role" value="<%= d.role || '' %>">
            </label>
          </div>
        <% } %>

        <% if (type === 'faq') { %>
          <div class="form-section">
            <h3 class="form-section-title">Section heading</h3>
            <label>Heading <span class="hint">(optional)</span>
              <input type="text" name="heading" value="<%= d.heading || '' %>">
            </label>
          </div>
          <% for (var j = 1; j <= 5; j++) { var item = (d.items && d.items[j-1]) || {}; %>
            <div class="form-section">
              <h3 class="form-section-title">Question <%= j %> <span class="hint">(leave blank to skip)</span></h3>
              <label>Question
                <input type="text" name="q<%= j %>" value="<%= item.question || '' %>">
              </label>
              <label>Answer
                <textarea name="a<%= j %>" rows="2"><%= item.answer || '' %></textarea>
              </label>
            </div>
          <% } %>
        <% } %>

        <% if (type === 'gallery') { %>
          <div class="form-section">
            <h3 class="form-section-title">Photos</h3>
            <div class="gallery-upload-grid" id="gallery-grid"></div>
            <input type="file" accept="image/*" multiple id="gallery-file-input" hidden>
            <div class="upload-actions">
              <button type="button" class="button button-secondary" id="gallery-add-btn">+ Add photos</button>
              <button type="button" class="button button-secondary" id="gallery-browse-btn">Choose from library</button>
            </div>
            <input type="hidden" name="imagesJson" id="gallery-json" value='<%- JSON.stringify(d.images || []) %>'>
          </div>
        <% } %>

      </div>

      <div class="form-sidebar">
        <% if (type === 'hero' || type === 'text_image') { %>
          <div class="form-section">
            <h3 class="form-section-title">Image</h3>
            <%- include('../partials/_upload-field', { key: 'image', value: d.image || '' }) %>
          </div>
        <% } %>
        <div class="form-section">
          <button type="submit" class="button button-primary form-save-button">Save block</button>
          <% if (block) { %>
            <form action="/admin/pages/<%= page.id %>/blocks/<%= block.id %>?_method=DELETE" method="POST"
                  onsubmit="return confirm('Delete this block?')" style="margin-top:0.75rem;">
              <button type="submit" class="button-ghost" style="width:100%;">Delete block</button>
            </form>
          <% } %>
        </div>
      </div>
    </div>
  </form>
</section>

<script src="/js/media-picker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.7/quill.min.js"></script>
<script>
  (function () {
    var BLOCK_UPLOAD_URL = '/admin/pages/<%= page.id %>/blocks/upload-image';
    var editorEl = document.getElementById('editor-body');
    if (editorEl) {
      var hidden = document.getElementById('input-body');
      var quill = new Quill(editorEl, {
        theme: 'snow',
        modules: { toolbar: [['bold', 'italic', 'underline'], [{ list: 'ordered' }, { list: 'bullet' }], ['link'], ['clean']] },
      });
      hidden.value = quill.root.innerHTML;
      quill.on('text-change', function () { hidden.value = quill.root.innerHTML; });
      document.getElementById('block-form').addEventListener('submit', function () {
        if (!hidden.value) hidden.value = editorEl.querySelector('.ql-editor') ? editorEl.querySelector('.ql-editor').innerHTML : '';
      });
    }

    function setupUploadField(key) {
      var fileInput = document.getElementById('file-' + key);
      var hiddenInput = document.getElementById('input-' + key);
      var preview = document.getElementById('preview-' + key);
      var removeBtn = document.querySelector('.upload-remove[data-target="' + key + '"]');
      var browseBtn = document.querySelector('.upload-browse[data-target="' + key + '"]');
      if (!fileInput || !hiddenInput || !preview) return;

      function refresh() {
        if (hiddenInput.value) {
          preview.innerHTML = '<img src="' + hiddenInput.value + '" alt="">';
          if (removeBtn) removeBtn.hidden = false;
        } else {
          preview.innerHTML = '<span class="upload-empty">No image yet</span>';
          if (removeBtn) removeBtn.hidden = true;
        }
      }

      fileInput.addEventListener('change', function () {
        if (!fileInput.files.length) return;
        var formData = new FormData();
        formData.append('file', fileInput.files[0]);
        preview.innerHTML = '<span class="upload-empty">Uploading&hellip;</span>';
        fetch(BLOCK_UPLOAD_URL, { method: 'POST', body: formData })
          .then(function (res) { return res.json(); })
          .then(function (resData) {
            if (resData.url) { hiddenInput.value = resData.url; } else { alert(resData.error || 'Upload failed.'); }
            refresh();
          })
          .catch(function () { alert('Upload failed. Please try again.'); refresh(); })
          .finally(function () { fileInput.value = ''; });
      });

      if (browseBtn) {
        browseBtn.addEventListener('click', function () {
          window.openMediaPicker({
            uploadUrl: BLOCK_UPLOAD_URL,
            onSelect: function (url) { hiddenInput.value = url; refresh(); },
          });
        });
      }

      if (removeBtn) removeBtn.addEventListener('click', function () { hiddenInput.value = ''; refresh(); });
      refresh();
    }
    ['image'].forEach(setupUploadField);

    var galleryGrid = document.getElementById('gallery-grid');
    if (galleryGrid) {
      var galleryJson = document.getElementById('gallery-json');
      var galleryFileInput = document.getElementById('gallery-file-input');
      var galleryAddBtn = document.getElementById('gallery-add-btn');
      var galleryBrowseBtn = document.getElementById('gallery-browse-btn');
      var galleryUrls = [];
      try { galleryUrls = JSON.parse(galleryJson.value || '[]'); } catch (e) { galleryUrls = []; }

      function renderGallery() {
        galleryGrid.innerHTML = '';
        galleryUrls.forEach(function (url, idx) {
          var item = document.createElement('div');
          item.className = 'gallery-upload-item';
          item.innerHTML = '<img src="' + url + '" alt="">' +
            '<button type="button" class="gallery-remove" data-idx="' + idx + '" aria-label="Remove photo">&times;</button>';
          galleryGrid.appendChild(item);
        });
        galleryJson.value = JSON.stringify(galleryUrls);
      }

      galleryGrid.addEventListener('click', function (e) {
        var btn = e.target.closest('.gallery-remove');
        if (!btn) return;
        galleryUrls.splice(parseInt(btn.getAttribute('data-idx'), 10), 1);
        renderGallery();
      });

      galleryAddBtn.addEventListener('click', function () { galleryFileInput.click(); });

      if (galleryBrowseBtn) {
        galleryBrowseBtn.addEventListener('click', function () {
          window.openMediaPicker({
            uploadUrl: BLOCK_UPLOAD_URL,
            onSelect: function (url) { galleryUrls.push(url); renderGallery(); },
          });
        });
      }

      galleryFileInput.addEventListener('change', function () {
        var files = Array.prototype.slice.call(galleryFileInput.files || []);
        if (!files.length) return;
        galleryAddBtn.textContent = 'Uploading…';
        galleryAddBtn.disabled = true;
        var uploads = files.map(function (file) {
          var formData = new FormData();
          formData.append('file', file);
          return fetch(BLOCK_UPLOAD_URL, { method: 'POST', body: formData }).then(function (res) { return res.json(); });
        });
        Promise.all(uploads).then(function (results) {
          results.forEach(function (resData) { if (resData.url) galleryUrls.push(resData.url); });
          renderGallery();
        }).catch(function () {
          alert('One or more photos failed to upload. Please try again.');
        }).finally(function () {
          galleryAddBtn.textContent = '+ Add photos';
          galleryAddBtn.disabled = false;
          galleryFileInput.value = '';
        });
      });

      renderGallery();
    }
  })();
</script>
