/* ============================================================
   FLOWSHIELD — Dashboard
   ============================================================ */
function TeamLaunch({ theme, icon, kicker, title, desc, stat, statLabel, onClick }) {
  const ref = useRefL(null);
  const onMove = (e) => {
    const el = ref.current; if (!el) return; const b = el.getBoundingClientRect();
    el.style.setProperty('--mx', ((e.clientX-b.left)/b.width)*100+'%');
    el.style.setProperty('--my', ((e.clientY-b.top)/b.height)*100+'%');
  };
  return (
    <div ref={ref} onMouseMove={onMove} onClick={onClick} className={'tool-card theme-'+theme} style={{ flexDirection:'column', padding:22, minHeight:188 }}>
      <span className="bracket tl" /><span className="bracket tr" /><span className="bracket bl" /><span className="bracket br" />
      <div style={{ display:'flex', justifyContent:'space-between', width:'100%', alignItems:'flex-start', position:'relative', zIndex:1 }}>
        <div className="tool-ico" style={{ width:50, height:50 }}><Icon name={icon} size={26} /></div>
        <Icon name="chevron" size={18} style={{ color:'var(--acc)' }} />
      </div>
      <div className="mono upper" style={{ fontSize:10, color:'var(--acc)', marginTop:16, letterSpacing:'.16em' }}>{kicker}</div>
      <div className="disp" style={{ fontSize:21, fontWeight:700, color:'var(--txt-hi)', margin:'6px 0 6px', position:'relative', zIndex:1 }}>{title}</div>
      <div style={{ fontSize:12.5, color:'var(--txt-dim)', lineHeight:1.5, position:'relative', zIndex:1 }}>{desc}</div>
      <div style={{ flex:1 }} />
      <div style={{ display:'flex', alignItems:'baseline', gap:8, marginTop:16, position:'relative', zIndex:1 }}>
        <span className="disp" style={{ fontSize:26, fontWeight:700, color:'var(--acc)' }}>{stat}</span>
        <span className="mono" style={{ fontSize:10.5, color:'var(--txt-mute)' }}>{statLabel}</span>
      </div>
    </div>
  );
}

