(function(window,document){
  'use strict';
  var icons={success:'fa-check',error:'fa-times',warning:'fa-exclamation',info:'fa-info'};
  function stack(){var node=document.querySelector('.cms-ui-toast-stack');if(!node){node=document.createElement('div');node.className='cms-ui-toast-stack';node.setAttribute('aria-live','polite');node.setAttribute('aria-atomic','false');document.body.appendChild(node);}return node;}
  function toast(message,type,title,duration){type=icons[type]?type:'info';duration=Math.max(1600,Math.min(10000,Number(duration)||3600));var item=document.createElement('div');item.className='cms-ui-toast is-'+type;item.setAttribute('role',type==='error'?'alert':'status');item.innerHTML='<span class="cms-ui-toast-icon"><i class="fa '+icons[type]+'"></i></span><div><strong></strong><p></p></div><button type="button" class="cms-ui-toast-close" aria-label="关闭">×</button>';item.querySelector('strong').textContent=title||({success:'操作成功',error:'操作失败',warning:'请注意',info:'系统提示'})[type];item.querySelector('p').textContent=String(message||'');stack().appendChild(item);var closed=false,timer;function close(){if(closed)return;closed=true;clearTimeout(timer);item.classList.add('is-leaving');setTimeout(function(){if(item.parentNode)item.parentNode.removeChild(item);},190);}item.querySelector('button').onclick=close;timer=setTimeout(close,duration);return close;}
  function confirmDialog(options){options=typeof options==='string'?{message:options}:(options||{});return new Promise(function(resolve){var tone=['danger','warning'].indexOf(options.tone)>=0?options.tone:'default',layer=document.createElement('div'),last=document.activeElement;layer.className='cms-ui-dialog-layer';layer.innerHTML='<section class="cms-ui-dialog is-'+tone+'" role="alertdialog" aria-modal="true" aria-labelledby="cmsUiDialogTitle"><div class="cms-ui-dialog-mark"><i class="fa '+(tone==='danger'?'fa-trash-o':tone==='warning'?'fa-exclamation':'fa-question')+'"></i></div><h2 id="cmsUiDialogTitle"></h2><p></p><div class="cms-ui-dialog-actions"><button type="button" class="btn btn-secondary cms-ui-dialog-cancel"></button><button type="button" class="btn btn-primary cms-ui-dialog-confirm '+(tone==='danger'?'cms-ui-confirm-danger':'')+'"></button></div></section>';layer.querySelector('h2').textContent=options.title||'确认操作';layer.querySelector('p').textContent=options.message||'此操作需要你的确认。';var cancel=layer.querySelector('.cms-ui-dialog-cancel'),ok=layer.querySelector('.cms-ui-dialog-confirm');cancel.textContent=options.cancelText||'取消';ok.textContent=options.confirmText||'确认';document.body.appendChild(layer);function done(value){document.removeEventListener('keydown',key);layer.remove();if(last&&last.focus)last.focus();resolve(value);}function key(event){if(event.key==='Escape')done(false);if(event.key==='Tab'){var target=document.activeElement===ok?cancel:ok;event.preventDefault();target.focus();}}cancel.onclick=function(){done(false);};ok.onclick=function(){done(true);};layer.onclick=function(e){if(e.target===layer)done(false);};document.addEventListener('keydown',key);ok.focus();});}
  function setLoading(button,loading,label){if(!button)return;loading=!!loading;if(loading){if(!button.dataset.cmsOriginal)button.dataset.cmsOriginal=button.innerHTML;button.disabled=true;button.setAttribute('aria-busy','true');button.classList.add('is-loading');button.innerHTML='<span class="cms-ui-spinner"></span>'+(label||'处理中');}else{button.disabled=false;button.removeAttribute('aria-busy');button.classList.remove('is-loading');if(button.dataset.cmsOriginal){button.innerHTML=button.dataset.cmsOriginal;delete button.dataset.cmsOriginal;}}}
  function flash(message,type){sessionStorage.setItem('cms-ui-flash',JSON.stringify({message:String(message||''),type:type||'success'}));}
  function reload(button,label){setLoading(button,true,label||'刷新中');setTimeout(function(){window.location.reload();},40);}
  var buttonToneRules=[
    ['danger',/(删除|清空|移除|禁用|停用|注销|作废|永久删除|delete|remove|disable)/i],
    ['review',/(审核|审阅|驳回|撤回|下架|取消发布|待审核|review|reject|unpublish)/i],
    ['transfer',/(导入|导出|下载|上传|备份|恢复|迁移|同步|import|export|download|upload|backup|restore|sync)/i],
    ['view',/(查看|详情|预览|浏览|日志|记录|view|detail|preview|log)/i],
    ['edit',/(编辑|修改|配置|设置|调整|管理|edit|update|config|setting)/i],
    ['save',/(保存|提交|发布|启用|通过|确认|完成|处理|授权|save|submit|publish|enable|approve|confirm)/i],
    ['create',/(新增|添加|创建|新建|复制|加入|add|create|new|copy)/i],
    ['search',/(查询|搜索|筛选|刷新|检测|重新加载|search|filter|refresh|reload|check)/i]
  ];
  function applyButtonTone(button){
    if(!button||button.nodeType!==1||button.dataset.cmsButtonTone||button.closest('.edui-editor,.cms-ui-toast'))return;
    if(button.matches('.cms-ui-confirm-danger,.btn-danger')||button.dataset.cmsTone==='danger'){button.dataset.cmsButtonTone='danger';return;}
    if(button.matches('.btn-success')){button.dataset.cmsButtonTone='save';return;}
    if(button.matches('.btn-warning')||button.dataset.cmsTone==='warning'){button.dataset.cmsButtonTone='review';return;}
    var signature=[button.textContent,button.getAttribute('title'),button.getAttribute('aria-label'),button.getAttribute('href'),button.getAttribute('onclick'),button.getAttribute('name'),button.getAttribute('value')].filter(Boolean).join(' ').replace(/\s+/g,' ').trim();
    for(var i=0;i<buttonToneRules.length;i++){if(buttonToneRules[i][1].test(signature)){button.dataset.cmsButtonTone=buttonToneRules[i][0];return;}}
    button.dataset.cmsButtonTone='neutral';
  }
  function applyButtonTones(root){
    if(!root||root.nodeType!==1&&root.nodeType!==9)return;
    if(root.matches&&root.matches('.btn'))applyButtonTone(root);
    if(root.querySelectorAll)root.querySelectorAll('.btn').forEach(applyButtonTone);
  }
  function boot(){try{var data=JSON.parse(sessionStorage.getItem('cms-ui-flash')||'null');sessionStorage.removeItem('cms-ui-flash');if(data&&data.message)toast(data.message,data.type);}catch(e){}applyButtonTones(document);new MutationObserver(function(records){records.forEach(function(record){record.addedNodes.forEach(function(node){applyButtonTones(node);});});}).observe(document.body,{childList:true,subtree:true});document.addEventListener('click',function(event){var trigger=event.target.closest('[data-cms-confirm]');if(!trigger)return;var form=trigger.form||trigger.closest('form');if(!form||trigger.dataset.cmsConfirmed==='1')return;event.preventDefault();confirmDialog({title:trigger.dataset.cmsTitle||'确认操作',message:trigger.dataset.cmsConfirm,tone:trigger.dataset.cmsTone||'warning',confirmText:trigger.dataset.cmsConfirmText||'确认'}).then(function(ok){if(!ok)return;trigger.dataset.cmsConfirmed='1';setLoading(trigger,true,trigger.dataset.cmsLoading||'处理中');if(form.requestSubmit)form.requestSubmit(trigger);else form.submit();});},true);}
  window.CMSAdminUI={toast:toast,confirm:confirmDialog,setLoading:setLoading,flash:flash,reload:reload};
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot);else boot();
})(window,document);
