<?php
 
 
$popMode   = $spot['pop_mode'] ?? 'url';
$popUrl    = $spot['popunder_url'] ?? '';
$popDelay  = (int) ($spot['pop_delay'] ?? 0);
$popCap    = (int) ($spot['pop_cap'] ?? 1);
$popWindow = (int) ($spot['pop_window'] ?? 24);
$isDelayPreset = in_array($popDelay, [0, 5, 20, 60, 90], true);
$isCapPreset   = in_array($popCap, [1, 2, 3, 5, 10], true);
$isPlayerPopunder = ($zone['slug'] ?? '') === 'player_popunder';
$popTrigger = $spot['pop_trigger'] ?? 'player_click';
$popTriggers = array_map('trim', explode(',', $popTrigger));
?>
<input type="hidden" name="ad_type" value="code">


<p class="text-sm font-medium text-gray-700 mb-2">What opens behind the visitor's tab?</p>
<div class="grid grid-cols-2 gap-3">
    <label class="ad-type-card relative flex flex-col items-center p-4 border-2 rounded-xl cursor-pointer transition-all hover:border-primary-300">
        <input type="radio" name="pop_mode" value="url" class="sr-only" <?= $popMode === 'url' ? 'checked' : '' ?> onchange="updatePopMode()">
        <svg class="w-6 h-6 mb-1.5 text-blue-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5"/></svg>
        <span class="text-xs font-semibold text-gray-800">Open a web address</span>
        <span class="text-[10px] text-gray-400 mt-0.5 text-center">Recommended &mdash; your offer link</span>
    </label>
    <label class="ad-type-card relative flex flex-col items-center p-4 border-2 rounded-xl cursor-pointer transition-all hover:border-primary-300">
        <input type="radio" name="pop_mode" value="code" class="sr-only" <?= $popMode === 'code' ? 'checked' : '' ?> onchange="updatePopMode()">
        <svg class="w-6 h-6 mb-1.5 text-purple-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
        <span class="text-xs font-semibold text-gray-800">Ad-network code</span>
        <span class="text-[10px] text-gray-400 mt-0.5 text-center">Advanced &mdash; paste a network tag</span>
    </label>
</div>
<div id="popUrlField" class="<?= $popMode !== 'url' ? 'hidden' : '' ?>">
    <label class="block text-sm font-medium text-gray-700 mb-1">Web address to open</label>
    <input type="text" name="popunder_url" value="<?= htmlspecialchars($popUrl) ?>" placeholder="https://advertiser.com/landing-page" class="<?= $ic ?>">
    <p class="mt-1.5 text-[11px] text-gray-400">Opens behind the current tab when a visitor clicks. You control the timing &amp; frequency below.</p>
</div>
<div id="popCodeField" class="<?= $popMode !== 'code' ? 'hidden' : '' ?>">
    <label class="block text-sm font-medium text-gray-700 mb-1">Ad-network popunder code</label>
    <textarea name="ad_code" rows="5" placeholder="Paste your network's popunder script here..." class="<?= $ic ?> font-mono text-xs"><?= htmlspecialchars($adCode) ?></textarea>
    <p class="mt-1.5 text-[11px] text-gray-400">Advanced &mdash; runs after the delay below, then the network controls its own behavior. Most operators should use a web address.</p>
</div>

<?php if ($isPlayerPopunder): ?>

<div class="pt-4 mt-2 border-t border-gray-100">
    <p class="text-sm font-medium text-gray-700 mb-1">What triggers it?</p>
    <p class="text-[11px] text-gray-400 mb-3">Tick one or more player actions &mdash; the popunder opens behind the current tab when any of them happens.</p>
    <div class="grid grid-cols-3 gap-3">
        <?php foreach ([['player_click', 'Player click', 'When the viewer clicks the player'], ['player_pause', 'On pause', 'When the viewer pauses the video'], ['player_play', 'On play', 'When the viewer starts or resumes']] as $tg): ?>
        <label class="ad-type-card relative flex flex-col items-center p-3 border-2 rounded-xl cursor-pointer transition-all hover:border-primary-300">
            <input type="checkbox" name="pop_trigger[]" value="<?= $tg[0] ?>" class="sr-only" <?= in_array($tg[0], $popTriggers, true) ? 'checked' : '' ?>>
            <span class="text-xs font-semibold text-gray-800"><?= $tg[1] ?></span>
            <span class="text-[10px] text-gray-400 mt-0.5 text-center"><?= $tg[2] ?></span>
        </label>
        <?php endforeach; ?>
    </div>
</div>
<?php else: ?>

<div class="pt-4 mt-2 border-t border-gray-100">
    <p class="text-sm font-medium text-gray-700 mb-1">When does it start?</p>
    <p class="text-[11px] text-gray-400 mb-3">Once a visitor has been on the page this long, the popunder is ready &mdash; it opens the next time they click anywhere. &ldquo;Instant&rdquo; means their first click.</p>
    <div class="flex flex-wrap items-center gap-2" id="delayChips">
        <?php foreach ([[0, 'Instant'], [5, '5 sec'], [20, '20 sec'], [60, '1 min'], [90, '1 min 30']] as $dp): ?>
        <button type="button" class="pop-chip px-3 py-1.5 rounded-lg border text-xs font-medium" data-delay="<?= $dp[0] ?>"><?= $dp[1] ?></button>
        <?php endforeach; ?>
        <button type="button" class="pop-chip px-3 py-1.5 rounded-lg border text-xs font-medium" data-delay="custom">Custom&hellip;</button>
    </div>
    <div id="delayCustomWrap" class="<?= $isDelayPreset ? 'hidden' : '' ?> mt-3 flex items-center gap-2">
        <input type="number" name="pop_delay" min="0" max="3600" step="1" value="<?= $popDelay ?>" class="<?= $ic ?> max-w-[150px]">
        <span class="text-sm text-gray-500">seconds after page load</span>
    </div>
    <input type="hidden" name="pop_delay_preset" id="popDelayPreset" value="<?= $isDelayPreset ? $popDelay : 'custom' ?>">
