/* Growth OS — Visão geral: sinais textuais + grid de indicadores */
(function(){
const R=window.React,h=R.createElement;
const G=window.GOS,L=window.GOSlib,Icon=window.GOSIcon;
const CATS=["Marketing","Comercial","Receita","Clientes","Operação","Personalizado"];

function dirWord(good){return good==="up"?"aumentou":good==="down"?"caiu":good==="warn"?"saiu da faixa":"manteve-se";}
function relWord(good){return good==="up"?"cresceu":good==="down"?"recuou":"variou";}

// spec §10: derive signals for the active period vs comparison
function generateSignals(co,period){
  const cur=period.keys,cmp=period.cmp&&!period.cmp.noData?period.cmp.keys:null;
  const out=[];
  co.indicators.forEach(ind=>{
    const c=L.agg(ind,cur);if(c==null)return;
    const p=cmp?L.agg(ind,cmp):L.agg(ind,["2026-05"]);
    const cmpName=cmp?"período anterior":"mês anterior";
    const d=L.delta(ind,c,p);
    const good=L.goodness(ind,c,p);
    const mag=d.ok&&d.pct!=null?Math.abs(d.pct):0;
    // faixa break
    if(ind.dir==="faixa"&&ind.faixa){const[lo,hi]=ind.faixa;if(c>hi||c<lo){
      out.push({kind:"warn",metricKey:ind.key,conf:ind.conf,mag:mag+30,
        text:[`${ind.name} está em `,L.fmtVal(ind,c),` — ${c>hi?"acima":"abaixo"} da faixa saudável (${L.fmtVal(ind,lo)}–${L.fmtVal(ind,hi)}).`],
        meta:ind.cat});return;}}
    if(!d.ok||d.pct==null)return;
    // anomaly
    if(mag>=20){out.push({kind:"anomaly",metricKey:ind.key,conf:ind.conf,mag:mag+40,
      text:[`${ind.name} ${relWord(good)} `,`${Math.abs(d.pct)}%`,` em relação ao ${cmpName} — variação fora da faixa histórica.`],meta:ind.cat});return;}
    // meta status
    if(ind.goal!=null){
      const hitGoal=ind.dir==="menor"?c<=ind.goal:c>=ind.goal;
      const gap=Math.abs(L.round((c-ind.goal)/ind.goal*100,0));
      if(hitGoal&&mag>=3){out.push({kind:"up",metricKey:ind.key,conf:ind.conf,mag:mag+15,
        text:[`${ind.name} atingiu a meta: `,L.fmtVal(ind,c),`, ${ind.dir==="menor"?"abaixo":"acima"} do alvo de ${L.fmtVal(ind,ind.goal)}.`],meta:ind.cat});return;}
      if(!hitGoal&&gap>=6&&(ind.dir==="maior"||ind.dir==="menor")){out.push({kind:"warn",metricKey:ind.key,conf:ind.conf,mag:gap+10,
        text:[`${ind.name} está `,`${gap}%`,` ${ind.dir==="menor"?"acima":"abaixo"} da meta (${L.fmtVal(ind,ind.goal)}).`],meta:ind.cat});return;}
    }
    // relevance threshold 5%
    if(mag>=5){
      const kind=good==="up"?"up":good==="down"?"down":"flat";
      const suffix=isPP(ind)?` (${d.pp>0?"+":""}${d.pp} p.p.)`:"";
      out.push({kind,metricKey:ind.key,conf:ind.conf,mag,
        text:[`${ind.name} ${dirWord(good)} `,`${Math.abs(d.pct)}%${suffix}`,` — de ${L.fmtVal(ind,p,true)} para ${L.fmtVal(ind,c,true)}.`],meta:ind.cat});
    } else if(mag<2){
      // stagnation only for star metrics
      if(ind.star)out.push({kind:"flat",metricKey:ind.key,conf:ind.conf,mag:1,
        text:[`${ind.name} estável em `,L.fmtVal(ind,c,true),` — sem mudança relevante frente ao ${cmpName}.`],meta:ind.cat});
    }
  });
  // data quality signal
  const bad=co.integrations.filter(i=>i.status==="erro"||i.status==="atencao");
  if(bad.length){out.push({kind:"warn",metricKey:null,conf:"—",mag:8,integ:true,
    text:[`${bad.length} ${bad.length>1?"integrações precisam":"integração precisa"} de atenção `,`(${bad.map(b=>b.name).join(", ")})`,` — pode afetar a confiança dos dados.`],meta:"Integrações"});}
  out.sort((a,b)=>b.mag-a.mag);
  return out.slice(0,9);
}
function isPP(ind){return ind.type==="percentual";}

function MetricCard(props){
  const{ind,period}=props;
  const cur=period.keys,cmp=period.cmp&&!period.cmp.noData?period.cmp.keys:["2026-05"];
  const c=L.agg(ind,cur),p=L.agg(ind,cmp),d=L.delta(ind,c,p),good=L.goodness(ind,c,p);
  const spark=G.keys6.map(k=>ind.series[k]);
  const pillCls=good==="up"?"up":good==="down"?"down":"flat";
  const goalPct=ind.goal!=null&&c!=null?(ind.dir==="menor"?Math.min(150,ind.goal/c*100):Math.min(150,c/ind.goal*100)):null;
  const goalHit=ind.goal!=null?(ind.dir==="menor"?c<=ind.goal:c>=ind.goal):null;
  const unit=L.unitLabel(ind);
  return h("button",{className:"metric",onClick:()=>props.onOpen(ind.key)},
    h("div",{className:"m-name"},ind.name,h("span",{className:"m-src"},ind.source)),
    h("div",{className:"m-val"},L.fmtVal(ind,c,true),unit&&h("span",{className:"m-unit"},unit)),
    d.ok&&d.pct!=null?h("div",{className:"m-delta"},
      h("span",{className:"md-pill "+pillCls},
        h(Icon,{name:pillCls==="up"?"arrowUp":pillCls==="down"?"arrowDown":"arrowR",size:12}),
        isPP(ind)?`${d.pp>0?"+":""}${d.pp} p.p.`:`${d.pct>0?"+":""}${d.pct}%`),
      h("span",{className:"md-vs"},"vs "+(period.cmp?period.cmp.label:"mai"))
    ):h("div",{className:"m-delta"},h("span",{className:"md-vs"},d.nc?"novo no período":"sem comparação")),
    h("div",{className:"m-spark"},h(L.Spark,{values:spark,good})),
    ind.goal!=null&&h("div",{className:"m-goal"},
      h("div",{className:"mg-track"},h("div",{className:"mg-fill"+(goalHit?"":" miss"),style:{width:Math.min(100,goalPct)+"%"}})),
      h("div",{className:"mg-cap"},h("span",null,"meta "+L.fmtVal(ind,ind.goal,true)),h("span",null,goalHit?"atingida":Math.round(goalPct)+"% da meta"))));
}

const HERO_SUG=["Qual foi o melhor mês de faturamento?","O ROI está aumentando?","Quanto o CAC variou de maio para junho?","Quanto falta para a meta?"];
function HeroSearch(props){
  const{co}=props;
  const[q,setQ]=React.useState("");
  return h("div",{className:"hero-search"},
    h("form",{className:"hs-bar",onSubmit:e=>{e.preventDefault();if(q.trim())props.onSearch(q.trim());}},
      h(Icon,{name:"search",size:20,style:{color:"var(--mist)"}}),
      h("input",{value:q,onChange:e=>setQ(e.target.value),placeholder:`Pergunte qualquer coisa sobre ${co.name}…`,autoComplete:"off"}),
      h("button",{type:"submit",className:"btn btn-lume btn-sm",disabled:!q.trim(),style:{opacity:q.trim()?1:.5}},"Perguntar")),
    h("div",{className:"hs-sug"},
      h("span",{className:"lbl",style:{marginRight:4}},"Tente"),
      HERO_SUG.map((s,i)=>h("button",{key:i,className:"chip",onClick:()=>props.onSearch(s)},s))));
}
function Overview(props){  const{company:co,period}=props;
  const signals=generateSignals(co,period);
  const byCat={};co.indicators.forEach(i=>{(byCat[i.cat]=byCat[i.cat]||[]).push(i);});
  const kindLabel={up:"Alta",down:"Queda",warn:"Atenção",flat:"Estável",anomaly:"Anomalia"};
  return h("div",{className:"wrap fade-in"},
    h("div",{className:"page-head"},
      h("div",null,
        h("p",{className:"kicker",style:{marginBottom:14}},"Visão geral · "+period.label),
        h("h1",null,"O que aconteceu"),
        h("p",{className:"ph-sub"},"Sinais derivados dos dados de ",h("b",{style:{color:"var(--papel)",fontWeight:400}},co.name),". Clique em qualquer indicador para abrir o detalhamento sem sair desta tela.")),
      h("div",{className:"ph-actions"},
        h("span",{className:"chip static"},h("span",{className:"dq-dot "+co.dataQ.level,style:{width:7,height:7,borderRadius:"50%"}}),"Dados "+co.dataQ.updated),
        h("button",{className:"btn btn-ghost btn-sm",onClick:props.onReport},h(Icon,{name:"file",size:15}),"Gerar relatório"))),
    h(HeroSearch,{co,onSearch:props.onSearch}),
    h("div",{className:"section-lbl"},h("h2",null,"Sinais do período"),h("span",{className:"sl-line"}),h("span",{className:"sl-count"},signals.length+" sinais")),
    signals.length?h("div",{className:"signal-strip"},
      signals.map((s,i)=>h("button",{key:i,className:"signal "+s.kind,onClick:()=>s.metricKey?props.onOpen(s.metricKey):props.onIntegrations&&props.onIntegrations()},
        h("div",{className:"sg-top"},
          h("span",{className:"sg-kind "+s.kind},kindLabel[s.kind]),
          h("span",{className:"sg-conf"},s.conf!=="—"?"confiança "+s.conf:s.meta)),
        h("div",{className:"sg-text"},s.text[0],h("b",null,s.text[1]),s.text[2]),
        h("div",{className:"sg-meta"},h(Icon,{name:"spark",size:11,style:{color:"var(--mist-2)"}}),s.meta,s.metricKey&&h(React.Fragment,null,h("span",null,"·"),"ver detalhe")))
    )):h("div",{className:"empty"},h("div",{className:"em-t"},"Sem sinais relevantes"),"Nenhuma mudança acima do limiar de relevância neste período."),
    CATS.filter(c=>byCat[c]).map(cat=>h("div",{key:cat},
      h("div",{className:"section-lbl"},h("h2",null,cat),h("span",{className:"sl-line"}),h("span",{className:"sl-count"},byCat[cat].length+" indicadores")),
      h("div",{className:"metric-grid"},byCat[cat].map(ind=>h(MetricCard,{key:ind.key,ind,period,onOpen:props.onOpen})))))
  );
}
window.GOSOverview=Overview;
window.GOSSignals=generateSignals;
window.GOSMetricCard=MetricCard;
})();
