<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <ul class="nav ab-tabs">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tableView">Table View</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#kanbanView" id="abKanbanTabLink">Pipeline</a></li>
  </ul>
  <div class="d-flex gap-2">
    <a href="<?= base_url('leads/import') ?>" class="btn btn-light-soft btn-sm"><i class="bi bi-upload me-1"></i>Import</a>
    <a href="<?= base_url('leads/export') ?>" class="btn btn-light-soft btn-sm"><i class="bi bi-download me-1"></i>Export</a>
    <?php if (\App\Core\Rbac::can('leads_customers.create')): ?>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abLeadModal" id="abNewLeadBtn"><i class="bi bi-plus-lg me-1"></i>New Lead</button>
    <?php endif; ?>
  </div>
</div>

<div class="tab-content">
  <div class="tab-pane fade show active" id="tableView">
    <div class="ab-table-card">
      <div class="ab-table-toolbar">
        <div class="ab-search"><i class="bi bi-search"></i><input type="text" id="abLeadSearch" placeholder="Search leads..." value="<?= e($_GET['search'] ?? '') ?>"></div>
        <select class="form-select form-select-sm" id="abFilterBl" style="width:150px;">
          <option value="">All Businesses</option>
          <?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?>
        </select>
        <select class="form-select form-select-sm" id="abFilterStage" style="width:130px;">
          <option value="">All Stages</option>
          <?php foreach ($lookups['stages'] as $s): ?><option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
        </select>
        <select class="form-select form-select-sm" id="abFilterPriority" style="width:130px;">
          <option value="">All Priorities</option>
          <option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="urgent">Urgent</option>
        </select>
      </div>
      <div class="ab-bulk-toolbar d-none align-items-center gap-2 px-3 py-2 border-bottom" id="abBulkToolbar" style="background:var(--ab-primary-100);">
        <span class="small fw-semibold"><span id="abBulkCount">0</span> selected</span>
        <select class="form-select form-select-sm" id="abBulkStageSelect" style="width:150px;">
          <option value="">Change stage to...</option>
          <?php foreach ($lookups['stages'] as $s): ?><option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
        </select>
        <button class="btn btn-light-soft btn-sm" id="abBulkDeleteBtn"><i class="bi bi-trash me-1"></i>Delete</button>
        <button class="btn btn-link btn-sm ms-auto" id="abBulkClearBtn">Clear selection</button>
      </div>
      <div class="table-responsive">
        <table class="table ab-table align-middle">
          <thead><tr><th style="width:36px;"><input type="checkbox" class="form-check-input" id="abSelectAllLeads"></th><th>Lead</th><th>Business</th><th>Stage</th><th>Priority</th><th>Source</th><th>Owner</th><th>Value</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($rows as $row): ?>
            <tr>
              <td><input type="checkbox" class="form-check-input ab-lead-checkbox" value="<?= (int) $row['id'] ?>"></td>
              <td><div class="d-flex align-items-center gap-2"><div class="ab-mini-avatar"><?= e(mb_strtoupper(mb_substr($row['first_name'],0,1))) ?></div>
                <div><a href="<?= base_url('leads/' . $row['id']) ?>" class="ab-cell-primary"><?= e($row['first_name'].' '.($row['last_name'] ?? '')) ?></a><div class="ab-cell-sub"><?= e($row['email'] ?? $row['phone'] ?? '') ?></div></div></div></td>
              <td><?= e($row['business_line_name'] ?? '—') ?></td>
              <td><span class="ab-badge bg-secondary-soft" style="<?= $row['color_hex'] ? "background:{$row['color_hex']}22; color:{$row['color_hex']};" : '' ?>"><?= e($row['stage_name']) ?></span></td>
              <td><span class="ab-badge <?= match($row['priority']) { 'urgent'=>'bg-danger-soft','high'=>'bg-warning-soft','low'=>'bg-secondary-soft',default=>'bg-primary-soft' } ?>"><?= e(ucfirst($row['priority'])) ?></span></td>
              <td><?= e($row['source_name'] ?? '—') ?></td>
              <td><?= e($row['owner_name'] ?? '—') ?></td>
              <td class="ab-mono"><?= e(money($row['estimated_value'])) ?></td>
              <td><a href="<?= base_url('leads/' . $row['id']) ?>" class="btn btn-icon btn-light-soft btn-sm"><i class="bi bi-arrow-right"></i></a></td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($rows)): ?><tr><td colspan="9" class="text-center p-4 ab-text-muted">No leads found.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="ab-table-pagination">
        <div>Showing <strong><?= (int) $meta['from'] ?>–<?= (int) $meta['to'] ?></strong> of <strong><?= (int) $meta['total'] ?></strong> leads</div>
        <?php if ((int) $meta['total_pages'] > 1): ?>
        <nav aria-label="Leads pagination">
          <ul class="pagination pagination-sm mb-0">
            <?php
              $currentPage = (int) $meta['page'];
              $lastPage = (int) $meta['total_pages'];
              $pageUrl = function (int $page) {
                  $params = $_GET;
                  $params['page'] = $page;
                  return base_url('leads') . '?' . http_build_query($params);
              };
              // Show first, last, current ± 2, collapsing the rest into "…".
              $pagesToShow = array_unique(array_filter(
                  range(max(1, $currentPage - 2), min($lastPage, $currentPage + 2)) + [1, $lastPage],
                  fn ($p) => $p >= 1 && $p <= $lastPage
              ));
              sort($pagesToShow);
            ?>
            <li class="page-item <?= !$meta['has_previous'] ? 'disabled' : '' ?>">
              <a class="page-link" href="<?= $meta['has_previous'] ? e($pageUrl($currentPage - 1)) : '#' ?>" aria-label="Previous">&laquo;</a>
            </li>
            <?php $previousPage = 0; foreach ($pagesToShow as $p): ?>
              <?php if ($p - $previousPage > 1): ?>
                <li class="page-item disabled"><span class="page-link">&hellip;</span></li>
              <?php endif; ?>
              <li class="page-item <?= $p === $currentPage ? 'active' : '' ?>">
                <a class="page-link" href="<?= e($pageUrl($p)) ?>"><?= $p ?></a>
              </li>
              <?php $previousPage = $p; ?>
            <?php endforeach; ?>
            <li class="page-item <?= !$meta['has_next'] ? 'disabled' : '' ?>">
              <a class="page-link" href="<?= $meta['has_next'] ? e($pageUrl($currentPage + 1)) : '#' ?>" aria-label="Next">&raquo;</a>
            </li>
          </ul>
        </nav>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="tab-pane fade" id="kanbanView">
    <div class="ab-kanban" id="abKanbanBoard">
      <div class="text-center p-4 ab-text-muted w-100">Loading pipeline…</div>
    </div>
  </div>
