/* Growth OS — Cabeçalho global: empresa, período, pesquisa */
(function(){
const R=window.React,h=R.createElement,{useState,useRef,useEffect}=R;
const G=window.GOS,L=window.GOSlib,Icon=window.GOSIcon;
const ALL=G.keys6; // ["2026-01"..."2026-06"]
function rangeKeys(a,b){const ia=ALL.indexOf(a),ib=ALL.indexOf(b);return ALL.slice(Math.min(ia,ib),Math.max(ia,ib)+1);}
function label(keys){if(keys.length===1)return L.monthLong(keys[0]);return`${L.monthName(keys[0])}–${L.monthName(keys[keys.length-1])}/26`;}
// comparison: preceding equivalent block of same length within available data
function prevBlock(keys){const first=ALL.indexOf(keys[0]),n=keys.length,start=first-n;if(start<0)return null;return ALL.slice(start,start+n);}
const SHORTCUTS=[
  {id:"jun",name:"Mês atual · Jun",keys:["2026-06"]},
  {id:"mai",name:"Mês anterior · Mai",keys:["2026-05"]},
  {id:"q2",name:"Trimestre atual · Q2",keys:rangeKeys("2026-04","2026-06")},
  {id:"q1",name:"Trimestre anterior · Q1",keys:rangeKeys("2026-01","2026-03")},
  {id:"sem",name:"Semestre · Jan–Jun",keys:rangeKeys("2026-01","2026-06")},
  {id:"ytd",name:"Ano até agora (YTD)",keys:rangeKeys("2026-01","2026-06")}
];
function buildPeriod(keys,cmpMode){
  const cmpMode2=cmpMode||"prev";
  let cmp=null;
  if(cmpMode2==="prev"){const b=prevBlock(keys);if(b)cmp={keys:b,label:label(b),name:"período anterior"};}
  else if(cmpMode2==="yoy"){cmp={keys:[],label:"2025",name:"mesmo período de 2025",noData:true};}
  return{keys,label:label(keys),cmp,cmpMode:cmpMode2};
}
function usePop(){
  const[open,setOpen]=useState(false);const ref=useRef();
  useEffect(()=>{if(!open)return;const f=e=>{if(ref.current&&!ref.current.contains(e.target))setOpen(false);};document.addEventListener("mousedown",f);return()=>document.removeEventListener("mousedown",f);},[open]);
  return[open,setOpen,ref];
}

function CompanySwitcher(props){
  const[open,setOpen,ref]=usePop();
  const co=props.company;
  return h("div",{ref,style:{position:"relative"}},
    h("button",{className:"co-switch",onClick:()=>setOpen(o=>!o)},
      h("span",{className:"co-dot",style:{background:co.color}},co.short),
      h("span",{className:"cs-meta"},
        h("span",{className:"cs-name"},co.name),
        h("span",{className:"cs-sub"},co.moeda+" · "+co.tz.split("/")[1].replace("_"," "))),
      h("span",{className:"cs-caret"},h(Icon,{name:"chevron",size:15}))),
    open&&h("div",{className:"pop co-pop",style:{top:"calc(100% + 8px)",left:0,right:0}},
      h("div",{className:"lbl",style:{padding:"6px 8px 8px"}},"Trocar empresa"),
      props.companies.map(c=>h("button",{key:c.id,className:"co-pop-item"+(c.id===co.id?" on":""),onClick:()=>{props.onSwitch(c.id);setOpen(false);}},
        h("span",{className:"co-dot",style:{background:c.color,width:28,height:28,fontSize:12}},c.short),
        h("span",{style:{minWidth:0,flex:1}},
          h("div",{className:"cs-name",style:{fontSize:13}},c.name),
          h("div",{className:"cs-sub"},c.seg.split("·")[0].trim())),
        c.id===co.id&&h("span",{style:{color:"var(--lume)"}},h(Icon,{name:"check",size:15})))),
      h("div",{className:"co-pop-sep"}),
      h("button",{className:"co-pop-item",onClick:()=>{props.onPortfolio();setOpen(false);}},
        h("span",{className:"co-dot",style:{background:"var(--foco-600)",width:28,height:28,color:"var(--lume)"}},h(Icon,{name:"grid",size:14})),
        h("span",{className:"cs-name",style:{fontSize:13}},"Ver portfólio")))
  );
}

function PeriodPicker(props){
  const[open,setOpen,ref]=usePop();
  const p=props.period;
  const[custStart,setCustStart]=useState(p.keys[0]);
  const[custEnd,setCustEnd]=useState(p.keys[p.keys.length-1]);
  const activeId=SHORTCUTS.find(s=>s.keys.join()===p.keys.join())?.id;
  const apply=keys=>{props.onChange(buildPeriod(keys,p.cmpMode));setOpen(false);};
  return h("div",{ref,style:{position:"relative"}},
    h("button",{className:"period-btn",onClick:()=>setOpen(o=>!o)},
      h(Icon,{name:"calendar",size:16,style:{color:"var(--mist)"}}),
      h("span",null,
        h("div",{className:"pb-lbl"},"Período"),
        h("div",{className:"pb-val"},p.label,p.cmp&&h("span",{className:"pb-cmp"}," vs "+p.cmp.label))),
      h(Icon,{name:"chevron",size:14,style:{color:"var(--mist-2)"}})),
    open&&h("div",{className:"pop period-pop",style:{top:"calc(100% + 8px)",right:0}},
      h("div",{className:"lbl",style:{marginBottom:10}},"Atalhos"),
      h("div",{className:"pp-shorts"},
        SHORTCUTS.map(s=>h("button",{key:s.id,className:"pp-short"+(activeId===s.id?" on":""),onClick:()=>apply(s.keys)},s.name))),
      h("div",{className:"lbl",style:{margin:"14px 0 8px"}},"Período personalizado"),
      h("div",{className:"pp-custom"},
        h("select",{value:custStart,onChange:e=>setCustStart(e.target.value),style:sel},ALL.map(k=>h("option",{key:k,value:k},L.monthLong(k)))),
        h("select",{value:custEnd,onChange:e=>setCustEnd(e.target.value),style:sel},ALL.map(k=>h("option",{key:k,value:k},L.monthLong(k))))),
      h("button",{className:"btn btn-ghost btn-sm",style:{marginTop:10,width:"100%",justifyContent:"center"},onClick:()=>apply(rangeKeys(custStart,custEnd))},"Aplicar intervalo"),
      h("div",{className:"pp-cmp"},
        h("div",{className:"lbl",style:{marginBottom:8}},"Comparar com"),
        h("div",{style:{display:"flex",gap:7,flexWrap:"wrap"}},
          [["prev","Período anterior"],["yoy","Mesmo período 2025"]].map(c=>
            h("button",{key:c[0],className:"chip"+(p.cmpMode===c[0]?" on":""),onClick:()=>props.onChange(buildPeriod(p.keys,c[0]))},c[1])))))
  );
}
const sel={background:"var(--foco-700)",border:"1px solid var(--line-d)",borderRadius:9,padding:"9px 10px",color:"var(--papel)",fontSize:12.5,fontFamily:"var(--mono)"};

function GlobalHeader(props){
  const co=props.company,dq=co.dataQ;
  return h("div",{className:"ghead"},
    h("div",{className:"ghead-in"},
      props.onMenu&&h("button",{className:"rail-mob-btn",onClick:props.onMenu},h(Icon,{name:"menu",size:18})),
      props.onBack&&h("button",{className:"btn btn-ghost btn-sm",onClick:props.onBack,title:"Voltar",style:{flexShrink:0}},h(Icon,{name:"chevron",size:15,style:{transform:"rotate(90deg)"}}),h("span",{className:"gp-txt"},props.backLabel||"Voltar")),
      h("button",{className:"btn btn-ghost btn-sm",onClick:props.onPortfolio,title:"Voltar ao portfólio",style:{flexShrink:0}},h(Icon,{name:"grid",size:15}),h("span",{className:"gp-txt"},"Portfólio")),
      h("form",{className:"gsearch",onSubmit:e=>{e.preventDefault();const v=e.target.q.value.trim();if(v)props.onSearch(v);}},
        h(Icon,{name:"search"}),
        h("input",{name:"q",placeholder:`Pergunte sobre ${co.name}… ex.: "qual foi o CPL de janeiro?"`,autoComplete:"off",onFocus:props.onSearchFocus}),
        h("span",{className:"gs-key"},"↵")),
      h("div",{className:"ghead-right"},
        h("div",{className:"dq"},
          h("span",{className:"dq-dot "+dq.level}),
          h("span",null,dq.updated),
          h("span",{style:{color:"var(--mist-2)"}},"·"),
          h("span",{style:{color:"var(--mist-2)"}},dq.note)),
        h(PeriodPicker,{period:props.period,onChange:props.onPeriod}),
        h("button",{className:"btn btn-lume btn-sm",onClick:props.onReport},h(Icon,{name:"download",size:15}),"Relatório"))));
}
// add a grid icon for the switcher
window.GOSHeader=GlobalHeader;
window.GOSCoSwitch=CompanySwitcher;
window.GOSPeriod={buildPeriod,SHORTCUTS,rangeKeys,label};
})();
