/* Growth OS — Portfólio e criação de empresa */
(function(){
const R=window.React,h=R.createElement,{useState}=R;
const G=window.GOS,L=window.GOSlib,Icon=window.GOSIcon;

function pfStat(co){
  const cur=[G.CUR];
  const rrec=co.indicators.find(i=>i.key==="rrec");
  const roi=co.indicators.find(i=>i.key==="roi");
  return{rec:L.fmtMoneyBRL(L.agg(rrec,cur),true),roi:roi?L.fmtVal(roi,L.agg(roi,cur)):"—"};
}
function topSignal(co){
  // pick the strongest star indicator delta for the card teaser
  const cur=[G.CUR],prev=["2026-05"];
  const stars=co.indicators.filter(i=>i.star);
  let best=null,bestMag=0;
  stars.forEach(ind=>{
    const c=L.agg(ind,cur),p=L.agg(ind,prev),d=L.delta(ind,c,p);
    if(d.ok&&d.pct!=null&&Math.abs(d.pct)>bestMag){bestMag=Math.abs(d.pct);best={ind,c,p,d,good:L.goodness(ind,c,p)};}
  });
  if(!best)return null;
  const{ind,c,d,good}=best;
  const dir=good==="up"?"subiu":good==="down"?"caiu":"variou";
  const val=L.fmtVal(ind,c,true);
  return{txt:`${ind.name} ${dir} `,strong:`${Math.abs(d.pct)}%`,tail:` — agora em ${val}.`,good};
}

function Portfolio(props){
  const[creating,setCreating]=useState(false);
  return h("div",{className:"portfolio-page fade-in"},
    h("div",{className:"pf-top"},
      h("div",{className:"pf-top-in"},
        h("div",{className:"pf-brand"},
          h("img",{src:"assets/symbol-orange.png",alt:""}),
          h("div",null,
            h("div",{className:"pb-t"},"Growth OS"),
            h("div",{className:"pb-s"},"Memória operacional de crescimento"))),
        h("div",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:12}},
          h("span",{className:"lbl"},"Conta"),
          h("div",{className:"rail-foot",style:{border:"none",padding:0}},
            h("div",{className:"rf-av"},"RF"),
            h("div",null,h("div",{className:"rf-n"},"Rodrigo Fass"),h("div",{className:"rf-r"},"Proprietário")))))),
    h("div",{className:"pf-body"},
      h("div",{className:"pf-hero"},
        h("p",{className:"kicker",style:{marginBottom:18}},"Portfólio · "+props.companies.length+" empresas"),
        h("h1",null,"Suas empresas, ",h("span",{style:{color:"var(--mist)"}},"cada uma em seu próprio ambiente.")),
        h("p",{className:"pf-lead"},"Dados, contexto, metas e relatórios totalmente isolados. Selecione uma empresa para operar dentro do contexto dela.")),
      h("div",{className:"pf-grid"},
        props.companies.map(co=>{
          const st=pfStat(co),sig=topSignal(co);
          return h("button",{key:co.id,className:"pf-card",onClick:()=>props.onOpen(co.id)},
            h("div",{className:"pc-top"},
              h("div",{className:"pc-dot",style:{background:co.color}},co.short),
              h("div",null,
                h("div",{className:"pc-name"},co.name),
                h("div",{className:"pc-seg"},co.seg.split("·")[0].trim()))),
            sig?h("p",{className:"pc-sig"},sig.txt,h("b",null,sig.strong),sig.tail):h("p",{className:"pc-sig muted"},"Sem sinais no período."),
            h("div",{className:"pc-foot"},
              h("div",{className:"pc-stat"},h("div",{className:"pcs-v"},st.rec),h("div",{className:"pcs-l"},"Receita · jun")),
              h("div",{className:"pc-stat"},h("div",{className:"pcs-v"},st.roi),h("div",{className:"pcs-l"},"ROI · jun")),
              h("span",{className:"pc-go"},h(Icon,{name:"arrowR",size:20}))));
        }),
        h("button",{className:"pf-add",onClick:()=>setCreating(true)},
          h("span",{className:"pa-plus"},h(Icon,{name:"plus",size:22})),
          h("div",{style:{textAlign:"center"}},
            h("div",{className:"sora",style:{fontSize:16}},"Criar empresa"),
            h("div",{className:"lbl",style:{marginTop:6}},"Novo ambiente isolado"))))),
    creating&&h(CreateCompany,{onClose:()=>setCreating(false),onCreate:props.onCreate}));
}

