/* Growth OS — App: shell, navegação, roteamento, orquestração */
(function(){
const R=window.React,h=R.createElement,{useState,useEffect}=R;
const G=window.GOS,L=window.GOSlib,Icon=window.GOSIcon,P=window.GOSPeriod;

const NAV=[
  {group:"Análise",items:[["overview","Visão geral","overview"],["growth","Growth Model","growth"]]},
  {group:"Áreas",items:[["cat:Marketing","Marketing e aquisição","marketing"],["cat:Comercial","Comercial","comercial"],["cat:Receita","Receita","receita"],["cat:Clientes","Clientes","clientes"],["cat:Operação","Operação","operacao"]]},
  {group:"Gestão",items:[["decisoes","Decisões e ações","decisoes"],["fechamento","Fechamento","calendar"],["relatorios","Relatórios","relatorios"]]},
  {group:"Dados",items:[["integracoes","Integrações","integracoes"],["contexto","Contexto","contexto"],["config","Configurações","config"]]}
];

function Rail(props){
  const co=props.company;
  return h("aside",{className:"rail"+(props.open?" open":"")},
    h("div",{className:"rail-top"},
      h("div",{className:"rail-brand"},
        h("img",{src:"assets/symbol-orange.png",alt:""}),
        h("div",null,h("div",{className:"rb-t"},"Growth OS"),h("div",{className:"rb-s"},"por Rodrigo Fass"))),
      h(window.GOSCoSwitch,{company:co,companies:props.companies,onSwitch:props.onSwitch,onPortfolio:props.onPortfolio})),
    h("nav",{className:"rail-nav"},
      NAV.map(g=>h("div",{className:"rail-group",key:g.group},
        h("div",{className:"rail-group-lbl"},g.group),
        g.items.map(it=>{
          const active=props.module===it[0];
          const badge=it[0].startsWith("cat:")?co.indicators.filter(i=>i.cat===it[0].slice(4)).length:null;
          return h("button",{key:it[0],className:"rnav"+(active?" on":""),onClick:()=>props.onNav(it[0])},
            h(Icon,{name:it[2],size:16}),h("span",null,it[1]),
            badge!=null&&h("span",{className:"rn-badge"},badge));
        })))),
    h("div",{className:"rail-foot"},
      h("div",{className:"rf-av"},"RF"),
      h("div",{style:{flex:1,minWidth:0}},h("div",{className:"rf-n"},"Rodrigo Fass"),h("div",{className:"rf-r"},"Admin · todas as empresas"))));
}

/* category module */
function CategoryModule(props){
  const{company:co,period,cat}=props;
  const inds=co.indicators.filter(i=>i.cat===cat);
  const allSig=window.GOSSignals(co,period);
  const sig=allSig.filter(s=>s.meta===cat);
  const question={Marketing:"De onde vieram demanda, tráfego e leads?",Comercial:"Como oportunidades avançaram ou foram perdidas?",Receita:"Quanto foi contratado, faturado e recebido?",Clientes:"Quantos entraram, permaneceram ou cancelaram?","Operação":"Existe capacidade para sustentar o crescimento?"}[cat];
  return h("div",{className:"wrap fade-in"},
    h("div",{className:"page-head"},
      h("div",null,
        h("p",{className:"kicker",style:{marginBottom:14}},cat+" · "+period.label),
        h("h1",null,cat),
        h("p",{className:"ph-sub"},question)),
      h("div",{className:"ph-actions"},h("button",{className:"btn btn-ghost btn-sm",onClick:props.onReport},h(Icon,{name:"file",size:15}),"Relatório da área"))),
    sig.length>0&&h(React.Fragment,null,
      h("div",{className:"section-lbl"},h("h2",null,"Sinais"),h("span",{className:"sl-line"}),h("span",{className:"sl-count"},sig.length)),
      h("div",{className:"signal-strip"},sig.map((s,i)=>h("button",{key:i,className:"signal "+s.kind,onClick:()=>s.metricKey&&props.onOpen(s.metricKey)},
        h("div",{className:"sg-top"},h("span",{className:"sg-kind "+s.kind},s.kind),h("span",{className:"sg-conf"},"confiança "+s.conf)),
        h("div",{className:"sg-text"},s.text[0],h("b",null,s.text[1]),s.text[2]))))),
    h("div",{className:"section-lbl"},h("h2",null,"Indicadores"),h("span",{className:"sl-line"}),h("span",{className:"sl-count"},inds.length)),
    inds.length?h("div",{className:"metric-grid"},inds.map(ind=>h(window.GOSMetricCard,{key:ind.key,ind,period,onOpen:props.onOpen}))):h("div",{className:"empty"},h("div",{className:"em-t"},"Nenhum indicador nesta área"),"Cadastre indicadores de "+cat.toLowerCase()+" em Configurações para acompanhar esta empresa."));
}

/* decisões e ações */
function Decisions(props){
  const{company:co}=props;
  const seed=[
    {dec:"Escalar investimento no criativo de vídeo de melhor CPL",who:"Marketing",due:"jul/26",status:"Em andamento"},
    {dec:"Contratar 2 desenvolvedores para aliviar capacidade técnica",who:"Operação",due:"ago/26",status:"Em andamento"},
    {dec:"Revisar tabela de preço da baixa temporada",who:"Comercial",due:"jun/26",status:"Concluída"},
    {dec:"Padronizar registro de reuniões no CRM",who:"Comercial",due:"jul/26",status:"Pendente"}
  ];
  const[list,setList]=useState(seed);
  const[form,setForm]=useState({dec:"",who:"Marketing",due:"jul/26",status:"Pendente"});
  const add=()=>{if(!form.dec.trim())return;setList(l=>[{...form},...l]);setForm(f=>({...f,dec:""}));props.toast("Decisão registrada.");};
  const stCol={"Concluída":"var(--up)","Em andamento":"var(--warn)","Pendente":"var(--mist)"};
  return h("div",{className:"wrap fade-in"},
    h("div",{className:"page-head"},h("div",null,
      h("p",{className:"kicker",style:{marginBottom:14}},"Decisões e ações"),
      h("h1",null,"O que foi decidido"),
      h("p",{className:"ph-sub"},"Decisões ligadas a responsável, prazo e status — a ponte entre o que os dados mostraram e o que a empresa fará."))),
    h("div",{className:"panel",style:{marginBottom:16}},
      h("div",{style:{display:"flex",gap:10,flexWrap:"wrap",alignItems:"flex-end"}},
        h("div",{className:"field",style:{flex:2,minWidth:220,marginBottom:0}},h("label",null,"Nova decisão"),h("input",{value:form.dec,onChange:e=>setForm(f=>({...f,dec:e.target.value})),placeholder:"Ex.: Testar nova oferta de manutenção"})),
        h("div",{className:"field",style:{marginBottom:0}},h("label",null,"Responsável"),h("select",{value:form.who,onChange:e=>setForm(f=>({...f,who:e.target.value}))},["Marketing","Comercial","Financeiro","Operação","CS"].map(o=>h("option",{key:o},o)))),
        h("div",{className:"field",style:{marginBottom:0}},h("label",null,"Prazo"),h("input",{value:form.due,onChange:e=>setForm(f=>({...f,due:e.target.value})),style:{width:90}})),
        h("button",{className:"btn btn-lume",onClick:add},h(Icon,{name:"plus",size:15}),"Adicionar"))),
    h("div",{className:"panel",style:{padding:0,overflow:"hidden"}},
      h("table",{className:"dtable"},
        h("thead",null,h("tr",null,h("th",null,"Decisão"),h("th",null,"Responsável"),h("th",null,"Prazo"),h("th",null,"Status"))),
        h("tbody",null,list.map((d,i)=>h("tr",{key:i},
          h("td",null,h("span",{className:"cell-name"},d.dec)),
          h("td",{style:{textAlign:"right",color:"var(--mist)"}},d.who),
          h("td",{className:"num"},d.due),
          h("td",{style:{textAlign:"right"}},h("span",{style:{color:stCol[d.status],fontFamily:"var(--mono)",fontSize:11}},"● "+d.status))))))));
}

function Toast(props){
  useEffect(()=>{const t=setTimeout(props.onClose,2600);return()=>clearTimeout(t);},[]);
  return h("div",{className:"toast"},h("span",{className:"t-ico"},h(Icon,{name:"check",size:16})),props.msg);
}

function App(){
  const companies=G.companies;
  const[view,setView]=useState("portfolio"); // 'portfolio' | 'workspace'
  const[coId,setCoId]=useState(companies[0].id);
  const[hist,setHist]=useState(["overview"]);
  const module=hist[hist.length-1];
  const setModule=m=>setHist([m]);
  const[period,setPeriod]=useState(P.buildPeriod(["2026-06"],"prev"));
  const[modal,setModal]=useState(null); // {type:'indicator',key} | {type:'search',q} | {type:'report',ind}
  const[railOpen,setRailOpen]=useState(false);
  const[toast,setToast]=useState(null);
  const co=companies.find(c=>c.id===coId);
  const showToast=m=>setToast(m);
  const openMetric=key=>setModal({type:"indicator",key});
  const openSearch=q=>setModal({type:"search",q});
  const openReport=ind=>{setHist(h=>h[h.length-1]==="relatorios"?h:[...h,"relatorios"]);setModal(null);setView("workspace");if(ind)showToast("Abra “Gerar relatório” para incluir "+ind.name+".");};
  const nav=m=>{setHist(h=>h[h.length-1]===m?h:[...h,m]);setRailOpen(false);};
  const back=()=>{if(hist.length>1)setHist(h=>h.slice(0,-1));else setView("portfolio");};
  useEffect(()=>{const f=e=>{if(e.key==="Escape")setModal(null);};window.addEventListener("keydown",f);return()=>window.removeEventListener("keydown",f);},[]);

  if(view==="portfolio")
    return h(React.Fragment,null,
      h(window.GOSPortfolio,{companies,onOpen:id=>{setCoId(id);setModule("overview");setView("workspace");},onCreate:f=>{showToast("Empresa “"+f.name+"” criada. Estrutura pronta — sem dados herdados.");}}),
      toast&&h(Toast,{msg:toast,onClose:()=>setToast(null)}));

  let content;
  const mp={company:co,period,onOpen:openMetric,onReport:()=>openReport(),toast:showToast};
  if(module==="overview")content=h(window.GOSOverview,{...mp,onSearch:openSearch,onIntegrations:()=>nav("integracoes")});
  else if(module==="growth")content=h(window.GOSGrowthModel,mp);
  else if(module.startsWith("cat:"))content=h(CategoryModule,{...mp,cat:module.slice(4)});
  else if(module==="decisoes")content=h(Decisions,mp);
  else if(module==="fechamento")content=h(window.GOSFechamento,mp);
  else if(module==="relatorios")content=h(window.GOSReports,mp);
  else if(module==="integracoes")content=h(window.GOSIntegrations,mp);
  else if(module==="contexto")content=h(window.GOSContext,mp);
  else if(module==="config")content=h(window.GOSConfig,mp);

  return h("div",{className:"app-shell"},
    h("div",{className:"rail-scrim"+(railOpen?" open":""),onClick:()=>setRailOpen(false)}),
    h(Rail,{company:co,companies,module,open:railOpen,
      onNav:nav,onSwitch:id=>{setCoId(id);setModule("overview");},onPortfolio:()=>setView("portfolio")}),
    h("div",{className:"main"},
      h(window.GOSHeader,{company:co,period,onPeriod:setPeriod,onSearch:openSearch,onSearchFocus:()=>{},onReport:()=>nav("relatorios"),onMenu:()=>setRailOpen(true),onPortfolio:()=>setView("portfolio"),onBack:back,backLabel:hist.length>1?"Voltar":"Portfólio"}),
      h("div",{className:"main-scroll"},content)),
    modal&&modal.type==="indicator"&&h(window.GOSIndicatorModal,{company:co,period,metricKey:modal.key,onClose:()=>setModal(null),onReport:ind=>openReport(ind)}),
    modal&&modal.type==="search"&&h(window.GOSSearchModal,{company:co,period,initial:modal.q,onClose:()=>setModal(null),onOpenMetric:key=>setModal({type:"indicator",key})}),
    toast&&h(Toast,{msg:toast,onClose:()=>setToast(null)}));
}
ReactDOM.render(h(App),document.getElementById("app"));
})();
