/* Views: Feed, Faturamento, Jurídico, Gestão, Config */
const { useState:vS, useMemo:vM } = React;

const canalCor = {Gestão:['#eef0f4','#3a4159'],RH:['#f5edde','#9a743b'],Jurídico:['#e6edf2','#3f6079'],Financeiro:['#e7f0ea','#3f7a57'],Geral:['#f3e6e3','#a8554a']};
const canPublish = (profile)=> profile.id==='ceo'||profile.id==='admin';

/* ============== FEED ============== */
function FeedView({profile,onToast}){
  const [posts,setPosts]=vS(MX.feed.map(p=>({...p})));
  const [canal,setCanal]=vS('Todos');
  const [compose,setCompose]=vS(false);
  const canais=['Todos','Gestão','RH','Jurídico','Financeiro'];
  const list = canal==='Todos'?posts:posts.filter(p=>p.canal===canal);

  const toggle=(id,key)=>setPosts(posts.map(p=>{
    if(p.id!==id) return p;
    const np={...p};
    if(key==='reagiu'){ np.reagiu=!p.reagiu; np.likes=p.likes+(p.reagiu?-1:1); }
    if(key==='imp'){ np.imp=!p.imp; np.importante=p.importante+(p.imp?-1:1); }
    return np;
  }));

  return (
    <div className="content-inner">
      <div className="feed-layout">
        <div>
          <div className="row gap8" style={{marginBottom:16,flexWrap:'wrap'}}>
            {canais.map(c=>(
              <button key={c} className={'chip'+(canal===c?' on':'')} onClick={()=>setCanal(c)}>{c}</button>
            ))}
          </div>

          {canPublish(profile) && (
            <div className="composer">
              <div className="cp-row">
                <div className="avatar" style={{width:40,height:40}}>{profile.ini}</div>
                <div className="cp-input" onClick={()=>setCompose(true)}>Compartilhar um comunicado com a equipe…</div>
                <button className="btn btn-gold" style={{height:42,padding:'0 16px'}} onClick={()=>setCompose(true)}>
                  <Icon name="plus" size={16}/> Publicar
                </button>
              </div>
            </div>
          )}

          <div className="stagger">
          {list.map(p=>{
            const [bg,fg]=canalCor[p.canal]||canalCor.Geral;
            return (
              <article key={p.id} className={'post'+(p.pinned?' pinned':'')}>
                <div className="post-h">
                  <div className="avatar" style={{width:42,height:42,background:p.ini==='JB'?'#b68b4c':'#3a4159'}}>{p.ini}</div>
                  <div className="ph-meta">
                    <div className="au">{p.autor}</div>
                    <div className="tm">{p.tempo} · <span className="audience"><Icon name="users" size={12}/> {p.audiencia}</span></div>
                  </div>
                  {p.pinned && <span className="post-pin"><Icon name="pin" size={12}/> Fixado</span>}
                </div>
                <div className="post-body">
                  <span className="post-ch" style={{background:bg,color:fg}}>{p.canal}</span>
                  <h3 style={{marginTop:10}}>{p.titulo}</h3>
                  <p>{p.corpo}</p>
                  {p.img && <div className="post-img placeholder-img" style={{height:200}}>imagem · resultados-1o-semestre.jpg</div>}
                  {p.anexo && (
                    <div className="post-attach">
                      <span className="pa-ic"><Icon name="file" size={16}/></span>
                      <span style={{flex:1}}>{p.anexo}</span>
                      <button className="icon-btn" style={{width:32,height:32}}><Icon name="download" size={15}/></button>
                    </div>
                  )}
                </div>
                <div className="post-foot">
                  <button className={'react-btn'+(p.reagiu?' on':'')} onClick={()=>toggle(p.id,'reagiu')}>
                    <Icon name="thumbsUp" size={15}/> Lido <b className="tnum">{p.likes}</b>
                  </button>
                  <button className={'react-btn'+(p.imp?' on':'')} onClick={()=>toggle(p.id,'imp')}>
                    <Icon name="star" size={15}/> Importante <b className="tnum">{p.importante}</b>
                  </button>
                  <button className="react-btn"><Icon name="comment" size={15}/> {p.comentarios}</button>
                  <span className="read-meta"><Icon name="eye" size={14}/> {p.lido} leram</span>
                </div>
              </article>
            );
          })}
          </div>
        </div>

        {/* right rail */}
        <div style={{display:'flex',flexDirection:'column',gap:16}}>
          <div className="card card-pad">
            <div className="section-title" style={{margin:'0 0 12px'}}>Engajamento</div>
            {[['Comunicados ativos','12'],['Taxa de leitura','87%'],['Não lidos por você','3']].map((x,i)=>(
              <div key={i} className="row between" style={{padding:'8px 0',borderBottom:i<2?'1px solid var(--border-2)':'none'}}>
                <span className="muted" style={{fontSize:13}}>{x[0]}</span><b style={{fontSize:14}}>{x[1]}</b>
              </div>
            ))}
          </div>
          <div className="card card-pad">
            <div className="section-title" style={{margin:'0 0 12px'}}>Canais</div>
            {Object.entries(canalCor).filter(([k])=>k!=='Geral').map(([k,[bg,fg]])=>(
              <div key={k} className="row between" style={{padding:'7px 0'}}>
                <span className="post-ch" style={{background:bg,color:fg}}>{k}</span>
                <span className="muted tnum" style={{fontSize:12.5}}>{Math.floor(Math.random()*6)+2} posts</span>
              </div>
            ))}
          </div>
          <div className="card card-pad" style={{background:'linear-gradient(160deg,#2d3245,#20253a)',color:'#fff',border:'none'}}>
            <Icon name="shield" size={22} style={{color:'#cba968'}}/>
            <h3 style={{color:'#fff',fontSize:16,margin:'12px 0 6px'}}>Publicações segmentadas</h3>
            <p style={{color:'#a7adc0',fontSize:12.5,lineHeight:1.55,margin:0}}>Cada colaborador vê apenas o que é direcionado ao seu perfil e unidade. A leitura é registrada automaticamente.</p>
          </div>
        </div>
      </div>

      {compose && <Composer profile={profile} onClose={()=>setCompose(false)} onPublish={(np)=>{
        setPosts([{...np,id:'new'+Date.now()},...posts]); setCompose(false); onToast('Publicação criada e enviada à audiência selecionada.');
      }}/>}
    </div>
  );
}

