const { useState, useMemo } = React;

// ─── 5×5 Risk Matrix ─────────────────────────────────────────────────────────
function RiskMatrix({ risks, onHover }) {
  const [hovered, setHovered] = useState(null);
  const CELL = 56;

  function cellBg(p, i) {
    const s = p * i;
    if (s >= 20) return { bg:'#FEE2E2', border:C.danger   };
    if (s >= 15) return { bg:'#FEF3C7', border:C.warning  };
    if (s >= 10) return { bg:'#FEF9C3', border:'#EAB308'  };
    if (s >= 5)  return { bg:'#ECFDF5', border:C.success  };
    return              { bg:'#F0FDF4', border:'#86EFAC'   };
  }

  function scoreLabel(s) {
    if (s >= 20) return { label:'CRÍTICO',  color:C.danger  };
    if (s >= 15) return { label:'MUITO ALTO',color:C.warning };
    if (s >= 10) return { label:'ALTO',      color:'#CA8A04' };
    if (s >= 5)  return { label:'MÉDIO',     color:C.success };
    return               { label:'BAIXO',    color:'#16A34A' };
  }

  const risksInCell = (prob, imp) => risks.filter(r => r.P === prob && r.I === imp);

  return (
    <div style={{ position:'relative' }}>
      {/* Y axis label */}
      <div style={{ display:'flex', alignItems:'flex-start', gap:4 }}>
        <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', paddingTop:24, gap:0 }}>
          <div style={{ fontSize:9, color:C.textSub, fontWeight:700, letterSpacing:0.5, transform:'rotate(-90deg)', transformOrigin:'right center', marginBottom:30, marginRight:-12 }}>PROBABILIDADE ↑</div>
        </div>
        <div>
          {/* Probability labels + rows */}
          {[5,4,3,2,1].map(prob => (
            <div key={prob} style={{ display:'flex', alignItems:'center', marginBottom:2 }}>
              <div style={{ width:22, textAlign:'right', paddingRight:6, fontSize:10.5, color:C.textSub, fontWeight:700, flexShrink:0 }}>{prob}</div>
              {[1,2,3,4,5].map(imp => {
                const { bg, border } = cellBg(prob, imp);
                const items = risksInCell(prob, imp);
                const cellKey = `${prob}-${imp}`;
                return (
                  <div key={imp}
                    style={{ width:CELL, height:CELL, background:bg, border:`1.5px solid ${border}55`, borderRadius:3,
                      display:'flex', flexWrap:'wrap', alignItems:'center', justifyContent:'center', gap:2, padding:3,
                      marginRight:2, cursor: items.length ? 'pointer' : 'default',
                      transition:'transform 0.1s', transform: hovered === cellKey && items.length ? 'scale(1.06)' : 'scale(1)',
                    }}
                    onMouseEnter={() => { setHovered(cellKey); if(items.length) onHover(items); }}
                    onMouseLeave={() => { setHovered(null); onHover([]); }}
                  >
                    {items.map(r => (
                      <div key={r.id} style={{
                        fontSize:8.5, fontWeight:800, color:'#374151',
                        background:'rgba(255,255,255,0.85)', padding:'1px 4px', borderRadius:2,
                        border:`1px solid ${border}88`, whiteSpace:'nowrap',
                      }}>{r.id}</div>
                    ))}
                    {!items.length && <div style={{ fontSize:9, color:`${border}66`, fontWeight:700 }}>{prob*imp}</div>}
                  </div>
                );
              })}
            </div>
          ))}
          {/* X axis */}
          <div style={{ display:'flex', marginTop:4 }}>
            <div style={{ width:22 }} />
            {[1,2,3,4,5].map(i => (
              <div key={i} style={{ width:CELL, textAlign:'center', fontSize:10.5, color:C.textSub, fontWeight:700, marginRight:2 }}>{i}</div>
            ))}
          </div>
          <div style={{ paddingLeft:28, fontSize:9, color:C.textSub, fontWeight:700, letterSpacing:0.5, marginTop:2 }}>IMPACTO →</div>
        </div>
      </div>

      {/* Legend */}
      <div style={{ display:'flex', gap:8, marginTop:10, flexWrap:'wrap' }}>
        {[{s:'≥20',l:'Crítico',bg:'#FEE2E2',c:C.danger},{s:'15–19',l:'Muito Alto',bg:'#FEF3C7',c:C.warning},{s:'10–14',l:'Alto',bg:'#FEF9C3',c:'#CA8A04'},{s:'5–9',l:'Médio',bg:'#ECFDF5',c:C.success},{s:'<5',l:'Baixo',bg:'#F0FDF4',c:'#16A34A'}].map(z => (
          <div key={z.s} style={{ display:'flex', alignItems:'center', gap:4, fontSize:10, color:z.c }}>
            <div style={{ width:12, height:12, background:z.bg, border:`1.5px solid ${z.c}44`, borderRadius:2 }} />
            <span style={{ fontWeight:600 }}>{z.s}</span> {z.l}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Risk Row ─────────────────────────────────────────────────────────────────
function RiskRow({ r, idx, highlight }) {
  const score = r.P * r.I;
  const col   = score >= 20 ? C.danger : score >= 15 ? C.warning : score >= 10 ? '#CA8A04' : C.success;
  const stale = false; // would check days since review
  const escalated = score >= 20;

  return (
    <tr style={{ background: highlight ? `${col}18` : idx%2===0 ? '#FAFBFC' : C.card }}>
      <Td>
        <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
          <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:10.5, fontWeight:700, color:C.primary }}>{r.id}</span>
          {escalated && <span style={{ fontSize:8, fontWeight:800, background:C.danger, color:'#fff', padding:'0px 4px', borderRadius:2, alignSelf:'flex-start' }}>ESCALONADO CEx</span>}
        </div>
      </Td>
      <Td><Badge label={r.category} variant={r.category==='Financeiro'?'primary':r.category==='Ambiental'?'success':r.category==='RH'?'default':'warning'} small /></Td>
      <Td style={{ maxWidth:220, fontSize:11.5, lineHeight:1.4 }}>{r.description}</Td>
      <Td style={{ textAlign:'center' }}><span style={{ fontWeight:700, color:col }}>{r.P}</span></Td>
      <Td style={{ textAlign:'center' }}><span style={{ fontWeight:700, color:col }}>{r.I}</span></Td>
      <Td style={{ textAlign:'center' }}>
        <div style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', width:30, height:30, borderRadius:'50%', background:`${col}22`, border:`2px solid ${col}55`, fontWeight:800, fontSize:13, color:col }}>{score}</div>
      </Td>
      <Td style={{ textAlign:'center' }}>
        <span style={{ fontSize:16, color: r.trend==='up'?C.danger : r.trend==='down'?C.success : C.textSub }}>
          {r.trend==='up'?'↑':r.trend==='down'?'↓':'→'}
        </span>
      </Td>
      <Td style={{ fontSize:11, maxWidth:180, lineHeight:1.4 }}>{r.strategy}</Td>
      <Td style={{ fontSize:11, fontWeight:500 }}>{r.owner}</Td>
      <Td style={{ fontSize:11, color:C.textSub, fontFamily:'IBM Plex Mono, monospace' }}>{r.lastReview}</Td>
    </tr>
  );
}

// ─── Screen 7: Gestão de Riscos ───────────────────────────────────────────────
function Screen7Riscos() {
  const { risks } = window.SIGP_DATA;
  const [hoveredRisks, setHoveredRisks] = useState([]);
  const [filterCat, setFilterCat] = useState('Todos');
  const [filterTrend, setFilterTrend] = useState('Todos');
  const [activeTab, setActiveTab] = useState('matrix');

  const cats = ['Todos', 'Financeiro', 'Técnico', 'Ambiental', 'RH'];

  const filtered = useMemo(() => risks.filter(r => {
    if (filterCat !== 'Todos' && r.category !== filterCat) return false;
    if (filterTrend !== 'Todos') {
      if (filterTrend === 'Piorando' && r.trend !== 'up')   return false;
      if (filterTrend === 'Melhorando' && r.trend !== 'down') return false;
    }
    return true;
  }), [filterCat, filterTrend]);

  const critical = risks.filter(r => r.P * r.I >= 20).length;
  const high     = risks.filter(r => { const s = r.P*r.I; return s>=15&&s<20; }).length;
  const worsened = risks.filter(r => r.trend === 'up').length;
  const improved = risks.filter(r => r.trend === 'down').length;

  return (
    <ScreenShell
      title="Gestão de Riscos"
      subtitle="RIS · Registro e monitoramento visual · Matriz 5×5 · Semana 8 · 23/05/2026"
    >
      {/* ── Summary KPIs ── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:10, marginBottom:14 }}>
        <KPICard label="Riscos Críticos (Score ≥20)"    value={critical}  sub="escalonados para CEx"   status={critical>0?'critical':'ok'} />
        <KPICard label="Riscos Alto (Score 15–19)"      value={high}      sub="plano de ação ativo"    status={high>0?'at_risk':'ok'} />
        <KPICard label="Piorando (↑) esta semana"       value={worsened}  sub="requerem revisão imediata" status={worsened>3?'at_risk':'warning'} />
        <KPICard label="Melhorando (↓) esta semana"     value={improved}  sub="estratégia efetiva"     status="ok" />
      </div>

      {/* ── Tabs ── */}
      <div style={{ display:'flex', gap:2, marginBottom:12 }}>
        {[{id:'matrix',label:'Matriz de Risco'},{id:'register',label:'Registro de Riscos'},{id:'trends',label:'Tendências'}].map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
            padding:'6px 14px', fontSize:11.5, fontWeight:activeTab===t.id?700:500,
            background:activeTab===t.id?C.primary:'#fff',
            color:activeTab===t.id?'#fff':C.textSub,
            border:`1px solid ${activeTab===t.id?C.primary:C.border}`,
            borderRadius:5, cursor:'pointer', fontFamily:'inherit',
          }}>{t.label}</button>
        ))}
      </div>

      {/* ── Matrix Tab ── */}
      {activeTab === 'matrix' && (
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:14 }}>
          <Card title="Matriz de Risco 5×5" subtitle="Hover sobre células para ver detalhes · CC = Caminho Crítico">
            <RiskMatrix risks={risks} onHover={setHoveredRisks} />
          </Card>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <Card title="Detalhes do Risco" subtitle={hoveredRisks.length ? `${hoveredRisks.length} risco(s) nesta célula` : 'Passe o mouse sobre a matriz'}>
              {hoveredRisks.length === 0 && (
                <div style={{ color:C.textSub, fontSize:12, padding:'12px 0', textAlign:'center' }}>Selecione uma célula na matriz →</div>
              )}
              {hoveredRisks.map(r => {
                const score = r.P * r.I;
                const col = score >= 20 ? C.danger : score >= 15 ? C.warning : score >= 10 ? '#CA8A04' : C.success;
                return (
                  <div key={r.id} style={{ marginBottom:10, padding:'10px', background:`${col}0A`, borderRadius:6, border:`1px solid ${col}33` }}>
                    <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4 }}>
                      <span style={{ fontFamily:'IBM Plex Mono, monospace', fontWeight:800, color:C.primary }}>{r.id}</span>
                      <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                        <Badge label={r.category} variant={r.category==='Financeiro'?'primary':'default'} small />
                        <span style={{ fontWeight:800, color:col, fontSize:14 }}>Score {score}</span>
                      </div>
                    </div>
                    <div style={{ fontSize:12, fontWeight:600, color:C.text, marginBottom:4, lineHeight:1.4 }}>{r.description}</div>
                    <div style={{ fontSize:11, color:C.textSub, marginBottom:2 }}><strong>Estratégia:</strong> {r.strategy}</div>
                    <div style={{ fontSize:11, color:C.textSub }}><strong>Owner:</strong> {r.owner} · <strong>Revisão:</strong> {r.lastReview}</div>
                  </div>
                );
              })}
            </Card>
            <Card title="Top 3 Riscos Críticos">
              {risks.sort((a,b) => b.P*b.I - a.P*a.I).slice(0,3).map((r,i) => {
                const score = r.P*r.I;
                const col = score>=20?C.danger:C.warning;
                return (
                  <div key={r.id} style={{ display:'flex', gap:10, padding:'8px 0', borderBottom:`1px solid ${C.borderSub}` }}>
                    <div style={{ width:32, height:32, borderRadius:6, background:`${col}22`, border:`2px solid ${col}55`, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, color:col, fontSize:13, flexShrink:0 }}>{score}</div>
                    <div>
                      <div style={{ fontSize:11, fontWeight:700, color:C.text, lineHeight:1.3 }}>{r.id} · {r.category}</div>
                      <div style={{ fontSize:10.5, color:C.textSub, lineHeight:1.3 }}>{r.description.substring(0,70)}…</div>
                      <div style={{ fontSize:10, color:col, fontWeight:600, marginTop:1 }}>{r.trend==='up'?'↑ Tendência piorando':r.trend==='down'?'↓ Tendência melhorando':'→ Estável'}</div>
                    </div>
                  </div>
                );
              })}
            </Card>
          </div>
        </div>
      )}

      {/* ── Register Tab ── */}
      {activeTab === 'register' && (
        <Card title="Registro de Riscos" noPad
          headerRight={
            <div style={{ display:'flex', gap:6 }}>
              {cats.map(c => (
                <button key={c} onClick={() => setFilterCat(c)} style={{
                  padding:'3px 9px', fontSize:10.5, cursor:'pointer', fontFamily:'inherit',
                  background: filterCat===c ? C.primary : C.card,
                  color: filterCat===c ? '#fff' : C.textSub,
                  border:`1px solid ${filterCat===c ? C.primary : C.border}`,
                  borderRadius:4, fontWeight: filterCat===c ? 700 : 400,
                }}>{c}</button>
              ))}
            </div>
          }
        >
          <Table>
            <thead>
              <tr>
                <Th>ID</Th>
                <Th>Categoria</Th>
                <Th>Descrição</Th>
                <Th style={{ textAlign:'center' }}>P</Th>
                <Th style={{ textAlign:'center' }}>I</Th>
                <Th style={{ textAlign:'center' }}>Score</Th>
                <Th style={{ textAlign:'center' }}>Tend.</Th>
                <Th>Estratégia de Resposta</Th>
                <Th>Owner</Th>
                <Th>Última Rev.</Th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, i) => (
                <RiskRow key={r.id} r={r} idx={i} highlight={hoveredRisks.some(h => h.id === r.id)} />
              ))}
            </tbody>
          </Table>
        </Card>
      )}

      {/* ── Trends Tab ── */}
      {activeTab === 'trends' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          <Card title="Riscos que Pioraram esta Semana" subtitle="Tendência ↑ — requerem revisão imediata">
            {risks.filter(r => r.trend === 'up').map((r, i) => {
              const score = r.P * r.I;
              const col = score >= 20 ? C.danger : score >= 15 ? C.warning : '#CA8A04';
              return (
                <div key={r.id} style={{ display:'flex', gap:10, padding:'9px 0', borderBottom:`1px solid ${C.borderSub}` }}>
                  <span style={{ fontSize:18, color:C.danger }}>↑</span>
                  <div style={{ flex:1 }}>
                    <div style={{ display:'flex', justifyContent:'space-between' }}>
                      <span style={{ fontSize:11.5, fontWeight:700, color:C.text }}>{r.id} · {r.category}</span>
                      <span style={{ fontWeight:800, color:col }}>Score {score}</span>
                    </div>
                    <div style={{ fontSize:11, color:C.textSub, lineHeight:1.4, marginTop:2 }}>{r.description}</div>
                    <div style={{ fontSize:10.5, color:C.primary, marginTop:2 }}>Owner: {r.owner}</div>
                  </div>
                </div>
              );
            })}
          </Card>
          <Card title="Riscos que Melhoraram" subtitle="Tendência ↓ — estratégias efetivas">
            {risks.filter(r => r.trend === 'down').map((r, i) => (
              <div key={r.id} style={{ display:'flex', gap:10, padding:'9px 0', borderBottom:`1px solid ${C.borderSub}` }}>
                <span style={{ fontSize:18, color:C.success }}>↓</span>
                <div style={{ flex:1 }}>
                  <div style={{ display:'flex', justifyContent:'space-between' }}>
                    <span style={{ fontSize:11.5, fontWeight:700, color:C.text }}>{r.id} · {r.category}</span>
                    <span style={{ fontWeight:800, color:C.success }}>Score {r.P*r.I}</span>
                  </div>
                  <div style={{ fontSize:11, color:C.textSub, lineHeight:1.4, marginTop:2 }}>{r.description}</div>
                  <div style={{ fontSize:10.5, color:C.success, marginTop:2 }}>Estratégia efetiva · {r.strategy.substring(0,50)}…</div>
                </div>
              </div>
            ))}
            {risks.filter(r => r.trend === 'down').length === 0 && (
              <div style={{ color:C.textSub, fontSize:12, textAlign:'center', padding:16 }}>Nenhum risco com tendência de melhora</div>
            )}
          </Card>
        </div>
      )}
    </ScreenShell>
  );
}

Object.assign(window, { Screen7Riscos });
