<?php
$counts = $counts ?? ['all' => 0, 'filtered' => 0, 'open' => 0, 'in_campaigns' => 0];
$unsubscribes = (int) ($unsubscribes ?? 0);
$rows = $rows ?? [];
$territories = $territories ?? [];
$stages = $stages ?? [];
$canCampaigns = can_see('campaigns');
$canUnsub = can_see('unsubscribes');
$kpis = [
    [(string) (int) $counts['all'], 'Lists', 'bi-collection-fill', '#2563eb', '#eff6ff', null],
    [(string) (int) $counts['filtered'], 'With a filter', 'bi-funnel-fill', '#7c3aed', '#f3e8ff', null],
    [(string) (int) $counts['in_campaigns'], 'Used in campaigns', 'bi-megaphone-fill', '#ea580c', '#fff7ed', $canCampaigns ? url('campaigns') : null],
    [(string) $unsubscribes, 'Unsubscribed', 'bi-slash-circle-fill', '#dc2626', '#fef2f2', $canUnsub ? url('unsubscribes') : null],
];
?>
<div class="lst-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Lists / Groups</h1>
      <p class="page-sub mb-0">Who should get the email — built from live CRM data, including real orders. Unsubscribed people are never included.</p>
    </div>
    <?php if ($canCampaigns): ?>
      <a class="btn btn-outline-primary" href="<?= e(url('campaigns')) ?>"><i class="bi bi-megaphone"></i> Campaigns</a>
    <?php endif; ?>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($kpis as $k): ?>
      <<?= $k[5] ? 'a' : 'div' ?> class="task-summary-card" <?php if ($k[5]): ?>href="<?= e($k[5]) ?>"<?php endif; ?> style="--task-accent: <?= e($k[3]) ?>; --task-tint: <?= e($k[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($k[2]) ?>"></i></div>
        <div>
          <div class="task-summary-n"><?= e($k[0]) ?></div>
          <div class="task-summary-l"><?= e($k[1]) ?></div>
        </div>
      </<?= $k[5] ? 'a' : 'div' ?>>
    <?php endforeach; ?>
  </div>

  <form class="camp-compose ajax-form mb-3" action="<?= e(url('lists')) ?>" method="post" id="listForm">
    <?= csrf_field() ?>
    <div class="camp-compose-head">
      <div class="task-summary-icon" style="--task-accent:#0f766e;--task-tint:#f0fdfa"><i class="bi bi-collection-fill"></i></div>
      <div class="min-w-0">
        <div class="camp-compose-title">New list</div>
        <p class="camp-compose-sub mb-0">Save who to mail. Preview first — unsubscribed and bounced emails stay out.</p>
      </div>
    </div>
    <div class="lst-compose-grid">
      <div>
        <label class="form-label" for="listName">Name</label>
        <input class="form-control" id="listName" name="name" placeholder="East buyers" required>
      </div>
      <div>
        <label class="form-label" for="listTerritory">Area</label>
        <select class="form-select" id="listTerritory" name="territory_id">
          <option value="">Any area</option>
          <?php foreach ($territories as $t): ?>
            <option value="<?= (int) $t['id'] ?>"><?= e($t['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="form-label" for="listIndustry">Type / industry</label>
        <input class="form-control" id="listIndustry" name="industry" placeholder="Optional">
      </div>
      <div>
        <label class="form-label" for="listStage">Deal stage</label>
        <select class="form-select" id="listStage" name="stage_id">
          <option value="">Any deal stage</option>
          <?php foreach ($stages as $s): ?>
            <option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="form-label" for="listOrder">Last order</label>
        <select class="form-select" id="listOrder" name="last_order">
          <option value="">Any last order</option>
          <option value="within_90">Ordered in last 90 days</option>
          <option value="none_90">No order in 90 days</option>
        </select>
      </div>
      <div>
        <label class="form-label" for="listEngagement">Opens / clicks</label>
        <select class="form-select" id="listEngagement" name="engagement">
          <option value="">Any score</option>
          <option value="high" <?= ($engagement ?? '') === 'high' ? 'selected' : '' ?>>High score</option>
          <option value="clicked" <?= ($engagement ?? '') === 'clicked' ? 'selected' : '' ?>>Clicked</option>
          <option value="opened" <?= ($engagement ?? '') === 'opened' ? 'selected' : '' ?>>Opened</option>
          <option value="opened_no_click" <?= ($engagement ?? '') === 'opened_no_click' ? 'selected' : '' ?>>Opened, no click</option>
          <option value="never_opened" <?= ($engagement ?? '') === 'never_opened' ? 'selected' : '' ?>>Never opened</option>
        </select>
      </div>
    </div>
    <div class="d-flex flex-wrap gap-2">
      <button class="btn btn-primary" type="submit">Save list</button>
      <button class="btn btn-outline-primary" type="button" id="previewList">Preview matches</button>
    </div>
  </form>

  <div id="previewBox" class="lst-preview d-none mb-3"></div>

  <?php if (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-collection"></i></div>
      <h2>No lists yet</h2>
      <p>Save a list above. Campaigns pick a live list — not a pasted spreadsheet.</p>
    </div>
  <?php else: ?>
    <?php foreach ($rows as $r):
        $chips = $r['chips'] ?? [];
        $matches = (int) ($r['match_count'] ?? 0);
        $camps = (int) ($r['campaign_count'] ?? 0);
    ?>
      <div class="lst-card">
        <div class="rpt-icon"><i class="bi bi-collection"></i></div>
        <div class="flex-grow-1 min-w-0">
          <div class="lead-name"><?= e($r['name']) ?></div>
          <div class="lst-chips">
            <?php if ($chips): ?>
              <?php foreach ($chips as $chip): ?>
                <span class="lst-chip"><?= e($chip) ?></span>
              <?php endforeach; ?>
            <?php else: ?>
              <span class="lst-chip lst-chip-open">Everyone with a good email</span>
            <?php endif; ?>
          </div>
        </div>
        <div class="lst-meta">
          <div class="rpt-metric-n"><?= $matches ?></div>
          <div class="rpt-metric-l"><?= $matches === 1 ? 'person' : 'people' ?></div>
        </div>
        <div class="lst-meta">
          <div class="rpt-metric-n"><?= $camps ?></div>
          <div class="rpt-metric-l"><?= $camps === 1 ? 'campaign' : 'campaigns' ?></div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
</div>
<script>
document.getElementById('previewList')?.addEventListener('click', function () {
  const form = document.getElementById('listForm');
  const params = new URLSearchParams(new FormData(form));
  params.delete('_csrf');
  fetch(window.APP_URL + '/lists/preview?' + params.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
    .then(function (r) { return r.json(); })
    .then(function (res) {
      const box = document.getElementById('previewBox');
      box.classList.remove('d-none');
      box.replaceChildren();
      if (!res.ok) {
        box.textContent = res.error || 'Could not preview.';
        return;
      }
      const head = document.createElement('div');
      head.className = 'lst-preview-head';
      const strong = document.createElement('strong');
      strong.textContent = (res.count || 0) + ' people';
      head.appendChild(strong);
      head.appendChild(document.createTextNode(' · unsubscribed and bounced emails are left out'));
      box.appendChild(head);
      (res.rows || []).slice(0, 12).forEach(function (row) {
        const line = document.createElement('div');
        line.className = 'lst-person';
        const av = document.createElement('div');
        av.className = 'lead-avatar';
        const parts = String(row.name || '').trim().split(/\s+/);
        av.textContent = ((parts[0] || '').charAt(0) + (parts[1] || '').charAt(0)).toUpperCase() || '?';
        const body = document.createElement('div');
        body.className = 'min-w-0';
        const name = document.createElement('div');
        name.className = 'lead-name';
        name.textContent = row.name || '—';
        const sub = document.createElement('div');
        sub.className = 'lead-sub';
        const bits = [row.email, row.company].filter(Boolean);
        sub.textContent = bits.join(' · ');
        body.appendChild(name);
        body.appendChild(sub);
        line.appendChild(av);
        line.appendChild(body);
        box.appendChild(line);
      });
    });
});
</script>
