// Debrieft — app.js v2

// ── Quote line item builder ────────────────────────────────────────────────────
// Use a counter that starts high so it never collides with server-rendered indices
var lineIndex = 1000;

function addLineItem() {
  var container = document.getElementById('line-items-container');
  if (!container) return;
  var sym = (typeof QUOTE_SYM !== 'undefined') ? QUOTE_SYM : '$';
  var i = lineIndex++;
  var row = document.createElement('div');
  row.className = 'line-item-row';
  row.innerHTML =
    '<input class="line-item-desc" type="text" name="items[' + i + '][description]" placeholder="e.g. Homepage design" required>' +
    '<input class="line-item-qty" type="number" name="items[' + i + '][quantity]" placeholder="1" min="0.01" step="0.01" value="1">' +
    '<input class="line-item-price" type="number" name="items[' + i + '][unit_price]" placeholder="0.00" min="0" step="0.01" value="0">' +
    '<span class="line-item-total">' + sym + '0.00</span>' +
    '<button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)" title="Remove" style="padding:6px 8px">✕</button>';

  // Attach listeners
  var qty   = row.querySelector('.line-item-qty');
  var price = row.querySelector('.line-item-price');
  qty.addEventListener('input',   function(){ calcRow(row); });
  price.addEventListener('input', function(){ calcRow(row); });

  container.appendChild(row);
  calcTotals();
}

function removeRow(btn) {
  btn.closest('.line-item-row').remove();
  calcTotals();
}

function calcRow(row) {
  var sym   = (typeof QUOTE_SYM !== 'undefined') ? QUOTE_SYM : '$';
  var qty   = parseFloat(row.querySelector('[name*="[quantity]"]').value)   || 0;
  var price = parseFloat(row.querySelector('[name*="[unit_price]"]').value) || 0;
  var total = row.querySelector('.line-item-total');
  if (total) total.textContent = sym + (qty * price).toFixed(2);
  calcTotals();
}

function calcTotals() {
  var sym = (typeof QUOTE_SYM !== 'undefined') ? QUOTE_SYM : '$';
  var subtotal = 0;
  document.querySelectorAll('.line-item-row').forEach(function(row) {
    var qty   = parseFloat((row.querySelector('[name*="[quantity]"]')  || {}).value) || 0;
    var price = parseFloat((row.querySelector('[name*="[unit_price]"]') || {}).value) || 0;
    subtotal += qty * price;
  });

  var discEl   = document.getElementById('discount');
  var taxEl    = document.getElementById('tax_percent');
  var discount = discEl   ? (parseFloat(discEl.value)   || 0) : 0;
  var taxPct   = taxEl    ? (parseFloat(taxEl.value)    || 0) : 0;

  var afterDisc = subtotal - discount;
  var tax       = afterDisc * (taxPct / 100);
  var total     = afterDisc + tax;

  function setEl(id, val) {
    var el = document.getElementById(id);
    if (el) el.textContent = sym + val.toFixed(2);
  }
  setEl('subtotal-display', subtotal);
  setEl('tax-display',      tax);
  setEl('total-display',    total);
}

// Init existing server-rendered rows
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.line-item-row').forEach(function(row) {
    var qty   = row.querySelector('[name*="[quantity]"]');
    var price = row.querySelector('[name*="[unit_price]"]');
    var del   = row.querySelector('[type=button]');

    if (qty && price) {
      qty.addEventListener('input',   function(){ calcRow(row); });
      price.addEventListener('input', function(){ calcRow(row); });
      // Set initial total display
      var q = parseFloat(qty.value) || 0;
      var p = parseFloat(price.value) || 0;
      var t = row.querySelector('.line-item-total');
      if (t) t.textContent = '$' + (q * p).toFixed(2);
    }

    if (del && !del.getAttribute('onclick')) {
      del.addEventListener('click', function(){ removeRow(del); });
    }
  });

  // Wire up discount/tax change
  var discEl = document.getElementById('discount');
  var taxEl  = document.getElementById('tax_percent');
  if (discEl) discEl.addEventListener('input', calcTotals);
  if (taxEl)  taxEl.addEventListener('input',  calcTotals);

  calcTotals();
});

// ── Signature pad ─────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.getElementById('sig-canvas');
  if (!canvas) return;

  var ctx = canvas.getContext('2d');
  var drawing = false;

  ctx.strokeStyle = '#1a1a2e';
  ctx.lineWidth   = 2.5;
  ctx.lineCap     = 'round';
  ctx.lineJoin    = 'round';

  function getPos(e) {
    var r = canvas.getBoundingClientRect();
    var t = e.touches ? e.touches[0] : e;
    return {
      x: (t.clientX - r.left) * (canvas.width  / r.width),
      y: (t.clientY - r.top)  * (canvas.height / r.height)
    };
  }

  canvas.addEventListener('mousedown', function(e) {
    drawing = true;
    ctx.beginPath();
    var p = getPos(e);
    ctx.moveTo(p.x, p.y);
  });

  canvas.addEventListener('mousemove', function(e) {
    if (!drawing) return;
    var p = getPos(e);
    ctx.lineTo(p.x, p.y);
    ctx.stroke();
  });

  canvas.addEventListener('mouseup',    function() { drawing = false; saveSignature(); });
  canvas.addEventListener('mouseleave', function() { if (drawing) { drawing = false; saveSignature(); } });

  canvas.addEventListener('touchstart', function(e) {
    e.preventDefault(); drawing = true;
    ctx.beginPath();
    var p = getPos(e); ctx.moveTo(p.x, p.y);
  }, { passive: false });

  canvas.addEventListener('touchmove', function(e) {
    e.preventDefault();
    if (!drawing) return;
    var p = getPos(e); ctx.lineTo(p.x, p.y); ctx.stroke();
  }, { passive: false });

  canvas.addEventListener('touchend', function(e) {
    e.preventDefault(); drawing = false; saveSignature();
  }, { passive: false });

  function saveSignature() {
    var inp = document.getElementById('sig-data');
    if (inp) inp.value = canvas.toDataURL('image/png');
  }

  var clearBtn = document.getElementById('sig-clear');
  if (clearBtn) {
    clearBtn.addEventListener('click', function() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      var inp = document.getElementById('sig-data');
      if (inp) inp.value = '';
    });
  }
});

// ── Sensitive items reveal ─────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.sensitive-mask').forEach(function(el) {
    el.title = 'Click to reveal';
    el.addEventListener('click', function() {
      el.classList.toggle('sensitive-mask');
    });
  });
});

// ── Confirm deletes ───────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('[data-confirm]').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
      if (!confirm(btn.getAttribute('data-confirm') || 'Are you sure?')) {
        e.preventDefault();
      }
    });
  });
});

// ── New client toggle in project-new ─────────────────────────────────────────
function toggleNewClient(val) {
  var fields = document.getElementById('new-client-fields');
  if (fields) fields.style.display = val ? 'none' : 'block';
}

// ── AI brief spinner ──────────────────────────────────────────────────────────
function showSpinner() {
  var spinner = document.getElementById('ai-spinner');
  var btn     = document.getElementById('gen-btn');
  if (spinner) spinner.classList.add('visible');
  if (btn)     btn.disabled = true;
}
