<?php if (!defined('TP_TOK_PICKER')): define('TP_TOK_PICKER', 1); ?>
<style>
.tok{position:relative}
.tok__wrap{display:flex;flex-wrap:wrap;gap:6px;padding:8px 10px;border:1px solid #d1d5db;border-radius:8px;min-height:42px;cursor:text;transition:border-color .15s,box-shadow .15s;background:#fff;align-items:center}
.tok__tags{display:flex;flex-wrap:wrap;gap:6px}
.tok__wrap:focus-within{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.15)}
.tok__tag{display:inline-flex;align-items:center;gap:4px;padding:3px 8px 3px 10px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:600;border-radius:6px;white-space:nowrap;line-height:1.4}
.tok__tag button{display:flex;align-items:center;justify-content:center;width:16px;height:16px;border:none;background:none;color:#3b82f6;font-size:16px;cursor:pointer;padding:0;border-radius:50%;line-height:1}
.tok__tag button:hover{background:#dbeafe;color:#1e40af}
.tok__input{flex:1;min-width:100px;border:none;outline:none;font-size:13px;padding:2px 0;background:transparent;color:#1f2937}
.tok__input::placeholder{color:#9ca3af}
.tok__drop{display:none;position:absolute;top:100%;left:0;right:0;margin-top:4px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.12);max-height:200px;overflow-y:auto;z-index:60}
.tok__drop.open{display:block}
.tok__opt{padding:8px 12px;font-size:13px;cursor:pointer;color:#374151;transition:background .1s}
.tok__opt:hover,.tok__opt.hl{background:#eff6ff;color:#1d4ed8}
.tok__opt:first-child{border-radius:8px 8px 0 0}
.tok__opt:last-child{border-radius:0 0 8px 8px}
.tok__empty{padding:8px 12px;font-size:12px;color:#9ca3af;font-style:italic}
</style>
<script>
(function(){
    if(window.tpTokInit)return;
    function initOne(el){
        if(el.__tok)return;
        el.__tok=true;
        var name=el.dataset.name;
        var items=JSON.parse(el.dataset.items);
        var selected=new Set(JSON.parse(el.dataset.selected).map(String));
        var wrap=el.querySelector('.tok__wrap');
        var tagsDiv=el.querySelector('.tok__tags');
        var input=el.querySelector('.tok__input');
        var drop=el.querySelector('.tok__drop');
        var hlIdx=-1;

        function render(){
            tagsDiv.innerHTML='';
            el.querySelectorAll('input[type=hidden]').forEach(function(h){h.remove();});
            items.forEach(function(item){
                if(!selected.has(String(item.id)))return;
                var span=document.createElement('span');
                span.className='tok__tag';
                span.innerHTML=esc(item.n)+'<button type="button">&times;</button>';
                span.querySelector('button').addEventListener('click',function(e){
                    e.stopPropagation();
                    selected.delete(String(item.id));
                    render();
                    input.focus();
                });
                tagsDiv.appendChild(span);
                var h=document.createElement('input');
                h.type='hidden';h.name=name;h.value=item.id;
                el.appendChild(h);
            });
        }

        function showDrop(filter){
            var f=filter.toLowerCase();
            var filtered=items.filter(function(i){return !selected.has(String(i.id))&&i.n.toLowerCase().indexOf(f)!==-1;});
            drop.innerHTML='';
            hlIdx=-1;
            if(!f||filtered.length===0){
                if(f&&filtered.length===0){
                    drop.innerHTML='<div class="tok__empty">No results</div>';
                    drop.classList.add('open');
                }else{drop.classList.remove('open');}
                return;
            }
            filtered.slice(0,12).forEach(function(item,idx){
                var d=document.createElement('div');
                d.className='tok__opt';
                d.textContent=item.n;
                d.addEventListener('mousedown',function(e){
                    e.preventDefault();
                    selected.add(String(item.id));
                    input.value='';
                    drop.classList.remove('open');
                    render();
                    input.focus();
                });
                drop.appendChild(d);
            });
            drop.classList.add('open');
        }

        input.addEventListener('input',function(){showDrop(input.value);});
        input.addEventListener('focus',function(){if(input.value)showDrop(input.value);});
        input.addEventListener('blur',function(){setTimeout(function(){drop.classList.remove('open');},150);});
        input.addEventListener('keydown',function(e){
            var opts=drop.querySelectorAll('.tok__opt');
            if(e.key==='ArrowDown'){e.preventDefault();hlIdx=Math.min(hlIdx+1,opts.length-1);updHl(opts);}
            else if(e.key==='ArrowUp'){e.preventDefault();hlIdx=Math.max(hlIdx-1,0);updHl(opts);}
            else if(e.key==='Enter'&&hlIdx>=0&&opts[hlIdx]){e.preventDefault();opts[hlIdx].dispatchEvent(new MouseEvent('mousedown'));}
            else if(e.key==='Backspace'&&input.value===''&&selected.size>0){
                var last=Array.from(selected).pop();
                selected.delete(last);
                render();
            }
        });

        wrap.addEventListener('click',function(){input.focus();});

        function updHl(opts){opts.forEach(function(o,i){o.classList.toggle('hl',i===hlIdx);});}
        function esc(s){var d=document.createElement('div');d.textContent=s;return d.innerHTML;}

        render();
    }
    function init(){document.querySelectorAll('.tok').forEach(initOne);}
    window.tpTokInit=init;
    if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',init);}else{init();}
})();
</script>
<?php endif; ?>