function CreateCompany(props){
  const[f,setF]=useState({name:"",seg:"",modelo:"B2B · Serviço recorrente",moeda:"BRL",tz:"America/Sao_Paulo",startY:"2026",startM:"01",site:"",desc:""});
  const set=(k,v)=>setF(p=>({...p,[k]:v}));
  const valid=f.name&&f.seg&&f.modelo&&f.moeda&&f.tz&&f.startY&&f.startM;
  return h("div",{className:"modal-scrim",onClick:props.onClose},
    h("div",{className:"modal",style:{width:"min(720px,94vw)"},onClick:e=>e.stopPropagation()},
      h("div",{className:"modal-hd"},
        h("div",null,
          h("div",{className:"modal-bc"},h("span",null,"Portfólio"),h(Icon,{name:"chevronR",size:12}),h("span",{style:{color:"var(--papel)"}},"Criar empresa")),
          h("h2",null,"Novo ambiente"),
          h("p",{className:"mh-def"},"Copia apenas a estrutura funcional. Nunca copia dados, credenciais, metas ou histórico de outra empresa.")),
        h("button",{className:"modal-close",onClick:props.onClose},h(Icon,{name:"close",size:18}))),
      h("div",{className:"modal-body"},
        h("div",{className:"grid-2"},
          field("Nome da empresa",true,h("input",{value:f.name,onChange:e=>set("name",e.target.value),placeholder:"Ex.: Minha Empresa Ltda"})),
          field("Segmento",true,h("input",{value:f.seg,onChange:e=>set("seg",e.target.value),placeholder:"Ex.: Serviços B2B"}))),
        h("div",{className:"grid-2"},
          field("Modelo de negócio",true,h("select",{value:f.modelo,onChange:e=>set("modelo",e.target.value)},
            ["B2B · Serviço recorrente","B2B · Projeto + manutenção","B2C · Transação","B2B2C · Misto","SaaS · Assinatura"].map(o=>h("option",{key:o},o)))),
          field("Moeda",true,h("select",{value:f.moeda,onChange:e=>set("moeda",e.target.value)},
            ["BRL","USD","EUR"].map(o=>h("option",{key:o},o))))),
        h("div",{className:"grid-3"},
          field("Fuso horário",true,h("select",{value:f.tz,onChange:e=>set("tz",e.target.value)},
            ["America/Sao_Paulo","America/New_York","Europe/Lisbon"].map(o=>h("option",{key:o},o)))),
          field("Ano inicial",true,h("select",{value:f.startY,onChange:e=>set("startY",e.target.value)},
            ["2025","2026"].map(o=>h("option",{key:o},o)))),
          field("Mês inicial",true,h("select",{value:f.startM,onChange:e=>set("startM",e.target.value)},
            G.MONTHS.map(m=>h("option",{key:m[0],value:m[0]},m[1]))))),
        field("Site",false,h("input",{value:f.site,onChange:e=>set("site",e.target.value),placeholder:"opcional"})),
        field("Descrição estratégica",false,h("textarea",{value:f.desc,onChange:e=>set("desc",e.target.value),rows:3,placeholder:"Opcional no cadastro, recomendada antes da análise."}))),
      h("div",{className:"modal-foot"},
        h("button",{className:"btn btn-ghost",onClick:props.onClose},"Cancelar"),
        h("button",{className:"btn btn-lume",disabled:!valid,style:{opacity:valid?1:.5,pointerEvents:valid?"auto":"none"},onClick:()=>props.onCreate(f)},h(Icon,{name:"plus",size:16}),"Criar empresa"))));
}
function field(label,req,input){
  return h("div",{className:"field"},h("label",null,label,req&&h("span",{className:"req"}," *")),input);
}
window.GOSPortfolio=Portfolio;
})();
