
(function(){
"use strict";
var SESSION_TIMEOUT=1800000,WARNING_BEFORE=300000;
var warningTimer,logoutTimer;
function resetTimers(){
    clearTimeout(warningTimer);clearTimeout(logoutTimer);
    warningTimer=setTimeout(showWarning,SESSION_TIMEOUT-WARNING_BEFORE);
    logoutTimer=setTimeout(doLogout,SESSION_TIMEOUT);
}
function showWarning(){
    var d=document.getElementById("session-warning");
    if(!d){d=document.createElement("div");d.id="session-warning";d.innerHTML="Session expiring. <a href='#' onclick='SessionGuard.ping();return false;'>Stay logged in</a>";d.style.cssText="position:fixed;top:0;left:0;right:0;background:rgba(255,213,79,.15);color:#eab308;text-align:center;padding:8px;font-size:12px;font-weight:700;z-index:10000";document.body.appendChild(d);}
}
function doLogout(){window.location.href="logout.php";}
function ping(){
    fetch("api/system/heartbeat.php",{method:"POST",credentials:"same-origin"}).then(function(r){return r.json();}).then(function(d){if(d.active){var w=document.getElementById("session-warning");if(w)w.remove();resetTimers();}else{doLogout();}});
}
document.addEventListener("mousemove",resetTimers);document.addEventListener("keydown",resetTimers);document.addEventListener("click",resetTimers);
window.SessionGuard={ping:ping,reset:resetTimers};resetTimers();
})();

document.addEventListener("DOMContentLoaded",function(){
"use strict";
document.querySelectorAll(".nav-link[href]").forEach(function(link){
    link.addEventListener("click",function(){
        document.querySelectorAll(".nav-link").forEach(function(l){l.classList.remove("active");});
        this.classList.add("active");
    });
});
var params = new URLSearchParams(window.location.search);
var view = params.get("view") || params.get("tab") || "overview";
document.querySelectorAll(".nav-link[data-tab]").forEach(function(l){
    if(l.dataset.tab === view) l.classList.add("active");
    else l.classList.remove("active");
});
window.TabNav={load:function(tabId){ window.location.href="index.php?view="+encodeURIComponent(tabId); }};
});


window.dashFetch=function(action,data){
"use strict";
var csrf=document.querySelector("meta[name='csrf-token']");
var fd=new FormData();fd.append("system_action",action);fd.append("_csrf",csrf?csrf.content:"");
if(data){Object.keys(data).forEach(function(k){fd.append("data["+k+"]",data[k]);});}
return fetch("index.php",{method:"POST",body:fd,credentials:"same-origin"}).then(function(r){return r.json();}).then(function(j){if(j._csrf&&csrf)csrf.content=j._csrf;return j;});
};

window.getCSRF=function(){var m=document.querySelector('meta[name="csrf-token"]');return m?m.content:'';};
window.timeAgo=function(dt){if(!dt)return '';var d=new Date(dt),n=Date.now(),s=Math.floor((n-d.getTime())/1000);if(s<60)return s+'s ago';if(s<3600)return Math.floor(s/60)+'m ago';if(s<86400)return Math.floor(s/3600)+'h ago';return Math.floor(s/86400)+'d ago';};

window.Systems={
notify:function(msg,type){
    type=type||"info";
    var el=document.createElement("div"),bg,c;
    if(type==="success"){bg="rgba(34,197,94,.15)";c="#22c55e";}
    else if(type==="error"){bg="rgba(239,68,68,.15)";c="#ef4444";}
    else if(type==="warning"){bg="rgba(255,213,79,.15)";c="#eab308";}
    else{bg="rgba(96,165,250,.15)";c="#60a5fa";}
    el.style.cssText="position:fixed;top:16px;right:16px;padding:12px 16px;border-radius:10px;font-size:13px;font-weight:600;z-index:10001;background:"+bg+";color:"+c+";border:1px solid "+bg.replace(")",",.2)")+";animation:fadeIn .3s ease;";
    el.textContent=msg;document.body.appendChild(el);
    setTimeout(function(){el.style.opacity="0";el.style.transition="opacity .3s";setTimeout(function(){if(el.parentNode)el.parentNode.removeChild(el);},300);},4000);
},
confirm:function(msg,onOk,onCancel){
    var o=document.createElement("div");
    o.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:10000;display:flex;align-items:center;justify-content:center;";
    var b=document.createElement("div");
    b.style.cssText="background:#10121a;border:1px solid rgba(255,255,255,.05);border-radius:14px;padding:24px;max-width:400px;width:90%;";
    b.innerHTML="<p style='margin-bottom:16px;color:#e8ecf4'>"+(msg||"Are you sure?")+"</p><div style='display:flex;gap:8px;justify-content:flex-end'><button class='btn btn-sm' id='sc' style='background:rgba(255,255,255,.06);color:#c8ccd4;border:1px solid rgba(255,255,255,.1);padding:6px 12px;border-radius:6px;cursor:pointer'>Cancel</button><button class='btn btn-sm' id='so' style='background:rgba(255,82,82,.15);color:#ff5252;border:1px solid rgba(255,82,82,.2);padding:6px 12px;border-radius:6px;cursor:pointer'>Confirm</button></div>";
    o.appendChild(b);document.body.appendChild(o);
    document.getElementById("so").onclick=function(){document.body.removeChild(o);if(onOk)onOk();};
    document.getElementById("sc").onclick=function(){document.body.removeChild(o);if(onCancel)onCancel();};
}
};

