// SGAB v2 — Dashboard
const { useState, useEffect } = React;

function Dashboard({ user, toast, onNav }) {
  const db = SGAB.getDB();
  const { fmt } = SGAB;
  const isAdmin = user.perfil === 'administrador';

  // ── FINANCIAL KPIs ─────────────────────────────────────────
  const receber = db.financeiro.receber;
  const pagar   = db.financeiro.pagar;
  const totalReceber = receber.filter(r=>r.status!=='Recebida').reduce((s,r)=>s+r.valor,0);
  const totalRecebido = receber.filter(r=>r.status==='Recebida').reduce((s,r)=>s+r.valor,0);
  const totalPagar    = pagar.filter(p=>p.status==='Pendente').reduce((s,p)=>s+p.valor,0);
  const totalPago     = pagar.filter(p=>p.status==='Paga').reduce((s,p)=>s+p.valor,0);
  const saldo = totalRecebido - totalPago;

  const osTotal = db.ordens.length;
  const osConcluidas = db.ordens.filter(o=>o.status==='Concluída').length;
  const osAgendadas  = db.ordens.filter(o=>o.status==='Agendada').length;
  const alertas = SGAB.getAlertas(db);

  // Calibrações vencendo em 30 dias
  const calibVencendo = db.equipamentos.filter(eq => {
    const d = fmt.daysTo(eq.proxCalib);
    return d !== null && d <= 30;
  }).length;

  // Estoque abaixo do mínimo
  const estoqueBaixo = db.estoque.filter(p => p.qtd <= p.estoqMin).length;

  // Faturamento mensal simulado (últimos 6 meses)
  const meses = ['Dez','Jan','Fev','Mar','Abr','Mai'];
  const fatMensal = [1800, 2400, 1600, 3200, 2800, 3500];
  const maxFat = Math.max(...fatMensal);

  // Ordens recentes
  const ordensRecentes = [...db.ordens].sort((a,b)=>b.data.localeCompare(a.data)).slice(0,5);

  // Próximas calibrações
  const proximasCalib = db.equipamentos
    .filter(eq=>eq.proxCalib)
    .sort((a,b)=>a.proxCalib.localeCompare(b.proxCalib))
    .slice(0,4);

  const tiposOS = ['Calibração RBC','Calibração Rastreada','Manutenção Corretiva','Manutenção Preventiva'];
  const tipoColors = ['#1E6FD9','#16A34A','#D97706','#8B5CF6'];
  const tipoCount  = tiposOS.map(t => db.ordens.filter(o=>o.tipo===t).length);
  const tipoMax    = Math.max(...tipoCount, 1);

  return (
    <div style={{opacity:1}}>
      {/* ALERTAS TOP */}
      {alertas.length > 0 && (
        <div style={{marginBottom:24}}>
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:12}}>
            <Icon name="bell" size={16} color="#D97706"/>
            <span style={{fontSize:13,fontWeight:700,color:'#92400E'}}>Atenção necessária — {alertas.length} alerta(s)</span>
          </div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(340px,1fr))',gap:8}}>
            {alertas.slice(0,4).map((al,i)=>{
              const target = {calibracao:'equipamentos',receber:'financeiro',pagar:'financeiro',estoque:'estoque'}[al.tipo];
              return <AlertItem key={i} {...al} onClick={target?()=>onNav(target):undefined}/>;
            })}
          </div>
          {alertas.length > 4 && <button onClick={()=>onNav('relatorios')} style={{marginTop:8,background:'none',border:'none',fontSize:12,color:'#1E6FD9',cursor:'pointer',fontFamily:'inherit',fontWeight:600}}>Ver todos os {alertas.length} alertas →</button>}
        </div>
      )}

      {/* KPI GRID */}
      {isAdmin ? (
        <div className="sgab-kpi-grid" style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:16,marginBottom:24}}>
          <KpiCard label="A Receber" value={fmt.money(totalReceber)} sub={`${receber.filter(r=>r.status!=='Recebida').length} conta(s) pendente(s)`} icon="financeiro" color="#D97706" onClick={()=>onNav('financeiro')}/>
          <KpiCard label="Recebido (Mês)" value={fmt.money(totalRecebido)} sub="Contas liquidadas" icon="trend" color="#16A34A" trend={12} onClick={()=>onNav('financeiro')}/>
          <KpiCard label="Saldo Atual" value={fmt.money(saldo)} sub="Recebido − Pago" icon="financeiro" color={saldo>=0?'#1E6FD9':'#DC2626'} onClick={()=>onNav('financeiro')}/>
          <KpiCard label="A Pagar" value={fmt.money(totalPagar)} sub={`${pagar.filter(p=>p.status==='Pendente').length} conta(s) pendente(s)`} icon="arrowDown" color="#DC2626" onClick={()=>onNav('financeiro')}/>
        </div>
      ) : null}

      <div className="sgab-kpi-grid" style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:16,marginBottom:24}}>
        <KpiCard label="OS Este Mês" value={osTotal} sub={`${osConcluidas} concluída(s)`} icon="ordens" color="#1E6FD9" onClick={()=>onNav('ordens')}/>
        <KpiCard label="Agendadas" value={osAgendadas} sub="Próximos serviços" icon="agenda" color="#8B5CF6" onClick={()=>onNav('agenda')}/>
        <KpiCard label="Calib. Vencendo" value={calibVencendo} sub="Próximos 30 dias" icon="calibracao" color="#D97706" onClick={()=>onNav('equipamentos')}/>
        <KpiCard label="Estoque Baixo" value={estoqueBaixo} sub="Itens abaixo do mínimo" icon="estoque" color={estoqueBaixo>0?'#DC2626':'#16A34A'} onClick={()=>onNav('estoque')}/>
      </div>

      {/* MAIN GRID */}
      <div className="sgab-main-grid" style={{display:'grid',gridTemplateColumns:'1fr 360px',gap:20,marginBottom:20}}>
        {/* FATURAMENTO CHART */}
        {isAdmin && (
          <Card style={{padding:24}}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:20}}>
              <div>
                <h3 style={{margin:0,fontSize:15,fontWeight:800,color:'#0D1B2A'}}>Faturamento — Últimos 6 Meses</h3>
                <p style={{margin:'3px 0 0',fontSize:12,color:'#9CA3AF'}}>Valores recebidos por mês</p>
              </div>
              <Badge color="blue">Mai 2026</Badge>
            </div>
            <div style={{display:'flex',alignItems:'flex-end',gap:8,height:160}}>
              {meses.map((m,i)=>(
                <div key={m} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:6}}>
                  <span style={{fontSize:10,fontWeight:700,color:'#6B7280'}}>{fmt.money(fatMensal[i]).replace('R$\u00a0','').replace(',00','')}</span>
                  <div style={{width:'100%',borderRadius:6,overflow:'hidden',height:120,display:'flex',alignItems:'flex-end',background:'#F8FAFF'}}>
                    <div style={{width:'100%',borderRadius:6,background:i===5?'linear-gradient(180deg,#1E6FD9,#60A5FA)':'#BFDBFE',
                      height:`${(fatMensal[i]/maxFat)*100}%`,transition:'height 0.4s ease',minHeight:4}}></div>
                  </div>
                  <span style={{fontSize:11,fontWeight:i===5?700:500,color:i===5?'#1E6FD9':'#9CA3AF'}}>{m}</span>
                </div>
              ))}
            </div>
          </Card>
        )}

        {/* TIPOS DE SERVIÇO */}
        <Card style={{padding:24}}>
          <h3 style={{margin:'0 0 16px',fontSize:15,fontWeight:800,color:'#0D1B2A'}}>Serviços por Tipo</h3>
          <div style={{display:'flex',flexDirection:'column',gap:14}}>
            {tiposOS.map((t,i)=>(
              <div key={t}>
                <div style={{display:'flex',justifyContent:'space-between',marginBottom:5}}>
                  <span style={{fontSize:12,fontWeight:600,color:'#374151'}}>{t}</span>
                  <span style={{fontSize:12,fontWeight:700,color:tipoColors[i]}}>{tipoCount[i]}</span>
                </div>
                <div style={{height:7,borderRadius:4,background:'#F1F5F9',overflow:'hidden'}}>
                  <div style={{height:'100%',borderRadius:4,background:tipoColors[i],width:`${(tipoCount[i]/tipoMax)*100}%`,transition:'width 0.5s ease'}}></div>
                </div>
              </div>
            ))}
          </div>
          <Divider/>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
            <div onClick={()=>onNav('clientes')}
              onMouseEnter={e=>{e.currentTarget.style.transform='translateY(-1px)';e.currentTarget.style.boxShadow='0 4px 12px rgba(22,163,74,0.18)';}}
              onMouseLeave={e=>{e.currentTarget.style.transform='';e.currentTarget.style.boxShadow='';}}
              style={{padding:'10px 14px',borderRadius:10,background:'#F0FDF4',border:'1px solid #BBF7D0',cursor:'pointer',transition:'all 0.15s'}}>
              <p style={{margin:0,fontSize:10,fontWeight:700,color:'#15803D',textTransform:'uppercase',letterSpacing:'0.04em'}}>Clientes</p>
              <p style={{margin:'4px 0 0',fontSize:20,fontWeight:800,color:'#15803D'}}>{db.clientes.filter(c=>c.ativo).length}</p>
            </div>
            <div onClick={()=>onNav('equipamentos')}
              onMouseEnter={e=>{e.currentTarget.style.transform='translateY(-1px)';e.currentTarget.style.boxShadow='0 4px 12px rgba(30,64,175,0.18)';}}
              onMouseLeave={e=>{e.currentTarget.style.transform='';e.currentTarget.style.boxShadow='';}}
              style={{padding:'10px 14px',borderRadius:10,background:'#EFF6FF',border:'1px solid #BFDBFE',cursor:'pointer',transition:'all 0.15s'}}>
              <p style={{margin:0,fontSize:10,fontWeight:700,color:'#1D4ED8',textTransform:'uppercase',letterSpacing:'0.04em'}}>Equipamentos</p>
              <p style={{margin:'4px 0 0',fontSize:20,fontWeight:800,color:'#1D4ED8'}}>{db.equipamentos.filter(e=>e.ativo).length}</p>
            </div>
          </div>
        </Card>
      </div>

      <div className="sgab-2col-grid" style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:20}}>
        {/* ORDENS RECENTES */}
        <Card style={{padding:0}}>
          <div style={{padding:'18px 20px',borderBottom:'1px solid #F1F5F9',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
            <h3 style={{margin:0,fontSize:15,fontWeight:800,color:'#0D1B2A'}}>Últimas Ordens de Serviço</h3>
            <Btn variant="ghost" size="sm" onClick={()=>onNav('ordens')}>Ver todas</Btn>
          </div>
          <div style={{padding:16}}>
            {ordensRecentes.map(os=>{
              const cli = db.clientes.find(c=>c.id===os.clienteId);
              return (
                <div key={os.id} onClick={()=>onNav('ordens')} style={{display:'flex',alignItems:'center',gap:12,padding:'10px 8px',borderRadius:8,cursor:'pointer',transition:'background 0.1s',marginBottom:4}}
                  onMouseEnter={e=>e.currentTarget.style.background='#F8FAFF'} onMouseLeave={e=>e.currentTarget.style.background=''}>
                  <div style={{width:36,height:36,borderRadius:9,background:'#EFF6FF',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                    <Icon name="ordens" size={17} color="#1E6FD9"/>
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:13,fontWeight:700,color:'#111827',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{os.numero}</div>
                    <div style={{fontSize:12,color:'#6B7280'}}>{cli?.fantasia} — {os.tipo}</div>
                  </div>
                  <div style={{textAlign:'right',flexShrink:0}}>
                    <StatusBadge status={os.status}/>
                    <div style={{fontSize:11,color:'#9CA3AF',marginTop:3}}>{fmt.date(os.data)}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* PRÓXIMAS CALIBRAÇÕES */}
        <Card style={{padding:0}}>
          <div style={{padding:'18px 20px',borderBottom:'1px solid #F1F5F9',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
            <h3 style={{margin:0,fontSize:15,fontWeight:800,color:'#0D1B2A'}}>Vencimento de Calibrações</h3>
            <Btn variant="ghost" size="sm" onClick={()=>onNav('equipamentos')}>Ver todos</Btn>
          </div>
          <div style={{padding:16}}>
            {proximasCalib.map(eq=>{
              const cli = db.clientes.find(c=>c.id===eq.clienteId);
              const dias = fmt.daysTo(eq.proxCalib);
              const cor = dias!==null&&dias<0?'#DC2626':dias!==null&&dias<=7?'#DC2626':dias!==null&&dias<=30?'#D97706':'#16A34A';
              const bgCor = dias!==null&&dias<0?'#FEF2F2':dias!==null&&dias<=7?'#FEF2F2':dias!==null&&dias<=30?'#FFFBEB':'#F0FDF4';
              return (
                <div key={eq.id} style={{display:'flex',alignItems:'center',gap:12,padding:'10px 8px',borderRadius:8,marginBottom:4}}>
                  <div style={{width:36,height:36,borderRadius:9,background:bgCor,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                    <Icon name="calibracao" size={17} color={cor}/>
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:13,fontWeight:700,color:'#111827'}}>{eq.tag} — {eq.modelo}</div>
                    <div style={{fontSize:12,color:'#6B7280'}}>{cli?.fantasia} • {eq.tipoCalib}</div>
                  </div>
                  <div style={{textAlign:'right',flexShrink:0}}>
                    <span style={{fontSize:11,fontWeight:700,color:cor,background:bgCor,padding:'3px 8px',borderRadius:6}}>
                      {dias===null?'—':dias<0?`${-dias}d vencida`:`${dias}d`}
                    </span>
                    <div style={{fontSize:10,color:'#9CA3AF',marginTop:3}}>{fmt.date(eq.proxCalib)}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