function Composer({profile,onClose,onPublish}){
  const [titulo,setTitulo]=vS('');
  const [corpo,setCorpo]=vS('');
  const [canal,setCanal]=vS('Gestão');
  const [aud,setAud]=vS('todos');
  const [unitsSel,setUnitsSel]=vS([]);
  const [agendar,setAgendar]=vS(false);
  const audMap={todos:'Todos os colaboradores',unidades:'Unidades selecionadas',perfis:'Perfis específicos',individual:'Usuários selecionados'};
  const audDesc = aud==='unidades' && unitsSel.length? unitsSel.map(u=>MX.unitById(u).nome).join(', ') : audMap[aud];

  return (
    <Modal title="Nova publicação" onClose={onClose} foot={<>
      <button className="btn btn-ghost" style={{height:42}} onClick={onClose}>Cancelar</button>
      <button className="btn btn-gold" style={{height:42}} disabled={!titulo.trim()}
        onClick={()=>onPublish({canal,autor:profile.nome,ini:profile.ini,tempo:'agora',pinned:false,
          titulo:titulo||'Nova publicação',corpo:corpo||'—',audiencia:audDesc,likes:0,importante:0,lido:0,comentarios:0,reagiu:false})}>
        {agendar?'Agendar':'Publicar'} <Icon name="arrowRight" size={16}/>
      </button></>}>
      <div className="field"><label>Canal</label>
        <div className="row gap8" style={{flexWrap:'wrap'}}>
          {['Gestão','RH','Jurídico','Financeiro','Geral'].map(c=>(
            <button key={c} className={'chip'+(canal===c?' on':'')} onClick={()=>setCanal(c)}>{c}</button>
          ))}
        </div>
      </div>
      <div className="field"><label>Título</label>
        <div className="ctrl"><input value={titulo} onChange={e=>setTitulo(e.target.value)} placeholder="Ex: Resultados do 1º semestre"/></div>
      </div>
      <div className="field"><label>Mensagem</label>
        <textarea value={corpo} onChange={e=>setCorpo(e.target.value)} rows={4} placeholder="Escreva o comunicado…"
          style={{width:'100%',background:'var(--surface-2)',border:'1px solid var(--border)',borderRadius:9,padding:'11px 13px',resize:'vertical',outline:'none',lineHeight:1.55}}/>
      </div>
      <div className="field"><label>Audiência</label>
        <div className="row gap8" style={{flexWrap:'wrap',marginBottom:10}}>
          {Object.entries(audMap).map(([k,v])=>(
            <button key={k} className={'chip'+(aud===k?' on':'')} onClick={()=>setAud(k)}>{v}</button>
          ))}
        </div>
        {aud==='unidades' && (
          <div className="row gap8" style={{flexWrap:'wrap'}}>
            {MX.units.map(u=>{
              const on=unitsSel.includes(u.id);
              return <button key={u.id} className={'chip'+(on?' on':'')}
                onClick={()=>setUnitsSel(on?unitsSel.filter(x=>x!==u.id):[...unitsSel,u.id])}>
                <span className="cdot" style={{background:u.cor}}></span>{u.nome}</button>;
            })}
          </div>
        )}
      </div>
      <div className="row between" style={{background:'var(--surface-2)',border:'1px solid var(--border-2)',borderRadius:10,padding:'11px 14px'}}>
        <div className="row gap12">
          <Icon name="calendar" size={17} style={{color:'var(--ink-3)'}}/>
          <div><div style={{fontSize:13,fontWeight:600}}>Agendar publicação</div><div style={{fontSize:11.5,color:'var(--ink-3)'}}>Definir data e hora de envio</div></div>
        </div>
        <div className={'check'+(agendar?' on':'')} onClick={()=>setAgendar(a=>!a)}>
          <span className="box">{agendar && <Icon name="check" size={12} stroke={3}/>}</span>
        </div>
      </div>
    </Modal>
  );
}

