(function(){
  'use strict';

  const PRIORITIES=new Set(['auto','fast','balanced','deep','maximum']);
  const LABELS={auto:'AUTO',fast:'FAST',balanced:'BALANCED',deep:'DEEP',maximum:'MAXIMUM'};
  const STORAGE_KEY='atlas.hermes.routing-priority';
  const EXPLICIT_EFFORT_KEY='atlas.hermes.explicit-reasoning';
  const ROUTE_LABELS={
    'atlas/auto/fast':'AUTO · Fast',
    'atlas/auto/balanced':'AUTO · Balanced',
    'atlas/auto/deep':'AUTO · Deep',
    'atlas/auto/maximum':'AUTO · Maximum',
    'atlas/manual/codex/luna':'Codex · Luna',
    'atlas/manual/codex/terra':'Codex · Terra',
    'atlas/manual/codex/sol':'Codex · SOL',
    'atlas/manual/claude/haiku':'Claude · Haiku',
    'atlas/manual/claude/fable':'Claude · Fable',
    'atlas/manual/claude/sonnet':'Claude · Sonnet',
    'atlas/manual/claude/opus':'Claude · Opus',
    'atlas/manual/local/qwen-14b':'Local · Qwen 14B'
  };

  function routeId(value){
    const raw=String(value||'').trim();
    if(ROUTE_LABELS[raw]) return raw;
    const marker=raw.indexOf(':atlas/');
    return marker>=0?raw.slice(marker+1):raw;
  }

  function friendlyRouteLabel(value){
    return ROUTE_LABELS[routeId(value)]||'';
  }

  function labelModelOptions(){
    ['modelSelect','settingsModel'].forEach(function(id){
      const select=document.getElementById(id);
      if(!select) return;
      Array.from(select.options||[]).forEach(function(option){
        const label=friendlyRouteLabel(option.value);
        if(label&&option.textContent!==label) option.textContent=label;
      });
    });
    if(typeof window.syncModelChip==='function') window.syncModelChip();
    if(typeof window.syncSettingsModelChip==='function') window.syncSettingsModelChip();
  }

  function watchModelOptions(id){
    const select=document.getElementById(id);
    if(!select||select.dataset.atlasFriendlyRoutes==='1') return;
    select.dataset.atlasFriendlyRoutes='1';
    new MutationObserver(labelModelOptions).observe(select,{childList:true,subtree:true});
    select.addEventListener('change',labelModelOptions);
  }

  function currentPriority(){
    let value='auto';
    try{value=String(localStorage.getItem(STORAGE_KEY)||'auto').toLowerCase();}catch(_){ }
    return PRIORITIES.has(value)?value:'auto';
  }

  function close(){
    const dropdown=document.getElementById('composerRoutingDropdown');
    const chip=document.getElementById('composerRoutingChip');
    if(dropdown) dropdown.classList.remove('open');
    if(chip){chip.classList.remove('active');chip.setAttribute('aria-expanded','false');}
  }

  function render(){
    const priority=currentPriority();
    const label=document.getElementById('composerRoutingLabel');
    if(label) label.textContent=LABELS[priority];
    document.querySelectorAll('#composerRoutingDropdown .routing-option').forEach(function(option){
      option.classList.toggle('selected',option.dataset.priority===priority);
    });
  }

  function position(){
    const dropdown=document.getElementById('composerRoutingDropdown');
    const chip=document.getElementById('composerRoutingChip');
    const footer=document.querySelector('.composer-footer');
    if(!dropdown||!chip||!footer) return;
    const chipRect=chip.getBoundingClientRect();
    const footerRect=footer.getBoundingClientRect();
    const maximum=Math.max(0,footer.clientWidth-dropdown.offsetWidth);
    dropdown.style.left=Math.max(0,Math.min(chipRect.left-footerRect.left,maximum))+'px';
  }

  function toggle(event){
    if(event) event.stopPropagation();
    const dropdown=document.getElementById('composerRoutingDropdown');
    const chip=document.getElementById('composerRoutingChip');
    if(!dropdown||!chip) return;
    const opening=!dropdown.classList.contains('open');
    if(typeof window.closeReasoningDropdown==='function') window.closeReasoningDropdown();
    if(typeof window.closeModelDropdown==='function') window.closeModelDropdown();
    close();
    if(opening){
      render();
      dropdown.classList.add('open');
      chip.classList.add('active');
      chip.setAttribute('aria-expanded','true');
      position();
    }
  }

  window.hermesRoutingRequest=function(){
    const priority=currentPriority();
    let explicitReasoning=false;
    try{explicitReasoning=localStorage.getItem(EXPLICIT_EFFORT_KEY)==='1';}catch(_){ }
    let effort='';
    if(explicitReasoning&&typeof window._atlasCurrentReasoningEffort!=='undefined'){
      effort=String(window._atlasCurrentReasoningEffort||'').toLowerCase();
    }
    return {
      routing_mode:'auto',
      routing_priority:priority,
      explicit_reasoning_effort:explicitReasoning&&effort?effort:undefined
    };
  };
  window.hermesFriendlyRouteLabel=friendlyRouteLabel;

  document.addEventListener('DOMContentLoaded',function(){
    render();
    labelModelOptions();
    watchModelOptions('modelSelect');
    watchModelOptions('settingsModel');
    const chip=document.getElementById('composerRoutingChip');
    if(chip) chip.addEventListener('click',toggle);
  });
  document.addEventListener('click',function(event){
    const option=event.target.closest&&event.target.closest('#composerRoutingDropdown .routing-option');
    if(option){
      const priority=String(option.dataset.priority||'auto').toLowerCase();
      if(PRIORITIES.has(priority)){
        try{localStorage.setItem(STORAGE_KEY,priority);}catch(_){ }
        render();
      }
      close();
      return;
    }
    if(!(event.target.closest&&event.target.closest('#composerRoutingWrap'))) close();
  });
  document.addEventListener('click',function(event){
    const option=event.target.closest&&event.target.closest('#composerReasoningDropdown .reasoning-option');
    if(!option) return;
    try{
      if(String(option.dataset.effort||'')) localStorage.setItem(EXPLICIT_EFFORT_KEY,'1');
      else localStorage.removeItem(EXPLICIT_EFFORT_KEY);
    }catch(_){ }
  },true);
})();