function Dashboard({ onNav }) {
  const [ov, setOv] = useStateL(null);
  const [demo, setDemo] = useStateL(false);
  const load = () => {
    window.fsApi('/api/results/overview', { method:'GET' })
      .then(d => { setOv(d); setDemo(!d || !d.scans || d.scans.total === 0); })
      .catch(() => { setDemo(true); });
  };
  useEffectL(() => { load(); }, []);
  const F = ov && ov.findings;
  const sevData = F ? F.sev : { crit:2, high:4, med:3, low:2 };
  const openN = F ? F.status.open : 9;
  const recentScans = (ov && ov.scans && ov.scans.recent && ov.scans.recent.length)
    ? ov.scans.recent.slice(0,4) : window.SEED_SCANS.slice(0,4);
  const btScore = ov && ov.blueteam_score != null ? ov.blueteam_score : null;
  const surf = (ov && ov.surface) || null;
  const compN = ov && ov.compliance_scans != null ? ov.compliance_scans : null;
  const maxSev = Math.max(1, sevData.crit||0, sevData.high||0, sevData.med||0, sevData.low||0);
  return (
    <div className="enter">
      <PageHeader title="Centro de operaciones" crumb="FLOWSHIELD / DASHBOARD"
        sub="Estado consolidado de la postura de seguridad del workspace en tiempo real."
        right={<><Btn variant="ghost" icon="reload" onClick={load}>Actualizar</Btn><Btn variant="primary" icon="bolt" onClick={()=>onNav('redteam')} className="theme-fs">Nuevo escaneo</Btn></>} />
      {demo && <DemoBanner what="escaneos" />}

      {/* three teams */}
      <div className="eyebrow theme-fs">Operaciones</div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16, marginBottom:30 }}>
        <TeamLaunch theme="red" icon="crosshair" kicker="// ofensiva" title="Red Team" desc="Reconocimiento, escaneo de vulnerabilidades y explotación controlada." stat={String(openN)} statLabel="hallazgos abiertos" onClick={()=>onNav('redteam')} />
        <TeamLaunch theme="blue" icon="shield" kicker="// defensa" title="Blue Team" desc="Hardening de servidores, redes y servicios según CIS Benchmark." stat={btScore!=null?btScore+'%':'—'} statLabel="cumplimiento CIS" onClick={()=>onNav('blueteam')} />
        <TeamLaunch theme="amber" icon="scroll" kicker="// cumplimiento" title="Normativa" desc="ENS, ISO 27001, NIST, PCI-DSS, RGPD y CIS Controls mapeados." stat={compN!=null?String(compN):'—'} statLabel="escaneos normativa" onClick={()=>onNav('normativa')} />
      </div>

      {/* posture row */}
      <div style={{ display:'grid', gridTemplateColumns:'1.3fr 1fr', gap:16, marginBottom:16 }}>
        <div className="panel theme-red" style={{ padding:22 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:18 }}>
            <div className="eyebrow" style={{ margin:0 }}>Resumen de vulnerabilidades</div>
            <span className="mono" style={{ fontSize:10.5, color:'var(--txt-mute)' }}>últimos 14 días</span>
          </div>
          <div style={{ display:'flex', gap:26, alignItems:'center' }}>
            <SevDonut data={sevData} />
            <div style={{ flex:1, display:'grid', gap:10 }}>
              {[['crit','Críticos'],['high','Altos'],['med','Medios'],['low','Bajos']].map(([k,l])=>{
                const n = sevData[k]||0;
                return (
                <div key={k} style={{ display:'flex', alignItems:'center', gap:10 }}>
                  <span className="dot" style={{ background:`var(--sev-${k})`, boxShadow:`0 0 6px var(--sev-${k})` }} />
                  <span style={{ flex:1, fontSize:13, color:'var(--txt)' }}>{l}</span>
                  <div className="bar" style={{ width:120 }}><span style={{ width:(n/maxSev*100)+'%', background:`var(--sev-${k})`, boxShadow:`0 0 8px var(--sev-${k})` }} /></div>
                  <span className="mono" style={{ fontSize:12, color:'var(--txt-hi)', width:18, textAlign:'right' }}>{n}</span>
                </div>
              );})}
            </div>
          </div>
        </div>

        <div className="panel theme-blue" style={{ padding:22, display:'flex', flexDirection:'column' }}>
          <div className="eyebrow" style={{ marginBottom:14 }}>Postura defensiva</div>
          <div style={{ display:'flex', gap:18, alignItems:'center', flex:1 }}>
            <Gauge value={btScore!=null?btScore:0} color="var(--blue)" sub="CIS GLOBAL" size={108} />
            <div style={{ flex:1, display:'grid', gap:9 }}>
              <Row k="Último escaneo CIS" v={btScore!=null?btScore+'%':'sin datos'} c={btScore!=null?'var(--blue)':'var(--txt-mute)'} />
              <Row k="Escaneos Blue Team" v={ov ? String((ov.scans.recent||[]).filter(s=>s.team==='blue').length || '—') : '—'} />
              <Row k="Ir al módulo" v="Blue Team →" c="var(--blue)" />
            </div>
          </div>
        </div>
      </div>

      {/* scan activity */}
      <div className="eyebrow theme-fs">Actividad de escaneo</div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16, marginBottom:30 }}>
        <Stat label="Activos descubiertos" value={surf ? surf.hosts : 0} icon="surface" accent="var(--fs)" />
        <Stat label="Escaneos realizados" value={ov ? ov.scans.total : 0} icon="scan" accent="var(--blue)" />
        <Stat label="Hallazgos abiertos" value={openN} icon="findings" accent="var(--red)" />
        <Stat label="Activos en riesgo" value={surf ? surf.at_risk : 0} icon="alert" accent="var(--amber)" />
      </div>

      {/* recent scans */}
      <div className="panel" style={{ overflow:'hidden', marginBottom:30 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'16px 20px', borderBottom:'1px solid var(--line)' }}>
          <div className="eyebrow theme-fs" style={{ margin:0 }}>Escaneos recientes</div>
          <button onClick={()=>onNav('scans')} style={{ background:'none', border:'none', color:'var(--fs)', fontSize:12, cursor:'pointer', fontFamily:'var(--font-mono)' }}>ver todos →</button>
        </div>
        <table className="tbl">
          <thead><tr><th>ID</th><th>Herramienta</th><th>Objetivo</th><th>Estado</th><th>Hallazgos</th><th>Fecha</th></tr></thead>
          <tbody>
            {recentScans.map(s => (
              <tr key={s.id} style={{ cursor:'pointer' }} onClick={()=>onNav('scans')}>
                <td className="mono" style={{ color:'var(--fs)' }}>{s.code||s.id}</td>
                <td style={{ color:'var(--txt-hi)', fontWeight:500 }}><span style={{ display:'inline-flex', alignItems:'center', gap:8 }}><span className="dot" style={{ background:s.team==='red'?'var(--red)':s.team==='amber'?'var(--amber)':'var(--blue)' }} />{s.tool}</span></td>
                <td className="mono" style={{ color:'var(--txt-dim)' }}>{s.target}</td>
                <td><StatusBadge status={s.status} /></td>
                <td>{s.status==='running' ? <span className="mono" style={{ color:'var(--blue)', fontSize:12 }}>{s.progress}%</span> : (
                  (s.found && (s.found.crit||s.found.high||s.found.med||s.found.low)) ? <div style={{ display:'flex', gap:5 }}>
                    {['crit','high','med','low'].map(k => s.found[k] ? <span key={k} className={'badge '+window.sevClass(k)} style={{ padding:'1px 7px', fontSize:10 }}>{s.found[k]}</span> : null)}
                  </div> : <span className="mono" style={{ color:'var(--txt-mute)', fontSize:11 }}>—</span>
                )}</td>
                <td className="mono" style={{ color:'var(--txt-mute)', fontSize:11.5 }}>{window.rptDate?window.rptDate(s.date):s.date}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Row({ k, v, c }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:12.5 }}>
      <span style={{ color:'var(--txt-dim)' }}>{k}</span>
      <span className="mono" style={{ color: c || 'var(--txt-hi)', fontWeight:600 }}>{v}</span>
    </div>
  );
}

Object.assign(window, { Dashboard });