/* ============== FATURAMENTO INDIVIDUAL ============== */
function FaturamentoView({profile,onToast}){
  const pid = profile.pessoaId || (profile.id==='gestor'?5:1);
  const me = MX.personById(pid);
  const [period,setPeriod]=vS('mes');
  const pf = period==='mes'?1:period==='tri'?2.96:7.0;
  const fat = Math.round(me.fatMes*pf), meta=Math.round(me.meta*pf);
  const serie = MX.meses.map((m,i)=> Math.round(me.fatMes*(0.82+0.05*i+ (i%2?-0.03:0.03))));
  const tipos=[
    {label:'Contencioso',value:Math.round(fat*0.52),color:'#b68b4c'},
    {label:'Consultivo',value:Math.round(fat*0.31),color:'#3f6079'},
    {label:'Administrativo',value:Math.round(fat*0.17),color:'#3f7a57'},
  ];
  const meusCasos = MX.casos.filter(c=>c.resp===pid);
  const f=(n)=>MX.fmtBRL(n,{compact:true});
  const pct=Math.round(fat/meta*100);

  return (
    <div className="content-inner">
      <div className="row between" style={{marginBottom:18,flexWrap:'wrap',gap:12}}>
        <div className="row gap12">
          <div className="avatar" style={{width:46,height:46,fontSize:16}}>{me.ini}</div>
          <div>
            <div style={{fontFamily:'Spectral,serif',fontSize:19,fontWeight:600}}>{me.nome}</div>
            <div style={{fontSize:12.5,color:'var(--ink-3)'}}>{me.cargo} · {MX.unitById(me.unit).nome}</div>
          </div>
        </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('Extrato exportado em PDF.')}><Icon name="download" size={16}/> Extrato</button>
        </div>
      </div>

      <div className="grid g-kpis stagger" style={{marginBottom:18}}>
        <KPI label="Meu faturamento" icon="wallet" value={f(fat)} delta={9.2} deltaLabel="vs. período anterior" spark={serie.slice(-7)}/>
        <KPI label="Meta atingida" icon="target" value={pct+'%'} delta={(fat/meta-1)*100} deltaLabel={`meta ${f(meta)}`} spark={[78,82,80,88,92,96,pct]} sparkColor="#3a4159"/>
        <KPI label="Casos ativos" icon="briefcase" value={me.casosAtivos} delta={4.0} deltaLabel={`${me.casosEnc} encerrados`} spark={[7,8,9,10,10,11,me.casosAtivos]} sparkColor="#3f6079"/>
        <KPI label="Taxa de êxito" icon="trending" value={me.exito+'%'} delta={1.8} deltaLabel="casos ganhos" spark={[80,82,81,83,84,84,me.exito]} sparkColor="#3f7a57"/>
      </div>

      <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 meu faturamento</h3><div className="ch-sub">Honorários atribuídos · últimos 8 meses</div></div></div>
          <LineChart series={[{name:'Faturamento',data:serie,color:'#b68b4c',fill:true},{name:'Meta',data:MX.meses.map(()=>me.meta),color:'#3a4159',dashed:true}]} labels={MX.meses} height={240} fmt={(v)=>MX.fmtBRL(v,{compact:true}).replace('R$ ','')}/>
        </div>
        <div className="card card-pad fade-up">
          <div className="card-h"><div><h3>Por tipo de serviço</h3></div></div>
          <Donut data={tipos} total={f(fat).replace('R$ ','')} centerLabel={pLabelOf(period)} fmt={f} size={150} thickness={22}/>
        </div>
      </div>

      <div className="card card-pad fade-up">
        <div className="card-h">
          <div><h3>Meus casos</h3><div className="ch-sub">{meusCasos.length} casos vinculados a você</div></div>
        </div>
        <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Processo</th><th>Cliente</th><th>Área</th><th>Status</th><th className="num">Honorários</th></tr></thead>
          <tbody>
            {meusCasos.length?meusCasos.map(c=>(
              <tr key={c.id}>
                <td><b style={{fontSize:12.5}}>{c.id}</b><div style={{fontSize:11.5,color:'var(--ink-3)'}}>{c.titulo}</div></td>
                <td>{c.cliente}</td>
                <td><span className="post-ch" style={{background:'var(--navy-tint)',color:'var(--navy-600)'}}>{MX.areaById(c.area).nome}</span></td>
                <td><span className={'tag '+c.status}>{statusLabel(c.status)}</span></td>
                <td className="num"><b className="tnum">{MX.fmtBRL(c.valor)}</b></td>
              </tr>
            )):<tr><td colSpan="5" style={{textAlign:'center',color:'var(--ink-3)',padding:'24px'}}>Nenhum caso vinculado neste período.</td></tr>}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}
