/* Componentes compartilhados — Login, Sidebar, Topbar, widgets */
const { useState:uS, useEffect:uE, useRef:uR } = React;

/* ---------------- LOGIN ---------------- */
function Login({onLogin}){
  const [perfil,setPerfil]=uS('ceo');
  const [show,setShow]=uS(false);
  const [remember,setRemember]=uS(true);
  const [email,setEmail]=uS('jean.barbosa@maximiano.adv.br');
  const [pwd,setPwd]=uS('••••••••••');
  const [loading,setLoading]=uS(false);
  const sel=MX.perfis.find(p=>p.id===perfil);

  uE(()=>{
    const map={ceo:'jean.barbosa',gestor:'joao.mendes',adv:'jackeline.batista',admin:'rodrigo'};
    setEmail(map[perfil]+'@maximiano.adv.br');
  },[perfil]);

  const submit=(e)=>{ e.preventDefault(); setLoading(true); setTimeout(()=>onLogin(perfil),650); };

  return (
    <div className="login">
      <div className="login-brand">
        <div className="lb-top">
          <img src="assets/logo-mark.png" alt="" style={{height:34}}/>
          <div style={{lineHeight:1.1}}>
            <div style={{fontFamily:'Spectral,serif',fontSize:16,fontWeight:600,color:'#fff',letterSpacing:'.02em'}}>Maximiano</div>
            <div style={{fontSize:9.5,letterSpacing:'.28em',color:'#cba968',textTransform:'uppercase',marginTop:2}}>Advogados</div>
          </div>
        </div>
        <div className="lb-mid">
          <h2>Portal Interno do escritório.</h2>
          <div className="lb-rule"></div>
          <p>Comunicação, faturamento, inteligência gerencial e atualização jurídica — reunidos em um só ambiente, seguro e controlado por perfil de acesso.</p>
        </div>
        <div className="lb-foot">ACESSO RESTRITO · COLABORADORES MAXIMIANO ADVOGADOS</div>
      </div>

      <div className="login-panel">
        <form className="login-card fade-up" onSubmit={submit}>
          <div className="eyebrow">Bem-vindo de volta</div>
          <h1>Acessar o portal</h1>
          <div className="sub">Entre com suas credenciais corporativas.</div>

          <div className="field">
            <label>E-mail corporativo</label>
            <div className="ctrl">
              <Icon name="mail" size={17}/>
              <input value={email} onChange={e=>setEmail(e.target.value)} autoComplete="off"/>
            </div>
          </div>
          <div className="field">
            <label>Senha</label>
            <div className="ctrl">
              <Icon name="lock" size={17}/>
              <input type={show?'text':'password'} value={pwd} onChange={e=>setPwd(e.target.value)}/>
              <button type="button" onClick={()=>setShow(s=>!s)} style={{color:'#8c8f9c',display:'grid',placeItems:'center'}}>
                <Icon name="eye" size={17}/>
              </button>
            </div>
          </div>

          <div className="login-row">
            <div className={'check'+(remember?' on':'')} onClick={()=>setRemember(r=>!r)}>
              <span className="box">{remember && <Icon name="check" size={12} stroke={3}/>}</span>
              Manter conectado
            </div>
            <a href="#" onClick={e=>e.preventDefault()}>Esqueci a senha</a>
          </div>

          <div className="role-pick">
            <div className="rp-label">Demonstração — entrar como</div>
            <div className="role-grid">
              {MX.perfis.map(p=>(
                <button type="button" key={p.id} className={'role-opt'+(perfil===p.id?' on':'')} onClick={()=>setPerfil(p.id)}>
                  <span className="ro-name">{p.papel.split('·')[0].trim()}</span>
                  <span className="ro-desc">{p.nome.replace('Dra. ','').replace('Dr. ','')}</span>
                </button>
              ))}
            </div>
          </div>

          <button className="btn btn-primary" style={{marginTop:24}} disabled={loading}>
            {loading? 'Entrando…' : <>Entrar no portal <Icon name="arrowRight" size={17}/></>}
          </button>
          <div style={{textAlign:'center',marginTop:18,fontSize:11.5,color:'#a9a294',display:'flex',alignItems:'center',justifyContent:'center',gap:6}}>
            <Icon name="shield" size={13}/> Conexão segura · MFA disponível · Sem cadastro público
          </div>
        </form>
      </div>
    </div>
  );
}

