const { useState } = React;

// ─── Status color for env ────────────────────────────────────────────────────
function envColor(s) {
  if (s === 'critical') return C.danger;
  if (s === 'at_risk')  return C.warning;
  if (s === 'warning')  return '#F97316';
  return C.success;
}
function envBg(s) {
  if (s === 'critical') return '#FFF5F5';
  if (s === 'at_risk')  return '#FFFBEB';
  if (s === 'warning')  return '#FFF7ED';
  return '#F0FDF4';
}

// ─── Counter card ─────────────────────────────────────────────────────────────
function EnvCounter({ label, value, color, icon }) {
  return (
    <div style={{ background:C.card, border:`1px solid ${color}44`, borderTop:`3px solid ${color}`, borderRadius:7, padding:'14px 16px', display:'flex', alignItems:'center', gap:14 }}>
      <div style={{ width:44, height:44, borderRadius:10, background:`${color}18`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:22 }}>{icon}</div>
      <div>
        <div style={{ fontSize:28, fontWeight:800, color, lineHeight:1 }}>{value}</div>
        <div style={{ fontSize:11, color:C.textSub, marginTop:3 }}>{label}</div>
      </div>
    </div>
  );
}

// ─── 90-day timeline ─────────────────────────────────────────────────────────
function EnvTimeline({ conditions }) {
  // Show next 90 days as weeks
  const weeks = Array.from({ length: 13 }, (_, i) => i); // 0 = current week
  const weekLabel = i => {
    const d = new Date(2026, 4, 23); // May 23
    d.setDate(d.getDate() + i * 7);
    return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}`;
  };
  const dayOfProject = days => Math.floor(days / 7); // which week slot

  return (
    <div style={{ overflowX:'auto' }}>
      <div style={{ minWidth: 780 }}>
        {/* Week headers */}
        <div style={{ display:'flex', marginBottom:6 }}>
          <div style={{ width:80, flexShrink:0 }} />
          {weeks.map(w => (
            <div key={w} style={{ flex:1, textAlign:'center', fontSize:9.5, color:C.textSub, fontWeight:600, padding:'2px 0', background: w===0 ? '#EFF6FF' : 'transparent', borderRadius:3 }}>
              {weekLabel(w)}{w===0?' (hoje)':''}
            </div>
          ))}
        </div>
        {/* Conditions */}
        {conditions.filter(c => c.daysLeft <= 90).map(c => {
          const weekSlot = Math.min(12, Math.floor(c.daysLeft / 7));
          const color = envColor(c.status);
          return (
            <div key={c.code} style={{ display:'flex', alignItems:'center', marginBottom:4 }}>
              <div style={{ width:80, flexShrink:0, fontSize:10, fontWeight:700, color, fontFamily:'IBM Plex Mono, monospace' }}>{c.code}</div>
              <div style={{ flex:1, position:'relative', display:'grid', gridTemplateColumns:`repeat(13, 1fr)`, height:22 }}>
                {weeks.map(w => (
                  <div key={w} style={{ borderRight:`1px solid ${C.borderSub}`, background: w < weekSlot ? `${color}08` : 'transparent' }} />
                ))}
                {/* Deadline marker */}
                <div style={{
                  position:'absolute',
                  left:`${(weekSlot / 13) * 100}%`,
                  top:2, width:18, height:18,
                  background:color, borderRadius:3,
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontSize:8, color:'#fff', fontWeight:800, cursor:'default',
                  transform:'translateX(-50%)',
                  boxShadow:`0 1px 3px ${color}66`,
                }} title={`${c.code}: ${c.desc}`}>
                  {c.daysLeft}d
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop:6, fontSize:10, color:C.textSub }}>
        <span style={{ color:C.danger, fontWeight:700 }}>■</span> Crítico &nbsp;
        <span style={{ color:C.warning, fontWeight:700 }}>■</span> Em risco &nbsp;
        <span style={{ color:'#F97316', fontWeight:700 }}>■</span> Atenção &nbsp;
        <span style={{ color:C.success, fontWeight:700 }}>■</span> OK · Números = dias restantes
      </div>
    </div>
  );
}

// ─── Risk heatmap ─────────────────────────────────────────────────────────────
function EnvRiskHeatmap() {
  const risks = [
    { P:4, I:4, label:'Embargo\nIMASQL' },
    { P:3, I:4, label:'Contaminação\nsolo' },
    { P:3, I:3, label:'Chuvas\nexcessivas' },
    { P:2, I:5, label:'Passivo\nambient.' },
    { P:2, I:3, label:'Ruído\ncomunidade' },
  ];
  const cellBg = (p, i) => {
    const s = p * i;
    if (s >= 16) return '#FEE2E2';
    if (s >= 12) return '#FEF3C7';
    if (s >= 6)  return '#FEF9C3';
    return '#DCFCE7';
  };
  const cellBorder = (p, i) => {
    const s = p * i;
    if (s >= 16) return C.danger;
    if (s >= 12) return C.warning;
    if (s >= 6)  return '#FDE047';
    return C.success;
  };
  const riskIn = (prob, imp) => risks.filter(r => r.P === prob && r.I === imp);

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:4, marginBottom:6 }}>
        <div style={{ width:60, fontSize:10, color:C.textSub, textAlign:'right', fontWeight:600 }}>PROB ↑</div>
        <div style={{ flex:1 }}>
          <div style={{ display:'flex', justifyContent:'space-around', fontSize:10, color:C.textSub, fontWeight:600, marginBottom:3 }}>
            {[1,2,3,4,5].map(i => <span key={i} style={{ flex:1, textAlign:'center' }}>{i}</span>)}
          </div>
        </div>
      </div>
      {[5,4,3,2,1].map(prob => (
        <div key={prob} style={{ display:'flex', alignItems:'center', gap:4, marginBottom:2 }}>
          <div style={{ width:60, textAlign:'right', fontSize:10, color:C.textSub, fontWeight:600, paddingRight:6 }}>{prob}</div>
          <div style={{ flex:1, display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:2 }}>
            {[1,2,3,4,5].map(imp => {
              const items = riskIn(prob, imp);
              return (
                <div key={imp} style={{
                  height:46, background:cellBg(prob,imp),
                  border:`1px solid ${cellBorder(prob,imp)}55`,
                  borderRadius:4, display:'flex', flexWrap:'wrap',
                  alignItems:'center', justifyContent:'center', gap:2, padding:2,
                }}>
                  {items.map((r, idx) => (
                    <div key={idx} style={{ fontSize:7.5, lineHeight:1.2, color:'#374151', fontWeight:700, textAlign:'center', background:'rgba(255,255,255,0.7)', padding:'1px 3px', borderRadius:2 }}>
                      {r.label.replace('\n',' ')}
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        </div>
      ))}
      <div style={{ marginTop:4, paddingLeft:66, fontSize:10, color:C.textSub }}>IMPACTO →</div>
    </div>
  );
}

// ─── Screen 5: Painel Ambiental ──────────────────────────────────────────────
function Screen5Ambiental() {
  const { envConditions, regulatoryStatus } = window.SIGP_DATA;
  const [activeTab, setActiveTab] = useState('lista');

  const cumpridas    = envConditions.filter(c => c.status === 'ok' && c.docsDone === c.docsReq).length;
  const emAndamento  = envConditions.filter(c => c.status === 'ok' && c.docsDone < c.docsReq).length + envConditions.filter(c => c.status === 'warning').length;
  const emRisco      = envConditions.filter(c => c.status === 'at_risk').length;
  const criticas     = envConditions.filter(c => c.status === 'critical').length;

  return (
    <ScreenShell
      title="Painel Ambiental — Condicionantes LI 000977/2022"
      subtitle="AMB · Controle de conformidade IMASUL/MS — Semáforo e countdown de prazos"
      actions={
        <Btn variant="success" onClick={() => alert('Gerando Relatório de Conformidade PDF para submissão ao IMASUL...')}>
          📄 Gerar Relatório de Conformidade PDF
        </Btn>
      }
    >
      {/* ── Counters ── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:10, marginBottom:14 }}>
        <EnvCounter label="Condicionantes Cumpridas"     value={cumpridas}   color={C.success} icon="✅" />
        <EnvCounter label="Em Andamento / OK"            value={emAndamento} color="#60A5FA"   icon="🔄" />
        <EnvCounter label="Em Risco (< 15 dias)"         value={emRisco}     color={C.warning} icon="⚠️" />
        <EnvCounter label="Vencidas / Críticas"          value={criticas}    color={C.danger}  icon="🚨" />
      </div>

      {/* ── Critical highlight ── */}
      <div style={{ padding:'10px 14px', background:'#FFF5F5', border:`2px solid ${C.danger}`, borderRadius:7, marginBottom:14 }}>
        <div style={{ fontSize:12, fontWeight:800, color:C.danger, marginBottom:6 }}>🚨 CONDICIONANTES CRÍTICAS — PRAZO &lt; 7 DIAS</div>
        <div style={{ display:'flex', gap:10 }}>
          {envConditions.filter(c => c.daysLeft <= 7).map(c => (
            <div key={c.code} style={{ flex:1, padding:'8px 10px', background:'#fff', border:`1px solid ${C.danger}44`, borderRadius:5 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:3 }}>
                <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, fontWeight:700, color:C.danger }}>{c.code}</span>
                <span style={{ fontSize:11, fontWeight:800, color:C.danger, background:'#FEE2E2', padding:'1px 7px', borderRadius:3 }}>{c.daysLeft}d restante{c.daysLeft !== 1 ? 's' : ''}</span>
              </div>
              <div style={{ fontSize:11.5, fontWeight:600, color:C.text, marginBottom:2 }}>{c.desc}</div>
              <div style={{ fontSize:10.5, color:C.textSub }}>Resp: {c.responsible} · Docs: {c.docsDone}/{c.docsReq} entregues</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Tabs ── */}
      <div style={{ display:'flex', gap:2, marginBottom:12 }}>
        {[{id:'lista',label:'Lista Detalhada'},{id:'timeline',label:'Timeline 90 dias'},{id:'heatmap',label:'Mapa de Risco Ambiental'},{id:'regulatorio',label:'Status Regulatório'}].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.success:'#fff',
            color:activeTab===t.id?'#fff':C.textSub,
            border:`1px solid ${activeTab===t.id?C.success:C.border}`,
            borderRadius:5, cursor:'pointer', fontFamily:'inherit',
          }}>{t.label}</button>
        ))}
      </div>

      {/* ── List Tab ── */}
      {activeTab === 'lista' && (
        <Card title="Condicionantes da LI 000977/2022" noPad>
          <Table>
            <thead>
              <tr>
                <Th>Código</Th>
                <Th>Descrição</Th>
                <Th>Prazo</Th>
                <Th style={{ textAlign:'center' }}>Dias</Th>
                <Th>Responsável</Th>
                <Th>Status Doc.</Th>
                <Th style={{ textAlign:'center' }}>Docs</Th>
                <Th>Status</Th>
                <Th>Upload</Th>
              </tr>
            </thead>
            <tbody>
              {envConditions.map((c, i) => {
                const col = envColor(c.status);
                return (
                  <tr key={c.code} style={{ background: c.status==='critical'?'#FFF5F5': c.status==='at_risk'?'#FFFBEB': i%2===0?'#FAFBFC':C.card }}>
                    <Td><span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, fontWeight:700, color:col }}>{c.code}</span></Td>
                    <Td style={{ maxWidth:240 }}><span style={{ fontSize:11.5, lineHeight:1.4 }}>{c.desc}</span></Td>
                    <Td><span style={{ fontSize:11, fontFamily:'IBM Plex Mono, monospace' }}>{c.deadline}</span></Td>
                    <Td style={{ textAlign:'center' }}>
                      <span style={{ fontWeight:800, fontSize:13, color:col }}>{c.daysLeft}</span>
                    </Td>
                    <Td style={{ fontSize:11 }}>{c.responsible}</Td>
                    <Td style={{ fontSize:11 }}>{c.docStatus}</Td>
                    <Td style={{ textAlign:'center' }}>
                      <span style={{ fontSize:11, color: c.docsDone < c.docsReq ? C.danger : C.success, fontWeight:700 }}>
                        {c.docsDone}/{c.docsReq}
                      </span>
                    </Td>
                    <Td>
                      <div style={{ display:'flex', alignItems:'center', gap:5 }}>
                        <span style={{ width:8, height:8, borderRadius:'50%', background:col, display:'inline-block', flexShrink:0 }} />
                        <span style={{ fontSize:10.5, color:col, fontWeight:600 }}>
                          {c.status==='critical'?'Crítico':c.status==='at_risk'?'Em risco':c.status==='warning'?'Atenção':'OK'}
                        </span>
                      </div>
                    </Td>
                    <Td>
                      <Btn small variant="ghost" onClick={() => alert(`Upload para ${c.code}`)}>↑ Upload</Btn>
                    </Td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        </Card>
      )}

      {/* ── Timeline Tab ── */}
      {activeTab === 'timeline' && (
        <Card title="Timeline de Condicionantes — Próximos 90 Dias" subtitle="Dias restantes até cada prazo · semanas a partir de 23/05/2026">
          <EnvTimeline conditions={envConditions} />
        </Card>
      )}

      {/* ── Heatmap Tab ── */}
      {activeTab === 'heatmap' && (
        <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:14 }}>
          <Card title="Matriz Probabilidade × Impacto" subtitle="Riscos ambientais identificados na LI 000977/2022">
            <EnvRiskHeatmap />
          </Card>
          <Card title="Legenda e Escala de Risco" subtitle="Critérios de avaliação IMASUL">
            {[
              { score:'16–25', label:'CRÍTICO',   color:C.danger,  desc:'Ação imediata requerida — protocolo IMASUL em até 48h' },
              { score:'10–15', label:'ALTO',       color:C.warning, desc:'Plano de ação documentado em até 5 dias úteis' },
              { score:'4–9',   label:'MÉDIO',      color:'#FDE047', desc:'Monitoramento semanal e medidas preventivas' },
              { score:'1–3',   label:'BAIXO',      color:C.success, desc:'Monitoramento mensal conforme plano ambiental' },
            ].map(r => (
              <div key={r.score} style={{ display:'flex', gap:10, padding:'8px 0', borderBottom:`1px solid ${C.borderSub}` }}>
                <div style={{ width:36, height:36, background:`${r.color}22`, border:`2px solid ${r.color}`, borderRadius:5, display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:800, color:r.color, flexShrink:0 }}>{r.score}</div>
                <div>
                  <div style={{ fontSize:12, fontWeight:700, color:r.color }}>{r.label}</div>
                  <div style={{ fontSize:11, color:C.textSub }}>{r.desc}</div>
                </div>
              </div>
            ))}
          </Card>
        </div>
      )}

      {/* ── Regulatory Tab ── */}
      {activeTab === 'regulatorio' && (
        <Card title="Status dos Processos Regulatórios">
          {regulatoryStatus.map((r, i) => {
            const col = envColor(r.status);
            return (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 12px', background: i%2===0?'#FAFBFC':C.card, borderRadius:5, marginBottom:4 }}>
                <div style={{ width:10, height:10, borderRadius:'50%', background:col, flexShrink:0 }} />
                <div style={{ minWidth:180 }}>
                  <div style={{ fontSize:12.5, fontWeight:700, color:C.text }}>{r.name}</div>
                  <div style={{ fontSize:10.5, color:C.textSub, fontFamily:'IBM Plex Mono, monospace' }}>{r.proc}</div>
                </div>
                <div style={{ flex:1, fontSize:11.5, color:C.textSub }}>{r.detail}</div>
                <Badge label={r.status==='ok'?'✓ Regular':r.status==='at_risk'?'⚠ Em Risco':'⚠ Atenção'} variant={r.status==='ok'?'success':r.status==='at_risk'?'danger':'warning'} small />
              </div>
            );
          })}
        </Card>
      )}
    </ScreenShell>
  );
}

Object.assign(window, { Screen5Ambiental });
