<section class="project-form-shell">
  <div class="admin-header">
    <h1><%= project ? 'Edit Project' : 'New Project' %></h1>
    <a class="button button-secondary" href="/admin/work">Back to Our Work</a>
  </div>

  <form method="POST" action="<%= project ? '/admin/work/' + project.id + '?_method=PUT' : '/admin/work' %>" id="project-form">

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

        <div class="form-section">
          <h3 class="form-section-title">Project details</h3>
          <label>
            Project title
            <input type="text" name="title" value="<%= project ? project.title : '' %>" required>
          </label>
          <label>
            Slug <span class="hint">(used in the URL, e.g. /work/your-slug)</span>
            <input type="text" name="slug" value="<%= project ? project.slug : '' %>" required>
          </label>
          <label>
            Summary <span class="hint">(short, one line, shown on the Our Work grid)</span>
            <input type="text" name="summary" value="<%= project && project.summary ? project.summary : '' %>">
          </label>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Client brief</h3>
          <p class="hint">What the client wanted from us.</p>
          <div id="editor-clientBrief" class="rich-editor"><%- project && project.clientBrief ? project.clientBrief : '' %></div>
          <textarea name="clientBrief" id="input-clientBrief" hidden></textarea>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Deliverables</h3>
          <p class="hint">What we actually delivered.</p>
          <div id="editor-deliverables" class="rich-editor"><%- project && project.deliverables ? project.deliverables : '' %></div>
          <textarea name="deliverables" id="input-deliverables" hidden></textarea>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Gallery</h3>
          <p class="hint">Small gallery of photos shown on the project page.</p>
          <div class="gallery-upload-grid" id="gallery-grid"></div>
          <input type="file" accept="image/*" multiple id="gallery-file-input" hidden>
          <button type="button" class="button button-secondary" id="gallery-add-btn">+ Add photos</button>
          <textarea name="galleryText" id="gallery-text" hidden><%= galleryText %></textarea>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Video</h3>
          <label>
            YouTube URL or link <span class="hint">(optional)</span>
            <input type="text" name="videoUrl" value="<%= project && project.videoUrl ? project.videoUrl : '' %>" placeholder="https://www.youtube.com/watch?v=...">
          </label>
        </div>

      </div>

      <div class="form-sidebar">

        <div class="form-section">
          <h3 class="form-section-title">Client logo</h3>
          <%- include('./_upload-field', { key: 'clientLogo', value: project && project.clientLogo ? project.clientLogo : '', label: null }) %>
          <label class="checkbox-inline" style="margin-top: 0.85rem;">
            <input type="checkbox" name="featuredClientLogo" <%= project && project.featuredClientLogo ? 'checked' : '' %>>
            Feature this logo on the homepage
          </label>
          <p class="hint" style="margin-top: 0.4rem;">Shows this client's logo in the "Organisations we've worked with" strip on the homepage. Requires a logo above and a client name.</p>
        </div>

        <div class="form-section">
          <label>
            Client name
            <input type="text" name="client" value="<%= project && project.client ? project.client : '' %>" placeholder="e.g. Sage Global Health">
          </label>
          <label>
            Client website <span class="hint">(optional — shown as a link on the case study page only if filled in)</span>
            <input type="text" name="websiteUrl" value="<%= project && project.websiteUrl ? project.websiteUrl : '' %>" placeholder="e.g. https://www.sageglobalhealth.com">
          </label>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">About the client</h3>
          <p class="hint">What the company/organisation does.</p>
          <div id="editor-clientDescription" class="rich-editor rich-editor-compact"><%- project && project.clientDescription ? project.clientDescription : '' %></div>
          <textarea name="clientDescription" id="input-clientDescription" hidden></textarea>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Featured image</h3>
          <p class="hint">Hero image shown at the top of the project and on the Our Work grid.</p>
          <%- include('./_upload-field', { key: 'featuredImage', value: project && project.featuredImage ? project.featuredImage : '', label: null }) %>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Categories</h3>
          <span class="checkbox-group">
            <% categories.forEach(function(cat) { %>
              <label class="checkbox-inline">
                <input type="checkbox" name="categoryIds" value="<%= cat.id %>"
                  <%= selectedCategoryIds.includes(cat.id) ? 'checked' : '' %>>
                <%= cat.name %>
              </label>
            <% }) %>
            <% if (!categories.length) { %><span class="hint">No categories yet. Add some under Admin &rarr; Categories.</span><% } %>
          </span>
        </div>

        <div class="form-section">
          <h3 class="form-section-title">Publishing</h3>
          <label>
            Status
            <select name="status">
              <option value="draft" <%= project && project.status === 'draft' ? 'selected' : '' %>>Draft</option>
              <option value="published" <%= project && project.status === 'published' ? 'selected' : '' %>>Published</option>
            </select>
          </label>
          <label>
            Published date <span class="hint">(leave blank to keep the existing date, or to auto-set on first publish)</span>
            <input type="datetime-local" name="publishedAt"
              value="<%= project && project.publishedAt ? project.publishedAt.toISOString().slice(0,16) : '' %>">
          </label>
          <button type="submit" class="button button-primary form-save-button">Save project</button>
        </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 PROJECT_UPLOAD_URL = '/admin/work/upload-image';

    function initRichEditor(key) {
      var container = document.getElementById('editor-' + key);
      var hidden = document.getElementById('input-' + key);
      if (!container || !hidden) return;
      var quill = new Quill(container, {
        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; });
    }
    ['clientBrief', 'deliverables', 'clientDescription'].forEach(initRichEditor);

    document.getElementById('project-form').addEventListener('submit', function () {
      document.querySelectorAll('.rich-editor').forEach(function (el) {
        var key = el.id.replace('editor-', '');
        var hidden = document.getElementById('input-' + key);
        if (hidden && !hidden.value) hidden.value = el.querySelector('.ql-editor') ? el.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(PROJECT_UPLOAD_URL, { method: 'POST', body: formData })
          .then(function (res) { return res.json(); })
          .then(function (data) {
            if (data.url) {
              hiddenInput.value = data.url;
            } else {
              alert(data.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: PROJECT_UPLOAD_URL,
            onSelect: function (url) { hiddenInput.value = url; refresh(); },
          });
        });
      }

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

    var galleryText = document.getElementById('gallery-text');
    var galleryGrid = document.getElementById('gallery-grid');
    var galleryFileInput = document.getElementById('gallery-file-input');
    var galleryAddBtn = document.getElementById('gallery-add-btn');
    var galleryUrls = (galleryText.value || '').split('\n').map(function (s) { return s.trim(); }).filter(Boolean);

    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);
      });
      galleryText.value = galleryUrls.join('\n');
    }

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

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

    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('/admin/work/upload-image', { method: 'POST', body: formData }).then(function (res) { return res.json(); });
      });
      Promise.all(uploads).then(function (results) {
        results.forEach(function (data) { if (data.url) galleryUrls.push(data.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>