/* ---------------- SIDEBAR ---------------- */
function Sidebar({active,onNav,profile,unreadFeed,onLogout,allowed,open,onClose}){
  const nav=[
    {id:'dashboard',label:'Dashboard',icon:'dashboard'},
    {id:'feed',label:'Comunicação',icon:'megaphone',badge:unreadFeed},
    {id:'faturamento',label:'Faturamento',icon:'wallet'},
    {id:'juridico',label:'Jurídico em Foco',icon:'scale'},
    {id:'gestao',label:'Gestão',icon:'users'},
  ].filter(n=>allowed.includes(n.id));
  const showConfig=allowed.includes('config');
  return (
    <>
    <div className={'sb-overlay'+(open?' sb-open':'')} onClick={onClose}/>
    <aside className={'sidebar'+(open?' sb-open':'')}>
      <div className="sb-brand">
        <img src="assets/logo-mark.png" alt="Maximiano"/>
        <div className="sbb-txt">
          <div className="n">Maximiano</div>
          <div className="a">Advogados</div>
        </div>
        <button className="sb-close-btn" onClick={onClose}><Icon name="x" size={18}/></button>
      </div>
      <div className="sb-section">
        <div className="sb-cap">Menu</div>
        {nav.map(n=>(
          <button key={n.id} className={'nav-item'+(active===n.id?' on':'')} onClick={()=>onNav(n.id)}>
            <Icon name={n.icon} size={18}/>
            <span>{n.label}</span>
            {n.badge>0 && <span className="badge">{n.badge}</span>}
          </button>
        ))}
        <div className="sb-cap">Sistema</div>
        {showConfig && (
        <button className={'nav-item'+(active==='config'?' on':'')} onClick={()=>onNav('config')}>
          <Icon name="settings" size={18}/><span>Configurações</span>
        </button>)}
        <button className="nav-item" onClick={onLogout}>
          <Icon name="logout" size={18}/><span>Sair</span>
        </button>
      </div>
      <div className="sb-foot">
        <div className="sb-user" onClick={onLogout} title="Sair">
          <div className="avatar" style={{width:36,height:36}}>{profile.ini}</div>
          <div className="su-txt" style={{flex:1}}>
            <div className="nm">{profile.nome.replace('Dra. ','').replace('Dr. ','')}</div>
            <div className="rl">{profile.papel.split('·')[0].trim()}</div>
          </div>
          <Icon name="logout" size={17} style={{color:'#a7adc0'}}/>
        </div>
      </div>
    </aside>
    </>
  );
}