function pLabelOf(p){return p==='mes'?'mês':p==='tri'?'trim.':'ano';}
function statusLabel(s){return {andamento:'Em andamento',encerrado:'Encerrado',suspenso:'Suspenso'}[s];}

/* ============== JURÍDICO ============== */
const jurCatCor={gold:['#f5edde','#9a743b'],info:['#e6edf2','#3f6079'],navy:['#eef0f4','#3a4159'],green:['#e7f0ea','#3f7a57']};
function JuridicoView({onToast}){
  const [cat,setCat]=vS('Todas');
  const [onlySaved,setOnlySaved]=vS(false);
  const [items,setItems]=vS(MX.juridico.map(j=>({...j})));
  const cats=['Todas','Legislação','Jurisprudência','Trabalhista','Cível','Criminal','Tributário'];
  let list=items;
  if(cat!=='Todas') list=list.filter(j=>j.cat===cat);
  if(onlySaved) list=list.filter(j=>j.salvo);
  const toggleSave=(id)=>setItems(items.map(j=>j.id===id?{...j,salvo:!j.salvo}:j));

  return (
    <div className="content-inner">
      <div className="row between" style={{marginBottom:18,flexWrap:'wrap',gap:12}}>
        <div className="row gap8" style={{flexWrap:'wrap'}}>
          {cats.map(c=><button key={c} className={'chip'+(cat===c?' on':'')} onClick={()=>setCat(c)}>{c}</button>)}
        </div>
        <button className={'chip'+(onlySaved?' on':'')} onClick={()=>setOnlySaved(s=>!s)}><Icon name="bookmark" size={14}/> Salvos</button>
      </div>

      {/* destaque */}
      {cat==='Todas' && !onlySaved && (()=>{ const j=items[0]; const[bg,fg]=jurCatCor[j.cor]; return (
        <div className="card fade-up g-dest" style={{marginBottom:18,overflow:'hidden'}}>
          <div style={{padding:'26px 28px'}}>
            <div className="row gap8">
              <span className="jur-cat" style={{background:bg,color:fg}}>{j.cat}</span>
              {j.urgente && <span className="jur-cat" style={{background:'var(--neg-bg)',color:'var(--neg)'}}><Icon name="alert" size={12}/> Urgente</span>}
            </div>
            <h2 style={{fontSize:25,margin:'14px 0 10px',lineHeight:1.2}}>{j.titulo}</h2>
            <p style={{color:'var(--ink-2)',fontSize:14,lineHeight:1.6,maxWidth:560}}>{j.resumo}</p>
            <div className="jur-foot" style={{marginTop:18}}>
              <span><Icon name="building" size={13} style={{verticalAlign:-2,marginRight:4}}/>{j.fonte}</span>
              <span>{j.data}</span><span>{j.leitura} de leitura</span>
              <button className={'save'+(j.salvo?' on':'')} onClick={()=>toggleSave(j.id)}><Icon name="bookmark" size={14}/> {j.salvo?'Salvo':'Salvar'}</button>
            </div>
          </div>
          <div className="placeholder-img" style={{minHeight:200}}>imagem · destaque-juridico.jpg</div>
        </div>
      );})()}

      <div className="jur-grid">
        {list.slice(cat==='Todas'&&!onlySaved?1:0).map(j=>{
          const[bg,fg]=jurCatCor[j.cor];
          return (
            <div key={j.id} className="jur-card fade-up">
              {j.urgente && <span className="urgent-flag">Urgente</span>}
              <span className="jur-cat" style={{background:bg,color:fg}}>{j.cat}</span>
              <h3>{j.titulo}</h3>
              <p>{j.resumo}</p>
              <div className="jur-foot">
                <span>{j.data}</span><span>{j.leitura}</span>
                <button className={'save'+(j.salvo?' on':'')} onClick={()=>toggleSave(j.id)}><Icon name="bookmark" size={13}/> {j.salvo?'Salvo':'Salvar'}</button>
              </div>
            </div>
          );
        })}
      </div>
      {list.length===0 && <div style={{textAlign:'center',color:'var(--ink-3)',padding:'48px'}}>Nenhuma novidade nesta seleção.</div>}
    </div>
  );
}

window.FeedView=FeedView; window.FaturamentoView=FaturamentoView; window.JuridicoView=JuridicoView;
