<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="container-fluid promo-safe-page" id="container-wrapper">
  <section class="promo-hero">
    <div>
      
      <h1>PROMOSI WHATSAPP &amp; BLAST SAFE QUEUE</h1>
      <p>Kirim promo diskon, pengingat, dan informasi pelanggan dengan proteksi anti-blokir otomatis (jeda acak, variasi pesan, dan batching queue).</p>
    </div>
    <div class="promo-hero-actions">
      <button type="button" class="promo-tip"><i class="fa fa-shield"></i> TIPS ANTI-BANNED WA</button>
    </div>
  </section>

  <nav class="promo-tabs" aria-label="Navigasi promosi">
    <a class="active promo-broadcast-tab" href="<?=base_url('promo/panel');?>"><i class="fa fa-paper-plane"></i> KIRIM PROMO BROADCAST</a>
    <a class="promo-template-tab" href="<?=base_url('promo/template');?>"><i class="fa fa-file-text-o"></i> KELOLA TEMPLATE PROMO (<?=count($promo);?>)</a>
    <a class="promo-report-tab" href="<?=base_url('promo/report');?>"><i class="fa fa-clock-o"></i> RIWAYAT PENGIRIMAN (<?=(int) $report_count;?>)</a>
    <button type="button" class="promo-guide"><i class="fa fa-info-circle"></i> PANDUAN KEAMANAN AKUN</button>
  </nav>

  <div class="promo-workspace">
    <div class="promo-left-column">
      <section class="promo-card target-card loading-promo">
        <div class="promo-card-head">
          <h2><i class="fa fa-users"></i> TARGET PENERIMA (<span class="total_kontak">0</span>)</h2>
          <button type="button" class="link-button reset_promo"><i class="fa fa-refresh"></i> RESET STATUS KONTAK</button>
        </div>
        <div class="target-device-row">
          <label class="target-device-label">DEVICE WHATSAPP
            <select name="device" id="device_promo" class="target-device" data-source-promo="<?=base_url('promo/load_device');?>" data-valueKey="id" data-displayKey="name" aria-label="Pilih device WhatsApp">
              <option value="">Pilih Device WhatsApp</option>
            </select>
          </label>
          <div class="target-device-status">
            <button type="button" id="cek_status" class="status-button">CEK STATUS DEVICE</button>
            <span id="device-status-text">Device belum dipilih</span>
          </div>
        </div>
        <div class="target-filters">
          <label>LEVEL MEMBER
			<select id="label" disabled>
			  <option value="1">Semua Pelanggan</option>
			  <?php if (!empty($member_levels)) { ?>
				<optgroup label="Filter Level Member">
				  <?php foreach ($member_levels as $row) { ?>
					<option value="member:<?=(int) $row->id;?>"><?=html_escape($row->title);?></option>
				  <?php } ?>
				</optgroup>
			  <?php } ?>
			</select>
          </label>
          <label>MAKS. KONTAK
            <input type="number" id="max_kirim" min="1" value="100" disabled>
          </label>
        </div>
        <div class="target-search"><i class="fa fa-search"></i><input type="text" id="target-search" placeholder="Cari nama / nomor HP pelanggan..." disabled></div>
        <div class="target-summary">
          <button type="button" id="toggle-all" class="target-toggle" disabled><i class="fa fa-check-circle-o"></i> Pilih Semua</button>
          <strong>Terpilih: <span id="selected-count">0</span> / <span id="contact-count">0</span> kontak</strong>
        </div>
        <div class="target-list" id="target-list"><div class="target-empty">Pilih device dan level pelanggan untuk menyiapkan antrean penerima.</div></div>
      </section>

      <section class="protection-card">
        <div class="protection-head">
          <h2><i class="fa fa-shield"></i> PENGATURAN PROTEKSI ANTI-BLOCK</h2>
          <span id="safe-status">SAFE MODE ACTIVE</span>
        </div>
        <div class="protection-block">
          <label class="block-title">MODE PENGIRIMAN</label>
          <div class="mode-grid">
            <button type="button" class="mode-option active" data-mode="direct"><i class="fa fa-bolt"></i><span><b>DIRECT GATEWAY</b><small>Otomatis via perangkat/API</small></span></button>
            <button type="button" class="mode-option" data-mode="semi"><i class="fa fa-whatsapp"></i><span><b>SEMI-AUTO WA WEB</b><small>Mode pendamping manual</small></span></button>
          </div>
        </div>
        <div class="protection-block">
          <div class="block-row"><b>Jeda Acak Antar Pesan:</b><strong><span id="delay-range">6 - 14</span> Detik</strong></div>
          <div class="two-inputs">
            <label>Min Jeda (s)<input type="number" id="delay_min" min="5" max="15" value="5"></label>
            <label>Max Jeda (s)<input type="number" id="delay" min="5" max="15" value="15" disabled></label>
          </div>
        </div>
        <div class="protection-block">
          <div class="block-row"><b>Sistem Pause Batch Otomatis</b><input type="checkbox" id="batch_enabled" checked></div>
          <div class="two-inputs">
            <label>Min. Kontak / Batch<input type="number" id="batch_size" min="15" max="20" value="15"></label>
            <label>Min. Istirahat (Detik)<input type="number" id="batch_pause" min="60" max="90" value="60"></label>
          </div>
        </div>
        <label class="optout"><input type="checkbox" id="optout" checked> Sertakan footer Opt-Out (_Balas STOP jika tidak berkenan_)</label>
      </section>
    </div>

    <div class="promo-right-column">
      <section class="promo-card template-card">
        <div class="promo-card-head">
          <h2><i class="fa fa-magic"></i> PILIH TEMPLATE PESAN PROMO</h2>
          <a class="link-button" href="<?=base_url('promo/template');?>"><i class="fa fa-plus"></i> Buat Template Custom</a>
        </div>
        <select id="text_promo" class="sr-only" disabled aria-label="Template promo">
          <option value="0">Pilih Konten Promo</option>
          <?php foreach ($promo as $row) { ?><option value="<?=$row->id;?>"><?=html_escape($row->title);?></option><?php } ?>
        </select>
        <div class="template-grid">
          <?php foreach ($promo as $index => $row) { ?>
            <button type="button" class="template-option" data-id="<?=$row->id;?>">
              <b><?=html_escape($row->title);?></b><small><?=!empty($row->jenis_pesan) ? 'MEDIA' : 'GENERAL';?></small>
            </button>
          <?php } ?>
          <?php if (empty($promo)) { ?><div class="template-empty">Belum ada template promo.</div><?php } ?>
        </div>
        <div class="variables">
          <span>KLIK VARIABEL DINAMIS UNTUK DISISIPKAN:</span>
          <div><button type="button">+ {nama}</button><button type="button">+ {level_member}</button><button type="button">+ {poin}</button><button type="button">+ {nama_toko}</button><button type="button">+ {telepon_toko}</button><button type="button" class="spintax-variable">+ {Halo|Hai|Selamat Siang}</button></div>
        </div>
        <label class="message-label">ISI PESAN PROMOSI (MENDUKUNG SPINTAX {A|B})</label>
        <textarea id="promo-message" rows="8" placeholder="Pilih template untuk menampilkan isi pesan..."></textarea>
        <div class="preview-card">
          <div class="preview-title">PRATINJAU HASIL TEKS PESAN (SATU PENERIMA CONTOH)</div>
          <div id="promo-preview">Pilih template promo untuk melihat pratinjau pesan.</div>
        </div>
        <div class="schedule-row">
          <label>Format Pengiriman
            <select id="format_pesan" disabled><option value="0">Langsung</option><option value="1">Terjadwal</option></select>
          </label>
          <label class="schedule">Jadwal<input type="datetime-local" id="schedule"></label>
        </div>
        <button type="button" id="kirim" class="send-promo" disabled><i class="fa fa-paper-plane"></i> MULAI KIRIM PROMOSI VIA WA (<span class="total_kontak">0</span> KONTAK)</button>
        <div class="promo-log" aria-live="polite">
          <div class="promo-log-head"><div class="log-dots"><i></i><i></i><i></i></div><strong id="queue-status">Aktivitas pengiriman</strong><span id="queue-summary">0 / 0</span></div>
          <div class="queue-live" id="queue-live"><i class="fa fa-info-circle"></i><span>Antrean belum dimulai.</span></div>
          <ul id="menu" class="logs"></ul>
        </div>
      </section>
    </div>
  </div>

  <section class="security-guide-page" id="security-guide-page" aria-hidden="true">
    <div class="security-guide-head">
      <span class="security-guide-icon"><i class="fa fa-shield"></i></span>
      <div><h2>PANDUAN LENGKAP MENCEGAH NOMOR WA TERBLOKIR (ANTI-BANNED)</h2><p>Memahami algoritma keamanan WhatsApp &amp; praktik terbaik pengiriman promosi.</p></div>
    </div>
    <div class="security-guide-grid">
      <article class="security-risk">
        <h3><i class="fa fa-warning"></i> MENGAPA NOMOR WA BISA TERBLOKIR?</h3>
        <ul>
          <li><strong>Pengiriman Beruntun Tanpa Jeda:</strong> Mengirim ratusan pesan dalam hitungan detik terdeteksi otomatis sebagai aktivitas bot/spam oleh WhatsApp server.</li>
          <li><strong>Pesan Identik 100%:</strong> Mengirimkan teks persis sama tanpa variasi ke banyak orang secara masal.</li>
          <li><strong>Dilaporkan oleh Pelanggan (Report Spam):</strong> Penerima merasa terganggu dan menekan tombol “Report &amp; Block”.</li>
          <li><strong>Nomor Pengirim Masih Baru:</strong> Nomor yang baru didaftarkan belum memiliki reputasi (chat history) tinggi.</li>
        </ul>
      </article>
      <article class="security-solution">
        <h3><i class="fa fa-check-circle-o"></i> SOLUSI PROTEKSI</h3>
        <ul>
          <li><strong>Human-Like Random Delay:</strong> Sistem memberikan jeda acak 5–15 detik antar pengiriman pesan.</li>
          <li><strong>Fitur Spintax Dynamic Text:</strong> Mengacak sinonim kalimat seperti <code>{Halo|Hai|Selamat Siang}</code> sehingga tiap pesan terasa unik.</li>
          <li><strong>Istirahat / Auto Pause Batching:</strong> Mengistirahatkan sesi pengiriman tiap 15–20 kontak.</li>
          <li><strong>Variabel Nama &amp; Level Poin:</strong> Menyebut nama pelanggan dan data personal agar pesan bernilai tinggi.</li>
        </ul>
      </article>
    </div>
    <article class="security-checklist">
      <h3><i class="fa fa-lightbulb-o"></i> CHECKLIST PRAKTIK TERBAIK PENGIRIM PROMOSI:</h3>
      <ol>
        <li>Gunakan nomor <strong>WhatsApp Business</strong> yang aktif dipakai minimal 1–2 bulan untuk komunikasi harian.</li>
        <li>Usahakan penerima promo adalah pelanggan yang pernah bertransaksi atau menyimpan nomor toko Anda.</li>
        <li>Jangan mengirimkan pesan promo lebih dari 1–2 kali dalam sebulan agar pelanggan tidak merasa terganggu.</li>
        <li>Selalu sertakan opsi opt-out ramah di bagian akhir pesan (_Balas STOP jika tidak berkenan_).</li>
      </ol>
    </article>
  </section>

  <section class="promo-template-page" id="promo-template-page" aria-hidden="true">
    <?php $this->load->view('promo/template', ['embedded' => true, 'template_cards' => $template_cards]); ?>
    <?php $this->load->view('promo/media'); ?>
  </section>

  <section class="promo-report-page" id="promo-report-page" aria-hidden="true">
    <?php $this->load->view('promo/report', ['embedded' => true]); ?>
  </section>
