<?php
if (!defined('ABSPATH')) exit;

use BLR\Backline\Core\Access;
use BLR\Backline\Modules\Outreach\Module as OutreachModule;

$base = rtrim((string)($ctx['base_url'] ?? ''), '/') . '/';
$is_edit = ($ctx['action'] ?? '') === 'edit';
$post_id = $is_edit ? (int)($ctx['id'] ?? 0) : 0;
$campaign = $is_edit ? get_post($post_id) : null;

if ($is_edit && (!$campaign || $campaign->post_type !== 'blr_outreach')) {
  echo '<div class="container-fluid p-0"><div class="alert alert-danger alert-dismissible fade show" role="alert">' . esc_html__('Campaign not found.', 'blr-backline') . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="' . esc_attr__('Close', 'blr-backline') . '"></button></div></div>';
  return;
}

if ($is_edit && !Access::can_edit_post($post_id, 'blr_outreach')) {
  echo '<div class="container-fluid p-0"><div class="alert alert-danger alert-dismissible fade show" role="alert">' . esc_html__('You do not have permission to edit this campaign.', 'blr-backline') . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="' . esc_attr__('Close', 'blr-backline') . '"></button></div></div>';
  return;
}

if (!$is_edit && !Access::can_create_post_type('blr_outreach')) {
  echo '<div class="container-fluid p-0"><div class="alert alert-danger alert-dismissible fade show" role="alert">' . esc_html__('You do not have permission to create outreach campaigns.', 'blr-backline') . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="' . esc_attr__('Close', 'blr-backline') . '"></button></div></div>';
  return;
}

$seed_contact_ids = [];

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only seed values used to preselect contacts in the new-campaign form.
if (isset($_GET['contacts'])) {
  // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized by OutreachModule::sanitize_id_list(), which accepts array or CSV input.
  $seed_contact_ids = OutreachModule::sanitize_id_list(wp_unslash($_GET['contacts']));
}
$existing_filters = $campaign ? OutreachModule::filters_from_json((string)get_post_meta($campaign->ID, 'blr_outreach_filter_payload', true)) : OutreachModule::default_filters();
$existing_manual_ids = $campaign ? OutreachModule::ids_from_csv((string)get_post_meta($campaign->ID, 'blr_outreach_manual_contact_ids', true)) : $seed_contact_ids;
$existing_excluded_ids = $campaign ? OutreachModule::ids_from_csv((string)get_post_meta($campaign->ID, 'blr_outreach_excluded_contact_ids', true)) : [];

$values = [
  'internal_title' => $campaign ? (string)$campaign->post_title : '',
  'subject' => $campaign ? (string)get_post_meta($campaign->ID, 'blr_outreach_subject', true) : '',
  'body' => $campaign ? (string)$campaign->post_content : '',
  'from_name' => $campaign ? (string)get_post_meta($campaign->ID, 'blr_outreach_from_name', true) : OutreachModule::default_from_name(),
  'from_email' => $campaign ? (string)get_post_meta($campaign->ID, 'blr_outreach_from_email', true) : OutreachModule::default_from_email(),
  'reply_to' => $campaign ? (string)get_post_meta($campaign->ID, 'blr_outreach_reply_to', true) : OutreachModule::default_reply_to(),
  'manual_contact_ids' => $existing_manual_ids,
  'excluded_contact_ids' => $existing_excluded_ids,
  'filters' => $existing_filters,
];

// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only notice and seed values from the URL.
$saved_notice = isset($_GET['saved']) ? absint((string) wp_unslash($_GET['saved'])) : 0;
$errors = isset($ctx['errors']) && is_array($ctx['errors']) ? $ctx['errors'] : [];
// phpcs:enable WordPress.Security.NonceVerification.Recommended

$values = isset($ctx['outreach_values']) && is_array($ctx['outreach_values']) ? array_replace($values, $ctx['outreach_values']) : $values;

$preview = OutreachModule::preview_payload($values['manual_contact_ids'], $values['filters'], $values['excluded_contact_ids']);
$preview_recipients = $preview['included'] ?? [];
$excluded_recipients = $preview['excluded'] ?? [];
$preview_count = (int)($preview['counts']['included'] ?? count($preview_recipients));
$excluded_count = (int)($preview['counts']['excluded'] ?? count($excluded_recipients));
$manual_count = (int)($preview['counts']['manual'] ?? 0);
$filtered_count = (int)($preview['counts']['filtered'] ?? 0);

