(function(){'use strict';
const tips={sidebarToggle:'Show or hide the main application navigation',openProjectsGuide:'Open the complete Projects workflow and safety guide',openTemplateLibrary:'Browse, use, export, or manage reusable project starters',openProjectImport:'Inspect and import a portable .ppphp project package',projectsSearch:'Search project names, slugs, databases, and descriptions',projectsDatabaseFilter:'Show projects using a specific database engine',projectsHealthFilter:'Filter projects by setup and connection readiness',projectsSort:'Choose how projects are ordered',schemaImport:'Add selected live database objects to the project model',schemaCreateMissing:'Create selected blueprint-backed tables without changing existing tables',schemaRebuild:'Refresh tracked project structures from the live database',schemaRefresh:'Run the schema comparison again',historyRefresh:'Reload checkpoints and local Git status',checkpointSubmit:'Capture editable configuration and Custom Files as a recovery point',gitInitialize:'Create a local Git repository with secret and database exclusions',gitCommit:'Commit current editable project changes',testConnBtn:'Verify the database connection without saving it',saveProjectSettings:'Save project identity and appearance changes'};
Object.entries(tips).forEach(([id,title])=>{const e=document.getElementById(id);if(e)e.dataset.projectTooltip=title});
document.querySelectorAll('[data-project-view="grid"]').forEach(e=>e.dataset.projectTooltip='Show projects as visual cards');document.querySelectorAll('[data-project-view="list"]').forEach(e=>e.dataset.projectTooltip='Show projects in a compact list');document.querySelectorAll('[data-project-action="settings"]').forEach(e=>e.dataset.projectTooltip='Edit project identity, database, archive, or deletion settings');document.querySelectorAll('.project-pin').forEach(e=>e.dataset.projectTooltip=e.title||'Pin or unpin this project');document.querySelectorAll('.project-menu-toggle').forEach(e=>e.dataset.projectTooltip='Open all project actions');document.querySelectorAll('[data-edit-database]').forEach(e=>{if(!e.dataset.projectTooltip)e.dataset.projectTooltip='Edit, test, or switch this project database connection'});
let controllerTip=null;
function hideControllerTip(){controllerTip?.remove();controllerTip=null}
function initControllerTip(e){if(e.dataset.projectControllerTip)return;e.dataset.projectControllerTip='1';const show=()=>{hideControllerTip();const tip=document.createElement('div');tip.className='tooltip projects-tooltip project-controller-tooltip show';tip.setAttribute('role','tooltip');const inner=document.createElement('div');inner.className='tooltip-inner';inner.textContent=e.dataset.projectTooltip;tip.append(inner);document.body.append(tip);const r=e.getBoundingClientRect(),t=tip.getBoundingClientRect(),half=t.width/2+8;tip.style.left=Math.max(half,Math.min(window.innerWidth-half,r.left+r.width/2))+'px';tip.style.top=(r.bottom+8)+'px';controllerTip=tip};e.addEventListener('mouseenter',show);e.addEventListener('focus',show);e.addEventListener('mouseleave',hideControllerTip);e.addEventListener('blur',hideControllerTip);e.addEventListener('click',hideControllerTip)}
function initTips(root=document){root.querySelectorAll('button[title],a[title],button[aria-label],a[aria-label]').forEach(e=>{if(!e.dataset.projectTooltip)e.dataset.projectTooltip=e.getAttribute('title')||e.getAttribute('aria-label');e.removeAttribute('title')});root.querySelectorAll('[data-project-tooltip]').forEach(e=>{if(e.hasAttribute('data-bs-toggle')){initControllerTip(e);return}if(bootstrap.Tooltip.getInstance(e))return;bootstrap.Tooltip.getOrCreateInstance(e,{title:e.dataset.projectTooltip,trigger:'hover focus',container:'body',customClass:'projects-tooltip',delay:{show:250,hide:60}})})}initTips();window.addEventListener('resize',hideControllerTip);document.addEventListener('shown.bs.modal',e=>initTips(e.target));document.addEventListener('hide.bs.modal',()=>{hideControllerTip();document.querySelectorAll('[data-project-tooltip]').forEach(e=>bootstrap.Tooltip.getInstance(e)?.hide())});
new MutationObserver(records=>records.forEach(record=>record.addedNodes.forEach(node=>{if(node.nodeType===1)initTips(node)}))).observe(document.body,{childList:true,subtree:true});
const guideEl=document.getElementById('projectsGuideModal'),guideSearch=document.getElementById('projectsGuideSearch');function selectTopic(topic){document.querySelectorAll('[data-guide-topic]').forEach(b=>{const active=b.dataset.guideTopic===topic;b.classList.toggle('active',active);b.setAttribute('aria-selected',String(active))});document.querySelectorAll('[data-guide-panel]').forEach(p=>p.classList.toggle('active',p.dataset.guidePanel===topic))}document.getElementById('openProjectsGuide')?.addEventListener('click',()=>bootstrap.Modal.getOrCreateInstance(guideEl).show());document.querySelectorAll('[data-guide-topic]').forEach(b=>b.addEventListener('click',()=>{guideSearch.value='';document.getElementById('projectsGuideNoResults').classList.remove('show');selectTopic(b.dataset.guideTopic)}));guideSearch?.addEventListener('input',()=>{const q=guideSearch.value.trim().toLowerCase(),panels=Array.from(document.querySelectorAll('[data-guide-panel]'));if(!q){selectTopic(document.querySelector('[data-guide-topic].active')?.dataset.guideTopic||'start');document.getElementById('projectsGuideNoResults').classList.remove('show');return}const match=panels.find(p=>(p.dataset.guideSearchable+' '+p.textContent).toLowerCase().includes(q));panels.forEach(p=>p.classList.toggle('active',p===match));document.querySelectorAll('[data-guide-topic]').forEach(b=>b.classList.toggle('active',!!match&&b.dataset.guideTopic===match.dataset.guidePanel));document.getElementById('projectsGuideNoResults').classList.toggle('show',!match)});
guideEl?.addEventListener('shown.bs.modal',()=>{if(window.matchMedia('(min-width:768px)').matches)guideSearch?.focus()});document.addEventListener('keydown',e=>{if(e.key==='/'&&!e.metaKey&&!e.ctrlKey&&!e.altKey){const tag=document.activeElement?.tagName;if(['INPUT','TEXTAREA','SELECT'].includes(tag))return;e.preventDefault();if(guideEl?.classList.contains('show'))guideSearch?.focus();else document.getElementById('projectsSearch')?.focus()}});
document.querySelectorAll('[role="tablist"]').forEach(list=>list.addEventListener('keydown',e=>{if(!['ArrowLeft','ArrowRight'].includes(e.key))return;const tabs=Array.from(list.querySelectorAll('[role="tab"]'));const i=tabs.indexOf(document.activeElement);if(i<0)return;e.preventDefault();tabs[(i+(e.key==='ArrowRight'?1:-1)+tabs.length)%tabs.length].focus()}));
})();

