<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abSegmentModal"><i class="bi bi-plus-lg me-1"></i>New Segment</button>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table">
      <thead><tr><th>Name</th><th>Description</th><th>Filter</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($rows as $s): ?>
        <?php $filter = json_decode($s['filter_definition'], true) ?? []; ?>
        <tr>
          <td class="ab-cell-primary"><?= e($s['name']) ?></td>
          <td class="ab-cell-sub"><?= e($s['description'] ?? '') ?></td>
          <td><code class="small"><?= e(json_encode($filter)) ?></code></td>
          <td><button class="btn btn-icon btn-light-soft btn-sm ab-delete-segment" data-id="<?= (int) $s['id'] ?>"><i class="bi bi-trash text-danger"></i></button></td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($rows)): ?><tr><td colspan="4" class="text-center p-4 ab-text-muted">No saved segments yet.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="abSegmentModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">New Audience Segment</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="abSegmentForm">
      <div class="mb-2"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
      <div class="mb-3"><label class="form-label">Description</label><input class="form-control" name="description"></div>
      <div class="row g-2 mb-2">
        <div class="col-6"><label class="form-label">Type</label><select class="form-select form-select-sm" id="abSegType"><option value="leads">Leads</option><option value="customers">Customers</option></select></div>
        <div class="col-6"><label class="form-label">Business Line</label><select class="form-select form-select-sm" id="abSegBl"><option value="both">Both brands</option><option value="homecare">Homecare</option><option value="janitorial">Cleaner</option></select></div>
      </div>
      <div class="mb-0"><label class="form-label">Priority (leads only)</label><select class="form-select form-select-sm" id="abSegPriority"><option value="">Any</option><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="urgent">Urgent</option></select></div>
    </form>
  </div>
  <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abSegmentSaveBtn">Save Segment</button></div>
</div></div></div>

<script>
document.getElementById('abSegmentSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abSegmentForm');
  var filter = { type: document.getElementById('abSegType').value, business_line: document.getElementById('abSegBl').value };
  if (document.getElementById('abSegPriority').value) filter.priority = document.getElementById('abSegPriority').value;

  abFetch('<?= base_url('audience-segments') ?>', {
    method: 'POST',
    body: { name: form.name.value, description: form.description.value, filter_definition: filter }
  }).then(function (res) {
    abToast(res.message);
    bootstrap.Modal.getInstance(document.getElementById('abSegmentModal')).hide();
    setTimeout(function () { window.location.reload(); }, 600);
  }).catch(function (err) {
    abShowFormErrors(form, err.errors);
    abToast(err.message || 'Save failed.', 'danger');
  });
});

document.querySelectorAll('.ab-delete-segment').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Delete this segment?')) return;
    abFetch('<?= base_url('audience-segments') ?>/' + this.dataset.id, { method: 'DELETE' })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
</script>