</div>

<div class="anti-ban-modal" id="anti-ban-modal" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="anti-ban-title">
  <div class="anti-ban-dialog" role="document">
    <div class="anti-ban-head">
      <div class="anti-ban-heading">
        <span class="anti-ban-icon"><i class="fa fa-shield"></i></span>
        <h2 id="anti-ban-title">PANDUAN LENGKAP ANTI-BLOCK WHATSAPP</h2>
      </div>
      <button type="button" class="anti-ban-close" aria-label="Tutup panduan">&times;</button>
    </div>
    <div class="anti-ban-body">
      <p><strong>Apakah nomor bisa terblokir?</strong> Ya, WhatsApp menggunakan sistem AI untuk memantau pengiriman pesan massal. Namun dengan sistem <strong>Safe Broadcast Queue PrintPro</strong>, risiko blokir dapat ditekan hingga tingkat sangat aman dengan mengikuti 4 pilar utama:</p>

      <section><h3>1. JEDA WAKTU RANDOM (HUMAN BEHAVIOR)</h3><p>Aplikasi ini secara otomatis mengatur jeda acak 5-15 detik per pengiriman. Mencegah deteksi pengiriman bersamaan dalam 1 milidetik.</p></section>
      <section><h3>2. VARIASI TEKS OTOMATIS (SPINTAX)</h3><p>Gunakan tag pilihan kata acak seperti <code>{Halo|Hai|Selamat Pagi}</code> agar pesan yang terkirim memiliki struktur kata yang selalu berbeda.</p></section>
      <section><h3>3. ISTIRAHAT SESI (BATCHING PAUSE)</h3><p>Setelah mengirim 15 kontak, sistem beristirahat 60-90 detik secara otomatis untuk mereplikasi perilaku pengetikan manusia.</p></section>
      <section><h3>4. MODE SEMI-AUTO WA WEB (100% BEBAS API)</h3><p>Jika ingin 100% aman tanpa risiko API, gunakan mode Semi-Auto WA Web di mana Anda hanya perlu mengklik satu tombol per kontak dari browser Anda.</p></section>
    </div>
    <div class="anti-ban-footer"><button type="button" class="anti-ban-understand">SAYA MENGERTI</button></div>
  </div>
</div>