/* Clickable KPI tiles — each stat filters the collection by reusing the existing
   tab buttons + health <select> (no existing behaviour is modified). Purely
   additive: if any target is missing it silently does nothing. */
(function(){'use strict';
    var coll=document.getElementById('projectsCollection'); if(!coll) return;
    var health=document.getElementById('projectsHealthFilter');
    var MAP={active:['active',''],pinned:['pinned',''],all:['all',''],ready:['active','ready']};
    var LABEL={active:'Show your active projects',pinned:'Show pinned projects',ready:'Show projects ready to continue',all:'Show every project in your catalog'};
    function go(tab,healthVal){
        if(health){ health.value=healthVal||''; health.dispatchEvent(new Event('change',{bubbles:true})); }
        var b=document.querySelector('[data-project-tab="'+tab+'"]'); if(b) b.click();
        coll.scrollIntoView({behavior:'smooth',block:'nearest'});
    }
    document.querySelectorAll('.project-metric').forEach(function(tile){
        var strong=tile.querySelector('[data-project-metric]'); if(!strong) return;
        var key=strong.getAttribute('data-project-metric'), m=MAP[key]; if(!m) return;
        tile.classList.add('is-actionable');
        tile.setAttribute('role','button');
        tile.setAttribute('tabindex','0');
        tile.setAttribute('aria-label',LABEL[key]||('Filter by '+key));
        tile.addEventListener('click',function(){ go(m[0],m[1]); });
        tile.addEventListener('keydown',function(e){ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); go(m[0],m[1]); } });
    });
})();

/* Row-density toggle — comfortable / compact. Toggles a class on the collection
   and remembers the choice. Exposes window.__ppSetDensity for saved views. */
(function(){'use strict';
    var coll=document.getElementById('projectsCollection'); if(!coll) return;
    var KEY='ppphpProjectsDensity', btns=document.querySelectorAll('[data-project-density]');
    if(!btns.length) return;
    function set(mode,persist){
        mode = mode==='compact' ? 'compact' : 'comfortable';
        coll.classList.toggle('density-compact', mode==='compact');
        btns.forEach(function(b){ var on=b.dataset.projectDensity===mode; b.classList.toggle('active',on); b.setAttribute('aria-pressed',String(on)); });
        if(persist!==false){ try{ localStorage.setItem(KEY,mode); }catch(e){} }
    }
    btns.forEach(function(b){ b.addEventListener('click',function(){ set(b.dataset.projectDensity,true); }); });
    var saved=null; try{ saved=localStorage.getItem(KEY); }catch(e){}
    if(saved) set(saved,false);
    window.__ppSetDensity=set;
})();

/* Saved views — capture the current search + filters + sort + tab + layout +
   density and recall them in one click. Stored per-browser in localStorage.
   Reuses the existing controls (fires their events) — no filter logic here. */
