<%
  // Pre-RTF quotes stored these fields as plain "one per line" text; new
  // ones store Quill's HTML. Detect which and render accordingly, rather
  // than escaping real markup or losing legacy line breaks.
  function renderRich(text) {
    if (!text) return '';
    if (/<[a-z][\s\S]*>/i.test(text)) return text;
    return '<p>' + text.replace(/\n/g, '<br>') + '</p>';
  }
%>
<section>
  <div class="admin-header">
    <h1><%= quote.quoteNumber %> <span class="tag tag-<%= quote.status %>"><%= quote.status %></span></h1>
    <div>
      <a class="button button-secondary" href="#" data-pdf-preview="/admin/finance/quotes/<%= quote.id %>/pdf" data-pdf-title="<%= quote.quoteNumber %>">Preview PDF</a>
      <a class="button button-secondary" href="/admin/finance/quotes/<%= quote.id %>/edit">Edit</a>
    </div>
  </div>

  <% var belowMin = Number(quote.profitMarginPercent) < Number(settings.minimumMarginPercent); %>
  <div class="margin-banner <%= belowMin ? 'margin-low' : 'margin-ok' %>">
    <div class="margin-item"><span class="margin-label">Sell total</span><strong><%= quote.currency %> <%= Number(quote.totalAmount).toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}) %></strong></div>
    <div class="margin-item"><span class="margin-label">Internal cost</span><strong><%= quote.currency %> <%= Number(quote.totalCost).toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}) %></strong></div>
    <div class="margin-item"><span class="margin-label">Profit</span><strong><%= quote.currency %> <%= Number(quote.profitAmount).toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}) %></strong></div>
    <div class="margin-item"><span class="margin-label">Margin</span><strong><%= quote.profitMarginPercent %>%</strong></div>
    <% if (belowMin) { %><span>Below the <%= settings.minimumMarginPercent %>% minimum - this quote cannot be marked "sent" without an explicit override.</span><% } %>
  </div>

  <div class="detail-grid">
    <div>
      <div class="detail-panel">
        <h3>Bill to</h3>
        <p><strong><%= quote.clientName %></strong><br>
        <% if (quote.clientOrganization) { %><%= quote.clientOrganization %><br><% } %>
        <% if (quote.clientEmail) { %><%= quote.clientEmail %><br><% } %>
        <% if (quote.clientPhone) { %><%= quote.clientPhone %><br><% } %>
        <% if (quote.billToExtra) { %><%= quote.billToExtra %><% } %></p>
        <% if (quote.referenceLine) { %><p class="hint">Re: <%= quote.referenceLine %></p><% } %>
      </div>

      <div class="detail-panel">
        <h3>Line items</h3>
        <table class="admin-table">
          <thead><tr><th>Description</th><th>Qty</th><th>Cost</th><th>Sell rate</th><th>Line total</th><th></th></tr></thead>
          <tbody>
            <% lineItems.forEach(function(li) { %>
              <tr>
                <td><%= li.description %><% if (li.category) { %><br><span class="hint"><%= li.category %></span><% } %></td>
                <td><%= Number(li.quantity) %><%= li.unit ? ' ' + li.unit : '' %></td>
                <td><%= Number(li.unitCost).toFixed(2) %></td>
                <td><%= Number(li.unitSellPrice).toFixed(2) %></td>
                <td><%= Number(li.lineSellTotal).toFixed(2) %></td>
                <td><% if (li.isOptional) { %><span class="tag">optional</span><% } %></td>
              </tr>
            <% }) %>
          </tbody>
        </table>
      </div>

      <% if (quote.inclusionsText || quote.exclusionsText || quote.termsText) { %>
        <div class="detail-panel">
          <% if (quote.inclusionsText) { %><h3>Inclusions</h3><div class="rich-text-display"><%- renderRich(quote.inclusionsText) %></div><% } %>
          <% if (quote.exclusionsText) { %><h3>Exclusions</h3><div class="rich-text-display"><%- renderRich(quote.exclusionsText) %></div><% } %>
          <% if (quote.termsText) { %><h3>Terms</h3><div class="rich-text-display"><%- renderRich(quote.termsText) %></div><% } %>
        </div>
      <% } %>

      <% if (quote.internalNotes) { %>
        <div class="detail-panel">
          <h3>Internal notes</h3>
          <div class="rich-text-display"><%- renderRich(quote.internalNotes) %></div>
        </div>
      <% } %>
    </div>

    <div>
      <div class="detail-panel">
        <h3>Status</h3>
        <form method="POST" action="/admin/finance/quotes/<%= quote.id %>/status?_method=PATCH">
          <label>
            <select name="status">
              <% STATUSES.forEach(function(s) { %>
                <option value="<%= s %>" <%= quote.status === s ? 'selected' : '' %>><%= s %></option>
              <% }) %>
            </select>
          </label>
          <% if (belowMin) { %>
            <label style="display:flex; align-items:center; gap:0.5rem; margin-top:0.5rem;">
              <input type="checkbox" name="overrideMargin" style="width:auto;">
              Send below minimum margin anyway
            </label>
          <% } %>
          <button type="submit" class="button button-primary" style="width:100%; margin-top:0.75rem;">Update status</button>
        </form>
      </div>

      <div class="detail-panel">
        <h3>Convert</h3>
        <% if (invoice) { %>
          <p class="hint">Already converted to invoice:</p>
          <a class="button button-secondary" style="width:100%;" href="/admin/finance/invoices/<%= invoice.id %>">View <%= invoice.invoiceNumber %> &rarr;</a>
        <% } else { %>
          <p class="hint">Create an invoice from this quote's line items (required items only).</p>
          <form method="POST" action="/admin/finance/quotes/<%= quote.id %>/convert" onsubmit="return confirm('Convert this quote to an invoice?')">
            <button type="submit" class="button button-primary" style="width:100%;">Convert to invoice</button>
          </form>
        <% } %>
      </div>

      <div class="detail-panel">
        <h3>Details</h3>
        <p class="hint">
          Event date: <%= quote.eventDate ? new Date(quote.eventDate).toLocaleDateString('en-GB', {day:'numeric', month:'long', year:'numeric'}) : 'not set' %><br>
          Guests: <%= quote.guestCount || 'not set' %><br>
          Valid until: <%= quote.validUntil ? new Date(quote.validUntil).toLocaleDateString('en-GB', {day:'numeric', month:'long', year:'numeric'}) : 'not set' %><br>
          Drafted by: <%= quote.draftedByName || 'not set' %><br>
          Sent: <%= quote.sentAt ? new Date(quote.sentAt).toLocaleDateString('en-GB', {day:'numeric', month:'long', year:'numeric'}) : 'not yet' %>
        </p>
      </div>

      <div class="detail-panel">
        <form action="/admin/finance/quotes/<%= quote.id %>?_method=DELETE" method="POST" onsubmit="return confirm('Delete this quote? This cannot be undone.')">
          <button type="submit" class="button button-ghost" style="width:100%;">Delete quote</button>
        </form>
      </div>
    </div>
  </div>
</section>
