<?php
$counts = $counts ?? ['all' => 0, 'used' => 0, 'unused' => 0];
$rows = $rows ?? [];
$canCampaigns = can_see('campaigns');
$tagLabels = [
    'first_name' => 'First name',
    'last_name' => 'Last name',
    'company' => 'Company',
    'email' => 'Email',
];
$kpis = [
    [(string) (int) $counts['all'], 'Templates', 'bi-file-earmark-text-fill', '#7c3aed', '#f3e8ff', null],
    [(string) (int) $counts['used'], 'Used in campaigns', 'bi-megaphone-fill', '#ea580c', '#fff7ed', $canCampaigns ? url('campaigns') : null],
    [(string) (int) $counts['unused'], 'Not used yet', 'bi-file-earmark', '#2563eb', '#eff6ff', null],
    ['4', 'Fill-in fields', 'bi-braces', '#0f766e', '#f0fdfa', null],
];
?>
<div class="tpl-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Email templates</h1>
      <p class="page-sub mb-0">Ready-made emails. Each send fills in the person’s name, company, and email.</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('templates')) ?>" method="post" id="tplForm">
    <?= csrf_field() ?>
    <div class="camp-compose-head">
      <div class="task-summary-icon" style="--task-accent:#7c3aed;--task-tint:#f3e8ff"><i class="bi bi-file-earmark-text-fill"></i></div>
      <div class="min-w-0">
        <div class="camp-compose-title">New template</div>
        <p class="camp-compose-sub mb-0">Write it once. Campaigns copy the subject and message, then fill in each person.</p>
      </div>
    </div>
    <div class="tpl-merges mb-3">
      <span class="tpl-merges-label">Insert</span>
      <?php foreach ($tagLabels as $tag => $label): ?>
        <button class="lst-chip tpl-merge" type="button" data-tag="{{<?= e($tag) ?>}}"><?= e($label) ?></button>
      <?php endforeach; ?>
    </div>
    <div class="tpl-compose-grid">
      <div>
        <label class="form-label" for="tplName">Name</label>
        <input class="form-control" id="tplName" name="name" placeholder="Spring catalog" required>
      </div>
      <div>
        <label class="form-label" for="tplSubject">Subject</label>
        <input class="form-control" id="tplSubject" name="subject" placeholder="A note for {{first_name}}" required>
      </div>
      <div class="tpl-compose-body">
        <label class="form-label" for="tplBody">Message</label>
        <textarea class="form-control" id="tplBody" name="body" rows="5" placeholder="Hi {{first_name}} at {{company}}, ..." required></textarea>
      </div>
    </div>
    <button class="btn btn-primary" type="submit">Save template</button>
  </form>

  <?php if (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-file-earmark-text"></i></div>
      <h2>No templates yet</h2>
      <p>Save one above, then pick it when you create a campaign.</p>
    </div>
  <?php else: ?>
    <div class="tpl-grid">
      <?php foreach ($rows as $r):
          $tags = $r['tags'] ?? [];
          $camps = (int) ($r['campaign_count'] ?? 0);
          $preview = mb_substr(strip_tags(merge_readable((string) $r['body'])), 0, 220);
      ?>
        <article class="tpl-card">
          <div class="tpl-card-top">
            <div class="rpt-icon"><i class="bi bi-file-earmark-text"></i></div>
            <div class="flex-grow-1 min-w-0">
              <div class="lead-name"><?= e($r['name']) ?></div>
              <div class="lead-sub text-truncate"><?= e(merge_readable($r['subject'])) ?></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 if ($preview !== ''): ?>
            <p class="tpl-preview"><?= e($preview) ?><?= mb_strlen(strip_tags(merge_readable((string) $r['body']))) > 220 ? '…' : '' ?></p>
          <?php endif; ?>
          <div class="lst-chips">
            <?php if ($tags): ?>
              <?php foreach ($tags as $tag): ?>
                <span class="lst-chip"><?= e($tagLabels[$tag] ?? $tag) ?></span>
              <?php endforeach; ?>
            <?php else: ?>
              <span class="lst-chip lst-chip-open">No fill-in fields</span>
            <?php endif; ?>
          </div>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

  <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
</div>
<script>
(function () {
  const body = document.getElementById('tplBody');
  const subject = document.getElementById('tplSubject');
  document.querySelectorAll('.tpl-merge').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const tag = btn.getAttribute('data-tag') || '';
      const el = (document.activeElement === subject) ? subject : body;
      if (!el) return;
      const start = el.selectionStart ?? el.value.length;
      const end = el.selectionEnd ?? start;
      el.value = el.value.slice(0, start) + tag + el.value.slice(end);
      el.focus();
      const pos = start + tag.length;
      el.setSelectionRange(pos, pos);
    });
  });
})();
</script>