var InlineEdit=(function(){
"use strict";
var API="api/inline-edit.php";
var csrf=document.querySelector("meta[name='csrf-token']")?document.querySelector("meta[name='csrf-token']").content:"";
var modal,overlay,cur={t:null,i:null,f:null,e:null};
function init(){
    if(document.getElementById("ie-modal"))return;
    var s=document.createElement("style");s.textContent="[data-editable]::after{content:'\u270E';position:absolute;right:4px;top:50%;transform:translateY(-50%);font-size:10px;color:#e6a817;opacity:0}[data-editable]:hover::after{opacity:1}";
    document.head.appendChild(s);
    overlay=document.createElement("div");overlay.className="ie-overlay";
    overlay.addEventListener("click",function(){close();});
    modal=document.createElement("div");modal.className="ie-modal";
    modal.innerHTML="<div class='ie-header'><h3 id='ie-title'>Edit</h3><button class='ie-close' onclick='InlineEdit.close()'>&times;</button></div><div class='ie-body' id='ie-body'></div><div class='ie-footer'><button class='ie-btn ie-btn-secondary' onclick='InlineEdit.close()'>Cancel</button><button class='ie-btn ie-btn-primary' onclick='InlineEdit.save()'>Save</button></div>";
    document.body.appendChild(overlay);document.body.appendChild(modal);
}
function bind(c){
    c=c||document;
    c.querySelectorAll("[data-editable]").forEach(function(el){el.addEventListener("click",onclick);});
}
function onclick(ev){
    ev.preventDefault();
    var el=ev.currentTarget,t=el.dataset.table||"",id=el.dataset.id||"",f=el.dataset.field,v=el.dataset.value||el.textContent.trim();
    if(!t||!id||!f)return;
    open(t,id,f,el,v);
}
function open(t,id,f,el,v){
    cur={t:t,i:id,f:f,e:el};
    document.getElementById("ie-title").textContent="Edit: "+f;
    var body=document.getElementById("ie-body"),long=v&&v.length>80;
    body.innerHTML="<div class='ie-status' id='ie-status'></div><div class='ie-field'><label>"+f+"</label>"+(long?"<textarea id='ie-inp' data-field='"+f+"' rows='6'>"+esc(v)+"</textarea>":"<input type='text' id='ie-inp' data-field='"+f+"' value='"+esc(v)+"'>")+"</div>";
    overlay.classList.add("show");modal.classList.add("show");
    var inp=document.getElementById("ie-inp");if(inp)inp.focus();
}
function save(){
    var inp=document.getElementById("ie-inp");if(!inp)return;
    var f=inp.dataset.field,v=inp.value;
    st("Saving...","");
    var b="_csrf="+encodeURIComponent(csrf)+"&inline_action=update&table="+encodeURIComponent(cur.t)+"&id="+cur.i+"&field="+encodeURIComponent(f)+"&value="+encodeURIComponent(v);
    fetch(API,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:b})
    .then(function(r){return r.json();})
    .then(function(d){if(d.success){st("Saved","ok");refresh(cur.e,d.value);setTimeout(close,600);}else{st(d.error||"Failed","err");}})
    .catch(function(e){st("Error: "+e.message,"err");});
}
function refresh(el,v){el.textContent=v;el.dataset.value=v;}
function close(){overlay.classList.remove("show");modal.classList.remove("show");cur={t:null,i:null,f:null,e:null};}
function st(msg,type){var s=document.getElementById("ie-status");if(!s)return;s.textContent=msg;s.className="ie-status"+(type?" "+type:"");}
function esc(s){var d=document.createElement("div");d.textContent=s;return d.innerHTML;}
function getCSRF(){var m=document.querySelector('meta[name="csrf-token"]');return m?m.content:'';}
function timeAgo(dt){if(!dt)return '';var d=new Date(dt),n=Date.now(),s=Math.floor((n-d.getTime())/1000);if(s<60)return s+'s ago';if(s<3600)return Math.floor(s/60)+'m ago';if(s<86400)return Math.floor(s/3600)+'h ago';return Math.floor(s/86400)+'d ago';}
if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",function(){init();bind();});}else{init();bind();}
return{open:open,close:close,save:save,bind:bind};
})();


(function(){
"use strict";
var layer=document.getElementById("earth-bg-layer");
if(!layer)return;
layer.innerHTML="";
var icons=[{cls:"fa-leaf",color:"rgba(45,106,79,.22)"},{cls:"fa-snowflake",color:"rgba(70,130,180,.18)"}];
for(var i=0;i<5;i++){
    var icon=icons[i%icons.length];
    var el=document.createElement("i");el.className="fa-solid "+icon.cls;
    el.style.cssText="color:"+icon.color+";font-size:"+((Math.random()*28)+18)+"px;left:"+(Math.random()*96+2)+"%;bottom:"+(Math.random()*35-10)+"vh;position:absolute;opacity:"+(0.18+Math.random()*0.18)+";animation:floatUp "+(24+Math.random()*18)+"s linear infinite;animation-delay:"+(Math.random()*-18)+"s;";
    layer.appendChild(el);
}
})();