$state_options = OutreachModule::state_options();
$type_options = OutreachModule::contact_type_options();
$company_options = OutreachModule::company_options();
$role_options = OutreachModule::role_options();
$manual_contact_options = OutreachModule::manual_contact_options($values['manual_contact_ids']);
$contact_search_url = wp_nonce_url(admin_url('admin-ajax.php?action=blr_ba_outreach_contact_search'), 'blr_ba_outreach_contact_search', 'nonce');
$preview_ajax_url = admin_url('admin-ajax.php');
$preview_action = 'blr_ba_outreach_recipient_preview';
$preview_nonce = wp_create_nonce('blr_ba_outreach_recipient_preview');

$recipient_meta = static function (array $recipient): string {
  $parts = [];

  if (!empty($recipient['company'])) {
    $parts[] = (string) $recipient['company'];
  }

  if (!empty($recipient['role'])) {
    $parts[] = (string) $recipient['role'];
  }

  $location = trim(implode(', ', array_filter([
    (string) ($recipient['city'] ?? ''),
    (string) ($recipient['state'] ?? ''),
  ], 'strlen')));

  if ($location !== '') {
    $parts[] = $location;
  }

  if (!empty($recipient['contact_type'])) {
    $parts[] = (string) $recipient['contact_type'];
  }

  return implode(' • ', $parts);
};
?>
<div class="container-fluid p-0">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h1 class="h3 mb-0"><?php echo $is_edit ? esc_html__('Edit Outreach Campaign', 'blr-backline') : esc_html__('New Outreach Campaign', 'blr-backline'); ?></h1>
    </div>
    <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'outreach/'); ?>"><?php echo esc_html__('Back', 'blr-backline'); ?></a>
  </div>

  <?php if ($saved_notice): ?>
    <div class="alert alert-success"><?php echo esc_html__('Saved.', 'blr-backline'); ?></div>
  <?php endif; ?>

  <?php foreach ($errors as $error): ?>
    <div class="alert alert-danger"><?php echo esc_html($error); ?></div>
  <?php endforeach; ?>

  <form method="post" id="blr-ba-outreach-form">
    <?php wp_nonce_field('blr_ba_save_outreach'); ?>
    <input type="hidden" name="send_now" id="blr-ba-send-now-input" value="">
    <div id="blr-ba-excluded-inputs">
      <?php foreach (OutreachModule::sanitize_id_list($values['excluded_contact_ids']) as $excluded_id): ?>
        <input type="hidden" name="excluded_contact_ids[]" value="<?php echo (int) $excluded_id; ?>">
      <?php endforeach; ?>
    </div>

    <div class="card">
      <div class="card-header"><h5 class="card-title mb-0"><?php echo esc_html__('Campaign', 'blr-backline'); ?></h5></div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-12 col-lg-6">
            <label class="form-label"><?php echo esc_html__('Campaign Name', 'blr-backline'); ?></label>
            <input class="form-control" type="text" name="internal_title" value="<?php echo esc_attr($values['internal_title']); ?>" placeholder="<?php echo esc_attr__('Internal label only', 'blr-backline'); ?>">
          </div>

          <div class="col-12 col-lg-6">
            <label class="form-label"><?php echo esc_html__('Email Subject', 'blr-backline'); ?></label>
            <input class="form-control" type="text" name="subject" value="<?php echo esc_attr($values['subject']); ?>" required>
          </div>

          <div class="col-12 col-md-4">
            <label class="form-label"><?php echo esc_html__('From Name', 'blr-backline'); ?></label>
            <input class="form-control" type="text" name="from_name" value="<?php echo esc_attr($values['from_name']); ?>">
          </div>

          <div class="col-12 col-md-4">
            <label class="form-label"><?php echo esc_html__('From Email', 'blr-backline'); ?></label>
            <input class="form-control" type="email" name="from_email" value="<?php echo esc_attr($values['from_email']); ?>">
          </div>

          <div class="col-12 col-md-4">
            <label class="form-label"><?php echo esc_html__('Reply-To', 'blr-backline'); ?></label>
            <input class="form-control" type="email" name="reply_to" value="<?php echo esc_attr($values['reply_to']); ?>">
          </div>

          <div class="col-12">
            <label class="form-label"><?php echo esc_html__('Email Body', 'blr-backline'); ?></label>
            <textarea class="form-control" name="body" rows="12" placeholder="<?php echo esc_attr__('Use merge tags like {{first_name}} or {{company}}.', 'blr-backline'); ?>"><?php echo esc_textarea($values['body']); ?></textarea>
          </div>

          <div class="col-12">
            <div class="alert alert-light border mb-0">
              <strong><?php echo esc_html__('Merge Tags', 'blr-backline'); ?></strong>
              <div class="small text-muted mt-2"><?php echo esc_html(implode(', ', OutreachModule::merge_tags())); ?></div>
              <div class="small text-muted mt-2"><?php echo esc_html__('Attachments are disabled for outreach. Add links in the email body for EPKs, streams, downloads, or other materials.', 'blr-backline'); ?></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="card mt-3" id="blr-ba-recipient-builder" data-preview-url="<?php echo esc_url($preview_ajax_url); ?>" data-preview-action="<?php echo esc_attr($preview_action); ?>" data-preview-nonce="<?php echo esc_attr($preview_nonce); ?>">
      <div class="card-header d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-2">
        <div>
          <h5 class="card-title mb-0"><?php echo esc_html__('Recipients', 'blr-backline'); ?></h5>
        </div>
        <div class="d-flex flex-wrap gap-2">
          <span class="badge text-bg-primary"><span id="blr-ba-recipient-count"><?php echo (int) $preview_count; ?></span> <span id="blr-ba-recipient-count-label"><?php echo esc_html(_n('recipient', 'recipients', max(1, $preview_count), 'blr-backline')); ?></span></span>
          <span class="badge text-bg-light border"><span id="blr-ba-manual-count"><?php echo (int) $manual_count; ?></span> <?php echo esc_html__('manual', 'blr-backline'); ?></span>
          <span class="badge text-bg-light border"><span id="blr-ba-filtered-count"><?php echo (int) $filtered_count; ?></span> <?php echo esc_html__('from filters', 'blr-backline'); ?></span>
          <span class="badge text-bg-light border"><span id="blr-ba-excluded-count"><?php echo (int) $excluded_count; ?></span> <?php echo esc_html__('excluded', 'blr-backline'); ?></span>
        </div>
      </div>
      <div class="card-body">
        <div class="border rounded p-3 mb-3 bg-light-subtle">
          <div class="row g-3">
            <div class="col-12 col-xl-5">
              <label class="form-label"><?php echo esc_html__('Pick Contacts', 'blr-backline'); ?></label>
              <select class="form-select blr-ba-select2 blr-ba-ajax-contact-select" name="manual_contact_ids[]" multiple data-placeholder="<?php echo esc_attr__('Choose contacts', 'blr-backline'); ?>" data-ajax-url="<?php echo esc_url($contact_search_url); ?>">
                <?php foreach ($manual_contact_options as $contact): ?>
                  <option value="<?php echo (int) $contact->ID; ?>" selected><?php echo esc_html(OutreachModule::contact_option_label((int) $contact->ID)); ?></option>
                <?php endforeach; ?>
              </select>
              <div class="form-text"><?php echo esc_html__('Manual picks are always included unless you explicitly exclude them below.', 'blr-backline'); ?></div>
            </div>

            <div class="col-12 col-xl-7">
              <div class="row g-3">
                <div class="col-12 col-md-6">
                  <label class="form-label"><?php echo esc_html__('Filter by Contact Type', 'blr-backline'); ?></label>
                  <select class="form-select blr-ba-select2" name="filter_contact_type[]" multiple>
                    <?php foreach ($type_options as $option): ?>
                      <option value="<?php echo esc_attr($option); ?>" <?php selected(in_array($option, $values['filters']['contact_type'], true)); ?>><?php echo esc_html($option); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-12 col-md-6">
                  <label class="form-label"><?php echo esc_html__('Filter by State', 'blr-backline'); ?></label>
                  <select class="form-select blr-ba-select2" name="filter_state[]" multiple>
                    <?php foreach ($state_options as $option): ?>
                      <option value="<?php echo esc_attr($option); ?>" <?php selected(in_array($option, $values['filters']['state'], true)); ?>><?php echo esc_html($option); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-12 col-md-6">
                  <label class="form-label"><?php echo esc_html__('Filter by Company', 'blr-backline'); ?></label>
                  <select class="form-select blr-ba-select2" name="filter_company[]" multiple>
                    <?php foreach ($company_options as $option): ?>
                      <option value="<?php echo esc_attr($option); ?>" <?php selected(in_array($option, $values['filters']['company'], true)); ?>><?php echo esc_html($option); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-12 col-md-6">
                  <label class="form-label"><?php echo esc_html__('Filter by Role', 'blr-backline'); ?></label>
                  <select class="form-select blr-ba-select2" name="filter_role[]" multiple>
                    <?php foreach ($role_options as $option): ?>
                      <option value="<?php echo esc_attr($option); ?>" <?php selected(in_array($option, $values['filters']['role'], true)); ?>><?php echo esc_html($option); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-12">
                  <div class="d-flex flex-column flex-md-row gap-3">
                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" id="filter_newsletter_only" name="filter_newsletter_only" value="1" <?php checked(!empty($values['filters']['newsletter_only'])); ?>>
                      <label class="form-check-label" for="filter_newsletter_only"><?php echo esc_html__('Newsletter signups only', 'blr-backline'); ?></label>
                    </div>

                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" id="filter_has_email" name="filter_has_email" value="1" <?php checked(!empty($values['filters']['has_email'])); ?>>
                      <label class="form-check-label" for="filter_has_email"><?php echo esc_html__('Only contacts with valid email', 'blr-backline'); ?></label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="row g-3 align-items-end mb-3">
          <div class="col-12 col-lg-6">
            <label class="form-label" for="blr-ba-recipient-search"><?php echo esc_html__('Search recipients in this campaign', 'blr-backline'); ?></label>
            <input class="form-control" type="search" id="blr-ba-recipient-search" placeholder="<?php echo esc_attr__('Filter the visible list by name, email, company, role, or state', 'blr-backline'); ?>">
          </div>
          <div class="col-12 col-lg-6">
            <div class="small text-muted" id="blr-ba-preview-status" aria-live="polite"><?php echo esc_html__('Excluded contacts override both manual picks and filters.', 'blr-backline'); ?></div>
          </div>
        </div>

        <div class="table-responsive border rounded">
          <table class="table table-hover align-middle mb-0">
            <thead>
              <tr>
                <th><?php echo esc_html__('Contact', 'blr-backline'); ?></th>
                <th><?php echo esc_html__('Details', 'blr-backline'); ?></th>
                <th><?php echo esc_html__('Email', 'blr-backline'); ?></th>
                <th><?php echo esc_html__('Source', 'blr-backline'); ?></th>
                <th class="text-end"><?php echo esc_html__('Action', 'blr-backline'); ?></th>
              </tr>
            </thead>
            <tbody id="blr-ba-recipient-preview-body">
              <?php if (!$preview_recipients): ?>
                <tr class="blr-ba-empty-row"><td colspan="5" class="text-muted text-center py-4"><?php echo esc_html__('Nobody matches yet.', 'blr-backline'); ?></td></tr>
              <?php else: ?>
                <?php foreach ($preview_recipients as $recipient): ?>
                  <?php $row_text = strtolower(implode(' ', array_filter([
                    (string) ($recipient['name'] ?? ''),
                    (string) ($recipient['email'] ?? ''),
                    (string) ($recipient['company'] ?? ''),
                    (string) ($recipient['role'] ?? ''),
                    (string) ($recipient['city'] ?? ''),
                    (string) ($recipient['state'] ?? ''),
                    (string) ($recipient['contact_type'] ?? ''),
                    (string) ($recipient['source_label'] ?? ''),
                  ], 'strlen'))); ?>
                  <tr data-contact-id="<?php echo (int) ($recipient['contact_id'] ?? 0); ?>" data-search="<?php echo esc_attr($row_text); ?>">
                    <td>
                      <div class="fw-semibold"><?php echo esc_html((string) ($recipient['name'] ?? '')); ?></div>
                    </td>
                    <td>
                      <?php $meta_text = $recipient_meta($recipient); ?>
                      <?php if ($meta_text !== ''): ?>
                        <div class="small text-muted"><?php echo esc_html($meta_text); ?></div>
                      <?php else: ?>
                        <div class="small text-muted"><?php echo esc_html__('—', 'blr-backline'); ?></div>
                      <?php endif; ?>
                    </td>
                    <td><a href="mailto:<?php echo esc_attr((string) ($recipient['email'] ?? '')); ?>"><?php echo esc_html((string) ($recipient['email'] ?? '')); ?></a></td>
                    <td><span class="badge text-bg-light border"><?php echo esc_html((string) ($recipient['source_label'] ?? '')); ?></span></td>
                    <td class="text-end"><button class="btn btn-sm btn-outline-danger blr-ba-recipient-exclude" type="button" data-contact-id="<?php echo (int) ($recipient['contact_id'] ?? 0); ?>"><?php echo esc_html__('Exclude', 'blr-backline'); ?></button></td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>

        <div class="mt-3">
          <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
            <h6 class="mb-0"><?php echo esc_html__('Excluded Recipients', 'blr-backline'); ?></h6>
            <span class="small text-muted"><?php echo esc_html__('Use this when a filter is mostly right but you need to pull a few people out.', 'blr-backline'); ?></span>
          </div>
          <div class="table-responsive border rounded">
            <table class="table table-sm table-hover align-middle mb-0">
              <thead>
                <tr>
                  <th><?php echo esc_html__('Contact', 'blr-backline'); ?></th>
                  <th><?php echo esc_html__('Details', 'blr-backline'); ?></th>
                  <th><?php echo esc_html__('Email', 'blr-backline'); ?></th>
                  <th><?php echo esc_html__('Source', 'blr-backline'); ?></th>
                  <th class="text-end"><?php echo esc_html__('Action', 'blr-backline'); ?></th>
                </tr>
              </thead>
              <tbody id="blr-ba-excluded-preview-body">
                <?php if (!$excluded_recipients): ?>
                  <tr class="blr-ba-empty-row"><td colspan="5" class="text-muted text-center py-3"><?php echo esc_html__('No exclusions yet.', 'blr-backline'); ?></td></tr>
                <?php else: ?>
                  <?php foreach ($excluded_recipients as $recipient): ?>
                    <?php $row_text = strtolower(implode(' ', array_filter([
                      (string) ($recipient['name'] ?? ''),
                      (string) ($recipient['email'] ?? ''),
                      (string) ($recipient['company'] ?? ''),
                      (string) ($recipient['role'] ?? ''),
                      (string) ($recipient['city'] ?? ''),
                      (string) ($recipient['state'] ?? ''),
                      (string) ($recipient['contact_type'] ?? ''),
                      (string) ($recipient['source_label'] ?? ''),
                    ], 'strlen'))); ?>
                    <tr data-contact-id="<?php echo (int) ($recipient['contact_id'] ?? 0); ?>" data-search="<?php echo esc_attr($row_text); ?>">
                      <td>
                        <div class="fw-semibold"><?php echo esc_html((string) ($recipient['name'] ?? '')); ?></div>
                      </td>
                      <td>
                        <?php $meta_text = $recipient_meta($recipient); ?>
                        <?php if ($meta_text !== ''): ?>
                          <div class="small text-muted"><?php echo esc_html($meta_text); ?></div>
                        <?php else: ?>
                          <div class="small text-muted"><?php echo esc_html__('—', 'blr-backline'); ?></div>
                        <?php endif; ?>
                      </td>
                      <td><a href="mailto:<?php echo esc_attr((string) ($recipient['email'] ?? '')); ?>"><?php echo esc_html((string) ($recipient['email'] ?? '')); ?></a></td>
                      <td><span class="badge text-bg-light border"><?php echo esc_html((string) ($recipient['source_label'] ?? '')); ?></span></td>
                      <td class="text-end"><button class="btn btn-sm btn-outline-secondary blr-ba-recipient-include" type="button" data-contact-id="<?php echo (int) ($recipient['contact_id'] ?? 0); ?>"><?php echo esc_html__('Re-include', 'blr-backline'); ?></button></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="d-flex gap-2 mt-3">
      <button class="btn btn-outline-primary" type="submit" name="save_draft" value="1"><?php echo esc_html__('Save Draft', 'blr-backline'); ?></button>
      <button class="btn btn-primary" type="button" id="blr-ba-open-send-modal" <?php disabled($preview_count <= 0); ?>><?php echo esc_html__('Send Now', 'blr-backline'); ?></button>
      <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'outreach/'); ?>"><?php echo esc_html__('Cancel', 'blr-backline'); ?></a>
    </div>
  </form>