/* ---------------- TOPBAR ---------------- */
function Topbar({title,crumb,profile,onSwitch,right,onMenuOpen}){
  const [menu,setMenu]=uS(null); // 'profile' | 'notif' | null
  const ref=uR(null);
  uE(()=>{
    const h=e=>{ if(ref.current && !ref.current.contains(e.target)) setMenu(null); };
    document.addEventListener('mousedown',h); return ()=>document.removeEventListener('mousedown',h);
  },[]);
  const [notifs,setNotifs]=uS(MX.notifications);
  const unread=notifs.filter(n=>n.unread).length;
  const notifColors={gold:['#f5edde','#9a743b'],green:['#e7f0ea','#3f7a57'],red:['#f3e6e3','#a8554a'],navy:['#eef0f4','#3a4159']};

  return (
    <header className="topbar" ref={ref}>
      <button className="icon-btn mob-menu-btn" onClick={onMenuOpen}><Icon name="menu" size={20}/></button>
      <div className="tb-title">
        <div className="crumb">{crumb}</div>
        <h1>{title}</h1>
      </div>
      <div className="spacer"></div>
      {right}
      <div className="search">
        <Icon name="search" size={17}/>
        <input placeholder="Buscar no portal…"/>
      </div>
      <div style={{position:'relative'}}>
        <button className="icon-btn" onClick={()=>setMenu(menu==='notif'?null:'notif')}>
          <Icon name="bell" size={18}/>
          {unread>0 && <span className="dot"></span>}
        </button>
        {menu==='notif' && (
          <div className="menu pop" style={{right:0,top:50,width:360,padding:8}}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'8px 8px 10px'}}>
              <b style={{fontSize:14}}>Notificações</b>
              <button style={{fontSize:12,color:'#9a743b',fontWeight:600}} onClick={()=>setNotifs(notifs.map(n=>({...n,unread:false})))}>Marcar todas como lidas</button>
            </div>
            <div style={{maxHeight:380,overflow:'auto'}}>
              {notifs.map(n=>{
                const[bg,fg]=notifColors[n.cor];
                return (
                  <div key={n.id} className={'notif'+(n.unread?' unread':'')} onClick={()=>setNotifs(notifs.map(x=>x.id===n.id?{...x,unread:false}:x))}>
                    <div className="nic" style={{background:bg,color:fg}}><Icon name={n.icon} size={17}/></div>
                    <div className="ntx" style={{flex:1}}>
                      <div className="nt-t">{n.titulo}</div>
                      <div className="nt-m">{n.msg}</div>
                      <div className="nt-tm">{n.tempo}</div>
                    </div>
                    {n.unread && <span style={{width:8,height:8,borderRadius:'50%',background:'#b68b4c',flexShrink:0,marginTop:5}}></span>}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
      <div style={{position:'relative'}}>
        <button onClick={()=>setMenu(menu==='profile'?null:'profile')}
          style={{display:'flex',alignItems:'center',gap:10,padding:'5px 9px 5px 5px',borderRadius:10,border:'1px solid var(--border)',background:'var(--surface)'}}>
          <div className="avatar" style={{width:32,height:32}}>{profile.ini}</div>
          <div className="tb-profile-txt" style={{textAlign:'left',lineHeight:1.15}}>
            <div style={{fontSize:12.5,fontWeight:600,color:'var(--ink)',whiteSpace:'nowrap'}}>{profile.nome.replace('Dra. ','').replace('Dr. ','')}</div>
            <div style={{fontSize:10.5,color:'var(--ink-3)'}}>{profile.papel.split('·')[0].trim()}</div>
          </div>
          <Icon name="chevDown" size={15} style={{color:'var(--ink-3)'}}/>
        </button>
        {menu==='profile' && (
          <div className="menu pop" style={{right:0,top:52,width:288}}>
            <div className="menu-cap">Trocar de perfil (demo)</div>
            {MX.perfis.map(p=>(
              <button key={p.id} className={'menu-item'+(p.id===profile.id?' on':'')} onClick={()=>{onSwitch(p.id);setMenu(null);}}>
                <div className="avatar" style={{width:34,height:34,background:p.id===profile.id?'#b68b4c':'#3a4159'}}>{p.ini}</div>
                <div style={{minWidth:0}}>
                  <div style={{fontWeight:600,fontSize:13}}>{p.papel.split('·')[0].trim()}</div>
                  <div style={{fontSize:11,color:'var(--ink-3)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.desc}</div>
                </div>
                {p.id===profile.id && <Icon name="check" size={16} className="mi-tick" stroke={2.5}/>}
              </button>
            ))}
            <div className="divider" style={{margin:'6px 4px'}}></div>
            <button className="menu-item"><Icon name="settings" size={17}/> Preferências da conta</button>
            <button className="menu-item"><Icon name="logout" size={17}/> Encerrar sessão</button>
          </div>
        )}
      </div>
    </header>
  );
}

/* ---------------- WIDGETS ---------------- */
function KPI({label,icon,value,delta,deltaLabel,spark,sparkColor}){
  return (
    <div className="card kpi">
      <div className="k-label"><span className="k-ic"><Icon name={icon} size={16}/></span>{label}</div>
      <div className="k-val">{value}</div>
      <div className="k-foot">
        {delta!=null && <span className={'delta '+(delta>=0?'up':'down')}>
          <Icon name={delta>=0?'arrowUp':'arrowDown'} size={12} stroke={2.5}/>{Math.abs(delta).toLocaleString('pt-BR',{minimumFractionDigits:1,maximumFractionDigits:1})}%
        </span>}
        <span className="muted" style={{fontSize:12}}>{deltaLabel}</span>
      </div>
      {spark && <div className="k-spark"><Sparkline data={spark} color={sparkColor||'#b68b4c'} w={130} h={46}/></div>}
    </div>
  );
}

function Modal({title,onClose,children,foot}){
  return (
    <div className="overlay" onMouseDown={e=>{if(e.target===e.currentTarget)onClose();}}>
      <div className="modal">
        <div className="modal-h">
          <h3 style={{fontSize:18}}>{title}</h3>
          <button className="icon-btn" style={{width:34,height:34,border:'none',background:'var(--surface-2)'}} onClick={onClose}><Icon name="x" size={17}/></button>
        </div>
        <div className="modal-b">{children}</div>
        {foot && <div style={{padding:'16px 24px',borderTop:'1px solid var(--border-2)',display:'flex',justifyContent:'flex-end',gap:10}}>{foot}</div>}
      </div>
    </div>
  );
}

Object.assign(window,{ Login, Sidebar, Topbar, KPI, Modal });
