/* Dashboard Executivo — CEO / Sócios */
const { useState:dS, useMemo:dM } = React;

function Dashboard({profile, onToast}){
  const [period,setPeriod]=dS('mes');
  const [units,setUnits]=dS([]); // [] = todas
  const restricted = profile.unit ? [profile.unit] : null; // gestor vê só a unidade
  const activeUnits = restricted || (units.length?units:MX.units.map(u=>u.id));
  const isAll = !restricted && units.length===0;

  const pf = period==='mes'?1 : period==='tri'?2.96 : 7.0;
  const pLabel = period==='mes'?'no mês':period==='tri'?'no trimestre':'no ano';
  const prevLabel = period==='mes'?'vs. abril':period==='tri'?'vs. tri. anterior':'vs. 2025';

  const selUnits = MX.units.filter(u=>activeUnits.includes(u.id));
  const fatBase = selUnits.reduce((a,u)=>a+u.fatMes,0);
  const metaBase = selUnits.reduce((a,u)=>a+u.metaMes,0);
  const fat = Math.round(fatBase*pf);
  const meta = Math.round(metaBase*pf);
  const casosAtivos = selUnits.reduce((a,u)=>a+u.casosAtivos,0);
  const casosEnc = selUnits.reduce((a,u)=>a+u.casosEnc,0);
  const share = fatBase / MX.units.reduce((a,u)=>a+u.fatMes,0);

  // série da linha
  const consolSerie = activeUnits.reduce((acc,id)=>{
    const s=MX.seriePorUnidade[id]; return acc.map((v,i)=>v+s[i]);
  }, new Array(MX.meses.length).fill(0));
  const metaSerie = MX.serieMetaConsol.map(v=>Math.round(v*share));
  const anoAntSerie = MX.serieAnoAnterior.map(v=>Math.round(v*share));

  const lineSeries=[
    {name:'Realizado', data:consolSerie, color:'#b68b4c', fill:true},
    {name:'Meta', data:metaSerie, color:'#3a4159', dashed:true},
    {name:'Ano anterior', data:anoAntSerie, color:'#c2b9a6', dashed:true},
  ];

  const unitBars = MX.units.map(u=>({label:u.nome.split(' ')[0], value:Math.round(u.fatMes*pf),
    color: activeUnits.includes(u.id)? u.cor : '#dcd5c7'}));

  const areaDonut = MX.areas.map(a=>({label:a.nome, value:Math.round(a.fatMes*pf*share), color:a.cor}));

  const ranked = [...MX.people].filter(p=>activeUnits.includes(p.unit)).sort((a,b)=>b.fatMes-a.fatMes).slice(0,7);
  const maxRank = ranked.length?ranked[0].fatMes:1;

  const casosFiltrados = MX.casos.filter(c=>activeUnits.includes(c.unit));
  const criticos = casosFiltrados.filter(c=>c.critico || c.status==='suspenso');

  const f = (n)=>MX.fmtBRL(n,{compact:true});
  const toggleUnit=(id)=> setUnits(prev=> prev.includes(id)? prev.filter(x=>x!==id) : [...prev,id]);

  return (
    <div className="content-inner">
      {/* Controles */}
      <div className="row between" style={{marginBottom:18,flexWrap:'wrap',gap:14}}>
        <div className="chips">
          {!restricted && (
            <button className={'chip'+(isAll?' on':'')} onClick={()=>setUnits([])}>
              <Icon name="layers" size={14}/> Todas as unidades
            </button>
          )}
          {MX.units.map(u=>{
            const on = restricted? u.id===restricted[0] : units.includes(u.id);
            const disabled = restricted && u.id!==restricted[0];
            return (
              <button key={u.id} className={'chip'+(on?' on':'')} disabled={disabled}
                style={disabled?{opacity:.4,cursor:'not-allowed'}:{}}
                onClick={()=>!restricted&&toggleUnit(u.id)}>
                <span className="cdot" style={{background:u.cor}}></span>{u.nome}
              </button>
            );
          })}
        </div>
        <div className="row gap12">
          <div className="seg">
            {[['mes','Mês'],['tri','Trimestre'],['ano','Ano']].map(([k,l])=>(
              <button key={k} className={period===k?'on':''} onClick={()=>setPeriod(k)}>{l}</button>
            ))}
          </div>
          <button className="btn btn-ghost" style={{height:40,padding:'0 14px'}} onClick={()=>onToast('Relatório executivo (PDF) gerado e enviado por e-mail.')}>
            <Icon name="download" size={16}/> Exportar
          </button>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid g-kpis stagger" style={{marginBottom:18}}>
        <KPI label={`Faturamento ${pLabel}`} icon="wallet" value={f(fat)}
          delta={MX.totals.varMes} deltaLabel={prevLabel} spark={consolSerie.slice(-7)} sparkColor="#b68b4c"/>
        <KPI label="Meta x realizado" icon="target" value={`${Math.round(fat/meta*100)}%`}
          delta={Math.round((fat/meta-1)*1000)/10} deltaLabel={`meta ${f(meta)}`} spark={metaSerie.slice(-7)} sparkColor="#3a4159"/>
        <KPI label="Casos ativos" icon="briefcase" value={MX.fmtNum(casosAtivos)}
          delta={6.1} deltaLabel={`${casosEnc} encerrados ${pLabel}`} spark={[40,42,41,44,46,45,casosAtivos]} sparkColor="#3f6079"/>
        <KPI label="Taxa de conversão" icon="trending" value={`${MX.totals.taxaConversao}%`}
          delta={2.4} deltaLabel="casos ganhos × ajuizados" spark={[68,70,69,71,72,72,73]} sparkColor="#3f7a57"/>
      </div>

      {/* Linha + Gauge */}
      <div className="grid g-chart-s" style={{marginBottom:18}}>
        <div className="card card-pad fade-up">
          <div className="card-h">
            <div>
              <h3>Evolução do faturamento</h3>
              <div className="ch-sub">{isAll?'Consolidado — todas as unidades':selUnits.map(u=>u.nome).join(', ')} · últimos 8 meses</div>
            </div>
            <div className="legend" style={{flexDirection:'row',gap:16}}>
              {lineSeries.map((s,i)=>(
                <div className="lg" key={i} style={{fontSize:11.5}}>
                  <span className="sw" style={{background:s.color,width:14,height:s.dashed?2:9,borderRadius:s.dashed?1:3}}></span>
                  <span className="ln">{s.name}</span>
                </div>
              ))}
            </div>
          </div>
          <LineChart series={lineSeries} labels={MX.meses} height={250} fmt={(v)=>MX.fmtBRL(v,{compact:true}).replace('R$ ','')}/>
        </div>
        <div className="card card-pad fade-up">
          <div className="card-h"><h3>Meta global</h3></div>
          <Gauge value={fat} max={meta} fmt={f}/>
          <div className="divider"></div>
          <div className="row between" style={{marginBottom:10}}>
            <span className="muted" style={{fontSize:12.5}}>Realizado</span>
            <b className="tnum">{MX.fmtBRL(fat)}</b>
          </div>
          <div className="row between" style={{marginBottom:10}}>
            <span className="muted" style={{fontSize:12.5}}>Meta {pLabel}</span>
            <b className="tnum">{MX.fmtBRL(meta)}</b>
          </div>
          <div className="row between">
            <span className="muted" style={{fontSize:12.5}}>Diferença</span>
            <b className="tnum" style={{color:fat>=meta?'var(--pos)':'var(--neg)'}}>{MX.fmtBRL(fat-meta,{sign:true})}</b>
          </div>
        </div>
      </div>

      {/* Unidades + Áreas */}
      <div className="grid g-asym" style={{marginBottom:18}}>
        <div className="card card-pad fade-up">
          <div className="card-h">
            <div><h3>Faturamento por unidade</h3><div className="ch-sub">{pLabel.charAt(0).toUpperCase()+pLabel.slice(1)} · ranking entre filiais</div></div>
          </div>
          <BarChart data={unitBars} fmt={(v)=>MX.fmtBRL(v,{compact:true}).replace('R$ ','')} height={210}/>
        </div>
        <div className="card card-pad fade-up">
          <div className="card-h"><div><h3>Receita por área</h3><div className="ch-sub">Distribuição por especialidade</div></div></div>
          <Donut data={areaDonut} total={MX.fmtNum(MX.areas.reduce((a,x)=>a+x.casos,0))} centerLabel="casos" fmt={f}/>
        </div>
      </div>

      {/* Top colaboradores + Indicadores */}
      <div className="grid g-2" style={{marginBottom:18}}>
        <div className="card card-pad fade-up">
          <div className="card-h"><div><h3>Top colaboradores</h3><div className="ch-sub">Por faturamento {pLabel}</div></div></div>
          <div>
            {ranked.map((p,i)=>(
              <div className="rank-row" key={p.id}>
                <div className="rk">{i+1}</div>
                <div>
                  <div className="row between" style={{marginBottom:0}}>
                    <span style={{fontWeight:600,fontSize:13}}>{p.nome}</span>
                    <b className="tnum" style={{fontSize:13}}>{MX.fmtBRL(Math.round(p.fatMes*pf),{compact:true})}</b>
                  </div>
                  <div className="rbar"><i style={{width:`${p.fatMes/maxRank*100}%`,background:i===0?'#b68b4c':'#3a4159'}}></i></div>
                  <div style={{fontSize:11,color:'var(--ink-3)',marginTop:4}}>{p.cargo} · {MX.unitById(p.unit).nome}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{display:'flex',flexDirection:'column',gap:18}}>
          <div className="card card-pad fade-up">
            <div className="card-h"><div><h3>Indicadores financeiros</h3></div></div>
            <div className="grid g-2" style={{gap:14}}>
              {[
                {l:'Realizado vs. a receber',v:f(Math.round(MX.totals.aReceber*share)),s:'em aberto'},
                {l:'Ticket médio',v:f(MX.totals.ticketMedio),s:'por caso'},
                {l:'Inadimplência',v:MX.totals.inadimplencia+'%',s:'da carteira'},
                {l:'Casos encerrados',v:MX.fmtNum(casosEnc),s:pLabel},
              ].map((x,i)=>(
                <div key={i} style={{background:'var(--surface-2)',border:'1px solid var(--border-2)',borderRadius:11,padding:'14px 15px'}}>
                  <div style={{fontSize:11.5,color:'var(--ink-2)',fontWeight:600,marginBottom:7}}>{x.l}</div>
                  <div style={{fontFamily:'Spectral,serif',fontSize:22,fontWeight:600}}>{x.v}</div>
                  <div style={{fontSize:11,color:'var(--ink-3)',marginTop:2}}>{x.s}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="card card-pad fade-up" style={{flex:1}}>
            <div className="card-h"><div><h3>Casos que exigem atenção</h3><div className="ch-sub">{criticos.length} casos críticos ou suspensos</div></div></div>
            <div style={{display:'flex',flexDirection:'column',gap:2}}>
              {criticos.slice(0,4).map(c=>(
                <div key={c.id} className="row gap12" style={{padding:'9px 0',borderBottom:'1px solid var(--border-2)'}}>
                  <div style={{width:34,height:34,borderRadius:9,display:'grid',placeItems:'center',background:c.critico?'var(--neg-bg)':'var(--warn-bg)',color:c.critico?'var(--neg)':'var(--warn)',flexShrink:0}}>
                    <Icon name={c.critico?'alert':'clock'} size={16}/>
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:13,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{c.titulo}</div>
                    <div style={{fontSize:11.5,color:'var(--ink-3)'}}>{c.id} · {c.cliente}</div>
                  </div>
                  <span className={'tag '+(c.critico?'critico':'suspenso')}>{c.critico?'Crítico':'Suspenso'}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.Dashboard = Dashboard;