</div>

<div class="modal fade" id="blr-ba-send-modal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><?php echo esc_html__('Send campaign now?', 'blr-backline'); ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"></button>
      </div>
      <div class="modal-body">
        <p class="mb-2"><?php echo esc_html__('This will send individual emails to', 'blr-backline'); ?> <strong id="blr-ba-send-modal-count"><?php echo (int) $preview_count; ?></strong> <span id="blr-ba-send-modal-label"><?php echo esc_html(_n('valid recipient', 'valid recipients', max(1, $preview_count), 'blr-backline')); ?></span>.</p>
        <p class="mb-0 text-muted"><?php echo esc_html__('Duplicate protection is on. Anyone already sent in this campaign will be skipped.', 'blr-backline'); ?></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal"><?php echo esc_html__('Cancel', 'blr-backline'); ?></button>
        <button type="button" class="btn btn-primary" id="blr-ba-confirm-send" <?php disabled($preview_count <= 0); ?>><?php echo esc_html__('Send', 'blr-backline'); ?></button>
      </div>
    </div>
  </div>
</div>

<?php ob_start(); ?>
(function(){
  var form = document.getElementById('blr-ba-outreach-form');
  var builder = document.getElementById('blr-ba-recipient-builder');
  var previewBody = document.getElementById('blr-ba-recipient-preview-body');
  var excludedBody = document.getElementById('blr-ba-excluded-preview-body');
  var excludedInputs = document.getElementById('blr-ba-excluded-inputs');
  var previewStatus = document.getElementById('blr-ba-preview-status');
  var searchInput = document.getElementById('blr-ba-recipient-search');
  var recipientCountEl = document.getElementById('blr-ba-recipient-count');
  var recipientCountLabelEl = document.getElementById('blr-ba-recipient-count-label');
  var manualCountEl = document.getElementById('blr-ba-manual-count');
  var filteredCountEl = document.getElementById('blr-ba-filtered-count');
  var excludedCountEl = document.getElementById('blr-ba-excluded-count');
  var openBtn = document.getElementById('blr-ba-open-send-modal');
  var confirmBtn = document.getElementById('blr-ba-confirm-send');
  var input = document.getElementById('blr-ba-send-now-input');
  var modalEl = document.getElementById('blr-ba-send-modal');
  var previewUrl = builder ? builder.getAttribute('data-preview-url') : '';
  var previewAction = builder ? builder.getAttribute('data-preview-action') : '';
  var previewNonce = builder ? builder.getAttribute('data-preview-nonce') : '';
  var refreshTimer = null;
  var requestCounter = 0;

  if (!form || !builder || !previewBody || !excludedBody || !excludedInputs || !previewStatus || !searchInput || !recipientCountEl || !recipientCountLabelEl || !manualCountEl || !filteredCountEl || !excludedCountEl || !previewUrl || !previewAction || !previewNonce) {
    return;
  }

  function escapeHtml(value) {
    return String(value === null || value === undefined ? '' : value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function uniqueIntList(values) {
    var seen = {};
    var out = [];
    (values || []).forEach(function(value){
      var parsed = parseInt(value, 10);
      if (!parsed || parsed < 1 || seen[parsed]) {
        return;
      }
      seen[parsed] = true;
      out.push(parsed);
    });
    return out;
  }

  function readExcludedIds() {
    return uniqueIntList(Array.prototype.map.call(excludedInputs.querySelectorAll('input[name="excluded_contact_ids[]"]'), function(inputEl){
      return inputEl.value;
    }));
  }

  var excludedIds = readExcludedIds();

  function writeExcludedIds(ids) {
    excludedIds = uniqueIntList(ids);
    excludedInputs.innerHTML = '';
    excludedIds.forEach(function(id){
      var hidden = document.createElement('input');
      hidden.type = 'hidden';
      hidden.name = 'excluded_contact_ids[]';
      hidden.value = String(id);
      excludedInputs.appendChild(hidden);
    });
  }

  function buildRowSearch(recipient) {
    return [recipient.name, recipient.email, recipient.company, recipient.role, recipient.city, recipient.state, recipient.contact_type, recipient.source_label]
      .filter(Boolean)
      .join(' ')
      .toLowerCase();
  }

  function recipientDetails(recipient) {
    var bits = [];
    if (recipient.company) bits.push(recipient.company);
    if (recipient.role) bits.push(recipient.role);
    var location = [recipient.city, recipient.state].filter(Boolean).join(', ');
    if (location) bits.push(location);
    if (recipient.contact_type) bits.push(recipient.contact_type);
    return bits.join(' • ');
  }

  function rowMarkup(recipient, kind) {
    var actionClass = kind === 'excluded' ? 'blr-ba-recipient-include btn-outline-secondary' : 'blr-ba-recipient-exclude btn-outline-danger';
    var actionLabel = kind === 'excluded' ? '<?php echo esc_js(__('Re-include', 'blr-backline')); ?>' : '<?php echo esc_js(__('Exclude', 'blr-backline')); ?>';
    var details = recipientDetails(recipient);
    return '<tr data-contact-id="' + escapeHtml(recipient.contact_id) + '" data-search="' + escapeHtml(buildRowSearch(recipient)) + '">' +
      '<td><div class="fw-semibold">' + escapeHtml(recipient.name || '') + '</div></td>' +
      '<td><div class="small text-muted">' + escapeHtml(details || '<?php echo esc_js(__('—', 'blr-backline')); ?>') + '</div></td>' +
      '<td><a href="mailto:' + escapeHtml(recipient.email || '') + '">' + escapeHtml(recipient.email || '') + '</a></td>' +
      '<td><span class="badge text-bg-light border">' + escapeHtml(recipient.source_label || '') + '</span></td>' +
      '<td class="text-end"><button class="btn btn-sm ' + actionClass + '" type="button" data-contact-id="' + escapeHtml(recipient.contact_id) + '">' + actionLabel + '</button></td>' +
    '</tr>';
  }

  function emptyRowMarkup(label, size) {
    var cols = size || 5;
    return '<tr class="blr-ba-empty-row"><td colspan="' + cols + '" class="text-muted text-center py-4">' + escapeHtml(label) + '</td></tr>';
  }

  function renderTable(target, items, kind) {
    if (!items || !items.length) {
      target.innerHTML = emptyRowMarkup(kind === 'excluded' ? '<?php echo esc_js(__('No exclusions yet.', 'blr-backline')); ?>' : '<?php echo esc_js(__('Nobody matches yet.', 'blr-backline')); ?>');
      return;
    }

    target.innerHTML = items.map(function(recipient){
      return rowMarkup(recipient, kind);
    }).join('');
  }

  function updateCounts(counts) {
    var included = parseInt(counts && counts.included ? counts.included : 0, 10) || 0;
    var excluded = parseInt(counts && counts.excluded ? counts.excluded : 0, 10) || 0;
    var manual = parseInt(counts && counts.manual ? counts.manual : 0, 10) || 0;
    var filtered = parseInt(counts && counts.filtered ? counts.filtered : 0, 10) || 0;

    recipientCountEl.textContent = String(included);
    recipientCountLabelEl.textContent = included === 1 ? '<?php echo esc_js(__('recipient', 'blr-backline')); ?>' : '<?php echo esc_js(__('recipients', 'blr-backline')); ?>';
    manualCountEl.textContent = String(manual);
    filteredCountEl.textContent = String(filtered);
    excludedCountEl.textContent = String(excluded);

    if (openBtn) {
      openBtn.disabled = included < 1;
    }
    if (confirmBtn) {
      confirmBtn.disabled = included < 1;
    }

    var sendModalCountEl = document.getElementById('blr-ba-send-modal-count');
    var sendModalLabelEl = document.getElementById('blr-ba-send-modal-label');
    if (sendModalCountEl) {
      sendModalCountEl.textContent = String(included);
    }
    if (sendModalLabelEl) {
      sendModalLabelEl.textContent = included === 1 ? '<?php echo esc_js(__('valid recipient', 'blr-backline')); ?>' : '<?php echo esc_js(__('valid recipients', 'blr-backline')); ?>';
    }
  }

  function applySearchFilter() {
    var query = String(searchInput.value || '').trim().toLowerCase();
    [previewBody, excludedBody].forEach(function(section){
      var rows = Array.prototype.slice.call(section.querySelectorAll('tr[data-search]'));
      var visible = 0;
      rows.forEach(function(row){
        var haystack = row.getAttribute('data-search') || '';
        var show = !query || haystack.indexOf(query) !== -1;
        row.style.display = show ? '' : 'none';
        if (show) {
          visible += 1;
        }
      });
      var empty = section.querySelector('.blr-ba-empty-row');
      if (empty) {
        empty.style.display = rows.length ? 'none' : '';
      }
      if (!rows.length) {
        return;
      }
      if (!visible) {
        if (!empty) {
          section.insertAdjacentHTML('beforeend', emptyRowMarkup('<?php echo esc_js(__('No visible matches for your search.', 'blr-backline')); ?>'));
        } else {
          empty.querySelector('td').textContent = '<?php echo esc_js(__('No visible matches for your search.', 'blr-backline')); ?>';
          empty.style.display = '';
        }
      } else if (empty) {
        empty.remove();
      }
    });
  }

  function renderPreview(payload) {
    var included = Array.isArray(payload && payload.included) ? payload.included : [];
    var excluded = Array.isArray(payload && payload.excluded) ? payload.excluded : [];
    var counts = payload && payload.counts ? payload.counts : {};

    renderTable(previewBody, included, 'included');
    renderTable(excludedBody, excluded, 'excluded');
    writeExcludedIds(excluded.map(function(recipient){ return recipient.contact_id; }));
    updateCounts(counts);
    applySearchFilter();
  }

  function setPreviewStatus(message, isError) {
    previewStatus.textContent = message;
    previewStatus.classList.toggle('text-danger', !!isError);
    previewStatus.classList.toggle('text-muted', !isError);
  }

  function previewFormData() {
    var data = new FormData(form);
    data.delete('_wpnonce');
    data.delete('send_now');
    data.delete('save_draft');
    data.append('action', previewAction);
    data.append('nonce', previewNonce);
    return data;
  }

  function refreshPreview() {
    requestCounter += 1;
    var currentRequest = requestCounter;
    setPreviewStatus('<?php echo esc_js(__('Refreshing recipients…', 'blr-backline')); ?>', false);

    fetch(previewUrl, {
      method: 'POST',
      credentials: 'same-origin',
      body: previewFormData()
    }).then(function(response){
      return response.json();
    }).then(function(response){
      if (currentRequest !== requestCounter) {
        return;
      }
      if (!response || !response.success || !response.data) {
        throw new Error('bad_response');
      }
      renderPreview(response.data);
      setPreviewStatus('<?php echo esc_js(__('Recipient list updated. Excluded contacts stay excluded until you re-include them or they no longer match the current selection.', 'blr-backline')); ?>', false);
    }).catch(function(error){
      if (currentRequest !== requestCounter) {
        return;
      }
      setPreviewStatus('<?php echo esc_js(__('Could not refresh the recipient list. The current preview is still shown.', 'blr-backline')); ?>', true);
      if (window.console && typeof window.console.error === 'function') {
        window.console.error('Backline recipient preview refresh failed.', error);
      }
    });
  }

  function queueRefresh() {
    if (refreshTimer) {
      window.clearTimeout(refreshTimer);
    }
    refreshTimer = window.setTimeout(refreshPreview, 225);
  }

  function submitSend(){
    if (!input || !form || (openBtn && openBtn.disabled)) {
      return;
    }
    input.value = '1';
    form.submit();
  }

  if (openBtn) {
    openBtn.addEventListener('click', function(){
      if (openBtn.disabled) {
        return;
      }
      if (window.bootstrap && bootstrap.Modal && modalEl) {
        bootstrap.Modal.getOrCreateInstance(modalEl).show();
      } else {
        submitSend();
      }
    });
  }

  if (confirmBtn) {
    confirmBtn.addEventListener('click', submitSend);
  }

  builder.addEventListener('click', function(event){
    var button = event.target.closest('button[data-contact-id]');
    if (!button) {
      return;
    }

    var id = parseInt(button.getAttribute('data-contact-id'), 10);
    if (!id) {
      return;
    }

    if (button.classList.contains('blr-ba-recipient-exclude')) {
      excludedIds.push(id);
      writeExcludedIds(excludedIds);
      queueRefresh();
      return;
    }

    if (button.classList.contains('blr-ba-recipient-include')) {
      writeExcludedIds(excludedIds.filter(function(existingId){
        return existingId !== id;
      }));
      queueRefresh();
    }
  });

  searchInput.addEventListener('input', applySearchFilter);

  var refreshSelectors = [
    'select[name="manual_contact_ids[]"]',
    'select[name="filter_contact_type[]"]',
    'select[name="filter_state[]"]',
    'select[name="filter_company[]"]',
    'select[name="filter_role[]"]',
    'input[name="filter_newsletter_only"]',
    'input[name="filter_has_email"]'
  ];
  var refreshSelector = refreshSelectors.join(',');

  form.addEventListener('change', function(event){
    var target = event.target;
    if (target && typeof target.matches === 'function' && target.matches(refreshSelector)) {
      queueRefresh();
    }
  });

  if (window.jQuery) {
    window.jQuery(form).on('select2:select select2:unselect select2:clear', refreshSelector, function(){
      queueRefresh();
    });
  }

  renderPreview({
    included: <?php echo wp_json_encode(array_values($preview_recipients)); ?>,
    excluded: <?php echo wp_json_encode(array_values($excluded_recipients)); ?>,
    counts: <?php echo wp_json_encode([
      'included' => $preview_count,
      'excluded' => $excluded_count,
      'manual' => $manual_count,
      'filtered' => $filtered_count,
    ]); ?>
  });
  setPreviewStatus('<?php echo esc_js(__('Excluded contacts override both manual picks and filters.', 'blr-backline')); ?>', false);
})();
<?php
wp_add_inline_script(
  'blr-ba-plugin',
  (string) ob_get_clean()
);
?>