</div>
<?php endif; ?>


<div class="pt-4 mt-2 border-t border-gray-100">
    <p class="text-sm font-medium text-gray-700 mb-3">How many times can it open?</p>
    <div class="flex flex-wrap items-center gap-2">
        <select name="pop_cap_preset" id="popCapPreset" class="<?= $ic ?> max-w-[150px]" onchange="updatePopCap()">
            <?php foreach ([1 => 'Once', 2 => 'Twice', 3 => '3 times', 5 => '5 times', 10 => '10 times'] as $cv => $clbl): ?>
            <option value="<?= $cv ?>" <?= ($isCapPreset && $popCap === $cv) ? 'selected' : '' ?>><?= $clbl ?></option>
            <?php endforeach; ?>
            <option value="0" <?= $popCap === 0 ? 'selected' : '' ?>>Unlimited</option>
            <option value="custom" <?= (!$isCapPreset && $popCap !== 0) ? 'selected' : '' ?>>Custom&hellip;</option>
        </select>
        <span class="text-sm text-gray-500">per</span>
        <select name="pop_window" id="popWindow" class="<?= $ic ?> max-w-[160px]" onchange="updatePopSentence()">
            <option value="0"   <?= $popWindow === 0   ? 'selected' : '' ?>>browser session</option>
            <option value="1"   <?= $popWindow === 1   ? 'selected' : '' ?>>hour</option>
            <option value="24"  <?= $popWindow === 24  ? 'selected' : '' ?>>day</option>
            <option value="168" <?= $popWindow === 168 ? 'selected' : '' ?>>week</option>
            <option value="720" <?= $popWindow === 720 ? 'selected' : '' ?>>30 days</option>
        </select>
        <span class="text-sm text-gray-500">per visitor</span>
    </div>
    <div id="capCustomWrap" class="<?= ($isCapPreset || $popCap === 0) ? 'hidden' : '' ?> mt-3 flex items-center gap-2">
        <input type="number" name="pop_cap" min="0" max="50" step="1" value="<?= $popCap ?>" class="<?= $ic ?> max-w-[150px]">
        <span class="text-sm text-gray-500">times</span>
    </div>
    <p id="popSentence" class="mt-3 text-xs text-gray-500"></p>
    <p id="popWarn" class="mt-2 text-xs text-amber-600 hidden">That's a lot of pops &mdash; visitors may leave. Most sites use 1&ndash;2 per day.</p>
</div>

<style>
.pop-chip { border-color:#e5e7eb; background:#fff; color:#374151; }
.pop-chip.is-active { border-color: var(--primary,#6366f1); background:#f5f3ff; color: var(--primary,#6366f1); }
</style>
<script>
function updatePopMode(){
  var m=(document.querySelector('input[name="pop_mode"]:checked')||{}).value||'url';
  var u=document.getElementById('popUrlField'), c=document.getElementById('popCodeField');
  if(u) u.classList.toggle('hidden', m!=='url');
  if(c) c.classList.toggle('hidden', m!=='code');
}
function setDelayChip(val){
  var hid=document.getElementById('popDelayPreset'), wrap=document.getElementById('delayCustomWrap');
  var chips=document.querySelectorAll('#delayChips .pop-chip');
  for(var i=0;i<chips.length;i++){ chips[i].classList.toggle('is-active', chips[i].getAttribute('data-delay')===String(val)); }
  if(hid) hid.value=val;
  if(wrap) wrap.classList.toggle('hidden', val!=='custom');
}
function updatePopCap(){
  var sel=document.getElementById('popCapPreset'), wrap=document.getElementById('capCustomWrap');
  if(wrap) wrap.classList.toggle('hidden', sel.value!=='custom');
  updatePopSentence();
}
function updatePopSentence(){
  var capSel=document.getElementById('popCapPreset'); if(!capSel) return;
  var cap = capSel.value==='custom'
     ? parseInt((document.querySelector('input[name="pop_cap"]')||{}).value||'0',10)
     : parseInt(capSel.value,10);
  var winSel=document.getElementById('popWindow');
  var winTxt = winSel.options[winSel.selectedIndex].text;
  var s=document.getElementById('popSentence'), warn=document.getElementById('popWarn');
  if(!cap){ if(s) s.textContent='Each visitor can open this popunder an unlimited number of times (safety-limited).'; }
  else if(s){ s.textContent='Each visitor opens this popunder at most '+cap+' time'+(cap===1?'':'s')+' per '+winTxt+'.'; }
  if(warn) warn.classList.toggle('hidden', !(cap>=5 && (winSel.value==='1' || winSel.value==='0')));
}
(function(){
  var hid=document.getElementById('popDelayPreset');
  if(hid){ setDelayChip(hid.value); }
  var chips=document.querySelectorAll('#delayChips .pop-chip');
  for(var i=0;i<chips.length;i++){ (function(b){ b.addEventListener('click', function(){ setDelayChip(b.getAttribute('data-delay')); }); })(chips[i]); }
  var capCustom=document.querySelector('input[name="pop_cap"]');
  if(capCustom){ capCustom.addEventListener('input', updatePopSentence); }
  if(document.getElementById('popCapPreset')){ updatePopCap(); }
  if(document.querySelector('input[name="pop_mode"]')){ updatePopMode(); }
})();
</script>