<style>
.promo-safe-page{--purple:#5142ee;--blue:#235fba;--green:#079c76;--ink:#0d1830;--muted:#8290aa;--line:#dfe6ef;max-width:1600px;margin:0 auto;padding-bottom:45px;color:var(--ink);font-size:13px}.promo-hero{display:flex;align-items:center;justify-content:space-between;gap:25px;min-height:180px;padding:30px 34px;border-radius:18px;color:#fff;background:linear-gradient(115deg,#079c76 0%,#128e86 42%,#326db5 73%,#5341d9 100%);box-shadow:0 18px 35px rgba(25,50,85,.14)}.promo-engine{display:inline-flex;align-items:center;gap:8px;padding:6px 14px;border-radius:18px;background:rgba(255,255,255,.17);font-weight:800}.promo-hero h1{margin:14px 0 8px;font-size:30px;font-weight:800;letter-spacing:-.5px}.promo-hero p{max-width:760px;margin:0;line-height:1.55;font-weight:600}.promo-hero-actions{display:flex;align-items:center;gap:12px;min-width:410px}.promo-tip,.promo-device{height:44px;border:1px solid rgba(255,255,255,.25);border-radius:14px}.promo-tip{padding:0 20px;border:0;background:#ffbd25;color:#201700;font-weight:800}.promo-device{flex:1;padding:0 15px;background:rgba(255,255,255,.12);color:#fff;font-weight:700}.promo-device option{color:#222}.promo-tabs{display:flex;align-items:center;gap:10px;margin:23px 0 24px;padding-bottom:14px;border-bottom:1px solid var(--line)}.promo-tabs a,.promo-tabs button{display:inline-flex;align-items:center;justify-content:center;gap:9px;min-height:42px;padding:0 22px;border:0;border-radius:22px;background:#f1f4f8;color:#3c4c66;font-weight:800;text-decoration:none}.promo-tabs a.active{color:#fff;background:linear-gradient(90deg,#4e3deb,#5d49e9);box-shadow:0 7px 17px rgba(81,66,238,.22)}.promo-tabs .promo-guide{color:#078366;background:#eaf9f4}.promo-workspace{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:30px}.promo-left-column,.promo-right-column{display:flex;flex-direction:column;gap:24px}.promo-card,.protection-card{border:1px solid var(--line);border-radius:16px;background:#fff;box-shadow:0 2px 4px rgba(15,30,55,.04)}.promo-card{padding:25px}.promo-card-head{display:flex;align-items:center;justify-content:space-between;gap:15px;padding-bottom:17px;border-bottom:1px solid #edf1f5}.promo-card-head h2,.protection-head h2{margin:0;font-size:15px;font-weight:800}.promo-card-head h2 i{margin-right:9px;color:var(--purple);font-size:19px}.link-button{border:0;background:transparent;color:var(--purple);font-weight:800;text-decoration:none}.target-filters,.two-inputs,.schedule-row{display:grid;grid-template-columns:1fr 1fr;gap:13px}.target-filters{margin-top:17px}.target-filters label,.two-inputs label,.schedule-row label,.message-label{color:#8996ad;font-size:10px;font-weight:800}.target-filters select,.target-filters input,.two-inputs input,.schedule-row select,.schedule-row input{width:100%;height:40px;margin-top:6px;padding:0 12px;border:1px solid #dce3ed;border-radius:12px;background:#f8fafc;color:#26354d}.target-search{display:flex;align-items:center;gap:10px;height:40px;margin-top:14px;padding:0 13px;border:1px solid #dce3ed;border-radius:12px;background:#f8fafc;color:#91a0b5}.target-search input{flex:1;border:0;outline:0;background:transparent}.target-summary{display:flex;justify-content:space-between;margin-top:15px;padding:13px 0;border-top:1px solid #edf1f5;color:#596a84}.target-summary span{color:var(--purple);font-weight:700}.target-empty{display:flex;align-items:center;justify-content:center;min-height:105px;color:#98a4b6;font-style:italic}.protection-card{padding:25px;color:#fff;border-color:#111a3a;background:linear-gradient(145deg,#0c142c,#20204e);box-shadow:0 14px 30px rgba(10,20,48,.17)}.protection-head,.block-row,.device-status-row{display:flex;align-items:center;justify-content:space-between;gap:15px}.protection-head{padding-bottom:17px;border-bottom:1px solid rgba(255,255,255,.12)}.protection-head h2{color:#35efbf}.protection-head span{padding:6px 12px;border:1px solid rgba(53,239,191,.25);border-radius:17px;color:#35efbf;background:rgba(0,160,120,.2);font-size:10px;font-weight:800}.protection-block{padding:17px 0;border-bottom:1px solid rgba(255,255,255,.12)}.block-title{display:block;margin-bottom:10px;color:#9db0d8;font-size:10px;font-weight:800}.mode-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.mode-option{display:flex;align-items:center;gap:10px;min-height:58px;padding:10px 14px;border:1px solid rgba(255,255,255,.16);border-radius:14px;background:rgba(255,255,255,.06);color:#aebbd3;text-align:left}.mode-option.active{border-color:#2fe4b3;background:#079c76;color:#fff}.mode-option span{display:flex;flex-direction:column}.mode-option small{margin-top:2px;font-size:9px}.block-row strong{color:#2fe4b3}.two-inputs{margin-top:10px}.two-inputs label{color:#9db0d8}.two-inputs input{border-color:rgba(255,255,255,.18);background:rgba(255,255,255,.09);color:#fff}.optout{display:flex;align-items:center;gap:9px;margin:17px 0}.device-status-row{padding-top:5px}.status-button{padding:8px 14px;border:1px solid #38ddb2;border-radius:8px;background:transparent;color:#38ddb2;font-weight:800}.template-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;margin:15px 0}.template-option{min-height:64px;padding:11px 12px;border:1px solid #dce3ed;border-radius:14px;background:#f8fafc;color:#182741;text-align:left}.template-option.active{border-color:#6b46ff;background:#fff;box-shadow:inset 0 0 0 1px #6b46ff}.template-option b,.template-option small{display:block}.template-option b{font-size:12px}.template-option small{margin-top:8px;color:var(--purple);font-size:9px;font-weight:800}.variables{padding:13px 0;border-top:1px solid #edf1f5}.variables>span,.message-label{display:block;margin-bottom:8px}.variables button{margin:0 5px 5px 0;padding:5px 9px;border:0;border-radius:13px;background:#f0f3f7;color:#25344c;font-size:10px;font-weight:700}.template-card textarea{width:100%;padding:14px;border:1px solid #dce3ed;border-radius:14px;background:#f8fafc;color:#17243b;resize:vertical}.preview-card{margin-top:17px;padding:16px;border-radius:15px;color:#eafff8;background:#154b3f}.preview-title{margin-bottom:12px;color:#3af0bd;font-size:10px;font-weight:800}.preview-card>div:last-child{min-height:115px;padding:13px;border:1px solid rgba(61,240,190,.2);border-radius:12px;background:#0d5545;white-space:pre-wrap;line-height:1.55}.schedule-row{margin-top:15px}.schedule{display:none}.send-promo{width:100%;height:52px;margin-top:16px;border:0;border-radius:14px;color:#fff;background:linear-gradient(90deg,#6ccab6,#8c83eb);font-weight:800}.send-promo:disabled{opacity:.6}.send-controls{display:flex;align-items:center;gap:8px;margin-top:12px}.send-controls button,.send-controls span{padding:7px 11px;border:1px solid #dfe5ed;border-radius:8px;background:#fff;color:#42516a}.promo-log{display:none;margin-top:13px;padding:12px;border-radius:12px;background:#080d1d;color:#dce8ff}.promo-log.has-logs{display:block}.log-dots{display:flex;gap:6px;margin-bottom:8px}.log-dots i{width:8px;height:8px;border-radius:50%;background:#ff335c}.log-dots i:nth-child(2){background:#ffc23c}.log-dots i:nth-child(3){background:#52d334}.logs{max-height:140px;margin:0;padding-left:20px;overflow:auto}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:1100px){.promo-workspace{grid-template-columns:1fr}.promo-hero{align-items:flex-start;flex-direction:column}.promo-hero-actions{width:100%;min-width:0}.promo-tabs{overflow-x:auto}.promo-tabs>*{flex:0 0 auto}}@media(max-width:650px){.promo-safe-page{padding-left:10px;padding-right:10px}.promo-hero{padding:23px}.promo-hero h1{font-size:23px}.promo-hero-actions{flex-direction:column;align-items:stretch}.promo-tabs{margin-top:15px}.promo-card,.protection-card{padding:18px}.target-filters,.two-inputs,.schedule-row,.mode-grid{grid-template-columns:1fr}.template-grid{grid-template-columns:1fr 1fr}.promo-card-head{align-items:flex-start;flex-direction:column}.send-controls{flex-wrap:wrap}}
</style>

<style>
.promo-hero{background:var(--app-theme-color,#3f51b5);color:var(--app-theme-text-color,#fff)}.promo-hero-actions{min-width:0}.target-device-row{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:14px;margin-top:17px}.target-device-label{display:block;margin:0;color:#8996ad;font-size:10px;font-weight:800}.target-device{display:block;width:100%;height:40px;margin-top:6px;padding:0 12px;border:1px solid #dce3ed;border-radius:12px;background:#f8fafc;color:#26354d;font-weight:600}.target-device:focus{border-color:var(--app-theme-color,#3f51b5);outline:0;box-shadow:0 0 0 2px color-mix(in srgb,var(--app-theme-color,#3f51b5) 15%,transparent)}.target-device-status{display:flex;align-items:center;gap:10px;min-height:40px}.target-device-status .status-button{height:40px;padding:0 14px;border-color:var(--app-theme-color,#3f51b5);color:var(--app-theme-color,#3f51b5);white-space:nowrap}.target-device-status #device-status-text{max-width:150px;color:#697891;font-size:11px;line-height:1.25}.target-device-status .status-button.connected{background:#079c76;border-color:#079c76;color:#fff}@media(max-width:800px){.target-device-row{grid-template-columns:1fr}.target-device-status{justify-content:space-between}.target-device-status #device-status-text{max-width:none;text-align:right}}
.target-toggle{padding:0;border:0;background:transparent;color:var(--purple);font-weight:700}.target-toggle:disabled{color:#98a4b6}.target-list{display:grid;gap:8px;max-height:245px;overflow:auto}.target-contact{display:flex;align-items:center;gap:12px;padding:11px 13px;border:1px solid #dfe6ef;border-radius:14px;background:#fff;cursor:pointer}.target-contact.selected{border-color:#7149ff;box-shadow:inset 0 0 0 1px #7149ff}.target-contact input{width:17px;height:17px;margin:0;accent-color:#2867ed}.target-contact-body{min-width:0}.target-contact-title{display:flex;align-items:center;gap:8px}.target-contact-name{max-width:310px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:800}.target-contact-badge{padding:3px 8px;border-radius:9px;background:#e8efff;color:#3762d4;font-size:9px;font-weight:800;text-transform:uppercase}.target-contact-meta{margin-top:3px;color:#718099;font-size:10px}
.anti-ban-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;padding:24px;background:rgba(24,34,54,.62);backdrop-filter:blur(4px)}.anti-ban-modal.open{display:flex}.anti-ban-dialog{width:min(672px,100%);max-height:calc(100vh - 48px);overflow:auto;border-radius:16px;background:#fff;box-shadow:0 24px 70px rgba(9,18,38,.3);color:#344157}.anti-ban-head{display:flex;align-items:center;justify-content:space-between;margin:0 32px;padding:32px 0 16px;border-bottom:1px solid #e7ebf1}.anti-ban-heading{display:flex;align-items:center;gap:13px}.anti-ban-heading h2{margin:0;color:#11182b;font-size:17px;font-weight:800}.anti-ban-icon{display:inline-flex;align-items:center;justify-content:center;width:45px;height:45px;border-radius:14px;background:#d6faec;color:#079c76;font-size:21px}.anti-ban-close{width:34px;height:34px;padding:0;border:0;background:transparent;color:#8da0ba;font-size:26px;font-weight:300;line-height:1}.anti-ban-body{padding:24px 32px 12px;font-size:12.5px;line-height:1.55}.anti-ban-body>p{margin:0 0 18px}.anti-ban-body section{margin:0 0 16px}.anti-ban-body h3{margin:0 0 7px;color:#20293b;font-size:12px;font-weight:800}.anti-ban-body section p{margin:0}.anti-ban-body code{padding:2px 5px;border-radius:3px;background:#edf1f5;color:#435068}.anti-ban-footer{display:flex;justify-content:flex-end;padding:4px 32px 32px}.anti-ban-understand{min-width:147px;height:38px;border:0;border-radius:20px;background:#5142ee;color:#fff;font-size:11px;font-weight:800;box-shadow:0 8px 18px rgba(81,66,238,.25)}body.anti-ban-open{overflow:hidden}@media(max-width:650px){.anti-ban-modal{padding:12px}.anti-ban-head{margin:0 20px;padding-top:22px}.anti-ban-heading h2{font-size:14px}.anti-ban-body{padding:20px}.anti-ban-footer{padding:2px 20px 22px}}
.anti-ban-body section{display:block!important;width:auto!important;height:auto!important;min-height:0!important;max-height:none!important;margin:0 0 16px!important;padding:0!important;background:transparent!important;box-shadow:none!important}.anti-ban-body section:last-child{margin-bottom:0!important}.anti-ban-body section h3,.anti-ban-body section p{position:static!important;transform:none!important}.anti-ban-dialog{height:auto!important}.anti-ban-footer{min-height:0!important}
.security-guide-page .security-checklist{margin-top:24px!important}
.promo-history-card{padding:24px;border:1px solid #dfe6ef;border-radius:16px;background:#fff;box-shadow:0 2px 4px rgba(15,30,55,.04)}.promo-history-head{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-bottom:17px;border-bottom:1px solid #e9edf3}.promo-history-head h2{margin:0 0 4px;color:#111a2d;font-size:18px;font-weight:800}.promo-history-head h2 i{margin-right:9px;color:#5946ee;font-size:20px}.promo-history-head p{margin:0;color:#718099}.promo-history-stats{display:flex;align-items:center;gap:9px}.promo-history-stats span{padding:6px 12px;border-radius:16px;background:#f1f4f7;color:#233149;font-size:11px;font-weight:700}.promo-history-stats .success{color:#087b61;background:#dcf8ed}.promo-history-stats .failed{color:#d52f45;background:#ffe7eb}.promo-history-filters{display:grid;grid-template-columns:minmax(260px,2fr) minmax(180px,1fr) minmax(200px,1fr);align-items:center;gap:12px;margin:25px 0;padding:16px;border:1px solid #edf1f5;border-radius:14px;background:#f8fafc}.promo-history-search{display:flex;align-items:center;gap:10px;height:38px;margin:0;padding:0 13px;border:1px solid #dce3ed;border-radius:12px;background:#fff;color:#8c9ab0}.promo-history-search input{width:100%;border:0;outline:0;background:transparent;color:#27364d}.promo-history-filters select{width:100%;height:38px;padding:0 12px;border:1px solid #dce3ed;border-radius:12px;background:#fff;color:#27364d}.promo-history-limit{display:flex;align-items:center;gap:10px;margin:0;color:#68778e;white-space:nowrap}.promo-history-limit select{flex:1}.promo-history-table{overflow:hidden;border:1px solid #edf1f5;border-radius:14px}.promo-history-data-table{width:100%;border-collapse:collapse}.promo-history-data-table th{padding:14px 12px!important;border:0!important;background:#f1f5f9!important;color:#52627b!important;font-size:10px;font-weight:800;text-align:left}.promo-history-data-table td{padding:14px 12px;border:0;border-top:1px solid #edf1f5;color:#33425a;vertical-align:top}.promo-history-data-table .number{width:38px;text-align:center}.promo-history-data-table .time{width:140px;white-space:nowrap}.promo-history-data-table .recipient{font-weight:700}.promo-history-data-table .whatsapp{width:170px;white-space:nowrap}.promo-history-data-table .whatsapp i{color:#18a96c}.promo-history-data-table .message{max-width:480px;white-space:normal}.promo-history-status{display:inline-flex;padding:5px 10px;border-radius:13px;background:#fff2d8;color:#a36a00;font-size:10px;font-weight:800}.promo-history-status.success{background:#dcf8ed;color:#087b61}.promo-history-status.failed{background:#ffe7eb;color:#d52f45}.promo-history-data-table .empty-row td{height:96px;color:#93a0b4;text-align:center;vertical-align:middle}.promo-history-data-table .empty-row i{display:block;margin-bottom:7px;color:#6c55ef;font-size:20px}.promo-history-pagination{display:flex;justify-content:flex-end;margin-top:16px}.promo-history-loading{padding:55px;color:#91a0b4;text-align:center}@media(max-width:900px){.promo-history-head{align-items:flex-start;flex-direction:column}.promo-history-filters{grid-template-columns:1fr}.promo-history-stats{flex-wrap:wrap}.promo-history-limit{justify-content:space-between}}
.promo-report-page{display:none!important;min-height:0!important;padding:0!important;background:transparent!important}.promo-report-page.open{display:block!important}.promo-report-embedded>div:first-child{margin-bottom:18px!important;padding:0 4px}.promo-report-embedded h1{font-size:25px!important}.promo-report-page .card{border:1px solid #dfe6ef;border-radius:16px;background:#fff;box-shadow:0 2px 4px rgba(15,30,55,.04)}.promo-report-page .card-header{padding:22px;border-bottom:1px solid #edf1f5;background:#fff}.promo-report-page .card-body{padding:22px}.promo-report-page .input-group-text{border-color:var(--app-theme-color,#3f51b5);background:var(--app-theme-color,#3f51b5);color:var(--app-theme-text-color,#fff);font-weight:800}.promo-report-page .form-control{height:38px;border-color:#dce3ed}.promo-report-page table{margin-bottom:0;background:#fff}.promo-report-page thead th{border-color:#dce3ed;background:#f1f5f9;color:#24324a}.promo-tabs .promo-report-tab.active{color:#fff;background:linear-gradient(90deg,#4e3deb,#5d49e9);box-shadow:0 7px 17px rgba(81,66,238,.22)}
.promo-template-page{display:none!important;min-height:0!important;padding:0!important;background:transparent!important}.promo-template-page.open{display:block!important}.promo-template-embedded{width:100%}.promo-template-embedded-title{margin-bottom:18px!important;padding:0 4px}.promo-template-embedded-title h1{font-size:25px!important}.promo-template-page .card{border:1px solid #dfe6ef;border-radius:16px;box-shadow:0 2px 4px rgba(15,30,55,.04)}.promo-template-page .card-header{padding:18px 22px;border-bottom:1px solid #edf1f5;background:#fff}.promo-template-page .card-body{padding:22px}.promo-tabs .promo-template-tab.active{color:#fff;background:linear-gradient(90deg,#4e3deb,#5d49e9);box-shadow:0 7px 17px rgba(81,66,238,.22)}
.promo-template-modern-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:24px;padding:24px;border:1px solid #dfe6ef;border-radius:16px;background:#fff;box-shadow:0 2px 4px rgba(15,30,55,.04)}.promo-template-modern-head h2{margin:0 0 5px;color:#101a30;font-size:18px;font-weight:800}.promo-template-modern-head p{margin:0;color:#718099}.promo-add-template{height:42px;padding:0 22px;border:0;border-radius:15px;background:linear-gradient(90deg,#4e3deb,#5d49e9);color:#fff;font-weight:800;box-shadow:0 8px 18px rgba(81,66,238,.23)}.promo-template-card-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px}.promo-template-manager-card{display:flex!important;flex-direction:column;width:auto!important;height:336px!important;min-height:0!important;margin:0!important;padding:24px!important;border:1px solid #dfe6ef;border-radius:16px!important;background:#fff!important;box-shadow:0 2px 4px rgba(15,30,55,.05)!important;transition:transform .18s ease,border-color .18s ease,box-shadow .18s ease}.promo-template-manager-card:hover{transform:translateY(-3px);border-color:#8067ff;box-shadow:0 12px 28px rgba(46,43,100,.12)!important}.promo-template-manager-card.inactive{opacity:.7}.promo-template-card-top{display:flex;align-items:center;justify-content:space-between;gap:10px}.promo-template-kind,.promo-template-state{padding:4px 9px;border-radius:11px;font-size:9px;font-weight:800}.promo-template-kind{color:#553bf0;background:#f5f2ff}.promo-template-state{color:#8796ad;background:#edf1f6}.promo-template-state.active{color:#078366;background:#e7f8f2}.promo-template-manager-card h3{margin:16px 0 12px;color:#111a2d;font-size:14px;font-weight:800;text-transform:uppercase}.promo-template-copy{flex:1;min-height:0;padding:13px;border:1px solid #e2e7ef;border-radius:12px;background:#f8fafc;color:#26354c;font-family:Consolas,monospace;font-size:11px;line-height:1.65;overflow:auto}.promo-template-card-actions{display:grid;grid-template-columns:minmax(0,1fr) 40px 40px;gap:8px;margin-top:15px;padding-top:10px;border-top:1px solid #edf1f5}.use-promo-template,.promo-template-icon{height:34px;border:0;border-radius:10px;font-weight:800}.use-promo-template{background:linear-gradient(90deg,#4e3deb,#5d49e9);color:#fff;font-size:11px}.use-promo-template:disabled{background:#cbd3df}.promo-template-icon{background:#f0f3f8;color:#53627a}.promo-template-icon.danger{color:#e23b4d;background:#fff0f2}.promo-template-modern-empty{grid-column:1/-1;padding:70px 20px;border:1px dashed #cfd7e4;border-radius:16px;color:#8794a8;background:#fff;text-align:center}.promo-template-manager-card.selected{border-color:#6d4cff;box-shadow:inset 0 0 0 1px #6d4cff,0 12px 28px rgba(46,43,100,.12)!important}@media(max-width:1150px){.promo-template-card-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:700px){.promo-template-modern-head{align-items:flex-start;flex-direction:column}.promo-add-template{width:100%}.promo-template-card-grid{grid-template-columns:1fr}.promo-template-manager-card{height:330px!important}}
.security-guide-page{display:none!important;min-height:0!important;padding:32px;border:1px solid #dfe6ef;border-radius:16px;background:#fff;box-shadow:0 2px 4px rgba(15,30,55,.04)}.security-guide-page.open{display:block!important}.security-guide-head{display:flex;align-items:center;gap:14px;padding-bottom:16px;border-bottom:1px solid #e9edf3}.security-guide-icon{display:flex;align-items:center;justify-content:center;width:52px;height:52px;flex:0 0 52px;border-radius:15px;background:#d8f9e9;color:#078c6c;font-size:25px}.security-guide-head h2{margin:0 0 3px;color:#0f172a;font-size:21px;font-weight:800}.security-guide-head p{margin:0;color:#63728a}.security-guide-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-top:24px}.security-guide-page article{display:block!important;width:auto!important;height:auto!important;min-height:0!important;margin:0!important;padding:23px 25px!important;border-radius:15px;box-shadow:none!important}.security-guide-page article h3{margin:0 0 12px;font-size:14px;font-weight:800}.security-guide-page ul,.security-guide-page ol{margin:0;padding-left:20px}.security-guide-page li{margin:0 0 8px;line-height:1.45}.security-guide-page li:last-child{margin-bottom:0}.security-risk{border:1px solid #f2ca57;background:#fff9e8!important;color:#a4531d}.security-risk h3{color:#8e360d}.security-solution{border:1px solid #85e7bb;background:#eafcf4!important;color:#08775f}.security-solution h3{color:#006c53}.security-solution code{padding:2px 4px;background:#d9f5e9;color:#08775f}.security-checklist{margin-top:24px!important;border:0;background:#0e1930!important;color:#fff}.security-checklist h3{color:#ffbe20}.security-checklist ol{padding-left:21px}.promo-tabs .promo-guide.active{color:#fff;background:#079c76;box-shadow:0 7px 17px rgba(7,156,118,.2)}@media(max-width:850px){.security-guide-page{padding:22px}.security-guide-grid{grid-template-columns:1fr}.security-guide-head{align-items:flex-start}.security-guide-head h2{font-size:17px}}
</style>
<style>
.promo-modern{--promo-action-color:var(--app-theme-color,#1958ae);--promo-action-text:var(--app-theme-text-color,#fff)}.promo-tabs .promo-tab.active,.promo-tabs .promo-broadcast-tab.active,.promo-tabs .promo-template-tab.active,.promo-tabs .promo-report-tab.active,.promo-tabs .promo-guide.active{background:var(--promo-action-color)!important;color:var(--promo-action-text)!important;box-shadow:0 7px 17px rgba(15,23,42,.18)!important}.promo-tabs .promo-tab.active i,.promo-tabs .promo-broadcast-tab.active i,.promo-tabs .promo-template-tab.active i,.promo-tabs .promo-report-tab.active i,.promo-tabs .promo-guide.active i{color:inherit!important}.promo-add-template,.use-promo-template,.promo-template-card-actions .use-promo-template{background:var(--promo-action-color)!important;color:var(--promo-action-text)!important;box-shadow:0 8px 18px rgba(15,23,42,.17)!important}.promo-add-template:hover,.use-promo-template:hover,.promo-template-card-actions .use-promo-template:hover{background:var(--promo-action-color)!important;color:var(--promo-action-text)!important;filter:brightness(.94);box-shadow:0 11px 23px rgba(15,23,42,.23)!important}
.promo-safe-page{--promo-action-color:var(--app-theme-color,#1958ae);--promo-action-text:var(--app-theme-text-color,#fff)}.promo-tabs a,.promo-tabs button,.promo-tabs .promo-guide{color:var(--promo-action-color)!important;background:#f1f4f8;background:color-mix(in srgb,var(--promo-action-color) 9%,#fff)!important}.promo-tabs a:hover,.promo-tabs button:hover{background:color-mix(in srgb,var(--promo-action-color) 15%,#fff)!important;color:var(--promo-action-color)!important}.promo-tabs .promo-broadcast-tab.active,.promo-tabs .promo-template-tab.active,.promo-tabs .promo-report-tab.active,.promo-tabs .promo-guide.active{background:var(--promo-action-color)!important;color:var(--promo-action-text)!important}.promo-safe-page{font-size:12px;line-height:1.5}.promo-safe-page button,.promo-safe-page input,.promo-safe-page select,.promo-safe-page textarea{font-family:inherit;font-size:12px;line-height:1.45}.promo-tabs a,.promo-tabs button{font-size:12px}.promo-card-head h2,.protection-head h2{font-size:15px}.target-filters label,.two-inputs label,.schedule-row label,.message-label,.variables>span,.block-title{font-size:11px}.target-filters select,.target-filters input,.target-search input,.two-inputs input,.schedule-row select,.schedule-row input{font-size:12px}.target-search,.target-summary,.target-empty,.device-status-row{font-size:12px}.template-option b,.template-option small{font-size:12px}.variables button{font-size:11px}.template-card textarea,.preview-card>div:last-child{font-size:12px}.mode-option b,.mode-option small,.block-row,.optout,.status-button{font-size:12px}.protection-head span,.preview-title{font-size:11px}.send-promo,.send-controls button,.send-controls span{font-size:12px}.promo-template-manager-card h3{font-size:14px}.promo-template-copy,.promo-template-kind,.promo-template-state,.use-promo-template,.promo-template-icon{font-size:11px}
.send-promo{position:relative;overflow:hidden;cursor:pointer;background:linear-gradient(100deg,#08a77e 0%,var(--promo-action-color) 58%,#6548df 100%)!important;box-shadow:0 10px 22px rgba(25,88,174,.22);transition:transform .18s ease,box-shadow .18s ease,filter .18s ease}.send-promo:not(:disabled):hover{transform:translateY(-2px);filter:brightness(1.05);box-shadow:0 14px 28px rgba(25,88,174,.3)}.send-promo:not(:disabled):active{transform:translateY(0);box-shadow:0 6px 14px rgba(25,88,174,.22)}.send-promo:focus-visible{outline:3px solid rgba(25,88,174,.28);outline-offset:3px}.send-promo:disabled{cursor:not-allowed;box-shadow:none;filter:saturate(.55)}.send-promo.is-sending{cursor:wait;filter:none;opacity:1}.send-promo.is-sending i{animation:promo-plane 1s ease-in-out infinite}.send-promo .send-progress{position:absolute;left:0;bottom:0;width:0;height:4px;background:rgba(255,255,255,.8);transition:width .25s ease}.promo-log{padding:0!important;overflow:hidden}.promo-log-head{display:flex;align-items:center;gap:10px;padding:12px 14px;border-bottom:1px solid rgba(255,255,255,.1)}.promo-log-head .log-dots{margin:0}.promo-log-head strong{flex:1}.promo-log-head span{padding:3px 8px;border-radius:10px;background:rgba(255,255,255,.1);font-size:10px}.queue-live{display:flex;align-items:center;gap:9px;margin:11px 14px 4px;padding:10px 12px;border-radius:9px;background:#101a34;color:#b9c8e7}.queue-live.sending{color:#7dd3fc;background:#0c2942}.queue-live.success{color:#6ee7b7;background:#073b35}.queue-live.error{color:#fda4af;background:#421524}.queue-live.pause{color:#fde68a;background:#3a2d0c}.queue-live.sending i{animation:promo-plane 1s ease-in-out infinite}.promo-log .logs{padding:7px 28px 12px}.promo-log .logs li{margin:4px 0}.promo-log .logs li[data-type="success"]{color:#6ee7b7}.promo-log .logs li[data-type="error"]{color:#fda4af}.promo-log .logs li[data-type="pause"]{color:#fde68a}@keyframes promo-plane{50%{transform:translate(4px,-3px)}}
.promo-history-stats .delivered{color:#087b61!important;background:#e4f7f1!important}.promo-history-stats .read{color:#2857c5!important;background:#e7efff!important}.promo-live-badge{display:inline-flex;align-items:center;gap:5px;margin-left:8px;padding:4px 8px;border-radius:10px;background:#e5f8f1;color:#078366;font-size:9px;vertical-align:middle}.promo-live-badge i{font-size:7px;animation:promo-live-pulse 1.4s ease-in-out infinite}.promo-history-status-cell{min-width:155px}.promo-history-status-cell small{display:block;margin-top:6px;color:#718099;font-size:9px;white-space:nowrap}.promo-history-status.read{color:#2857c5!important;background:#e7efff!important}@keyframes promo-live-pulse{50%{opacity:.3}}
</style>

<script>
(function($){
  'use strict';
  var timer = null, countdownTimer = null, running = false, maxManuallyEdited = false, sentCount = 0, failedCount = 0, targetContacts = [], activeQueue = [], queueIndex = 0, previewDefaults = {}, batchProcessed = 0, nextBatchSize = 15;
  function liveStatus(message,type,icon){$('#queue-live').removeClass('sending success error pause').addClass(type||'').html('<i class="fa '+(icon||'fa-info-circle')+'"></i><span></span>').find('span').text(message);}
  function updateSendButton(){
    var selected=selectedContacts().length,$button=$('#kirim'),processed=sentCount+failedCount,total=activeQueue.length||selected,percent=total?Math.min(100,Math.round(processed/total*100)):0;
    $button.toggleClass('is-sending',running).attr('aria-busy',running?'true':'false');
    if(running){$button.html('<i class="fa fa-paper-plane"></i> MENGIRIM '+processed+' / '+total+' KONTAK <span class="send-progress" aria-hidden="true"></span>');$button.find('.send-progress').css('width',percent+'%');}
    else{$button.html('<i class="fa fa-paper-plane"></i> MULAI KIRIM PROMOSI VIA WA (<span class="total_kontak">'+selected+'</span> KONTAK)');}
  }
  function log(message, type){ var $log=$('<li>').text(message).attr('data-type',type||'info'); $('#menu').append($log); $('.promo-log').addClass('has-logs'); $('.logs').scrollTop($('.logs')[0].scrollHeight); }
  function updateCounters(){ var processed=sentCount+failedCount,total=activeQueue.length||selectedContacts().length;$('.berhasil').text(sentCount); $('.gagal').text(failedCount); $('.total').text(processed);$('#queue-summary').text(processed+' / '+total); updateSendButton(); }
  function waitBeforeNext(delayMs,label){
    var remaining=Math.max(1,Math.round(delayMs/1000));clearInterval(countdownTimer);
    function tick(){liveStatus((label||'Jeda aman')+' '+remaining+' detik sebelum penerima berikutnya','pause','fa-clock-o');remaining--;if(remaining<0)clearInterval(countdownTimer);}
    tick();countdownTimer=setInterval(tick,1000);timer=setTimeout(function(){clearInterval(countdownTimer);countdownTimer=null;nextRecipient();},delayMs);
  }
  function randomInt(min,max){return Math.floor(Math.random()*(max-min+1))+min;}
  function safeDelayRange(){var min=Math.min(15,Math.max(5,parseInt($('#delay_min').val(),10)||5)),max=Math.min(15,Math.max(min,parseInt($('#delay').val(),10)||15));return {min:min,max:max};}
  function randomDelay(){var range=safeDelayRange();return randomInt(range.min,range.max)*1000;}
  function updateDelayLabel(){var range=safeDelayRange();$('#delay_min').val(range.min);$('#delay').val(range.max);$('#delay-range').text(range.min+' - '+range.max);}
  function clampBatchSettings(){var size=Math.min(20,Math.max(15,parseInt($('#batch_size').val(),10)||15)),pause=Math.min(90,Math.max(60,parseInt($('#batch_pause').val(),10)||60));$('#batch_size').val(size);$('#batch_pause').val(pause);}
  function hasSpintax(message){return /\{[^{}|]+\|[^{}]+\}/.test(message||'');}
  function selectedContacts(){ return $.grep(targetContacts,function(contact){return contact.selected;}); }
  function previewContact(){var selected=selectedContacts();return selected[0]||targetContacts[0]||{nama:'Budi Santoso',label:'Member Regular',poin:0,no_hp:'0812-3456-7890'};}
  function renderMessagePreview(){
    var message=$('#promo-message').val()||'',contact=previewContact(),values={nama:contact.nama||'Budi Santoso',level_member:contact.label||'Member Regular',poin:contact.poin||0,nama_toko:previewDefaults.nama_toko||previewDefaults.perusahaan||'Nama Toko',telepon_toko:previewDefaults.telepon_toko||previewDefaults.hp||'',panggilan:'Kak',perusahaan:previewDefaults.perusahaan||'Nama Toko',hp:previewDefaults.hp||'',selamat:previewDefaults.selamat||'Salam'};
    message=message.replace(/\{([^{}|]+(?:\|[^{}]+)+)\}/g,function(_,choices){return choices.split('|')[0];});
    message=message.replace(/\{([a-z_]+)\}/gi,function(full,key){return Object.prototype.hasOwnProperty.call(values,key)?values[key]:full;});
    if($('#optout').is(':checked')&&message.trim())message=message.replace(/\s+$/,'')+'\n\n_Balas STOP untuk berhenti menerima promo_';
    $('#promo-preview').text(message||'Pilih template promo untuk melihat pratinjau pesan.');
  }
  function updateTargetCounters(){
    var selected=selectedContacts().length,total=targetContacts.length;
    $('.total_kontak').text(selected);$('#selected-count').text(selected);$('#contact-count').text(total);
    $('#max_kirim').prop('disabled',total===0||running).attr('max',Math.max(total,1));
    if(!maxManuallyEdited)$('#max_kirim').val(Math.max(selected,1));
    else if(parseInt($('#max_kirim').val(),10)>selected)$('#max_kirim').val(Math.max(selected,1));
    $('#toggle-all').prop('disabled',total===0||running).html('<i class="fa fa-check-circle-o"></i> '+(selected===total&&total?'Batal Pilih Semua':'Pilih Semua'));
    renderMessagePreview();refreshButton();
  }
  function visibleContacts(){var term=$.trim($('#target-search').val()).toLowerCase();return $.grep(targetContacts,function(c){return !term||(c.nama+' '+c.no_hp+' '+c.label).toLowerCase().indexOf(term)!==-1;});}
  function renderContacts(){
    var rows=visibleContacts(),$list=$('#target-list').empty();
    if(!rows.length){$list.append($('<div class="target-empty">').text(targetContacts.length?'Tidak ada kontak yang cocok dengan pencarian.':'Tidak ada kontak yang cocok dengan level ini.'));updateTargetCounters();return;}
    $.each(rows,function(_,c){
      var $check=$('<input type="checkbox" class="target-check">').prop('checked',c.selected).attr('data-id',c.id);
      var $title=$('<div class="target-contact-title">').append($('<span class="target-contact-name">').text(c.nama||'Tanpa nama'),$('<span class="target-contact-badge">').text(c.label||'Regular'));
      var $body=$('<div class="target-contact-body">').append($title,$('<div class="target-contact-meta">').text('WA: '+c.no_hp+' • '+(c.poin||0)+' Poin'));
      $list.append($('<label class="target-contact">').toggleClass('selected',c.selected).append($check,$body));
    });
    updateTargetCounters();
  }
  function loadContacts(level){
    targetContacts=[];maxManuallyEdited=false;$('#target-search').val('').prop('disabled',true);$('#target-list').html('<div class="target-empty">Memuat daftar kontak...</div>');updateTargetCounters();
    if(!level){$('#target-list').html('<div class="target-empty">Pilih device dan level member untuk menyiapkan antrean penerima.</div>');return;}
    $('.loading-promo').loading({zIndex:1060});
    $.post(base_url+'promo/target_contacts',{level:level},null,'json').done(function(res){targetContacts=$.map(res.contacts||[],function(c){c.selected=true;return c;});$('#target-search').prop('disabled',targetContacts.length===0);renderContacts();}).fail(function(){$('#target-list').html('<div class="target-empty">Daftar kontak gagal dimuat.</div>');}).always(function(){$('.loading-promo').loading('stop');});
  }
  function refreshButton(){ var ready=$('#device_promo').val()&&$('#label').val()&&parseInt($('#text_promo').val(),10)>0&&$.trim($('#promo-message').val()).length>0&&selectedContacts().length>0; $('#kirim').prop('disabled',!ready||running); updateSendButton(); }
  function stopQueue(message){ running=false; if(timer){clearTimeout(timer);timer=null;}if(countdownTimer){clearInterval(countdownTimer);countdownTimer=null;} $('#label,#target-search,.target-check').prop('disabled',false);updateTargetCounters();updateSendButton(); if(message)log(message,'info');liveStatus('Antrean selesai: '+sentCount+' berhasil, '+failedCount+' gagal.','success','fa-check-circle');$('#queue-status').text('Pengiriman selesai'); if(sentCount&&typeof window.search_LaporanGrup==='function')window.search_LaporanGrup(undefined,true); }
  function loadDevices(){ var $select=$('#device_promo'); $.getJSON($select.data('source-promo')).done(function(rows){ $.each(rows||[],function(_,row){$select.append($('<option>').val(row.id).text(row.name));}); }); }
  function loadPreview(id){ $.post(base_url+'promo/cek_contoh',{id:id},null,'json').done(function(res){ if(res.status){previewDefaults=res.replacements||{};$('#promo-message').val(res.template||'');renderMessagePreview();} }); }
  function markSent(number,id){ return $.post(base_url+'promo/pesan_terkirim',{type:'terkirim',number:number,id:id}); }
  function markFailed(number){ return $.post(base_url+'promo/pesan_gagal',{type:'gagal',number:number}); }
  function nextRecipient(){
    if(!running)return;
    var max=parseInt($('#max_kirim').val(),10)||0,total=sentCount+failedCount;
    if((max>0&&total>=max)||queueIndex>=activeQueue.length){stopQueue('Antrean kontak terpilih selesai.');return;}
    if($('#batch_enabled').is(':checked')&&batchProcessed>=nextBatchSize){var minPause=Math.min(90,Math.max(60,parseInt($('#batch_pause').val(),10)||60)),pauseSeconds=randomInt(minPause,90);batchProcessed=0;nextBatchSize=randomInt(15,20);log('Batch selesai. Antrean dijeda '+pauseSeconds+' detik; batch berikutnya '+nextBatchSize+' kontak.','pause');waitBeforeNext(pauseSeconds*1000,'Istirahat batch');return;}
    fetchRecipient();
  }
  function fetchRecipient(){
    if(!running)return;
    var contact=activeQueue[queueIndex++];
    if(!contact){stopQueue('Antrean kontak terpilih selesai.');return;}
    sendMessage({id:contact.id,name:contact.nama,number:contact.no_hp,title:'Promo'});
  }
  function sendMessage(recipient){
    var delayMs=randomDelay();
    liveStatus('Sedang mengirim ke '+recipient.name+' ('+recipient.number+')','sending','fa-paper-plane');log('Memproses '+recipient.name+' - '+recipient.number,'info');
    $.ajax({url:base_url+'promo/kirim_pesan',type:'POST',dataType:'json',data:{jenis:'text',number:recipient.number,delay:Math.round(delayMs/1000),promo:$('#text_promo').val(),message_template:$('#promo-message').val(),schedule:$('#schedule').val(),format_pesan:$('#format_pesan').val(),device:$('#device_promo').val(),optout:$('#optout').is(':checked')?1:0}}).done(function(res){
      if(res.status){sentCount++;markSent(recipient.number,recipient.id);log('Berhasil dikirim ke '+recipient.name+' ('+recipient.number+')','success');var firstLine=$.trim((res.rendered_message||'').split(/\r?\n/)[0]);if(firstLine)log('Variasi Spintax: '+firstLine,'success');if(res.tracking&&res.tracking.active===false)log('Peringatan pelacakan status: '+(res.tracking.message||'callback Fonnte belum aktif'),'error');liveStatus('Pesan berhasil dikirim ke '+recipient.name,'success','fa-check-circle');}
      else{failedCount++;markFailed(recipient.number);log('Gagal mengirim ke '+recipient.name+': '+(res.msg||'ditolak oleh server'),'error');liveStatus('Gagal mengirim ke '+recipient.name,'error','fa-times-circle');}
      batchProcessed++;updateCounters();if(queueIndex>=activeQueue.length){stopQueue('Semua kontak dalam antrean telah diproses.');}else{log('Jeda aman '+Math.round(delayMs/1000)+' detik sebelum penerima berikutnya.','pause');waitBeforeNext(delayMs,'Jeda aman');}
    }).fail(function(){failedCount++;batchProcessed++;markFailed(recipient.number);updateCounters();log('Koneksi gagal untuk '+recipient.name+' ('+recipient.number+')','error');liveStatus('Koneksi gagal saat mengirim ke '+recipient.name,'error','fa-times-circle');if(queueIndex>=activeQueue.length)stopQueue('Semua kontak dalam antrean telah diproses.');else waitBeforeNext(delayMs,'Jeda aman');});
  }
  $(function(){
    loadDevices(); $('.schedule').hide(); updateDelayLabel();
    $('#delay_min,#delay').on('change',updateDelayLabel);$('#batch_size,#batch_pause').on('change',clampBatchSettings);clampBatchSettings();
    $('.mode-option').on('click',function(){ $('.mode-option').removeClass('active');$(this).addClass('active'); });
    $('#device_promo').on('change',function(){ var selected=!!this.value;$('#label,#delay,#format_pesan,#text_promo').prop('disabled',!selected);$('#device-status-text').text(selected?'Device dipilih, silakan cek status':'Device belum dipilih');refreshButton(); });
    $('#cek_status').on('click',function(){ var token=$('#device_promo').val();if(!token){$('#device-status-text').text('Pilih device terlebih dahulu');return;}var $btn=$(this);$btn.prop('disabled',true);$.post(base_url+'promo/cek_status',{token:token},null,'json').done(function(data){var connected=data.device_status==='connect';$btn.text(connected?'CONNECTED':'DISCONNECTED').toggleClass('connected',connected);$('#device-status-text').text(connected?'Device terhubung dan siap digunakan':'Device tidak terhubung');}).always(function(){$btn.prop('disabled',false);}); });
    $('#label').on('change',function(){loadContacts(this.value);});
    $('#max_kirim').on('input change',function(){maxManuallyEdited=true;var selected=selectedContacts().length,value=parseInt(this.value,10)||1;this.value=Math.max(1,Math.min(value,Math.max(selected,1)));});
    $('#target-search').on('input',renderContacts);
    $('#target-list').on('change','.target-check',function(){var id=String($(this).data('id')),checked=this.checked;$.each(targetContacts,function(_,c){if(String(c.id)===id)c.selected=checked;});$(this).closest('.target-contact').toggleClass('selected',checked);updateTargetCounters();});
    $('#toggle-all').on('click',function(){var rows=visibleContacts(),allSelected=rows.length&&$.grep(rows,function(c){return c.selected;}).length===rows.length;$.each(rows,function(_,c){c.selected=!allSelected;});renderContacts();});
    $('.template-option').on('click',function(){var id=$(this).data('id');$('.template-option').removeClass('active');$(this).addClass('active');$('#text_promo').val(id);loadPreview(id);refreshButton();});
    $('.variables button').on('click',function(){var field=document.getElementById('promo-message'),text=$(this).text().replace(/^\+\s*/,''),start=field.selectionStart,end=field.selectionEnd,before=field.value.substring(0,start),after=field.value.substring(end),spaceBefore=before&&!/\s$/.test(before)?' ':'',spaceAfter=after&&!/^\s/.test(after)?' ':'';field.value=before+spaceBefore+text+spaceAfter+after;var caret=(before+spaceBefore+text).length;field.focus();field.setSelectionRange(caret,caret);renderMessagePreview();refreshButton();});
    $('#promo-message').on('input',function(){renderMessagePreview();refreshButton();});
    $('#optout').on('change',renderMessagePreview);
    $('#format_pesan').on('change',function(){$('.schedule').toggle(this.value==='1');});
    $('#kirim').on('click',function(){if(running)return;if($('#format_pesan').val()==='1'&&!$('#schedule').val()){sweet('Peringatan!!!','Jadwal pengiriman belum diisi','warning','warning');return;}if(selectedContacts().length>1&&!hasSpintax($('#promo-message').val())){sweet('Spintax diperlukan','Tambahkan variasi seperti {Halo|Hai|Selamat Siang} agar pesan broadcast tidak identik.','warning','warning');return;}activeQueue=selectedContacts().slice(0,parseInt($('#max_kirim').val(),10)||selectedContacts().length);queueIndex=0;if(!activeQueue.length)return;sentCount=0;failedCount=0;batchProcessed=0;nextBatchSize=randomInt(15,20);running=true;$('#menu').empty();$('.promo-log').addClass('has-logs');$('#queue-status').text('Pengiriman sedang berjalan');liveStatus('Menyiapkan antrean '+activeQueue.length+' kontak...','sending','fa-spinner fa-spin');$(this).prop('disabled',true);updateCounters();$('#label,#target-search,#max_kirim,.target-check,#toggle-all').prop('disabled',true);log('Antrean '+activeQueue.length+' kontak dimulai dengan jeda acak 5–15 detik dan batch pertama '+nextBatchSize+' kontak.','info');nextRecipient();});
    $('.reset_promo').on('click',function(){$.post(base_url+'promo/reset_promo',{},null,'json').done(function(res){if(res.status){sweet('Sukses','Status pengiriman kontak telah direset','success','success');$('#label').trigger('change');}});});
    function openAntiBanModal(){$('#anti-ban-modal').addClass('open').attr('aria-hidden','false');$('body').addClass('anti-ban-open');$('.anti-ban-close').trigger('focus');}
    function closeAntiBanModal(){$('#anti-ban-modal').removeClass('open').attr('aria-hidden','true');$('body').removeClass('anti-ban-open');$('.promo-tip').trigger('focus');}
    $('.promo-tip').on('click',openAntiBanModal);
    $('.anti-ban-close,.anti-ban-understand').on('click',closeAntiBanModal);
    $('#anti-ban-modal').on('click',function(event){if(event.target===this)closeAntiBanModal();});
    $(document).on('keydown.antiBan',function(event){if(event.key==='Escape'&&$('#anti-ban-modal').hasClass('open'))closeAntiBanModal();});
    function showSecurityGuide(){
      $('.promo-workspace').hide().attr('aria-hidden','true');$('#promo-template-page,#promo-report-page').removeClass('open').attr('aria-hidden','true');
      $('#security-guide-page').addClass('open').attr('aria-hidden','false');
      $('.promo-broadcast-tab,.promo-template-tab,.promo-report-tab').removeClass('active');$('.promo-guide').addClass('active');
      window.scrollTo({top:$('.promo-tabs').offset().top-15,behavior:'smooth'});
    }
    function showTemplatePage(){
      $('.promo-workspace').hide().attr('aria-hidden','true');$('#security-guide-page,#promo-report-page').removeClass('open').attr('aria-hidden','true');
      $('#promo-template-page').addClass('open').attr('aria-hidden','false');
      $('.promo-broadcast-tab,.promo-guide,.promo-report-tab').removeClass('active');$('.promo-template-tab').addClass('active');
      if(window.location.hash!=='#kelola-template')history.replaceState(null,'',window.location.pathname+window.location.search+'#kelola-template');
      window.scrollTo({top:$('.promo-tabs').offset().top-15,behavior:'smooth'});
    }
    function showReportPage(){
      $('.promo-workspace').hide().attr('aria-hidden','true');$('#security-guide-page,#promo-template-page').removeClass('open').attr('aria-hidden','true');
      $('#promo-report-page').addClass('open').attr('aria-hidden','false');
      $('.promo-broadcast-tab,.promo-template-tab,.promo-guide').removeClass('active');$('.promo-report-tab').addClass('active');
      if(window.location.hash!=='#riwayat-pengiriman')history.replaceState(null,'',window.location.pathname+window.location.search+'#riwayat-pengiriman');
      if(typeof window.search_LaporanGrup==='function')window.search_LaporanGrup(undefined,true);
      window.scrollTo({top:$('.promo-tabs').offset().top-15,behavior:'smooth'});
    }
    function showBroadcastPanel(){
      $('#security-guide-page,#promo-template-page,#promo-report-page').removeClass('open').attr('aria-hidden','true');
      $('.promo-workspace').show().attr('aria-hidden','false');
      $('.promo-guide,.promo-template-tab,.promo-report-tab').removeClass('active');$('.promo-broadcast-tab').addClass('active');
      if(window.location.hash==='#kelola-template'||window.location.hash==='#riwayat-pengiriman')history.replaceState(null,'',window.location.pathname+window.location.search);
    }
    $('.promo-guide').on('click',showSecurityGuide);
    $('.promo-broadcast-tab').on('click',function(event){if($('#security-guide-page').hasClass('open')||$('#promo-template-page').hasClass('open')||$('#promo-report-page').hasClass('open')){event.preventDefault();showBroadcastPanel();}});
    $('.promo-template-tab').on('click',function(event){
      event.preventDefault();
      showTemplatePage();
    });
    $('.promo-report-tab').on('click',function(event){event.preventDefault();showReportPage();});
    $('.use-promo-template').on('click',function(){
      var id=$(this).data('id'),$option=$('.template-option[data-id="'+id+'"]');
      $('.promo-template-manager-card').removeClass('selected');$(this).closest('.promo-template-manager-card').addClass('selected');
      showBroadcastPanel();
      if($option.length){$option.trigger('click');window.scrollTo({top:$('.promo-tabs').offset().top-15,behavior:'smooth'});}
    });
    if(window.location.hash==='#kelola-template'){showTemplatePage();}
    else if(window.location.hash==='#riwayat-pengiriman'){showReportPage();}
  });
})(jQuery);
</script>