(function(){'use strict';
    var chips=document.getElementById('projectsViewChips'),
        saveBtn=document.getElementById('projectsSaveView'),
        empty=document.getElementById('projectsViewEmpty'),
        coll=document.getElementById('projectsCollection');
    if(!chips||!saveBtn||!coll) return;
    var KEY='ppphpProjectsSavedViews', $=function(id){return document.getElementById(id);};
    function load(){ try{ return JSON.parse(localStorage.getItem(KEY))||[]; }catch(e){ return []; } }
    function store(v){ try{ localStorage.setItem(KEY,JSON.stringify(v)); }catch(e){} }
    function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
    function activeAttr(sel,attr){ var e=document.querySelector(sel+'.active'); return e?e.getAttribute(attr):null; }
    function fire(el,type){ if(el) el.dispatchEvent(new Event(type,{bubbles:true})); }
    function capture(){
        return {
            search:($('projectsSearch')||{}).value||'',
            database:($('projectsDatabaseFilter')||{}).value||'',
            health:($('projectsHealthFilter')||{}).value||'',
            sort:($('projectsSort')||{}).value||'activity',
            tab:activeAttr('[data-project-tab]','data-project-tab')||'active',
            view:activeAttr('[data-project-view]','data-project-view')||'grid',
            density:coll.classList.contains('density-compact')?'compact':'comfortable'
        };
    }
    function apply(s){
        if($('projectsSearch')){ $('projectsSearch').value=s.search||''; fire($('projectsSearch'),'input'); }
        if($('projectsDatabaseFilter')){ $('projectsDatabaseFilter').value=s.database||''; fire($('projectsDatabaseFilter'),'change'); }
        if($('projectsHealthFilter')){ $('projectsHealthFilter').value=s.health||''; fire($('projectsHealthFilter'),'change'); }
        if($('projectsSort')){ $('projectsSort').value=s.sort||'activity'; fire($('projectsSort'),'change'); }
        var tabBtn=document.querySelector('[data-project-tab="'+(s.tab||'active')+'"]'); if(tabBtn) tabBtn.click();
        var viewBtn=document.querySelector('[data-project-view="'+(s.view||'grid')+'"]'); if(viewBtn) viewBtn.click();
        if(window.__ppSetDensity) window.__ppSetDensity(s.density||'comfortable',true);
        else coll.classList.toggle('density-compact', s.density==='compact');
    }
    function summary(s){
        var p=[]; if(s.tab&&s.tab!=='active')p.push(s.tab); if(s.search)p.push('“'+s.search+'”');
        if(s.database)p.push(s.database); if(s.health)p.push(s.health); if(s.view==='list')p.push('list');
        return p.length?p.join(' · '):'active projects';
    }
    function render(){
        var views=load();
        chips.innerHTML=views.map(function(v){
            return '<span class="pv-chip" role="listitem" tabindex="0" data-id="'+esc(v.id)+'" title="'+esc(summary(v.state))+'">'
                +'<i class="bi bi-bookmark-fill"></i>'+esc(v.name)
                +'<button type="button" class="pv-del" aria-label="Delete view '+esc(v.name)+'" title="Delete view">×</button></span>';
        }).join('');
        if(empty) empty.style.display=views.length?'none':'';
    }
    chips.addEventListener('click',function(e){
        var chip=e.target.closest('.pv-chip'); if(!chip) return;
        var id=chip.getAttribute('data-id'), views=load(), v=views.find(function(x){return x.id===id;}); if(!v) return;
        if(e.target.closest('.pv-del')){ store(views.filter(function(x){return x.id!==id;})); render(); return; }
        apply(v.state);
        chips.querySelectorAll('.pv-chip').forEach(function(c){ c.classList.toggle('is-active',c===chip); });
    });
    chips.addEventListener('keydown',function(e){ if((e.key==='Enter'||e.key===' ')&&e.target.classList&&e.target.classList.contains('pv-chip')){ e.preventDefault(); e.target.click(); } });
    saveBtn.addEventListener('click',function(){
        var state=capture();
        function doSave(name){ name=(name||'').trim(); if(!name) return; var views=load(); views.push({id:'v'+Date.now().toString(36),name:name.slice(0,32),state:state}); store(views); render(); }
        if(window.Swal){
            Swal.fire({title:'Save this view',input:'text',inputLabel:'Name it so you can jump back later',inputPlaceholder:'e.g. Ready MySQL apps',
                inputAttributes:{maxlength:32,'aria-label':'View name'},showCancelButton:true,confirmButtonText:'Save view',
                customClass:{popup:'projects-swal'},inputValidator:function(val){ if(!val||!val.trim()) return 'Give the view a name.'; }})
                .then(function(r){ if(r.isConfirmed) doSave(r.value); });
        } else { doSave(window.prompt('Name this view:')); }
    });
    render();
})();
