<section class="project-form-shell">
  <div class="admin-header">
    <h1>New Draft &middot; <%= prospect.companyName %></h1>
    <a class="button button-secondary" href="/admin/crm/<%= prospect.id %>/edit">Back to prospect</a>
  </div>

  <form method="POST" action="/admin/crm/<%= prospect.id %>/drafts">
    <div class="form-section">
      <label>
        Start from a template <span class="hint">(optional - fills in subject/body below, still fully editable)</span>
        <select id="template-picker">
          <option value="">Blank</option>
          <% templates.forEach(function(t) { %>
            <option value="<%= t.id %>"><%= t.category ? t.category + ' - ' : '' %><%= t.name %></option>
          <% }) %>
        </select>
      </label>
      <% if (!templates.length) { %>
        <p class="hint">No templates yet - <a href="/admin/crm/templates/new">create one</a> to reuse it here next time.</p>
      <% } %>
    </div>

    <div class="form-section">
      <label>
        Direction
        <select name="direction">
          <option value="outbound">Outbound (first outreach / follow-up)</option>
          <option value="reply">Reply (to something this prospect sent)</option>
        </select>
      </label>
      <label>
        Subject
        <input type="text" name="subject" id="draft-subject" required>
      </label>
      <label>
        Body
        <textarea name="body" id="draft-body" rows="12" required></textarea>
      </label>
    </div>
    <button type="submit" class="button button-primary">Add to review queue</button>
  </form>
</section>

<script>
  (function () {
    var PROSPECT = <%- JSON.stringify({
      companyName: prospect.companyName || '',
      contactName: prospect.contactName || '',
      email: prospect.email || '',
      sector: prospect.sector || '',
      region: prospect.region || '',
    }).replace(/</g, '\\u003c') %>;

    var TEMPLATES = <%- JSON.stringify(templates.map(function (t) {
      return { id: t.id, subject: t.subject, body: t.body };
    })).replace(/</g, '\\u003c') %>;

    function fillPlaceholders(text) {
      return text.replace(/\{\{(\w+)\}\}/g, function (match, key) {
        return Object.prototype.hasOwnProperty.call(PROSPECT, key) ? PROSPECT[key] : match;
      });
    }

    var picker = document.getElementById('template-picker');
    var subjectField = document.getElementById('draft-subject');
    var bodyField = document.getElementById('draft-body');

    picker.addEventListener('change', function () {
      var template = TEMPLATES.filter(function (t) { return String(t.id) === picker.value; })[0];
      if (!template) return;
      subjectField.value = fillPlaceholders(template.subject);
      bodyField.value = fillPlaceholders(template.body);
    });
  })();
</script>