</div>

<!-- New Lead Modal -->
<div class="modal fade" id="abLeadModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">New Lead</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div id="abDuplicateWarning" class="alert alert-warning d-none"></div>
        <form id="abLeadForm">
          <input type="hidden" name="confirm_duplicate" value="0">
          <div class="row g-3">
            <div class="col-md-6"><label class="form-label ab-req">First Name</label><input class="form-control" name="first_name" required></div>
            <div class="col-md-6"><label class="form-label">Last Name</label><input class="form-control" name="last_name"></div>
            <div class="col-md-6"><label class="form-label">Email</label><input type="email" class="form-control" name="email"></div>
            <div class="col-md-6"><label class="form-label">Phone</label><input class="form-control" name="phone"></div>
            <div class="col-md-6"><label class="form-label ab-req">Business Line</label>
              <select class="form-select" name="business_line_id" required>
                <?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6"><label class="form-label">Lead Source</label>
              <select class="form-select" name="lead_source_id">
                <?php foreach ($lookups['sources'] as $s): ?><option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6"><label class="form-label ab-req">Stage</label>
              <select class="form-select" name="lead_stage_id" required>
                <?php foreach ($lookups['stages'] as $s): ?><option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6"><label class="form-label">Priority</label>
              <select class="form-select" name="priority"><option value="low">Low</option><option value="medium" selected>Medium</option><option value="high">High</option><option value="urgent">Urgent</option></select>
            </div>
            <div class="col-md-6"><label class="form-label">Estimated Value</label><input class="form-control" name="estimated_value" placeholder="0.00"></div>
            <div class="col-12"><label class="form-label">Notes</label><textarea class="form-control" name="notes" rows="2"></textarea></div>
          </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="abLeadSaveBtn">Create Lead</button>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  function buildParams() {
    return new URLSearchParams({
      search: document.getElementById('abLeadSearch').value,
      business_line_id: document.getElementById('abFilterBl').value,
      lead_stage_id: document.getElementById('abFilterStage').value,
      priority: document.getElementById('abFilterPriority').value
    });
  }
  ['abLeadSearch'].forEach(function (id) {
    document.getElementById(id).addEventListener('keydown', function (e) { if (e.key === 'Enter') reload(); });
  });
  ['abFilterBl', 'abFilterStage', 'abFilterPriority'].forEach(function (id) {
    document.getElementById(id).addEventListener('change', reload);
  });
  function reload() { window.location.href = '<?= base_url('leads') ?>?' + buildParams().toString(); }

  document.getElementById('abLeadSaveBtn').addEventListener('click', function () {
    var form = document.getElementById('abLeadForm');
    var fd = new FormData(form);
    var data = Object.fromEntries(fd.entries());

    abFetch('<?= base_url('leads') ?>', { method: 'POST', body: data }).then(function (res) {
      abToast(res.message);
      bootstrap.Modal.getInstance(document.getElementById('abLeadModal')).hide();
      setTimeout(function () { window.location.reload(); }, 600);
    }).catch(function (err) {
      if (err.errors && err.errors.duplicates) {
        var box = document.getElementById('abDuplicateWarning');
        box.classList.remove('d-none');
        box.innerHTML = '<strong>Possible duplicate found:</strong> ' + err.errors.duplicates.map(function (d) { return d.first_name + ' ' + (d.last_name||'') + ' (' + (d.email||d.phone) + ')'; }).join(', ') +
          '<div class="mt-2"><button type="button" class="btn btn-sm btn-warning" id="abConfirmDupBtn">Create Anyway</button></div>';
        document.getElementById('abConfirmDupBtn').addEventListener('click', function () {
          form.confirm_duplicate.value = '1';
          document.getElementById('abLeadSaveBtn').click();
        });
      } else {
        abShowFormErrors(form, err.errors);
        abToast(err.message || 'Save failed.', 'danger');
      }
    });
  });

  // Load Kanban pipeline lazily when that tab is first shown.
  var kanbanLoaded = false;
  document.getElementById('abKanbanTabLink').addEventListener('shown.bs.tab', function () {
    if (kanbanLoaded) return;
    kanbanLoaded = true;

    var params = buildParams();
    params.set('view', 'pipeline');
    abFetch('<?= base_url('leads') ?>?' + params.toString()).then(function (res) {
      var board = document.getElementById('abKanbanBoard');
      board.innerHTML = res.data.map(function (col) {
        var cards = col.leads.map(function (l) {
          return '<div class="ab-kanban-card" draggable="true" data-lead-id="' + l.id + '">' +
            '<h4><a href="<?= base_url('leads') ?>/' + l.id + '" class="text-dark text-decoration-none">' + l.first_name + ' ' + (l.last_name||'') + '</a></h4>' +
            '<div class="ab-cell-sub">' + (l.business_line_name||'') + ' · $' + Number(l.estimated_value).toLocaleString() + '</div>' +
            '</div>';
        }).join('');
        return '<div class="ab-kanban-col" data-stage-id="' + col.stage.id + '">' +
          '<div class="ab-kanban-col-head"><span>' + col.stage.name + ' <span class="ab-badge bg-secondary-soft ms-1">' + col.leads.length + '</span></span></div>' +
          '<div class="ab-kanban-col-body">' + (cards || '<div class="ab-empty small py-3">No leads</div>') + '</div>' +
          '</div>';
      }).join('');

      // Wire drag-and-drop -> stage change API call.
      board.querySelectorAll('.ab-kanban-card[draggable="true"]').forEach(function (card) {
        card.addEventListener('dragstart', function () { card.classList.add('dragging'); });
        card.addEventListener('dragend', function () { card.classList.remove('dragging'); });
      });
      board.querySelectorAll('.ab-kanban-col-body').forEach(function (col) {
        col.addEventListener('dragover', function (e) {
          e.preventDefault();
          var dragging = board.querySelector('.ab-kanban-card.dragging');
          if (dragging) col.appendChild(dragging);
        });
        col.addEventListener('drop', function () {
          var dragging = board.querySelector('.ab-kanban-card.dragging');
          var stageId = col.closest('.ab-kanban-col').dataset.stageId;
          if (!dragging) return;
          abFetch('<?= base_url('leads') ?>/' + dragging.dataset.leadId + '/stage', { method: 'POST', body: { lead_stage_id: stageId } })
            .then(function () { abToast('Stage updated.'); })
            .catch(function (err) { abToast(err.message, 'danger'); });
        });
      });
    });
  });
})();
// Bulk selection toolbar.
(function () {
  var selectAll = document.getElementById('abSelectAllLeads');
  var toolbar = document.getElementById('abBulkToolbar');
  var countLabel = document.getElementById('abBulkCount');

  function checkboxes() { return Array.prototype.slice.call(document.querySelectorAll('.ab-lead-checkbox')); }
  function selectedIds() { return checkboxes().filter(function (c) { return c.checked; }).map(function (c) { return c.value; }); }

  function refreshToolbar() {
    var count = selectedIds().length;
    countLabel.textContent = count;
    toolbar.classList.toggle('d-none', count === 0);
    toolbar.classList.toggle('d-flex', count > 0);
  }

  if (selectAll) {
    selectAll.addEventListener('change', function () {
      checkboxes().forEach(function (c) { c.checked = selectAll.checked; });
      refreshToolbar();
    });
  }
  checkboxes().forEach(function (c) { c.addEventListener('change', refreshToolbar); });

  document.getElementById('abBulkClearBtn')?.addEventListener('click', function () {
    checkboxes().forEach(function (c) { c.checked = false; });
    if (selectAll) selectAll.checked = false;
    refreshToolbar();
  });

  function runBulkAction(action, extra) {
    var ids = selectedIds();
    if (ids.length === 0) return;
    var body = Object.assign({ ids: ids, action: action }, extra || {});

    abFetch('<?= base_url('leads/bulk-action') ?>', { method: 'POST', body: body })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message || 'Bulk action failed.', 'danger'); });
  }

  document.getElementById('abBulkStageSelect')?.addEventListener('change', function () {
    if (!this.value) return;
    runBulkAction('change_stage', { lead_stage_id: this.value });
  });

  document.getElementById('abBulkDeleteBtn')?.addEventListener('click', function () {
    var ids = selectedIds();
    if (ids.length === 0) return;
    if (!confirm('Move ' + ids.length + ' lead(s) to trash?')) return;
    runBulkAction('delete');
  });
})();
</script>
